id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_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; memset(&map, 0, sizeof(map)); map.mem_start = dev->mem_start; map.mem_end = dev->mem_end; map.base_addr = dev->base_addr; map.irq = dev->irq; map.dma = dev->dma; map.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/good_5050_0
crossvul-cpp_data_bad_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 (!memcmp(buf + 5, "include", 7)) { do_ssi_include(conn, path, buf + 12, include_level + 1); #if !defined(NO_POPEN) } else if (!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/bad_203_0
crossvul-cpp_data_good_1508_2
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 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 <sys/utsname.h> #include "libabrt.h" #include <selinux/selinux.h> #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 static int g_user_core_flags; static int g_need_nonrelative; /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static DIR *proc_cwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static DIR *open_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); DIR *cwd = opendir(buf); if (cwd == NULL) perror_msg("Can't open process's CWD for CompatCore"); return cwd; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_proc_fs_id(char type) { const char *scanf_format = "%*cid:\t%d\t%d\t%d\t%d\n"; char id_type[] = "_id"; id_type[0] = type; int real, e_id, saved; int fs_id = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, id_type, 3) == 0) { int n = sscanf(line, scanf_format, &real, &e_id, &saved, &fs_id); if (n != 4) { perror_msg_and_die("Can't parse %cid: line", type); } return fs_id; } line = strchr(line, '\n'); if (!line) break; line++; } perror_msg_and_die("Failed to get file system %cID of the crashed process", type); } static int get_fsuid(void) { return get_proc_fs_id(/*UID*/'U'); } static int get_fsgid(void) { return get_proc_fs_id(/*GID*/'G'); } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } /* Computes a security context of new file created by the given process with * pid in the given directory represented by file descriptor. * * On errors returns negative number. Returns 0 if the function succeeds and * computes the context and returns positive number and assigns NULL to newcon * if the security context is not needed (SELinux disabled). */ static int compute_selinux_con_for_new_file(pid_t pid, int dir_fd, security_context_t *newcon) { security_context_t srccon; security_context_t dstcon; const int r = is_selinux_enabled(); if (r == 0) { *newcon = NULL; return 1; } else if (r == -1) { perror_msg("Couldn't get state of SELinux"); return -1; } else if (r != 1) error_msg_and_die("Unexpected SELinux return value: %d", r); if (getpidcon_raw(pid, &srccon) < 0) { perror_msg("getpidcon_raw(%d)", pid); return -1; } if (fgetfilecon_raw(dir_fd, &dstcon) < 0) { perror_msg("getfilecon_raw(%s)", user_pwd); return -1; } if (security_compute_create_raw(srccon, dstcon, string_to_security_class("file"), newcon) < 0) { perror_msg("security_compute_create_raw(%s, %s, 'file')", srccon, dstcon); return -1; } return 0; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { proc_cwd = open_cwd(pid); if (proc_cwd == NULL) return -1; errno = 0; /* http://article.gmane.org/gmane.comp.security.selinux/21842 */ security_context_t newcon; if (compute_selinux_con_for_new_file(pid, dirfd(proc_cwd), &newcon) < 0) { log_notice("Not going to create a user core due to SELinux errors"); return -1; } xsetegid(get_fsgid()); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } if (g_need_nonrelative && core_basename[0] != '/') { error_msg("Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern"); return -1; } /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ /* Set SELinux context like kernel when creating core dump file */ if (newcon != NULL && setfscreatecon_raw(newcon) < 0) { perror_msg("setfscreatecon_raw(%s)", newcon); return -1; } struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = openat(dirfd(proc_cwd), core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */ if (newcon != NULL && setfscreatecon_raw(NULL) < 0) { error_msg("setfscreatecon_raw(NULL)"); goto user_core_fail; } xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 || sb.st_uid != fsuid ) { if (user_core_fd < 0) perror_msg("Can't open '%s' at '%s'", core_basename, user_pwd); else perror_msg("'%s' at '%s' is not a regular file with link count 1 owned by UID(%d)", core_basename, user_pwd, fsuid); goto user_core_fail; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' at '%s' to size 0", core_basename, user_pwd); goto user_core_fail; } return user_core_fd; user_core_fail: if (user_core_fd >= 0) { close(user_core_fd); unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); } return -1; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "wx"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) fsuid = tmp_fsuid; else { g_user_core_flags = O_EXCL; g_need_nonrelative = 1; } } /* If PrivateReports is on, root owns all problem directories */ const uid_t dduid = g_settings_privatereports ? 0 : fsuid; /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ if (snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash) >= sizeof(path)) error_msg_and_die("Error saving '%s': truncated long file path", path); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); if (proc_cwd != NULL) closedir(proc_cwd); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use dduid (either fsuid or 0) instead of uid, so we don't expose any * sensitive information of suided app in /var/tmp/abrt * * dd_create_skeleton() creates a new directory and leaves ownership to * the current user, hence, we have to call dd_reset_ownership() after the * directory is populated. */ dd = dd_create_skeleton(path, dduid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0); if (dd) { char *rootdir = get_rootdir(pid); /* This function uses fsuid only for its value. The function stores fsuid in a file name 'uid'*/ dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* And finally set the right uid and gid */ dd_reset_ownership(dd); /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); if (proc_cwd != NULL) closedir(proc_cwd); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s' at '%s'", core_basename, user_pwd); unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); if (proc_cwd != NULL) closedir(proc_cwd); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); if (proc_cwd != NULL) closedir(proc_cwd); return 1; } log("Saved core dump of pid %lu to %s at %s (%llu bytes)", (long)pid, core_basename, user_pwd, (long long)core_size); } if (proc_cwd != NULL) closedir(proc_cwd); return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_1508_2
crossvul-cpp_data_good_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); 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_3826_0
crossvul-cpp_data_bad_1102_0
/* * Copyright (c) 2006, 2018 Oracle and/or its affiliates. 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, struct in6_addr *saddr) { refcount_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 = ktime_set(0, 0); memset(inc->i_rx_lat_trace, 0, sizeof(inc->i_rx_lat_trace)); } EXPORT_SYMBOL_GPL(rds_inc_init); void rds_inc_path_init(struct rds_incoming *inc, struct rds_conn_path *cp, struct in6_addr *saddr) { refcount_set(&inc->i_refcount, 1); INIT_LIST_HEAD(&inc->i_item); inc->i_conn = cp->cp_conn; inc->i_conn_path = cp; inc->i_saddr = *saddr; inc->i_rdma_cookie = 0; inc->i_rx_tstamp = ktime_set(0, 0); } EXPORT_SYMBOL_GPL(rds_inc_path_init); static void rds_inc_addref(struct rds_incoming *inc) { rdsdebug("addref inc %p ref %d\n", inc, refcount_read(&inc->i_refcount)); refcount_inc(&inc->i_refcount); } void rds_inc_put(struct rds_incoming *inc) { rdsdebug("put inc %p ref %d\n", inc, refcount_read(&inc->i_refcount)); if (refcount_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; if (delta > 0) rds_stats_add(s_recv_bytes_added_to_socket, delta); else rds_stats_add(s_recv_bytes_removed_from_socket, -delta); /* loop transport doesn't send/recv congestion updates */ if (rs->rs_transport->t_type == RDS_TRANS_LOOP) return; now_congested = rs->rs_rcv_bytes > rds_sk_rcvbuf(rs); rdsdebug("rs %p (%pI6c:%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 */ } static void rds_conn_peer_gen_update(struct rds_connection *conn, u32 peer_gen_num) { int i; struct rds_message *rm, *tmp; unsigned long flags; WARN_ON(conn->c_trans->t_type != RDS_TRANS_TCP); if (peer_gen_num != 0) { if (conn->c_peer_gen_num != 0 && peer_gen_num != conn->c_peer_gen_num) { for (i = 0; i < RDS_MPATH_WORKERS; i++) { struct rds_conn_path *cp; cp = &conn->c_path[i]; spin_lock_irqsave(&cp->cp_lock, flags); cp->cp_next_tx_seq = 1; cp->cp_next_rx_seq = 0; list_for_each_entry_safe(rm, tmp, &cp->cp_retrans, m_conn_item) { set_bit(RDS_MSG_FLUSH, &rm->m_flags); } spin_unlock_irqrestore(&cp->cp_lock, flags); } } conn->c_peer_gen_num = peer_gen_num; } } /* * 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; } } } static void rds_recv_hs_exthdrs(struct rds_header *hdr, struct rds_connection *conn) { unsigned int pos = 0, type, len; union { struct rds_ext_header_version version; u16 rds_npaths; u32 rds_gen_num; } buffer; u32 new_peer_gen_num = 0; 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_NPATHS: conn->c_npaths = min_t(int, RDS_MPATH_WORKERS, be16_to_cpu(buffer.rds_npaths)); break; case RDS_EXTHDR_GEN_NUM: new_peer_gen_num = be32_to_cpu(buffer.rds_gen_num); break; default: pr_warn_ratelimited("ignoring unknown exthdr type " "0x%x\n", type); } } /* if RDS_EXTHDR_NPATHS was not found, default to a single-path */ conn->c_npaths = max_t(int, conn->c_npaths, 1); conn->c_ping_triggered = 0; rds_conn_peer_gen_update(conn, new_peer_gen_num); } /* rds_start_mprds() will synchronously start multiple paths when appropriate. * The scheme is based on the following rules: * * 1. rds_sendmsg on first connect attempt sends the probe ping, with the * sender's npaths (s_npaths) * 2. rcvr of probe-ping knows the mprds_paths = min(s_npaths, r_npaths). It * sends back a probe-pong with r_npaths. After that, if rcvr is the * smaller ip addr, it starts rds_conn_path_connect_if_down on all * mprds_paths. * 3. sender gets woken up, and can move to rds_conn_path_connect_if_down. * If it is the smaller ipaddr, rds_conn_path_connect_if_down can be * called after reception of the probe-pong on all mprds_paths. * Otherwise (sender of probe-ping is not the smaller ip addr): just call * rds_conn_path_connect_if_down on the hashed path. (see rule 4) * 4. rds_connect_worker must only trigger a connection if laddr < faddr. * 5. sender may end up queuing the packet on the cp. will get sent out later. * when connection is completed. */ static void rds_start_mprds(struct rds_connection *conn) { int i; struct rds_conn_path *cp; if (conn->c_npaths > 1 && rds_addr_cmp(&conn->c_laddr, &conn->c_faddr) < 0) { for (i = 0; i < conn->c_npaths; i++) { cp = &conn->c_path[i]; rds_conn_path_connect_if_down(cp); } } } /* * 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, struct in6_addr *saddr, struct in6_addr *daddr, struct rds_incoming *inc, gfp_t gfp) { struct rds_sock *rs = NULL; struct sock *sk; unsigned long flags; struct rds_conn_path *cp; inc->i_conn = conn; inc->i_rx_jiffies = jiffies; if (conn->c_trans->t_mp_capable) cp = inc->i_conn_path; else cp = &conn->c_path[0]; 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)cp->cp_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) < cp->cp_next_rx_seq && (inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) { rds_stats_inc(s_recv_drop_old_seq); goto out; } cp->cp_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1; if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) { if (inc->i_hdr.h_sport == 0) { rdsdebug("ignore ping with 0 sport from %pI6c\n", saddr); goto out; } rds_stats_inc(s_recv_ping); rds_send_pong(cp, inc->i_hdr.h_sport); /* if this is a handshake ping, start multipath if necessary */ if (RDS_HS_PROBE(be16_to_cpu(inc->i_hdr.h_sport), be16_to_cpu(inc->i_hdr.h_dport))) { rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn); rds_start_mprds(cp->cp_conn); } goto out; } if (be16_to_cpu(inc->i_hdr.h_dport) == RDS_FLAG_PROBE_PORT && inc->i_hdr.h_sport == 0) { rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn); /* if this is a handshake pong, start multipath if necessary */ rds_start_mprds(cp->cp_conn); wake_up(&cp->cp_conn->c_hs_waitq); goto out; } rs = rds_find_bound(daddr, inc->i_hdr.h_dport, conn->c_bound_if); 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)) inc->i_rx_tstamp = ktime_get_real(); rds_inc_addref(inc); inc->i_rx_lat_trace[RDS_MSG_RX_END] = local_clock(); 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) goto out; } if ((inc->i_rx_tstamp != 0) && sock_flag(rds_rs_to_sk(rs), SOCK_RCVTSTAMP)) { struct __kernel_old_timeval tv = ns_to_kernel_old_timeval(inc->i_rx_tstamp); if (!sock_flag(rds_rs_to_sk(rs), SOCK_TSTAMP_NEW)) { ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD, sizeof(tv), &tv); } else { struct __kernel_sock_timeval sk_tv; sk_tv.tv_sec = tv.tv_sec; sk_tv.tv_usec = tv.tv_usec; ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW, sizeof(sk_tv), &sk_tv); } if (ret) goto out; } if (rs->rs_rx_traces) { struct rds_cmsg_rx_trace t; int i, j; memset(&t, 0, sizeof(t)); inc->i_rx_lat_trace[RDS_MSG_RX_CMSG] = local_clock(); t.rx_traces = rs->rs_rx_traces; for (i = 0; i < rs->rs_rx_traces; i++) { j = rs->rs_rx_trace[i]; t.rx_trace_pos[i] = j; t.rx_trace[i] = inc->i_rx_lat_trace[j + 1] - inc->i_rx_lat_trace[j]; } ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RXPATH_LATENCY, sizeof(t), &t); if (ret) goto out; } out: return ret; } static bool rds_recvmsg_zcookie(struct rds_sock *rs, struct msghdr *msg) { struct rds_msg_zcopy_queue *q = &rs->rs_zcookie_queue; struct rds_msg_zcopy_info *info = NULL; struct rds_zcopy_cookies *done; unsigned long flags; if (!msg->msg_control) return false; if (!sock_flag(rds_rs_to_sk(rs), SOCK_ZEROCOPY) || msg->msg_controllen < CMSG_SPACE(sizeof(*done))) return false; spin_lock_irqsave(&q->lock, flags); if (!list_empty(&q->zcookie_head)) { info = list_entry(q->zcookie_head.next, struct rds_msg_zcopy_info, rs_zcookie_next); list_del(&info->rs_zcookie_next); } spin_unlock_irqrestore(&q->lock, flags); if (!info) return false; done = &info->zcookies; if (put_cmsg(msg, SOL_RDS, RDS_CMSG_ZCOPY_COMPLETION, sizeof(*done), done)) { spin_lock_irqsave(&q->lock, flags); list_add(&info->rs_zcookie_next, &q->zcookie_head); spin_unlock_irqrestore(&q->lock, flags); return false; } kfree(info); return true; } 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_in6 *, sin6, msg->msg_name); 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; if (msg_flags & MSG_ERRQUEUE) return sock_recv_errqueue(sk, msg, size, SOL_IP, IP_RECVERR); while (1) { /* 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) { bool reaped = rds_recvmsg_zcookie(rs, msg); ret = reaped ? 0 : -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 %pI6c:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); 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); iov_iter_revert(&msg->msg_iter, ret); 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_recvmsg_zcookie(rs, msg); rds_stats_inc(s_recv_delivered); if (msg->msg_name) { if (ipv6_addr_v4mapped(&inc->i_saddr)) { sin = (struct sockaddr_in *)msg->msg_name; sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr.s6_addr32[3]; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); msg->msg_namelen = sizeof(*sin); } else { sin6 = (struct sockaddr_in6 *)msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = inc->i_hdr.h_sport; sin6->sin6_addr = inc->i_saddr; sin6->sin6_flowinfo = 0; sin6->sin6_scope_id = rs->rs_bound_scope_id; msg->msg_namelen = sizeof(*sin6); } } 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); minfo.tos = inc->i_conn->c_tos; 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)); } #if IS_ENABLED(CONFIG_IPV6) void rds6_inc_info_copy(struct rds_incoming *inc, struct rds_info_iterator *iter, struct in6_addr *saddr, struct in6_addr *daddr, int flip) { struct rds6_info_message minfo6; minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence); minfo6.len = be32_to_cpu(inc->i_hdr.h_len); if (flip) { minfo6.laddr = *daddr; minfo6.faddr = *saddr; minfo6.lport = inc->i_hdr.h_dport; minfo6.fport = inc->i_hdr.h_sport; } else { minfo6.laddr = *saddr; minfo6.faddr = *daddr; minfo6.lport = inc->i_hdr.h_sport; minfo6.fport = inc->i_hdr.h_dport; } rds_info_copy(iter, &minfo6, sizeof(minfo6)); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1102_0
crossvul-cpp_data_bad_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 = 100; 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 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 the check host-wide RFC 5961 rate limit. */ now = jiffies / HZ; if (now != challenge_timestamp) { challenge_timestamp = now; challenge_count = 0; } if (++challenge_count <= sysctl_tcp_challenge_ack_limit) { 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/bad_5130_0
crossvul-cpp_data_good_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/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/good_438_5
crossvul-cpp_data_good_438_4
/* * 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: Configuration file parser/reader. Place into the dynamic * data structure representation the conf file representing * the loadbalanced server pool. * * 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 <stdint.h> #include <stdbool.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <ctype.h> #ifdef _HAVE_SCHED_RT_ #include <sched.h> #endif #include <strings.h> #include <sys/types.h> #include <sys/stat.h> #ifdef _WITH_SNMP_ #include "snmp.h" #endif #include "global_parser.h" #include "global_data.h" #include "main.h" #include "parser.h" #include "smtp.h" #include "utils.h" #include "logger.h" #if HAVE_DECL_CLONE_NEWNET #include "namespaces.h" #endif #define LVS_MAX_TIMEOUT (86400*31) /* 31 days */ /* data handlers */ /* Global def handlers */ static void use_polling_handler(vector_t *strvec) { if (!strvec) return; global_data->linkbeat_use_polling = true; } static void routerid_handler(vector_t *strvec) { FREE_PTR(global_data->router_id); global_data->router_id = set_value(strvec); } static void emailfrom_handler(vector_t *strvec) { FREE_PTR(global_data->email_from); global_data->email_from = set_value(strvec); } static void smtpto_handler(vector_t *strvec) { unsigned timeout; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &timeout, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "smtp_connect_timeout '%s' must be in [0, %d] - ignoring", FMT_STR_VSLOT(strvec, 1), UINT_MAX / TIMER_HZ); return; } if (timeout == 0) { report_config_error(CONFIG_GENERAL_ERROR, "smtp_conect_timeout must be greater than 0, setting to 1"); timeout = 1; } global_data->smtp_connection_to = timeout * TIMER_HZ; } #ifdef _WITH_VRRP_ static void dynamic_interfaces_handler(vector_t *strvec) { char *str; global_data->dynamic_interfaces = true; if (vector_size(strvec) >= 2) { str = strvec_slot(strvec, 1); if (!strcmp(str, "allow_if_changes")) global_data->allow_if_changes = true; else report_config_error(CONFIG_GENERAL_ERROR, "Unknown dynamic_interfaces option '%s'",str); } } static void no_email_faults_handler(__attribute__((unused))vector_t *strvec) { global_data->no_email_faults = true; } #endif static void smtpserver_handler(vector_t *strvec) { int ret = -1; char *port_str = SMTP_PORT_STR; /* Has a port number been specified? */ if (vector_size(strvec) >= 3) port_str = strvec_slot(strvec,2); /* It can't be an IP address if it contains '-' or '/' */ if (!strpbrk(strvec_slot(strvec, 1), "-/")) ret = inet_stosockaddr(strvec_slot(strvec, 1), port_str, &global_data->smtp_server); if (ret < 0) domain_stosockaddr(strvec_slot(strvec, 1), port_str, &global_data->smtp_server); if (global_data->smtp_server.ss_family == AF_UNSPEC) report_config_error(CONFIG_GENERAL_ERROR, "Invalid smtp server %s %s", FMT_STR_VSLOT(strvec, 1), port_str); } static void smtphelo_handler(vector_t *strvec) { char *helo_name; if (vector_size(strvec) < 2) return; helo_name = MALLOC(strlen(strvec_slot(strvec, 1)) + 1); if (!helo_name) return; strcpy(helo_name, strvec_slot(strvec, 1)); global_data->smtp_helo_name = helo_name; } static void email_handler(vector_t *strvec) { vector_t *email_vec = read_value_block(strvec); unsigned int i; char *str; if (!email_vec) { report_config_error(CONFIG_GENERAL_ERROR, "Warning - empty notification_email block"); return; } for (i = 0; i < vector_size(email_vec); i++) { str = vector_slot(email_vec, i); alloc_email(str); } free_strvec(email_vec); } static void smtp_alert_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global smtp_alert specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->smtp_alert = res; } #ifdef _WITH_VRRP_ static void smtp_alert_vrrp_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global smtp_alert_vrrp specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->smtp_alert_vrrp = res; } #endif #ifdef _WITH_LVS_ static void smtp_alert_checker_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global smtp_alert_checker specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->smtp_alert_checker = res; } #endif #ifdef _WITH_VRRP_ static void default_interface_handler(vector_t *strvec) { if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "default_interface requires interface name"); return; } FREE_PTR(global_data->default_ifname); global_data->default_ifname = set_value(strvec); /* On a reload, the VRRP process needs the default_ifp */ #ifndef _DEBUG_ if (prog_type == PROG_TYPE_VRRP) #endif { global_data->default_ifp = if_get_by_ifname(global_data->default_ifname, IF_CREATE_IF_DYNAMIC); if (!global_data->default_ifp) report_config_error(CONFIG_GENERAL_ERROR, "WARNING - default interface %s doesn't exist", global_data->default_ifname); } } #endif #ifdef _WITH_LVS_ static void lvs_timeouts(vector_t *strvec) { unsigned val; size_t i; if (vector_size(strvec) < 3) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_timeouts requires at least one option"); return; } for (i = 1; i < vector_size(strvec); i++) { if (!strcmp(strvec_slot(strvec, i), "tcp")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout tcp - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout tcp (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_tcp_timeout = val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "tcpfin")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout tcpfin - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout tcpfin (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_tcpfin_timeout = val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "udp")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout udp - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout udp (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_udp_timeout = val; i++; /* skip over value */ continue; } report_config_error(CONFIG_GENERAL_ERROR, "Unknown option %s specified for lvs_timeouts", FMT_STR_VSLOT(strvec, i)); } } #if defined _WITH_LVS_ && defined _WITH_VRRP_ static void lvs_syncd_handler(vector_t *strvec) { unsigned val; size_t i; if (global_data->lvs_syncd.ifname) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon has already been specified as %s %s - ignoring", global_data->lvs_syncd.ifname, global_data->lvs_syncd.vrrp_name); return; } if (vector_size(strvec) < 3) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon requires interface, VRRP instance"); return; } if (strlen(strvec_slot(strvec, 1)) >= IP_VS_IFNAME_MAXLEN) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon interface name '%s' too long - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } if (strlen(strvec_slot(strvec, 2)) >= IP_VS_IFNAME_MAXLEN) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon vrrp interface name '%s' too long - ignoring", FMT_STR_VSLOT(strvec, 2)); return; } global_data->lvs_syncd.ifname = set_value(strvec); global_data->lvs_syncd.vrrp_name = MALLOC(strlen(strvec_slot(strvec, 2)) + 1); if (!global_data->lvs_syncd.vrrp_name) return; strcpy(global_data->lvs_syncd.vrrp_name, strvec_slot(strvec, 2)); /* This is maintained for backwards compatibility, prior to adding "id" option */ if (vector_size(strvec) >= 4 && isdigit(FMT_STR_VSLOT(strvec, 3)[0])) { report_config_error(CONFIG_GENERAL_ERROR, "Please use keyword \"id\" before lvs_sync_daemon syncid value"); if (!read_unsigned_strvec(strvec, 3, &val, 0, 255, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid syncid (%s) - defaulting to vrid", FMT_STR_VSLOT(strvec, 3)); else global_data->lvs_syncd.syncid = val; i = 4; } else i = 3; for ( ; i < vector_size(strvec); i++) { if (!strcmp(strvec_slot(strvec, i), "id")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon id, defaulting to vrid"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 255, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid syncid (%s) - defaulting to vrid", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.syncid = val; i++; /* skip over value */ continue; } #ifdef _HAVE_IPVS_SYNCD_ATTRIBUTES_ if (!strcmp(strvec_slot(strvec, i), "maxlen")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon maxlen - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 65535 - 20 - 8, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon maxlen (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.sync_maxlen = (uint16_t)val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "port")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon port - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 65535, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon port (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.mcast_port = (uint16_t)val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "ttl")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon ttl - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 255, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon ttl (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.mcast_ttl = (uint8_t)val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "group")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon group - ignoring"); continue; } if (inet_stosockaddr(strvec_slot(strvec, i+1), NULL, &global_data->lvs_syncd.mcast_group) < 0) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon group (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); if ((global_data->lvs_syncd.mcast_group.ss_family == AF_INET && !IN_MULTICAST(htonl(((struct sockaddr_in *)&global_data->lvs_syncd.mcast_group)->sin_addr.s_addr))) || (global_data->lvs_syncd.mcast_group.ss_family == AF_INET6 && !IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&global_data->lvs_syncd.mcast_group)->sin6_addr))) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon group address %s is not multicast - ignoring", FMT_STR_VSLOT(strvec, i+1)); global_data->lvs_syncd.mcast_group.ss_family = AF_UNSPEC; } i++; /* skip over value */ continue; } #endif report_config_error(CONFIG_GENERAL_ERROR, "Unknown option %s specified for lvs_sync_daemon", FMT_STR_VSLOT(strvec, i)); } } #endif static void lvs_flush_handler(__attribute__((unused)) vector_t *strvec) { global_data->lvs_flush = true; } #endif #ifdef _HAVE_SCHED_RT_ static int get_realtime_priority(vector_t *strvec, const char *process) { int min_priority; int max_priority; int priority; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %s process real-time priority specified", process); return -1; } min_priority = sched_get_priority_min(SCHED_RR); max_priority = sched_get_priority_max(SCHED_RR); if (!read_int_strvec(strvec, 1, &priority, INT_MIN, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "%s process real-time priority '%s' invalid", process, FMT_STR_VSLOT(strvec, 1)); return -1; } if (priority < min_priority) { report_config_error(CONFIG_GENERAL_ERROR, "%s process real-time priority %d less than minimum %d - setting to minimum", process, priority, min_priority); priority = min_priority; } else if (priority > max_priority) { report_config_error(CONFIG_GENERAL_ERROR, "%s process real-time priority %d greater than maximum %d - setting to maximum", process, priority, max_priority); priority = max_priority; } return priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static rlim_t get_rt_rlimit(vector_t *strvec, const char *process) { unsigned limit; rlim_t rlim; if (!read_unsigned_strvec(strvec, 1, &limit, 1, UINT32_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid %s real-time limit - %s", process, FMT_STR_VSLOT(strvec, 1)); return 0; } rlim = limit; return rlim; } #endif #endif static int8_t get_priority(vector_t *strvec, const char *process) { int priority; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %s process priority specified", process); return 0; } if (!read_int_strvec(strvec, 1, &priority, -20, 19, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid %s process priority specified", process); return 0; } return (int8_t)priority; } #ifdef _WITH_VRRP_ static void vrrp_mcast_group4_handler(vector_t *strvec) { struct sockaddr_in *mcast = &global_data->vrrp_mcast_group4; int ret; ret = inet_stosockaddr(strvec_slot(strvec, 1), 0, (struct sockaddr_storage *)mcast); if (ret < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: Cant parse vrrp_mcast_group4 [%s]. Skipping" , FMT_STR_VSLOT(strvec, 1)); } } static void vrrp_mcast_group6_handler(vector_t *strvec) { struct sockaddr_in6 *mcast = &global_data->vrrp_mcast_group6; int ret; ret = inet_stosockaddr(strvec_slot(strvec, 1), 0, (struct sockaddr_storage *)mcast); if (ret < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: Cant parse vrrp_mcast_group6 [%s]. Skipping" , FMT_STR_VSLOT(strvec, 1)); } } static void vrrp_garp_delay_handler(vector_t *strvec) { unsigned timeout; if (!read_unsigned_strvec(strvec, 1, &timeout, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_delay '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } global_data->vrrp_garp_delay = timeout * TIMER_HZ; } static void vrrp_garp_rep_handler(vector_t *strvec) { unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_repeat '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_repeat must be greater than 0, setting to 1"); repeats = 1; } global_data->vrrp_garp_rep = repeats; } static void vrrp_garp_refresh_handler(vector_t *strvec) { unsigned refresh; if (!read_unsigned_strvec(strvec, 1, &refresh, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_garp_master_refresh '%s' - ignoring", FMT_STR_VSLOT(strvec, 1)); global_data->vrrp_garp_refresh.tv_sec = 0; } else global_data->vrrp_garp_refresh.tv_sec = refresh; global_data->vrrp_garp_refresh.tv_usec = 0; } static void vrrp_garp_refresh_rep_handler(vector_t *strvec) { unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_refresh_repeat '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_refresh_repeat must be greater than 0, setting to 1"); repeats = 1; } global_data->vrrp_garp_refresh_rep = repeats; } static void vrrp_garp_lower_prio_delay_handler(vector_t *strvec) { unsigned delay; if (!read_unsigned_strvec(strvec, 1, &delay, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_lower_prio_delay '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } global_data->vrrp_garp_lower_prio_delay = delay * TIMER_HZ; } static void vrrp_garp_lower_prio_rep_handler(vector_t *strvec) { unsigned garp_lower_prio_rep; if (!read_unsigned_strvec(strvec, 1, &garp_lower_prio_rep, 0, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_garp_lower_prio_repeat '%s'", FMT_STR_VSLOT(strvec, 1)); return; } global_data->vrrp_garp_lower_prio_rep = garp_lower_prio_rep; } static void vrrp_garp_interval_handler(vector_t *strvec) { double interval; if (!read_double_strvec(strvec, 1, &interval, 1.0 / TIMER_HZ, UINT_MAX / TIMER_HZ, true)) report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_interval '%s' is invalid", FMT_STR_VSLOT(strvec, 1)); else global_data->vrrp_garp_interval = (unsigned)(interval * TIMER_HZ); if (global_data->vrrp_garp_interval >= 1 * TIMER_HZ) log_message(LOG_INFO, "The vrrp_garp_interval is very large - %s seconds", FMT_STR_VSLOT(strvec, 1)); } static void vrrp_gna_interval_handler(vector_t *strvec) { double interval; if (!read_double_strvec(strvec, 1, &interval, 1.0 / TIMER_HZ, UINT_MAX / TIMER_HZ, true)) report_config_error(CONFIG_GENERAL_ERROR, "vrrp_gna_interval '%s' is invalid", FMT_STR_VSLOT(strvec, 1)); else global_data->vrrp_gna_interval = (unsigned)(interval * TIMER_HZ); if (global_data->vrrp_gna_interval >= 1 * TIMER_HZ) log_message(LOG_INFO, "The vrrp_gna_interval is very large - %s seconds", FMT_STR_VSLOT(strvec, 1)); } static void vrrp_lower_prio_no_advert_handler(vector_t *strvec) { int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) report_config_error(CONFIG_GENERAL_ERROR, "Invalid value for vrrp_lower_prio_no_advert specified"); else global_data->vrrp_lower_prio_no_advert = res; } else global_data->vrrp_lower_prio_no_advert = true; } static void vrrp_higher_prio_send_advert_handler(vector_t *strvec) { int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) report_config_error(CONFIG_GENERAL_ERROR, "Invalid value for vrrp_higher_prio_send_advert specified"); else global_data->vrrp_higher_prio_send_advert = res; } else global_data->vrrp_higher_prio_send_advert = true; } static void vrrp_iptables_handler(vector_t *strvec) { global_data->vrrp_iptables_inchain[0] = '\0'; global_data->vrrp_iptables_outchain[0] = '\0'; if (vector_size(strvec) >= 2) { if (strlen(strvec_slot(strvec,1)) >= sizeof(global_data->vrrp_iptables_inchain)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : iptables in chain name too long - ignored"); return; } strcpy(global_data->vrrp_iptables_inchain, strvec_slot(strvec,1)); } if (vector_size(strvec) >= 3) { if (strlen(strvec_slot(strvec,2)) >= sizeof(global_data->vrrp_iptables_outchain)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : iptables out chain name too long - ignored"); return; } strcpy(global_data->vrrp_iptables_outchain, strvec_slot(strvec,2)); } } #ifdef _HAVE_LIBIPSET_ static void vrrp_ipsets_handler(vector_t *strvec) { size_t len; if (vector_size(strvec) >= 2) { if (strlen(strvec_slot(strvec,1)) >= sizeof(global_data->vrrp_ipset_address)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : ipset address name too long - ignored"); return; } strcpy(global_data->vrrp_ipset_address, strvec_slot(strvec,1)); } else { global_data->using_ipsets = false; return; } if (vector_size(strvec) >= 3) { if (strlen(strvec_slot(strvec,2)) >= sizeof(global_data->vrrp_ipset_address6)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : ipset IPv6 address name too long - ignored"); return; } strcpy(global_data->vrrp_ipset_address6, strvec_slot(strvec,2)); } else { /* No second set specified, copy first name and add "6" */ strcpy(global_data->vrrp_ipset_address6, global_data->vrrp_ipset_address); global_data->vrrp_ipset_address6[sizeof(global_data->vrrp_ipset_address6) - 2] = '\0'; strcat(global_data->vrrp_ipset_address6, "6"); } if (vector_size(strvec) >= 4) { if (strlen(strvec_slot(strvec,3)) >= sizeof(global_data->vrrp_ipset_address_iface6)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : ipset IPv6 address_iface name too long - ignored"); return; } strcpy(global_data->vrrp_ipset_address_iface6, strvec_slot(strvec,3)); } else { /* No third set specified, copy second name and add "_if6" */ strcpy(global_data->vrrp_ipset_address_iface6, global_data->vrrp_ipset_address6); len = strlen(global_data->vrrp_ipset_address_iface6); if (global_data->vrrp_ipset_address_iface6[len-1] == '6') global_data->vrrp_ipset_address_iface6[--len] = '\0'; global_data->vrrp_ipset_address_iface6[sizeof(global_data->vrrp_ipset_address_iface6) - 5] = '\0'; strcat(global_data->vrrp_ipset_address_iface6, "_if6"); } } #endif static void vrrp_version_handler(vector_t *strvec) { int version; if (!read_int_strvec(strvec, 1, &version, 2, 3, true)) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error: Version must be either 2 or 3"); return; } global_data->vrrp_version = version; } static void vrrp_check_unicast_src_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_check_unicast_src = 1; } static void vrrp_check_adv_addr_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_skip_check_adv_addr = 1; } static void vrrp_strict_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_strict = 1; } static void vrrp_prio_handler(vector_t *strvec) { global_data->vrrp_process_priority = get_priority(strvec, "vrrp"); } static void vrrp_no_swap_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_no_swap = true; } #ifdef _HAVE_SCHED_RT_ static void vrrp_rt_priority_handler(vector_t *strvec) { int priority = get_realtime_priority(strvec, "vrrp"); if (priority >= 0) global_data->vrrp_realtime_priority = priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static void vrrp_rt_rlimit_handler(vector_t *strvec) { global_data->vrrp_rlimit_rt = get_rt_rlimit(strvec, "vrrp"); } #endif #endif #endif static void notify_fifo(vector_t *strvec, const char *type, notify_fifo_t *fifo) { if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %snotify_fifo name specified", type); return; } if (fifo->name) { report_config_error(CONFIG_GENERAL_ERROR, "%snotify_fifo already specified - ignoring %s", type, FMT_STR_VSLOT(strvec,1)); return; } fifo->name = MALLOC(strlen(strvec_slot(strvec, 1)) + 1); strcpy(fifo->name, strvec_slot(strvec, 1)); } static void notify_fifo_script(vector_t *strvec, const char *type, notify_fifo_t *fifo) { char *id_str; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %snotify_fifo_script specified", type); return; } if (fifo->script) { report_config_error(CONFIG_GENERAL_ERROR, "%snotify_fifo_script already specified - ignoring %s", type, FMT_STR_VSLOT(strvec,1)); return; } id_str = MALLOC(strlen(type) + strlen("notify_fifo") + 1); strcpy(id_str, type); strcat(id_str, "notify_fifo"); fifo->script = notify_script_init(1, id_str); FREE(id_str); } static void global_notify_fifo(vector_t *strvec) { notify_fifo(strvec, "", &global_data->notify_fifo); } static void global_notify_fifo_script(vector_t *strvec) { notify_fifo_script(strvec, "", &global_data->notify_fifo); } #ifdef _WITH_VRRP_ static void vrrp_notify_fifo(vector_t *strvec) { notify_fifo(strvec, "vrrp_", &global_data->vrrp_notify_fifo); } static void vrrp_notify_fifo_script(vector_t *strvec) { notify_fifo_script(strvec, "vrrp_", &global_data->vrrp_notify_fifo); } #endif #ifdef _WITH_LVS_ static void lvs_notify_fifo(vector_t *strvec) { notify_fifo(strvec, "lvs_", &global_data->lvs_notify_fifo); } static void lvs_notify_fifo_script(vector_t *strvec) { notify_fifo_script(strvec, "lvs_", &global_data->lvs_notify_fifo); } #endif #ifdef _WITH_LVS_ static void checker_prio_handler(vector_t *strvec) { global_data->checker_process_priority = get_priority(strvec, "checker"); } static void checker_no_swap_handler(__attribute__((unused)) vector_t *strvec) { global_data->checker_no_swap = true; } #ifdef _HAVE_SCHED_RT_ static void checker_rt_priority_handler(vector_t *strvec) { int priority = get_realtime_priority(strvec, "checker"); if (priority >= 0) global_data->checker_realtime_priority = priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static void checker_rt_rlimit_handler(vector_t *strvec) { global_data->checker_rlimit_rt = get_rt_rlimit(strvec, "checker"); } #endif #endif #endif #ifdef _WITH_BFD_ static void bfd_prio_handler(vector_t *strvec) { global_data->bfd_process_priority = get_priority(strvec, "bfd"); } static void bfd_no_swap_handler(__attribute__((unused)) vector_t *strvec) { global_data->bfd_no_swap = true; } #ifdef _HAVE_SCHED_RT_ static void bfd_rt_priority_handler(vector_t *strvec) { int priority = get_realtime_priority(strvec, "BFD"); if (priority >= 0) global_data->bfd_realtime_priority = priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static void bfd_rt_rlimit_handler(vector_t *strvec) { global_data->bfd_rlimit_rt = get_rt_rlimit(strvec, "bfd"); } #endif #endif #endif #ifdef _WITH_SNMP_ static void snmp_socket_handler(vector_t *strvec) { if (vector_size(strvec) > 2) { report_config_error(CONFIG_GENERAL_ERROR, "Too many parameters specified for snmp_socket - ignoring"); return; } if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "SNMP error : snmp socket name missing"); return; } if (strlen(strvec_slot(strvec,1)) > PATH_MAX - 1) { report_config_error(CONFIG_GENERAL_ERROR, "SNMP error : snmp socket name too long - ignored"); return; } if (global_data->snmp_socket) { report_config_error(CONFIG_GENERAL_ERROR, "SNMP socket already set to %s - ignoring", global_data->snmp_socket); return; } global_data->snmp_socket = MALLOC(strlen(strvec_slot(strvec, 1) + 1)); strcpy(global_data->snmp_socket, strvec_slot(strvec,1)); } static void trap_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_traps = true; } #ifdef _WITH_SNMP_VRRP_ static void snmp_vrrp_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_vrrp = true; } #endif #ifdef _WITH_SNMP_RFC_ static void snmp_rfc_handler(__attribute__((unused)) vector_t *strvec) { #ifdef _WITH_SNMP_RFCV2_ global_data->enable_snmp_rfcv2 = true; #endif #ifdef _WITH_SNMP_RFCV3_ global_data->enable_snmp_rfcv3 = true; #endif } #endif #ifdef _WITH_SNMP_RFCV2_ static void snmp_rfcv2_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_rfcv2 = true; } #endif #ifdef _WITH_SNMP_RFCV3_ static void snmp_rfcv3_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_rfcv3 = true; } #endif #ifdef _WITH_SNMP_CHECKER_ static void snmp_checker_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_checker = true; } #endif #endif #if HAVE_DECL_CLONE_NEWNET static void net_namespace_handler(vector_t *strvec) { if (!strvec) return; /* If we are reloading, there has already been a check that the * namespace hasn't changed */ if (!reload) { if (!global_data->network_namespace) { global_data->network_namespace = set_value(strvec); use_pid_dir = true; } else report_config_error(CONFIG_GENERAL_ERROR, "Duplicate net_namespace definition %s - ignoring", FMT_STR_VSLOT(strvec, 1)); } } static void namespace_ipsets_handler(vector_t *strvec) { if (!strvec) return; global_data->namespace_with_ipsets = true; } #endif #ifdef _WITH_DBUS_ static void enable_dbus_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_dbus = true; } static void dbus_service_name_handler(vector_t *strvec) { FREE_PTR(global_data->dbus_service_name); global_data->dbus_service_name = set_value(strvec); } #endif static void instance_handler(vector_t *strvec) { if (!strvec) return; if (!reload) { if (!global_data->instance_name) { global_data->instance_name = set_value(strvec); use_pid_dir = true; } else report_config_error(CONFIG_GENERAL_ERROR, "Duplicate instance definition %s - ignoring", FMT_STR_VSLOT(strvec, 1)); } } static void use_pid_dir_handler(vector_t *strvec) { if (!strvec) return; use_pid_dir = true; } static void script_user_handler(vector_t *strvec) { if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No script username specified"); return; } if (set_default_script_user(strvec_slot(strvec, 1), vector_size(strvec) > 2 ? strvec_slot(strvec, 2) : NULL)) report_config_error(CONFIG_GENERAL_ERROR, "Error setting global script uid/gid"); } static void script_security_handler(__attribute__((unused)) vector_t *strvec) { script_security = true; } static void child_wait_handler(vector_t *strvec) { unsigned secs; if (!strvec) return; if (!read_unsigned_strvec(strvec, 1, &secs, 0, UINT_MAX, false)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid child_wait_time %s", FMT_STR_VSLOT(strvec, 1)); return; } child_wait_time = secs; } #ifdef _WITH_VRRP_ static void vrrp_rx_bufs_policy_handler(vector_t *strvec) { unsigned rx_buf_size; unsigned i; if (!strvec) return; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_rx_bufs_policy missing"); return; } for (i = 1; i < vector_size(strvec); i++) { if (!strcasecmp(strvec_slot(strvec, i), "MTU")) global_data->vrrp_rx_bufs_policy |= RX_BUFS_POLICY_MTU; else if (!strcasecmp(strvec_slot(strvec, i), "ADVERT")) global_data->vrrp_rx_bufs_policy |= RX_BUFS_POLICY_ADVERT; else { if (!read_unsigned_strvec(strvec, 1, &rx_buf_size, 0, UINT_MAX, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_rx_bufs_policy %s", FMT_STR_VSLOT(strvec, i)); else { global_data->vrrp_rx_bufs_size = rx_buf_size; global_data->vrrp_rx_bufs_policy |= RX_BUFS_SIZE; } } } if ((global_data->vrrp_rx_bufs_policy & RX_BUFS_SIZE) && (global_data->vrrp_rx_bufs_policy & (RX_BUFS_POLICY_MTU | RX_BUFS_POLICY_ADVERT))) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot set vrrp_rx_bufs_policy size and policy, ignoring policy"); global_data->vrrp_rx_bufs_policy &= ~(RX_BUFS_POLICY_MTU | RX_BUFS_POLICY_ADVERT); } else if ((global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_MTU) && (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_ADVERT)) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot set both vrrp_rx_bufs_policy MTU and ADVERT, ignoring ADVERT"); global_data->vrrp_rx_bufs_policy &= ~RX_BUFS_POLICY_ADVERT; } } static void vrrp_rx_bufs_multiplier_handler(vector_t *strvec) { unsigned rx_buf_mult; if (!strvec) return; if (vector_size(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_rx_bufs_multiplier"); return; } if (!read_unsigned_strvec(strvec, 1, &rx_buf_mult, 1, UINT_MAX, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_rx_bufs_multiplier %s", FMT_STR_VSLOT(strvec, 1)); else global_data->vrrp_rx_bufs_multiples = rx_buf_mult; } #endif #if defined _WITH_VRRP_ || defined _WITH_LVS_ static unsigned get_netlink_rcv_bufs_size(vector_t *strvec, const char *type) { unsigned val; if (!strvec) return 0; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "%s_rcv_bufs size missing", type); return 0; } if (!read_unsigned_strvec(strvec, 1, &val, 0, UINT_MAX, false)) { report_config_error(CONFIG_GENERAL_ERROR, "%s_rcv_bufs size (%s) invalid", type, FMT_STR_VSLOT(strvec, 1)); return 0; } return val; } #endif #ifdef _WITH_VRRP_ static void vrrp_netlink_monitor_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "vrrp_netlink_monitor"); if (val) global_data->vrrp_netlink_monitor_rcv_bufs = val; } static void vrrp_netlink_monitor_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global vrrp_netlink_monitor_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->vrrp_netlink_monitor_rcv_bufs_force = res; } static void vrrp_netlink_cmd_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "vrrp_netlink_cmd"); if (val) global_data->vrrp_netlink_cmd_rcv_bufs = val; } static void vrrp_netlink_cmd_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global vrrp_netlink_cmd_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->vrrp_netlink_cmd_rcv_bufs_force = res; } #endif #ifdef _WITH_LVS_ static void lvs_netlink_monitor_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "lvs_netlink_monitor"); if (val) global_data->lvs_netlink_monitor_rcv_bufs = val; } static void lvs_netlink_monitor_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global lvs_netlink_monitor_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->lvs_netlink_monitor_rcv_bufs_force = res; } static void lvs_netlink_cmd_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "lvs_netlink_cmd"); if (val) global_data->lvs_netlink_cmd_rcv_bufs = val; } static void lvs_netlink_cmd_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global lvs_netlink_cmd_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->lvs_netlink_cmd_rcv_bufs_force = res; } static void rs_init_notifies_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global rs_init_notifies specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->rs_init_notifies = res; } static void no_checker_emails_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global no_checker_emails specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->no_checker_emails = res; } #endif static void umask_handler(vector_t *strvec) { long umask_long; mode_t umask_val = 0; char *mask = strvec_slot(strvec, 1); char *endptr; unsigned i; char *p; if (umask_cmdline) { log_message(LOG_INFO, "umask command line option specified, ignoring config option"); return; } if (isdigit(mask[0])) { if (vector_size(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "%s parameter(s) to umask option", vector_size(strvec) == 1 ? "Missing" : "Extra"); return; } umask_long = strtol(mask, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { report_config_error(CONFIG_GENERAL_ERROR, "invalid umask value %s", mask); return; } umask_val = umask_long & 0777; } else { bool need_or = false; for (i = 1; i < vector_size(strvec); i++) { for (p = strvec_slot(strvec, i); *p; ) { if (need_or) { if (*p == '|') { need_or = false; p++; continue; } report_config_error(CONFIG_GENERAL_ERROR, "Invalid umask syntax %s", FMT_STR_VSLOT(strvec, i)); return; } if (!strncmp(p, "IRUSR", 5)) umask_val |= S_IRUSR; else if (!strncmp(p, "IWUSR", 5)) umask_val |= S_IWUSR; else if (!strncmp(p, "IXUSR", 5)) umask_val |= S_IXUSR; else if (!strncmp(p, "IRGRP", 5)) umask_val |= S_IRGRP; else if (!strncmp(p, "IWGRP", 5)) umask_val |= S_IWGRP; else if (!strncmp(p, "IXGRP", 5)) umask_val |= S_IXGRP; else if (!strncmp(p, "IROTH", 5)) umask_val |= S_IROTH; else if (!strncmp(p, "IWOTH", 5)) umask_val |= S_IWOTH; else if (!strncmp(p, "IXOTH", 5)) umask_val |= S_IXOTH; else { report_config_error(CONFIG_GENERAL_ERROR, "Unknown umask bit %s", p); return; } p += 5; need_or = true; } } if (!need_or) { report_config_error(CONFIG_GENERAL_ERROR, "umask missing bit value"); return; } } global_data->umask = umask_val; umask(umask_val); } void init_global_keywords(bool global_active) { /* global definitions mapping */ install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active); #if HAVE_DECL_CLONE_NEWNET install_keyword_root("net_namespace", &net_namespace_handler, global_active); install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active); #endif install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active); install_keyword_root("instance", &instance_handler, global_active); install_keyword_root("child_wait_time", &child_wait_handler, global_active); install_keyword_root("global_defs", NULL, global_active); install_keyword("router_id", &routerid_handler); install_keyword("notification_email_from", &emailfrom_handler); install_keyword("smtp_server", &smtpserver_handler); install_keyword("smtp_helo_name", &smtphelo_handler); install_keyword("smtp_connect_timeout", &smtpto_handler); install_keyword("notification_email", &email_handler); install_keyword("smtp_alert", &smtp_alert_handler); #ifdef _WITH_VRRP_ install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler); #endif #ifdef _WITH_LVS_ install_keyword("smtp_alert_checker", &smtp_alert_checker_handler); #endif #ifdef _WITH_VRRP_ install_keyword("dynamic_interfaces", &dynamic_interfaces_handler); install_keyword("no_email_faults", &no_email_faults_handler); install_keyword("default_interface", &default_interface_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_timeouts", &lvs_timeouts); install_keyword("lvs_flush", &lvs_flush_handler); #ifdef _WITH_VRRP_ install_keyword("lvs_sync_daemon", &lvs_syncd_handler); #endif #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler); install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler); install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler); install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler); install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler); install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("vrrp_version", &vrrp_version_handler); install_keyword("vrrp_iptables", &vrrp_iptables_handler); #ifdef _HAVE_LIBIPSET_ install_keyword("vrrp_ipsets", &vrrp_ipsets_handler); #endif install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler); install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler); install_keyword("vrrp_strict", &vrrp_strict_handler); install_keyword("vrrp_priority", &vrrp_prio_handler); install_keyword("vrrp_no_swap", &vrrp_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler); #endif #endif #endif install_keyword("notify_fifo", &global_notify_fifo); install_keyword("notify_fifo_script", &global_notify_fifo_script); #ifdef _WITH_VRRP_ install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo); install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script); #endif #ifdef _WITH_LVS_ install_keyword("lvs_notify_fifo", &lvs_notify_fifo); install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script); install_keyword("checker_priority", &checker_prio_handler); install_keyword("checker_no_swap", &checker_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("checker_rt_priority", &checker_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_BFD_ install_keyword("bfd_priority", &bfd_prio_handler); install_keyword("bfd_no_swap", &bfd_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("bfd_rt_priority", &bfd_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_SNMP_ install_keyword("snmp_socket", &snmp_socket_handler); install_keyword("enable_traps", &trap_handler); #ifdef _WITH_SNMP_VRRP_ install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler); install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */ #endif #ifdef _WITH_SNMP_RFC_ install_keyword("enable_snmp_rfc", &snmp_rfc_handler); #endif #ifdef _WITH_SNMP_RFCV2_ install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler); #endif #ifdef _WITH_SNMP_RFCV3_ install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler); #endif #ifdef _WITH_SNMP_CHECKER_ install_keyword("enable_snmp_checker", &snmp_checker_handler); #endif #endif #ifdef _WITH_DBUS_ install_keyword("enable_dbus", &enable_dbus_handler); install_keyword("dbus_service_name", &dbus_service_name_handler); #endif install_keyword("script_user", &script_user_handler); install_keyword("enable_script_security", &script_security_handler); #ifdef _WITH_VRRP_ install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler); install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler); install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler); install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler); install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("rs_init_notifies", &rs_init_notifies_handler); install_keyword("no_checker_emails", &no_checker_emails_handler); #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler); install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler); #endif install_keyword("umask", &umask_handler); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_438_4
crossvul-cpp_data_bad_5684_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; sk_for_each(sk, &rfcomm_sk_list.head) { if (rfcomm_pi(sk)->channel == channel && !bacmp(&bt_sk(sk)->src, src)) break; } return sk ? 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; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, &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 sk ? 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 %pMR", sk, &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_nested(sk, SINGLE_DEPTH_NESTING); 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_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 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); memset(sa, 0, sizeof(*sa)); 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; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, &rfcomm_sk_list.head) { seq_printf(f, "%pMR %pMR %d %d\n", &bt_sk(sk)->src, &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) { BT_ERR("RFCOMM socket layer registration failed"); goto error; } err = bt_procfs_init(THIS_MODULE, &init_net, "rfcomm", &rfcomm_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create RFCOMM proc file"); bt_sock_unregister(BTPROTO_RFCOMM); 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: proto_unregister(&rfcomm_proto); return err; } void __exit rfcomm_cleanup_sockets(void) { bt_procfs_cleanup(&init_net, "rfcomm"); 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_5684_0
crossvul-cpp_data_bad_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 ++; bprm->interp = iname; /* for binfmt_script */ 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/bad_3769_0
crossvul-cpp_data_bad_2752_0
/******************************************************************************* * * Module Name: nseval - Object evaluation, includes control method execution * ******************************************************************************/ /****************************************************************************** * * 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 "acinterp.h" #include "acnamesp.h" #define _COMPONENT ACPI_NAMESPACE ACPI_MODULE_NAME ("nseval") /* Local prototypes */ static void AcpiNsExecModuleCode ( ACPI_OPERAND_OBJECT *MethodObj, ACPI_EVALUATE_INFO *Info); /******************************************************************************* * * FUNCTION: AcpiNsEvaluate * * PARAMETERS: Info - Evaluation info block, contains these fields * and more: * PrefixNode - Prefix or Method/Object Node to execute * RelativePath - Name of method to execute, If NULL, the * Node is the object to execute * Parameters - List of parameters to pass to the method, * terminated by NULL. Params itself may be * NULL if no parameters are being passed. * ParameterType - Type of Parameter list * ReturnObject - Where to put method's return value (if * any). If NULL, no value is returned. * Flags - ACPI_IGNORE_RETURN_VALUE to delete return * * RETURN: Status * * DESCRIPTION: Execute a control method or return the current value of an * ACPI namespace object. * * MUTEX: Locks interpreter * ******************************************************************************/ ACPI_STATUS AcpiNsEvaluate ( ACPI_EVALUATE_INFO *Info) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsEvaluate); if (!Info) { return_ACPI_STATUS (AE_BAD_PARAMETER); } if (!Info->Node) { /* * Get the actual namespace node for the target object if we * need to. Handles these cases: * * 1) Null node, valid pathname from root (absolute path) * 2) Node and valid pathname (path relative to Node) * 3) Node, Null pathname */ Status = AcpiNsGetNode (Info->PrefixNode, Info->RelativePathname, ACPI_NS_NO_UPSEARCH, &Info->Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } /* * For a method alias, we must grab the actual method node so that * proper scoping context will be established before execution. */ if (AcpiNsGetType (Info->Node) == ACPI_TYPE_LOCAL_METHOD_ALIAS) { Info->Node = ACPI_CAST_PTR ( ACPI_NAMESPACE_NODE, Info->Node->Object); } /* Complete the info block initialization */ Info->ReturnObject = NULL; Info->NodeFlags = Info->Node->Flags; Info->ObjDesc = AcpiNsGetAttachedObject (Info->Node); ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%s [%p] Value %p\n", Info->RelativePathname, Info->Node, AcpiNsGetAttachedObject (Info->Node))); /* Get info if we have a predefined name (_HID, etc.) */ Info->Predefined = AcpiUtMatchPredefinedMethod (Info->Node->Name.Ascii); /* Get the full pathname to the object, for use in warning messages */ Info->FullPathname = AcpiNsGetNormalizedPathname (Info->Node, TRUE); if (!Info->FullPathname) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Count the number of arguments being passed in */ Info->ParamCount = 0; if (Info->Parameters) { while (Info->Parameters[Info->ParamCount]) { Info->ParamCount++; } /* Warn on impossible argument count */ if (Info->ParamCount > ACPI_METHOD_NUM_ARGS) { ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS, "Excess arguments (%u) - using only %u", Info->ParamCount, ACPI_METHOD_NUM_ARGS)); Info->ParamCount = ACPI_METHOD_NUM_ARGS; } } /* * For predefined names: Check that the declared argument count * matches the ACPI spec -- otherwise this is a BIOS error. */ AcpiNsCheckAcpiCompliance (Info->FullPathname, Info->Node, Info->Predefined); /* * For all names: Check that the incoming argument count for * this method/object matches the actual ASL/AML definition. */ AcpiNsCheckArgumentCount (Info->FullPathname, Info->Node, Info->ParamCount, Info->Predefined); /* For predefined names: Typecheck all incoming arguments */ AcpiNsCheckArgumentTypes (Info); /* * Three major evaluation cases: * * 1) Object types that cannot be evaluated by definition * 2) The object is a control method -- execute it * 3) The object is not a method -- just return it's current value */ switch (AcpiNsGetType (Info->Node)) { case ACPI_TYPE_DEVICE: case ACPI_TYPE_EVENT: case ACPI_TYPE_MUTEX: case ACPI_TYPE_REGION: case ACPI_TYPE_THERMAL: case ACPI_TYPE_LOCAL_SCOPE: /* * 1) Disallow evaluation of certain object types. For these, * object evaluation is undefined and not supported. */ ACPI_ERROR ((AE_INFO, "%s: Evaluation of object type [%s] is not supported", Info->FullPathname, AcpiUtGetTypeName (Info->Node->Type))); Status = AE_TYPE; goto Cleanup; case ACPI_TYPE_METHOD: /* * 2) Object is a control method - execute it */ /* Verify that there is a method object associated with this node */ if (!Info->ObjDesc) { ACPI_ERROR ((AE_INFO, "%s: Method has no attached sub-object", Info->FullPathname)); Status = AE_NULL_OBJECT; goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "**** Execute method [%s] at AML address %p length %X\n", Info->FullPathname, Info->ObjDesc->Method.AmlStart + 1, Info->ObjDesc->Method.AmlLength - 1)); /* * Any namespace deletion must acquire both the namespace and * interpreter locks to ensure that no thread is using the portion of * the namespace that is being deleted. * * Execute the method via the interpreter. The interpreter is locked * here before calling into the AML parser */ AcpiExEnterInterpreter (); Status = AcpiPsExecuteMethod (Info); AcpiExExitInterpreter (); break; default: /* * 3) All other non-method objects -- get the current object value */ /* * Some objects require additional resolution steps (e.g., the Node * may be a field that must be read, etc.) -- we can't just grab * the object out of the node. * * Use ResolveNodeToValue() to get the associated value. * * NOTE: we can get away with passing in NULL for a walk state because * the Node is guaranteed to not be a reference to either a method * local or a method argument (because this interface is never called * from a running method.) * * Even though we do not directly invoke the interpreter for object * resolution, we must lock it because we could access an OpRegion. * The OpRegion access code assumes that the interpreter is locked. */ AcpiExEnterInterpreter (); /* TBD: ResolveNodeToValue has a strange interface, fix */ Info->ReturnObject = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Info->Node); Status = AcpiExResolveNodeToValue (ACPI_CAST_INDIRECT_PTR ( ACPI_NAMESPACE_NODE, &Info->ReturnObject), NULL); AcpiExExitInterpreter (); if (ACPI_FAILURE (Status)) { Info->ReturnObject = NULL; goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Returned object %p [%s]\n", Info->ReturnObject, AcpiUtGetObjectTypeName (Info->ReturnObject))); Status = AE_CTRL_RETURN_VALUE; /* Always has a "return value" */ break; } /* * For predefined names, check the return value against the ACPI * specification. Some incorrect return value types are repaired. */ (void) AcpiNsCheckReturnValue (Info->Node, Info, Info->ParamCount, Status, &Info->ReturnObject); /* Check if there is a return value that must be dealt with */ if (Status == AE_CTRL_RETURN_VALUE) { /* If caller does not want the return value, delete it */ if (Info->Flags & ACPI_IGNORE_RETURN_VALUE) { AcpiUtRemoveReference (Info->ReturnObject); Info->ReturnObject = NULL; } /* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */ Status = AE_OK; } ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "*** Completed evaluation of object %s ***\n", Info->RelativePathname)); Cleanup: /* * Namespace was unlocked by the handling AcpiNs* function, so we * just free the pathname and return */ ACPI_FREE (Info->FullPathname); Info->FullPathname = NULL; return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiNsExecModuleCodeList * * PARAMETERS: None * * RETURN: None. Exceptions during method execution are ignored, since * we cannot abort a table load. * * DESCRIPTION: Execute all elements of the global module-level code list. * Each element is executed as a single control method. * ******************************************************************************/ void AcpiNsExecModuleCodeList ( void) { ACPI_OPERAND_OBJECT *Prev; ACPI_OPERAND_OBJECT *Next; ACPI_EVALUATE_INFO *Info; UINT32 MethodCount = 0; ACPI_FUNCTION_TRACE (NsExecModuleCodeList); /* Exit now if the list is empty */ Next = AcpiGbl_ModuleCodeList; if (!Next) { return_VOID; } /* Allocate the evaluation information block */ Info = ACPI_ALLOCATE (sizeof (ACPI_EVALUATE_INFO)); if (!Info) { return_VOID; } /* Walk the list, executing each "method" */ while (Next) { Prev = Next; Next = Next->Method.Mutex; /* Clear the link field and execute the method */ Prev->Method.Mutex = NULL; AcpiNsExecModuleCode (Prev, Info); MethodCount++; /* Delete the (temporary) method object */ AcpiUtRemoveReference (Prev); } ACPI_INFO (( "Executed %u blocks of module-level executable AML code", MethodCount)); ACPI_FREE (Info); AcpiGbl_ModuleCodeList = NULL; return_VOID; } /******************************************************************************* * * FUNCTION: AcpiNsExecModuleCode * * PARAMETERS: MethodObj - Object container for the module-level code * Info - Info block for method evaluation * * RETURN: None. Exceptions during method execution are ignored, since * we cannot abort a table load. * * DESCRIPTION: Execute a control method containing a block of module-level * executable AML code. The control method is temporarily * installed to the root node, then evaluated. * ******************************************************************************/ static void AcpiNsExecModuleCode ( ACPI_OPERAND_OBJECT *MethodObj, ACPI_EVALUATE_INFO *Info) { ACPI_OPERAND_OBJECT *ParentObj; ACPI_NAMESPACE_NODE *ParentNode; ACPI_OBJECT_TYPE Type; ACPI_STATUS Status; ACPI_FUNCTION_TRACE (NsExecModuleCode); /* * Get the parent node. We cheat by using the NextObject field * of the method object descriptor. */ ParentNode = ACPI_CAST_PTR ( ACPI_NAMESPACE_NODE, MethodObj->Method.NextObject); Type = AcpiNsGetType (ParentNode); /* * Get the region handler and save it in the method object. We may need * this if an operation region declaration causes a _REG method to be run. * * We can't do this in AcpiPsLinkModuleCode because * AcpiGbl_RootNode->Object is NULL at PASS1. */ if ((Type == ACPI_TYPE_DEVICE) && ParentNode->Object) { MethodObj->Method.Dispatch.Handler = ParentNode->Object->Device.Handler; } /* Must clear NextObject (AcpiNsAttachObject needs the field) */ MethodObj->Method.NextObject = NULL; /* Initialize the evaluation information block */ memset (Info, 0, sizeof (ACPI_EVALUATE_INFO)); Info->PrefixNode = ParentNode; /* * Get the currently attached parent object. Add a reference, * because the ref count will be decreased when the method object * is installed to the parent node. */ ParentObj = AcpiNsGetAttachedObject (ParentNode); if (ParentObj) { AcpiUtAddReference (ParentObj); } /* Install the method (module-level code) in the parent node */ Status = AcpiNsAttachObject (ParentNode, MethodObj, ACPI_TYPE_METHOD); if (ACPI_FAILURE (Status)) { goto Exit; } /* Execute the parent node as a control method */ Status = AcpiNsEvaluate (Info); ACPI_DEBUG_PRINT ((ACPI_DB_INIT_NAMES, "Executed module-level code at %p\n", MethodObj->Method.AmlStart)); /* Delete a possible implicit return value (in slack mode) */ if (Info->ReturnObject) { AcpiUtRemoveReference (Info->ReturnObject); } /* Detach the temporary method object */ AcpiNsDetachObject (ParentNode); /* Restore the original parent object */ if (ParentObj) { Status = AcpiNsAttachObject (ParentNode, ParentObj, Type); } else { ParentNode->Type = (UINT8) Type; } Exit: if (ParentObj) { AcpiUtRemoveReference (ParentObj); } return_VOID; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2752_0
crossvul-cpp_data_good_1508_7
/* Copyright (C) 2012 ABRT Team Copyright (C) 2012 Red Hat, 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" /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) enum { OPT_v = 1 << 0, OPT_s = 1 << 1, OPT_o = 1 << 2, OPT_d = 1 << 3, OPT_D = 1 << 4, OPT_x = 1 << 5, OPT_m = 1 << 6, }; /* How many problem dirs to create at most? * Also causes cooldown sleep if exceeded - * useful when called from a log watcher. */ #define MAX_DUMPED_DD_COUNT 5 static unsigned g_bt_count = 0; static unsigned g_opts; static const char *debug_dumps_dir = "."; static char *skip_pfx(char *p) { if (p[0] != '[') return p; char *q = strchr(p, ']'); if (!q) return p; if (q[1] == ' ') return q + 2; return p; } static char *list2lines(GList *list) { struct strbuf *s = strbuf_new(); while (list) { strbuf_append_str(s, (char*)list->data); strbuf_append_char(s, '\n'); free(list->data); list = g_list_delete_link(list, list); } return strbuf_free_nobuf(s); } static void save_bt_to_dump_dir(const char *bt, const char *exe, const char *reason) { time_t t = time(NULL); const char *iso_date = iso_date_string(&t); /* dump should be readable by all if we're run with -x */ uid_t my_euid = (uid_t)-1L; mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH; /* and readable only for the owner otherwise */ if (!(g_opts & OPT_x)) { mode = DEFAULT_DUMP_DIR_MODE; my_euid = geteuid(); } if (g_settings_privatereports) { if ((g_opts & OPT_x)) log("Not going to make dump directories world readable because PrivateReports is on"); mode = DEFAULT_DUMP_DIR_MODE; my_euid = 0; } pid_t my_pid = getpid(); char base[sizeof("xorg-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3]; sprintf(base, "xorg-%s-%lu-%u", iso_date, (long)my_pid, g_bt_count); char *path = concat_path_file(debug_dumps_dir, base); struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode); if (dd) { dd_create_basic_files(dd, /*uid:*/ my_euid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); dd_save_text(dd, FILENAME_ANALYZER, "xorg"); dd_save_text(dd, FILENAME_TYPE, "xorg"); dd_save_text(dd, FILENAME_REASON, reason); dd_save_text(dd, FILENAME_BACKTRACE, bt); /* * Reporters usually need component name to file a bug. * It is usually derived from executable. * We _guess_ X server's executable name as a last resort. * Better ideas? */ if (!exe) { exe = "/usr/bin/X"; if (access("/usr/bin/Xorg", X_OK) == 0) exe = "/usr/bin/Xorg"; } dd_save_text(dd, FILENAME_EXECUTABLE, exe); dd_close(dd); notify_new_path(path); } free(path); } /* Called after "Backtrace:" line was read. * Example (yes, stray newline before 'B' is real): [ 86985.879]<space> Backtrace: [ 86985.880] 0: /usr/bin/Xorg (xorg_backtrace+0x2f) [0x462d8f] [ 86985.880] 1: /usr/bin/Xorg (0x400000+0x67b56) [0x467b56] [ 86985.880] 2: /lib64/libpthread.so.0 (0x30a5800000+0xf4f0) [0x30a580f4f0] [ 86985.880] 3: /usr/lib64/xorg/modules/extensions/librecord.so (0x7ff6c225e000+0x26c3) [0x7ff6c22606c3] [ 86985.880] 4: /usr/bin/Xorg (_CallCallbacks+0x3c) [0x43820c] [ 86985.880] 5: /usr/bin/Xorg (WriteToClient+0x1f5) [0x466315] [ 86985.880] 6: /usr/lib64/xorg/modules/extensions/libdri2.so (ProcDRI2WaitMSCReply+0x4f) [0x7ff6c1e4feef] [ 86985.880] 7: /usr/lib64/xorg/modules/extensions/libdri2.so (DRI2WaitMSCComplete+0x52) [0x7ff6c1e4e6d2] [ 86985.880] 8: /usr/lib64/xorg/modules/drivers/intel_drv.so (0x7ff6c1bfb000+0x25ae4) [0x7ff6c1c20ae4] [ 86985.880] 9: /usr/lib64/libdrm.so.2 (drmHandleEvent+0xa3) [0x376b407513] [ 86985.880] 10: /usr/bin/Xorg (WakeupHandler+0x6b) [0x4379db] [ 86985.880] 11: /usr/bin/Xorg (WaitForSomething+0x1a9) [0x460289] [ 86985.880] 12: /usr/bin/Xorg (0x400000+0x3379a) [0x43379a] [ 86985.880] 13: /usr/bin/Xorg (0x400000+0x22dc5) [0x422dc5] [ 86985.880] 14: /lib64/libc.so.6 (__libc_start_main+0xed) [0x30a542169d] [ 86985.880] 15: /usr/bin/Xorg (0x400000+0x230b1) [0x4230b1] [ 86985.880] Segmentation fault at address 0x7ff6bf09e010 */ static void process_xorg_bt(void) { char *reason = NULL; char *exe = NULL; GList *list = NULL; unsigned cnt = 0; char *line; while ((line = xmalloc_fgetline(stdin)) != NULL) { char *p = skip_pfx(line); /* xorg-server-1.12.0/os/osinit.c: * if (sip->si_code == SI_USER) { * ErrorF("Recieved signal %d sent by process %ld, uid %ld\n", * ^^^^^^^^ yes, typo here! Can't grep for this word! :( * signo, (long) sip->si_pid, (long) sip->si_uid); * } else { * switch (signo) { * case SIGSEGV: * case SIGBUS: * case SIGILL: * case SIGFPE: * ErrorF("%s at address %p\n", strsignal(signo), sip->si_addr); */ if (*p < '0' || *p > '9') { if (strstr(p, " at address ") || strstr(p, " sent by process ")) { overlapping_strcpy(line, p); reason = line; line = NULL; } /* TODO: Other cases when we have useful reason string? */ break; } errno = 0; char *end; IGNORE_RESULT(strtoul(p, &end, 10)); if (errno || end == p || *end != ':') break; /* This looks like bt line */ /* Guess Xorg server's executable name from it */ if (!exe) { char *filename = skip_whitespace(end + 1); char *filename_end = skip_non_whitespace(filename); char sv = *filename_end; *filename_end = '\0'; /* Does it look like "[/usr]/[s]bin/Xfoo"? */ if (strstr(filename, "bin/X")) exe = xstrdup(filename); *filename_end = sv; } /* Save it to list */ overlapping_strcpy(line, p); list = g_list_prepend(list, line); line = NULL; if (++cnt > 255) /* prevent ridiculously large bts */ break; } free(line); if (list) { list = g_list_reverse(list); char *bt = list2lines(list); /* frees list */ if (g_opts & OPT_o) printf("%s%s%s\n", bt, reason ? reason : "", reason ? "\n" : ""); if (g_opts & (OPT_d|OPT_D)) if (g_bt_count <= MAX_DUMPED_DD_COUNT) save_bt_to_dump_dir(bt, exe, reason ? reason : "Xorg server crashed"); free(bt); } free(reason); free(exe); } 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 = _( "& [-vsoxm] [-d DIR]/[-D] [FILE]\n" "\n" "Extract Xorg crash from FILE (or standard input)" ); /* Keep OPT_z enums and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL( 's', NULL, NULL, _("Log to syslog")), OPT_BOOL( 'o', NULL, NULL, _("Print found crash data on standard output")), OPT_STRING('d', NULL, &debug_dumps_dir, "DIR", _("Create problem directory in DIR for every crash found")), OPT_BOOL( 'D', NULL, NULL, _("Same as -d DumpLocation, DumpLocation is specified in abrt.conf")), OPT_BOOL( 'x', NULL, NULL, _("Make the problem directory world readable")), OPT_BOOL( 'm', NULL, NULL, _("Print search string(s) to stdout and exit")), OPT_END() }; unsigned opts = g_opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(0); msg_prefix = g_progname; if ((opts & OPT_s) || getenv("ABRT_SYSLOG")) { logmode = LOGMODE_JOURNAL; } if (opts & OPT_m) { puts("Backtrace"); return 0; } if (opts & OPT_D) { if (opts & OPT_d) show_usage_and_die(program_usage_string, program_options); load_abrt_conf(); debug_dumps_dir = g_settings_dump_location; g_settings_dump_location = NULL; free_abrt_conf_data(); } argv += optind; if (argv[0]) xmove_fd(xopen(argv[0], O_RDONLY), STDIN_FILENO); char *line; while ((line = xmalloc_fgetline(stdin)) != NULL) { char *p = skip_pfx(line); if (strcmp(p, "Backtrace:") == 0) { free(line); g_bt_count++; process_xorg_bt(); continue; } free(line); } /* If we are run by a log watcher, this delays log rescan * (because log watcher waits to us to terminate) * and possibly prevents dreaded "abrt storm". */ if (opts & (OPT_d|OPT_D)) { if (g_bt_count > MAX_DUMPED_DD_COUNT) sleep(g_bt_count - MAX_DUMPED_DD_COUNT); } return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_1508_7
crossvul-cpp_data_bad_295_2
/* $OpenBSD: auth2-pubkey.c,v 1.82 2018/07/11 18:55:11 markus 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 <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <paths.h> #include <pwd.h> #include <signal.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <time.h> #include <unistd.h> #include <limits.h> #include "xmalloc.h" #include "ssh.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 "pathnames.h" #include "uidswap.h" #include "auth-options.h" #include "canohost.h" #ifdef GSSAPI #include "ssh-gss.h" #endif #include "monitor_wrap.h" #include "authfile.h" #include "match.h" #include "ssherr.h" #include "channels.h" /* XXX for session.h */ #include "session.h" /* XXX for child_set_env(); refactor? */ /* import */ extern ServerOptions options; extern u_char *session_id2; extern u_int session_id2_len; static char * format_key(const struct sshkey *key) { char *ret, *fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT); xasprintf(&ret, "%s %s", sshkey_type(key), fp); free(fp); return ret; } static int userauth_pubkey(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; struct passwd *pw = authctxt->pw; struct sshbuf *b; struct sshkey *key = NULL; char *pkalg, *userstyle = NULL, *key_s = NULL, *ca_s = NULL; u_char *pkblob, *sig, have_sig; size_t blen, slen; int r, pktype; int authenticated = 0; struct sshauthopt *authopts = NULL; if (!authctxt->valid) { debug2("%s: disabled because of invalid user", __func__); return 0; } if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 || (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 || (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0) fatal("%s: parse request failed: %s", __func__, ssh_err(r)); pktype = sshkey_type_from_name(pkalg); if (pktype == KEY_UNSPEC) { /* this is perfectly legal */ verbose("%s: unsupported public key algorithm: %s", __func__, pkalg); goto done; } if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) { error("%s: could not parse key: %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) { logit("Refusing RSA key because client uses unsafe " "signature scheme"); goto done; } if (auth2_key_already_used(authctxt, key)) { logit("refusing previously-used %s key", sshkey_type(key)); goto done; } if (match_pattern_list(pkalg, options.pubkey_key_types, 0) != 1) { logit("%s: key type %s not in PubkeyAcceptedKeyTypes", __func__, sshkey_ssh_name(key)); goto done; } key_s = format_key(key); if (sshkey_is_cert(key)) ca_s = format_key(key->cert->signature_key); if (have_sig) { debug3("%s: have %s signature for %s%s%s", __func__, pkalg, key_s, ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s); if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 || (r = sshpkt_get_end(ssh)) != 0) fatal("%s: %s", __func__, ssh_err(r)); if ((b = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); if (ssh->compat & SSH_OLD_SESSIONID) { if ((r = sshbuf_put(b, session_id2, session_id2_len)) != 0) fatal("%s: sshbuf_put session id: %s", __func__, ssh_err(r)); } else { if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0) fatal("%s: sshbuf_put_string session id: %s", __func__, ssh_err(r)); } /* reconstruct packet */ xasprintf(&userstyle, "%s%s%s", authctxt->user, authctxt->style ? ":" : "", authctxt->style ? authctxt->style : ""); if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || (r = sshbuf_put_cstring(b, userstyle)) != 0 || (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || (r = sshbuf_put_cstring(b, "publickey")) != 0 || (r = sshbuf_put_u8(b, have_sig)) != 0 || (r = sshbuf_put_cstring(b, pkalg) != 0) || (r = sshbuf_put_string(b, pkblob, blen)) != 0) fatal("%s: build packet failed: %s", __func__, ssh_err(r)); #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif /* test for correct signature */ authenticated = 0; if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) && PRIVSEP(sshkey_verify(key, sig, slen, sshbuf_ptr(b), sshbuf_len(b), (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL, ssh->compat)) == 0) { authenticated = 1; } sshbuf_free(b); free(sig); auth2_record_key(authctxt, authenticated, key); } else { debug("%s: test pkalg %s pkblob %s%s%s", __func__, pkalg, key_s, ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s); if ((r = sshpkt_get_end(ssh)) != 0) fatal("%s: %s", __func__, ssh_err(r)); /* XXX fake reply and always send PK_OK ? */ /* * XXX this allows testing whether a user is allowed * to login: if you happen to have a valid pubkey this * message is sent. the message is NEVER sent at all * if a user is not allowed to login. is this an * issue? -markus */ if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) { if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK)) != 0 || (r = sshpkt_put_cstring(ssh, pkalg)) != 0 || (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 || (r = sshpkt_send(ssh)) != 0 || (r = ssh_packet_write_wait(ssh)) != 0) fatal("%s: %s", __func__, ssh_err(r)); authctxt->postponed = 1; } } done: if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) { debug("%s: key options inconsistent with existing", __func__); authenticated = 0; } debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg); sshauthopt_free(authopts); sshkey_free(key); free(userstyle); free(pkalg); free(pkblob); free(key_s); free(ca_s); return authenticated; } static int match_principals_option(const char *principal_list, struct sshkey_cert *cert) { char *result; u_int i; /* XXX percent_expand() sequences for authorized_principals? */ for (i = 0; i < cert->nprincipals; i++) { if ((result = match_list(cert->principals[i], principal_list, NULL)) != NULL) { debug3("matched principal from key options \"%.100s\"", result); free(result); return 1; } } return 0; } /* * Process a single authorized_principals format line. Returns 0 and sets * authoptsp is principal is authorised, -1 otherwise. "loc" is used as a * log preamble for file/line information. */ static int check_principals_line(struct ssh *ssh, char *cp, const struct sshkey_cert *cert, const char *loc, struct sshauthopt **authoptsp) { u_int i, found = 0; char *ep, *line_opts; const char *reason = NULL; struct sshauthopt *opts = NULL; if (authoptsp != NULL) *authoptsp = NULL; /* Trim trailing whitespace. */ ep = cp + strlen(cp) - 1; while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t')) *ep-- = '\0'; /* * If the line has internal whitespace then assume it has * key options. */ line_opts = NULL; if ((ep = strrchr(cp, ' ')) != NULL || (ep = strrchr(cp, '\t')) != NULL) { for (; *ep == ' ' || *ep == '\t'; ep++) ; line_opts = cp; cp = ep; } if ((opts = sshauthopt_parse(line_opts, &reason)) == NULL) { debug("%s: bad principals options: %s", loc, reason); auth_debug_add("%s: bad principals options: %s", loc, reason); return -1; } /* Check principals in cert against those on line */ for (i = 0; i < cert->nprincipals; i++) { if (strcmp(cp, cert->principals[i]) != 0) continue; debug3("%s: matched principal \"%.100s\"", loc, cert->principals[i]); found = 1; } if (found && authoptsp != NULL) { *authoptsp = opts; opts = NULL; } sshauthopt_free(opts); return found ? 0 : -1; } static int process_principals(struct ssh *ssh, FILE *f, const char *file, const struct sshkey_cert *cert, struct sshauthopt **authoptsp) { char loc[256], *line = NULL, *cp, *ep; size_t linesize = 0; u_long linenum = 0; u_int found_principal = 0; if (authoptsp != NULL) *authoptsp = NULL; while (getline(&line, &linesize, f) != -1) { linenum++; /* Always consume entire input */ if (found_principal) continue; /* Skip leading whitespace. */ for (cp = line; *cp == ' ' || *cp == '\t'; cp++) ; /* Skip blank and comment lines. */ if ((ep = strchr(cp, '#')) != NULL) *ep = '\0'; if (!*cp || *cp == '\n') continue; snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum); if (check_principals_line(ssh, cp, cert, loc, authoptsp) == 0) found_principal = 1; } free(line); return found_principal; } /* XXX remove pw args here and elsewhere once ssh->authctxt is guaranteed */ static int match_principals_file(struct ssh *ssh, struct passwd *pw, char *file, struct sshkey_cert *cert, struct sshauthopt **authoptsp) { FILE *f; int success; if (authoptsp != NULL) *authoptsp = NULL; temporarily_use_uid(pw); debug("trying authorized principals file %s", file); if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) { restore_uid(); return 0; } success = process_principals(ssh, f, file, cert, authoptsp); fclose(f); restore_uid(); return success; } /* * Checks whether principal is allowed in output of command. * returns 1 if the principal is allowed or 0 otherwise. */ static int match_principals_command(struct ssh *ssh, struct passwd *user_pw, const struct sshkey *key, struct sshauthopt **authoptsp) { struct passwd *runas_pw = NULL; const struct sshkey_cert *cert = key->cert; FILE *f = NULL; int r, ok, found_principal = 0; int i, ac = 0, uid_swapped = 0; pid_t pid; char *tmp, *username = NULL, *command = NULL, **av = NULL; char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL; char serial_s[16], uidstr[32]; void (*osigchld)(int); if (authoptsp != NULL) *authoptsp = NULL; if (options.authorized_principals_command == NULL) return 0; if (options.authorized_principals_command_user == NULL) { error("No user for AuthorizedPrincipalsCommand specified, " "skipping"); return 0; } /* * NB. all returns later this function should go via "out" to * ensure the original SIGCHLD handler is restored properly. */ osigchld = signal(SIGCHLD, SIG_DFL); /* Prepare and verify the user for the command */ username = percent_expand(options.authorized_principals_command_user, "u", user_pw->pw_name, (char *)NULL); runas_pw = getpwnam(username); if (runas_pw == NULL) { error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s", username, strerror(errno)); goto out; } /* Turn the command into an argument vector */ if (argv_split(options.authorized_principals_command, &ac, &av) != 0) { error("AuthorizedPrincipalsCommand \"%s\" contains " "invalid quotes", command); goto out; } if (ac == 0) { error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments", command); goto out; } if ((ca_fp = sshkey_fingerprint(cert->signature_key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) { error("%s: sshkey_fingerprint failed", __func__); goto out; } if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) { error("%s: sshkey_fingerprint failed", __func__); goto out; } if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) { error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r)); goto out; } if ((r = sshkey_to_base64(key, &keytext)) != 0) { error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r)); goto out; } snprintf(serial_s, sizeof(serial_s), "%llu", (unsigned long long)cert->serial); snprintf(uidstr, sizeof(uidstr), "%llu", (unsigned long long)user_pw->pw_uid); for (i = 1; i < ac; i++) { tmp = percent_expand(av[i], "U", uidstr, "u", user_pw->pw_name, "h", user_pw->pw_dir, "t", sshkey_ssh_name(key), "T", sshkey_ssh_name(cert->signature_key), "f", key_fp, "F", ca_fp, "k", keytext, "K", catext, "i", cert->key_id, "s", serial_s, (char *)NULL); if (tmp == NULL) fatal("%s: percent_expand failed", __func__); free(av[i]); av[i] = tmp; } /* Prepare a printable command for logs, etc. */ command = argv_assemble(ac, av); if ((pid = subprocess("AuthorizedPrincipalsCommand", runas_pw, command, ac, av, &f, SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD)) == 0) goto out; uid_swapped = 1; temporarily_use_uid(runas_pw); ok = process_principals(ssh, f, "(command)", cert, authoptsp); fclose(f); f = NULL; if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0) goto out; /* Read completed successfully */ found_principal = ok; out: if (f != NULL) fclose(f); signal(SIGCHLD, osigchld); for (i = 0; i < ac; i++) free(av[i]); free(av); if (uid_swapped) restore_uid(); free(command); free(username); free(ca_fp); free(key_fp); free(catext); free(keytext); return found_principal; } static void skip_space(char **cpp) { char *cp; for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++) ; *cpp = cp; } /* * Advanced *cpp past the end of key options, defined as the first unquoted * whitespace character. Returns 0 on success or -1 on failure (e.g. * unterminated quotes). */ static int advance_past_options(char **cpp) { char *cp = *cpp; int quoted = 0; for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) { if (*cp == '\\' && cp[1] == '"') cp++; /* Skip both */ else if (*cp == '"') quoted = !quoted; } *cpp = cp; /* return failure for unterminated quotes */ return (*cp == '\0' && quoted) ? -1 : 0; } /* * Check a single line of an authorized_keys-format file. Returns 0 if key * matches, -1 otherwise. Will return key/cert options via *authoptsp * on success. "loc" is used as file/line location in log messages. */ static int check_authkey_line(struct ssh *ssh, struct passwd *pw, struct sshkey *key, char *cp, const char *loc, struct sshauthopt **authoptsp) { int want_keytype = sshkey_is_cert(key) ? KEY_UNSPEC : key->type; struct sshkey *found = NULL; struct sshauthopt *keyopts = NULL, *certopts = NULL, *finalopts = NULL; char *key_options = NULL, *fp = NULL; const char *reason = NULL; int ret = -1; if (authoptsp != NULL) *authoptsp = NULL; if ((found = sshkey_new(want_keytype)) == NULL) { debug3("%s: keytype %d failed", __func__, want_keytype); goto out; } /* XXX djm: peek at key type in line and skip if unwanted */ if (sshkey_read(found, &cp) != 0) { /* no key? check for options */ debug2("%s: check options: '%s'", loc, cp); key_options = cp; if (advance_past_options(&cp) != 0) { reason = "invalid key option string"; goto fail_reason; } skip_space(&cp); if (sshkey_read(found, &cp) != 0) { /* still no key? advance to next line*/ debug2("%s: advance: '%s'", loc, cp); goto out; } } /* Parse key options now; we need to know if this is a CA key */ if ((keyopts = sshauthopt_parse(key_options, &reason)) == NULL) { debug("%s: bad key options: %s", loc, reason); auth_debug_add("%s: bad key options: %s", loc, reason); goto out; } /* Ignore keys that don't match or incorrectly marked as CAs */ if (sshkey_is_cert(key)) { /* Certificate; check signature key against CA */ if (!sshkey_equal(found, key->cert->signature_key) || !keyopts->cert_authority) goto out; } else { /* Plain key: check it against key found in file */ if (!sshkey_equal(found, key) || keyopts->cert_authority) goto out; } /* We have a candidate key, perform authorisation checks */ if ((fp = sshkey_fingerprint(found, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) fatal("%s: fingerprint failed", __func__); debug("%s: matching %s found: %s %s", loc, sshkey_is_cert(key) ? "CA" : "key", sshkey_type(found), fp); if (auth_authorise_keyopts(ssh, pw, keyopts, sshkey_is_cert(key), loc) != 0) { reason = "Refused by key options"; goto fail_reason; } /* That's all we need for plain keys. */ if (!sshkey_is_cert(key)) { verbose("Accepted key %s %s found at %s", sshkey_type(found), fp, loc); finalopts = keyopts; keyopts = NULL; goto success; } /* * Additional authorisation for certificates. */ /* Parse and check options present in certificate */ if ((certopts = sshauthopt_from_cert(key)) == NULL) { reason = "Invalid certificate options"; goto fail_reason; } if (auth_authorise_keyopts(ssh, pw, certopts, 0, loc) != 0) { reason = "Refused by certificate options"; goto fail_reason; } if ((finalopts = sshauthopt_merge(keyopts, certopts, &reason)) == NULL) goto fail_reason; /* * If the user has specified a list of principals as * a key option, then prefer that list to matching * their username in the certificate principals list. */ if (keyopts->cert_principals != NULL && !match_principals_option(keyopts->cert_principals, key->cert)) { reason = "Certificate does not contain an authorized principal"; goto fail_reason; } if (sshkey_cert_check_authority(key, 0, 0, keyopts->cert_principals == NULL ? pw->pw_name : NULL, &reason) != 0) goto fail_reason; verbose("Accepted certificate ID \"%s\" (serial %llu) " "signed by CA %s %s found at %s", key->cert->key_id, (unsigned long long)key->cert->serial, sshkey_type(found), fp, loc); success: if (finalopts == NULL) fatal("%s: internal error: missing options", __func__); if (authoptsp != NULL) { *authoptsp = finalopts; finalopts = NULL; } /* success */ ret = 0; goto out; fail_reason: error("%s", reason); auth_debug_add("%s", reason); out: free(fp); sshauthopt_free(keyopts); sshauthopt_free(certopts); sshauthopt_free(finalopts); sshkey_free(found); return ret; } /* * Checks whether key is allowed in authorized_keys-format file, * returns 1 if the key is allowed or 0 otherwise. */ static int check_authkeys_file(struct ssh *ssh, struct passwd *pw, FILE *f, char *file, struct sshkey *key, struct sshauthopt **authoptsp) { char *cp, *line = NULL, loc[256]; size_t linesize = 0; int found_key = 0; u_long linenum = 0; if (authoptsp != NULL) *authoptsp = NULL; while (getline(&line, &linesize, f) != -1) { linenum++; /* Always consume entire file */ if (found_key) continue; /* Skip leading whitespace, empty and comment lines. */ cp = line; skip_space(&cp); if (!*cp || *cp == '\n' || *cp == '#') continue; snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum); if (check_authkey_line(ssh, pw, key, cp, loc, authoptsp) == 0) found_key = 1; } free(line); return found_key; } /* Authenticate a certificate key against TrustedUserCAKeys */ static int user_cert_trusted_ca(struct ssh *ssh, struct passwd *pw, struct sshkey *key, struct sshauthopt **authoptsp) { char *ca_fp, *principals_file = NULL; const char *reason; struct sshauthopt *principals_opts = NULL, *cert_opts = NULL; struct sshauthopt *final_opts = NULL; int r, ret = 0, found_principal = 0, use_authorized_principals; if (authoptsp != NULL) *authoptsp = NULL; if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL) return 0; if ((ca_fp = sshkey_fingerprint(key->cert->signature_key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) return 0; if ((r = sshkey_in_file(key->cert->signature_key, options.trusted_user_ca_keys, 1, 0)) != 0) { debug2("%s: CA %s %s is not listed in %s: %s", __func__, sshkey_type(key->cert->signature_key), ca_fp, options.trusted_user_ca_keys, ssh_err(r)); goto out; } /* * If AuthorizedPrincipals is in use, then compare the certificate * principals against the names in that file rather than matching * against the username. */ if ((principals_file = authorized_principals_file(pw)) != NULL) { if (match_principals_file(ssh, pw, principals_file, key->cert, &principals_opts)) found_principal = 1; } /* Try querying command if specified */ if (!found_principal && match_principals_command(ssh, pw, key, &principals_opts)) found_principal = 1; /* If principals file or command is specified, then require a match */ use_authorized_principals = principals_file != NULL || options.authorized_principals_command != NULL; if (!found_principal && use_authorized_principals) { reason = "Certificate does not contain an authorized principal"; goto fail_reason; } if (use_authorized_principals && principals_opts == NULL) fatal("%s: internal error: missing principals_opts", __func__); if (sshkey_cert_check_authority(key, 0, 1, use_authorized_principals ? NULL : pw->pw_name, &reason) != 0) goto fail_reason; /* Check authority from options in key and from principals file/cmd */ if ((cert_opts = sshauthopt_from_cert(key)) == NULL) { reason = "Invalid certificate options"; goto fail_reason; } if (auth_authorise_keyopts(ssh, pw, cert_opts, 0, "cert") != 0) { reason = "Refused by certificate options"; goto fail_reason; } if (principals_opts == NULL) { final_opts = cert_opts; cert_opts = NULL; } else { if (auth_authorise_keyopts(ssh, pw, principals_opts, 0, "principals") != 0) { reason = "Refused by certificate principals options"; goto fail_reason; } if ((final_opts = sshauthopt_merge(principals_opts, cert_opts, &reason)) == NULL) { fail_reason: error("%s", reason); auth_debug_add("%s", reason); goto out; } } /* Success */ verbose("Accepted certificate ID \"%s\" (serial %llu) signed by " "%s CA %s via %s", key->cert->key_id, (unsigned long long)key->cert->serial, sshkey_type(key->cert->signature_key), ca_fp, options.trusted_user_ca_keys); if (authoptsp != NULL) { *authoptsp = final_opts; final_opts = NULL; } ret = 1; out: sshauthopt_free(principals_opts); sshauthopt_free(cert_opts); sshauthopt_free(final_opts); free(principals_file); free(ca_fp); return ret; } /* * Checks whether key is allowed in file. * returns 1 if the key is allowed or 0 otherwise. */ static int user_key_allowed2(struct ssh *ssh, struct passwd *pw, struct sshkey *key, char *file, struct sshauthopt **authoptsp) { FILE *f; int found_key = 0; if (authoptsp != NULL) *authoptsp = NULL; /* Temporarily use the user's uid. */ temporarily_use_uid(pw); debug("trying public key file %s", file); if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) { found_key = check_authkeys_file(ssh, pw, f, file, key, authoptsp); fclose(f); } restore_uid(); return found_key; } /* * Checks whether key is allowed in output of command. * returns 1 if the key is allowed or 0 otherwise. */ static int user_key_command_allowed2(struct ssh *ssh, struct passwd *user_pw, struct sshkey *key, struct sshauthopt **authoptsp) { struct passwd *runas_pw = NULL; FILE *f = NULL; int r, ok, found_key = 0; int i, uid_swapped = 0, ac = 0; pid_t pid; char *username = NULL, *key_fp = NULL, *keytext = NULL; char uidstr[32], *tmp, *command = NULL, **av = NULL; void (*osigchld)(int); if (authoptsp != NULL) *authoptsp = NULL; if (options.authorized_keys_command == NULL) return 0; if (options.authorized_keys_command_user == NULL) { error("No user for AuthorizedKeysCommand specified, skipping"); return 0; } /* * NB. all returns later this function should go via "out" to * ensure the original SIGCHLD handler is restored properly. */ osigchld = signal(SIGCHLD, SIG_DFL); /* Prepare and verify the user for the command */ username = percent_expand(options.authorized_keys_command_user, "u", user_pw->pw_name, (char *)NULL); runas_pw = getpwnam(username); if (runas_pw == NULL) { error("AuthorizedKeysCommandUser \"%s\" not found: %s", username, strerror(errno)); goto out; } /* Prepare AuthorizedKeysCommand */ if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) { error("%s: sshkey_fingerprint failed", __func__); goto out; } if ((r = sshkey_to_base64(key, &keytext)) != 0) { error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r)); goto out; } /* Turn the command into an argument vector */ if (argv_split(options.authorized_keys_command, &ac, &av) != 0) { error("AuthorizedKeysCommand \"%s\" contains invalid quotes", command); goto out; } if (ac == 0) { error("AuthorizedKeysCommand \"%s\" yielded no arguments", command); goto out; } snprintf(uidstr, sizeof(uidstr), "%llu", (unsigned long long)user_pw->pw_uid); for (i = 1; i < ac; i++) { tmp = percent_expand(av[i], "U", uidstr, "u", user_pw->pw_name, "h", user_pw->pw_dir, "t", sshkey_ssh_name(key), "f", key_fp, "k", keytext, (char *)NULL); if (tmp == NULL) fatal("%s: percent_expand failed", __func__); free(av[i]); av[i] = tmp; } /* Prepare a printable command for logs, etc. */ command = argv_assemble(ac, av); /* * If AuthorizedKeysCommand was run without arguments * then fall back to the old behaviour of passing the * target username as a single argument. */ if (ac == 1) { av = xreallocarray(av, ac + 2, sizeof(*av)); av[1] = xstrdup(user_pw->pw_name); av[2] = NULL; /* Fix up command too, since it is used in log messages */ free(command); xasprintf(&command, "%s %s", av[0], av[1]); } if ((pid = subprocess("AuthorizedKeysCommand", runas_pw, command, ac, av, &f, SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD)) == 0) goto out; uid_swapped = 1; temporarily_use_uid(runas_pw); ok = check_authkeys_file(ssh, user_pw, f, options.authorized_keys_command, key, authoptsp); fclose(f); f = NULL; if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0) goto out; /* Read completed successfully */ found_key = ok; out: if (f != NULL) fclose(f); signal(SIGCHLD, osigchld); for (i = 0; i < ac; i++) free(av[i]); free(av); if (uid_swapped) restore_uid(); free(command); free(username); free(key_fp); free(keytext); return found_key; } /* * Check whether key authenticates and authorises the user. */ int user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key, int auth_attempt, struct sshauthopt **authoptsp) { u_int success, i; char *file; struct sshauthopt *opts = NULL; if (authoptsp != NULL) *authoptsp = NULL; if (auth_key_is_revoked(key)) return 0; if (sshkey_is_cert(key) && auth_key_is_revoked(key->cert->signature_key)) return 0; if ((success = user_cert_trusted_ca(ssh, pw, key, &opts)) != 0) goto out; sshauthopt_free(opts); opts = NULL; if ((success = user_key_command_allowed2(ssh, pw, key, &opts)) != 0) goto out; sshauthopt_free(opts); opts = NULL; for (i = 0; !success && i < options.num_authkeys_files; i++) { if (strcasecmp(options.authorized_keys_files[i], "none") == 0) continue; file = expand_authorized_keys( options.authorized_keys_files[i], pw); success = user_key_allowed2(ssh, pw, key, file, &opts); free(file); } out: if (success && authoptsp != NULL) { *authoptsp = opts; opts = NULL; } sshauthopt_free(opts); return success; } Authmethod method_pubkey = { "publickey", userauth_pubkey, &options.pubkey_authentication };
./CrossVul/dataset_final_sorted/CWE-200/c/bad_295_2
crossvul-cpp_data_good_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 0; } 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/good_437_0
crossvul-cpp_data_good_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; memset(&ifc, 0, sizeof(ifc)); 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/good_3827_0
crossvul-cpp_data_good_603_0
// SPDX-License-Identifier: GPL-2.0 /* sbuslib.c: Helper library for SBUS framebuffer drivers. * * Copyright (C) 2003 David S. Miller (davem@redhat.com) */ #include <linux/compat.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/string.h> #include <linux/fb.h> #include <linux/mm.h> #include <linux/uaccess.h> #include <linux/of_device.h> #include <asm/fbio.h> #include "sbuslib.h" void sbusfb_fill_var(struct fb_var_screeninfo *var, struct device_node *dp, int bpp) { memset(var, 0, sizeof(*var)); var->xres = of_getintprop_default(dp, "width", 1152); var->yres = of_getintprop_default(dp, "height", 900); var->xres_virtual = var->xres; var->yres_virtual = var->yres; var->bits_per_pixel = bpp; } EXPORT_SYMBOL(sbusfb_fill_var); static unsigned long sbusfb_mmapsize(long size, unsigned long fbsize) { if (size == SBUS_MMAP_EMPTY) return 0; if (size >= 0) return size; return fbsize * (-size); } int sbusfb_mmap_helper(struct sbus_mmap_map *map, unsigned long physbase, unsigned long fbsize, unsigned long iospace, struct vm_area_struct *vma) { unsigned int size, page, r, map_size; unsigned long map_offset = 0; unsigned long off; int i; if (!(vma->vm_flags & (VM_SHARED | VM_MAYSHARE))) return -EINVAL; size = vma->vm_end - vma->vm_start; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) return -EINVAL; off = vma->vm_pgoff << PAGE_SHIFT; /* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by remap_pfn_range() */ vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); /* Each page, see which map applies */ for (page = 0; page < size; ){ map_size = 0; for (i = 0; map[i].size; i++) if (map[i].voff == off+page) { map_size = sbusfb_mmapsize(map[i].size, fbsize); #ifdef __sparc_v9__ #define POFF_MASK (PAGE_MASK|0x1UL) #else #define POFF_MASK (PAGE_MASK) #endif map_offset = (physbase + map[i].poff) & POFF_MASK; break; } if (!map_size) { page += PAGE_SIZE; continue; } if (page + map_size > size) map_size = size - page; r = io_remap_pfn_range(vma, vma->vm_start + page, MK_IOSPACE_PFN(iospace, map_offset >> PAGE_SHIFT), map_size, vma->vm_page_prot); if (r) return -EAGAIN; page += map_size; } return 0; } EXPORT_SYMBOL(sbusfb_mmap_helper); int sbusfb_ioctl_helper(unsigned long cmd, unsigned long arg, struct fb_info *info, int type, int fb_depth, unsigned long fb_size) { switch(cmd) { case FBIOGTYPE: { struct fbtype __user *f = (struct fbtype __user *) arg; if (put_user(type, &f->fb_type) || __put_user(info->var.yres, &f->fb_height) || __put_user(info->var.xres, &f->fb_width) || __put_user(fb_depth, &f->fb_depth) || __put_user(0, &f->fb_cmsize) || __put_user(fb_size, &f->fb_cmsize)) return -EFAULT; return 0; } case FBIOPUTCMAP_SPARC: { struct fbcmap __user *c = (struct fbcmap __user *) arg; struct fb_cmap cmap; u16 red, green, blue; u8 red8, green8, blue8; unsigned char __user *ured; unsigned char __user *ugreen; unsigned char __user *ublue; unsigned int index, count, i; if (get_user(index, &c->index) || __get_user(count, &c->count) || __get_user(ured, &c->red) || __get_user(ugreen, &c->green) || __get_user(ublue, &c->blue)) return -EFAULT; cmap.len = 1; cmap.red = &red; cmap.green = &green; cmap.blue = &blue; cmap.transp = NULL; for (i = 0; i < count; i++) { int err; if (get_user(red8, &ured[i]) || get_user(green8, &ugreen[i]) || get_user(blue8, &ublue[i])) return -EFAULT; red = red8 << 8; green = green8 << 8; blue = blue8 << 8; cmap.start = index + i; err = fb_set_cmap(&cmap, info); if (err) return err; } return 0; } case FBIOGETCMAP_SPARC: { struct fbcmap __user *c = (struct fbcmap __user *) arg; unsigned char __user *ured; unsigned char __user *ugreen; unsigned char __user *ublue; struct fb_cmap *cmap = &info->cmap; unsigned int index, count, i; u8 red, green, blue; if (get_user(index, &c->index) || __get_user(count, &c->count) || __get_user(ured, &c->red) || __get_user(ugreen, &c->green) || __get_user(ublue, &c->blue)) return -EFAULT; if (index + count > cmap->len) return -EINVAL; for (i = 0; i < count; i++) { red = cmap->red[index + i] >> 8; green = cmap->green[index + i] >> 8; blue = cmap->blue[index + i] >> 8; if (put_user(red, &ured[i]) || put_user(green, &ugreen[i]) || put_user(blue, &ublue[i])) return -EFAULT; } return 0; } default: return -EINVAL; } } EXPORT_SYMBOL(sbusfb_ioctl_helper); #ifdef CONFIG_COMPAT static int fbiogetputcmap(struct fb_info *info, unsigned int cmd, unsigned long arg) { struct fbcmap32 __user *argp = (void __user *)arg; struct fbcmap __user *p = compat_alloc_user_space(sizeof(*p)); u32 addr; int ret; ret = copy_in_user(p, argp, 2 * sizeof(int)); ret |= get_user(addr, &argp->red); ret |= put_user(compat_ptr(addr), &p->red); ret |= get_user(addr, &argp->green); ret |= put_user(compat_ptr(addr), &p->green); ret |= get_user(addr, &argp->blue); ret |= put_user(compat_ptr(addr), &p->blue); if (ret) return -EFAULT; return info->fbops->fb_ioctl(info, (cmd == FBIOPUTCMAP32) ? FBIOPUTCMAP_SPARC : FBIOGETCMAP_SPARC, (unsigned long)p); } static int fbiogscursor(struct fb_info *info, unsigned long arg) { struct fbcursor __user *p = compat_alloc_user_space(sizeof(*p)); struct fbcursor32 __user *argp = (void __user *)arg; compat_uptr_t addr; int ret; ret = copy_in_user(p, argp, 2 * sizeof (short) + 2 * sizeof(struct fbcurpos)); ret |= copy_in_user(&p->size, &argp->size, sizeof(struct fbcurpos)); ret |= copy_in_user(&p->cmap, &argp->cmap, 2 * sizeof(int)); ret |= get_user(addr, &argp->cmap.red); ret |= put_user(compat_ptr(addr), &p->cmap.red); ret |= get_user(addr, &argp->cmap.green); ret |= put_user(compat_ptr(addr), &p->cmap.green); ret |= get_user(addr, &argp->cmap.blue); ret |= put_user(compat_ptr(addr), &p->cmap.blue); ret |= get_user(addr, &argp->mask); ret |= put_user(compat_ptr(addr), &p->mask); ret |= get_user(addr, &argp->image); ret |= put_user(compat_ptr(addr), &p->image); if (ret) return -EFAULT; return info->fbops->fb_ioctl(info, FBIOSCURSOR, (unsigned long)p); } int sbusfb_compat_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg) { switch (cmd) { case FBIOGTYPE: case FBIOSATTR: case FBIOGATTR: case FBIOSVIDEO: case FBIOGVIDEO: case FBIOGCURSOR32: /* This is not implemented yet. Later it should be converted... */ case FBIOSCURPOS: case FBIOGCURPOS: case FBIOGCURMAX: return info->fbops->fb_ioctl(info, cmd, arg); case FBIOPUTCMAP32: return fbiogetputcmap(info, cmd, arg); case FBIOGETCMAP32: return fbiogetputcmap(info, cmd, arg); case FBIOSCURSOR32: return fbiogscursor(info, arg); default: return -ENOIOCTLCMD; } } EXPORT_SYMBOL(sbusfb_compat_ioctl); #endif
./CrossVul/dataset_final_sorted/CWE-200/c/good_603_0
crossvul-cpp_data_bad_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->len = 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/bad_2330_0
crossvul-cpp_data_good_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 (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 (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/good_2825_0
crossvul-cpp_data_bad_1394_0
// SPDX-License-Identifier: GPL-2.0 /* * linux/mm/mincore.c * * Copyright (C) 1994-2006 Linus Torvalds */ /* * The mincore() system call. */ #include <linux/pagemap.h> #include <linux/gfp.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/syscalls.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/shmem_fs.h> #include <linux/hugetlb.h> #include <linux/uaccess.h> #include <asm/pgtable.h> static int mincore_hugetlb(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { #ifdef CONFIG_HUGETLB_PAGE unsigned char present; unsigned char *vec = walk->private; /* * Hugepages under user process are always in RAM and never * swapped out, but theoretically it needs to be checked. */ present = pte && !huge_pte_none(huge_ptep_get(pte)); for (; addr != end; vec++, addr += PAGE_SIZE) *vec = present; walk->private = vec; #else BUG(); #endif return 0; } /* * Later we can get more picky about what "in core" means precisely. * For now, simply check to see if the page is in the page cache, * and is up to date; i.e. that no page-in operation would be required * at this time if an application were to map and access this page. */ static unsigned char mincore_page(struct address_space *mapping, pgoff_t pgoff) { unsigned char present = 0; struct page *page; /* * When tmpfs swaps out a page from a file, any process mapping that * file will not get a swp_entry_t in its pte, but rather it is like * any other file mapping (ie. marked !present and faulted in with * tmpfs's .fault). So swapped out tmpfs mappings are tested here. */ #ifdef CONFIG_SWAP if (shmem_mapping(mapping)) { page = find_get_entry(mapping, pgoff); /* * shmem/tmpfs may return swap: account for swapcache * page too. */ if (xa_is_value(page)) { swp_entry_t swp = radix_to_swp_entry(page); page = find_get_page(swap_address_space(swp), swp_offset(swp)); } } else page = find_get_page(mapping, pgoff); #else page = find_get_page(mapping, pgoff); #endif if (page) { present = PageUptodate(page); put_page(page); } return present; } static int __mincore_unmapped_range(unsigned long addr, unsigned long end, struct vm_area_struct *vma, unsigned char *vec) { unsigned long nr = (end - addr) >> PAGE_SHIFT; int i; if (vma->vm_file) { pgoff_t pgoff; pgoff = linear_page_index(vma, addr); for (i = 0; i < nr; i++, pgoff++) vec[i] = mincore_page(vma->vm_file->f_mapping, pgoff); } else { for (i = 0; i < nr; i++) vec[i] = 0; } return nr; } static int mincore_unmapped_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { walk->private += __mincore_unmapped_range(addr, end, walk->vma, walk->private); return 0; } static int mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { spinlock_t *ptl; struct vm_area_struct *vma = walk->vma; pte_t *ptep; unsigned char *vec = walk->private; int nr = (end - addr) >> PAGE_SHIFT; ptl = pmd_trans_huge_lock(pmd, vma); if (ptl) { memset(vec, 1, nr); spin_unlock(ptl); goto out; } if (pmd_trans_unstable(pmd)) { __mincore_unmapped_range(addr, end, vma, vec); goto out; } ptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); for (; addr != end; ptep++, addr += PAGE_SIZE) { pte_t pte = *ptep; if (pte_none(pte)) __mincore_unmapped_range(addr, addr + PAGE_SIZE, vma, vec); else if (pte_present(pte)) *vec = 1; else { /* pte is a swap entry */ swp_entry_t entry = pte_to_swp_entry(pte); if (non_swap_entry(entry)) { /* * migration or hwpoison entries are always * uptodate */ *vec = 1; } else { #ifdef CONFIG_SWAP *vec = mincore_page(swap_address_space(entry), swp_offset(entry)); #else WARN_ON(1); *vec = 1; #endif } } vec++; } pte_unmap_unlock(ptep - 1, ptl); out: walk->private += nr; cond_resched(); return 0; } /* * Do a chunk of "sys_mincore()". We've already checked * all the arguments, we hold the mmap semaphore: we should * just return the amount of info we're asked for. */ static long do_mincore(unsigned long addr, unsigned long pages, unsigned char *vec) { struct vm_area_struct *vma; unsigned long end; int err; struct mm_walk mincore_walk = { .pmd_entry = mincore_pte_range, .pte_hole = mincore_unmapped_range, .hugetlb_entry = mincore_hugetlb, .private = vec, }; vma = find_vma(current->mm, addr); if (!vma || addr < vma->vm_start) return -ENOMEM; mincore_walk.mm = vma->vm_mm; end = min(vma->vm_end, addr + (pages << PAGE_SHIFT)); err = walk_page_range(addr, end, &mincore_walk); if (err < 0) return err; return (end - addr) >> PAGE_SHIFT; } /* * The mincore(2) system call. * * mincore() returns the memory residency status of the pages in the * current process's address space specified by [addr, addr + len). * The status is returned in a vector of bytes. The least significant * bit of each byte is 1 if the referenced page is in memory, otherwise * it is zero. * * Because the status of a page can change after mincore() checks it * but before it returns to the application, the returned vector may * contain stale information. Only locked pages are guaranteed to * remain in memory. * * return values: * zero - success * -EFAULT - vec points to an illegal address * -EINVAL - addr is not a multiple of PAGE_SIZE * -ENOMEM - Addresses in the range [addr, addr + len] are * invalid for the address space of this process, or * specify one or more pages which are not currently * mapped * -EAGAIN - A kernel resource was temporarily unavailable. */ SYSCALL_DEFINE3(mincore, unsigned long, start, size_t, len, unsigned char __user *, vec) { long retval; unsigned long pages; unsigned char *tmp; /* Check the start address: needs to be page-aligned.. */ if (start & ~PAGE_MASK) return -EINVAL; /* ..and we need to be passed a valid user-space range */ if (!access_ok((void __user *) start, len)) return -ENOMEM; /* This also avoids any overflows on PAGE_ALIGN */ pages = len >> PAGE_SHIFT; pages += (offset_in_page(len)) != 0; if (!access_ok(vec, pages)) return -EFAULT; tmp = (void *) __get_free_page(GFP_USER); if (!tmp) return -EAGAIN; retval = 0; while (pages) { /* * Do at most PAGE_SIZE entries per iteration, due to * the temporary buffer size. */ down_read(&current->mm->mmap_sem); retval = do_mincore(start, min(pages, PAGE_SIZE), tmp); up_read(&current->mm->mmap_sem); if (retval <= 0) break; if (copy_to_user(vec, tmp, retval)) { retval = -EFAULT; break; } pages -= retval; vec += retval; start += retval << PAGE_SHIFT; retval = 0; } free_page((unsigned long) tmp); return retval; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1394_0
crossvul-cpp_data_good_2490_1
/* 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 entrynodes.c * \brief Code to manage our fixed first nodes for various functions. * * Entry nodes can be guards (for general use) or bridges (for censorship * circumvention). * * In general, we use entry guards to prevent traffic-sampling attacks: * if we chose every circuit independently, an adversary controlling * some fraction of paths on the network would observe a sample of every * user's traffic. Using guards gives users a chance of not being * profiled. * * The current entry guard selection code is designed to try to avoid * _ever_ trying every guard on the network, to try to stick to guards * that we've used before, to handle hostile/broken networks, and * to behave sanely when the network goes up and down. * * Our algorithm works as follows: First, we maintain a SAMPLE of guards * we've seen in the networkstatus consensus. We maintain this sample * over time, and store it persistently; it is chosen without reference * to our configuration or firewall rules. Guards remain in the sample * as they enter and leave the consensus. We expand this sample as * needed, up to a maximum size. * * As a subset of the sample, we maintain a FILTERED SET of the guards * that we would be willing to use if we could connect to them. The * filter removes all the guards that we're excluding because they're * bridges (or not bridges), because we have restrictive firewall rules, * because of ExcludeNodes, because we of path bias restrictions, * because they're absent from the network at present, and so on. * * As a subset of the filtered set, we keep a REACHABLE FILTERED SET * (also called a "usable filtered set") of those guards that we call * "reachable" or "maybe reachable". A guard is reachable if we've * connected to it more recently than we've failed. A guard is "maybe * reachable" if we have never tried to connect to it, or if we * failed to connect to it so long ago that we no longer think our * failure means it's down. * * As a persistent ordered list whose elements are taken from the * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes * confirmed when we successfully build a circuit through it, and decide * to use that circuit. We order the guards on this list by the order * in which they became confirmed. * * And as a final group, we have an ordered list of PRIMARY GUARDS, * whose elements are taken from the filtered set. We prefer * confirmed guards to non-confirmed guards for this list, and place * other restrictions on it. The primary guards are the ones that we * connect to "when nothing is wrong" -- circuits through them can be used * immediately. * * To build circuits, we take a primary guard if possible -- or a * reachable filtered confirmed guard if no primary guard is possible -- * or a random reachable filtered guard otherwise. If the guard is * primary, we can use the circuit immediately on success. Otherwise, * the guard is now "pending" -- we won't use its circuit unless all * of the circuits we're trying to build through better guards have * definitely failed. * * While we're building circuits, we track a little "guard state" for * each circuit. We use this to keep track of whether the circuit is * one that we can use as soon as its done, or whether it's one that * we should keep around to see if we can do better. In the latter case, * a periodic call to entry_guards_upgrade_waiting_circuits() will * eventually upgrade it. **/ /* DOCDOC -- expand this. * * Information invariants: * * [x] whenever a guard becomes unreachable, clear its usable_filtered flag. * * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered * flag is set, set its usable_filtered flag. * * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.) * * [x] Whenever the configuration changes in a relevant way, update the * filtered/usable flags. (LATER.) * * [x] Whenever we add a guard to the sample, make sure its filtered/usable * flags are set as possible. * * [x] Whenever we remove a guard from the sample, remove it from the primary * and confirmed lists. * * [x] When we make a guard confirmed, update the primary list. * * [x] When we make a guard filtered or unfiltered, update the primary list. * * [x] When we are about to pick a guard, make sure that the primary list is * full. * * [x] Before calling sample_reachable_filtered_entry_guards(), make sure * that the filtered, primary, and confirmed flags are up-to-date. * * [x] Call entry_guard_consider_retry every time we are about to check * is_usable_filtered or is_reachable, and every time we set * is_filtered to 1. * * [x] Call entry_guards_changed_for_guard_selection() whenever we update * a persistent field. */ #define ENTRYNODES_PRIVATE #include "or.h" #include "channel.h" #include "bridges.h" #include "circpathbias.h" #include "circuitbuild.h" #include "circuitlist.h" #include "circuitstats.h" #include "config.h" #include "confparse.h" #include "connection.h" #include "control.h" #include "directory.h" #include "entrynodes.h" #include "main.h" #include "microdesc.h" #include "networkstatus.h" #include "nodelist.h" #include "policies.h" #include "router.h" #include "routerlist.h" #include "routerparse.h" #include "routerset.h" #include "transports.h" #include "statefile.h" /** A list of existing guard selection contexts. */ static smartlist_t *guard_contexts = NULL; /** The currently enabled guard selection context. */ static guard_selection_t *curr_guard_context = NULL; /** A value of 1 means that at least one context has changed, * and those changes need to be flushed to disk. */ static int entry_guards_dirty = 0; static void entry_guard_set_filtered_flags(const or_options_t *options, guard_selection_t *gs, entry_guard_t *guard); static void pathbias_check_use_success_count(entry_guard_t *guard); static void pathbias_check_close_success_count(entry_guard_t *guard); static int node_is_possible_guard(const node_t *node); static int node_passes_guard_filter(const or_options_t *options, const node_t *node); static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs, const uint8_t *rsa_id_digest, const char *nickname, const tor_addr_port_t *bridge_addrport); static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs, const tor_addr_port_t *addrport); static int entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst); /** Return 0 if we should apply guardfraction information found in the * consensus. A specific consensus can be specified with the * <b>ns</b> argument, if NULL the most recent one will be picked.*/ int should_apply_guardfraction(const networkstatus_t *ns) { /* We need to check the corresponding torrc option and the consensus * parameter if we need to. */ const or_options_t *options = get_options(); /* If UseGuardFraction is 'auto' then check the same-named consensus * parameter. If the consensus parameter is not present, default to * "off". */ if (options->UseGuardFraction == -1) { return networkstatus_get_param(ns, "UseGuardFraction", 0, /* default to "off" */ 0, 1); } return options->UseGuardFraction; } /** Return true iff we know a descriptor for <b>guard</b> */ static int guard_has_descriptor(const entry_guard_t *guard) { const node_t *node = node_get_by_id(guard->identity); if (!node) return 0; return node_has_descriptor(node); } /** * Try to determine the correct type for a selection named "name", * if <b>type</b> is GS_TYPE_INFER. */ STATIC guard_selection_type_t guard_selection_infer_type(guard_selection_type_t type, const char *name) { if (type == GS_TYPE_INFER) { if (!strcmp(name, "bridges")) type = GS_TYPE_BRIDGE; else if (!strcmp(name, "restricted")) type = GS_TYPE_RESTRICTED; else type = GS_TYPE_NORMAL; } return type; } /** * Allocate and return a new guard_selection_t, with the name <b>name</b>. */ STATIC guard_selection_t * guard_selection_new(const char *name, guard_selection_type_t type) { guard_selection_t *gs; type = guard_selection_infer_type(type, name); gs = tor_malloc_zero(sizeof(*gs)); gs->name = tor_strdup(name); gs->type = type; gs->sampled_entry_guards = smartlist_new(); gs->confirmed_entry_guards = smartlist_new(); gs->primary_entry_guards = smartlist_new(); return gs; } /** * Return the guard selection called <b>name</b>. If there is none, and * <b>create_if_absent</b> is true, then create and return it. If there * is none, and <b>create_if_absent</b> is false, then return NULL. */ STATIC guard_selection_t * get_guard_selection_by_name(const char *name, guard_selection_type_t type, int create_if_absent) { if (!guard_contexts) { guard_contexts = smartlist_new(); } SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) { if (!strcmp(gs->name, name)) return gs; } SMARTLIST_FOREACH_END(gs); if (! create_if_absent) return NULL; log_debug(LD_GUARD, "Creating a guard selection called %s", name); guard_selection_t *new_selection = guard_selection_new(name, type); smartlist_add(guard_contexts, new_selection); return new_selection; } /** * Allocate the first guard context that we're planning to use, * and make it the current context. */ static void create_initial_guard_context(void) { tor_assert(! curr_guard_context); if (!guard_contexts) { guard_contexts = smartlist_new(); } guard_selection_type_t type = GS_TYPE_INFER; const char *name = choose_guard_selection( get_options(), networkstatus_get_live_consensus(approx_time()), NULL, &type); tor_assert(name); // "name" can only be NULL if we had an old name. tor_assert(type != GS_TYPE_INFER); log_notice(LD_GUARD, "Starting with guard context \"%s\"", name); curr_guard_context = get_guard_selection_by_name(name, type, 1); } /** Get current default guard_selection_t, creating it if necessary */ guard_selection_t * get_guard_selection_info(void) { if (!curr_guard_context) { create_initial_guard_context(); } return curr_guard_context; } /** Return a statically allocated human-readable description of <b>guard</b> */ const char * entry_guard_describe(const entry_guard_t *guard) { static char buf[256]; tor_snprintf(buf, sizeof(buf), "%s ($%s)", strlen(guard->nickname) ? guard->nickname : "[bridge]", hex_str(guard->identity, DIGEST_LEN)); return buf; } /** Return <b>guard</b>'s 20-byte RSA identity digest */ const char * entry_guard_get_rsa_id_digest(const entry_guard_t *guard) { return guard->identity; } /** Return the pathbias state associated with <b>guard</b>. */ guard_pathbias_t * entry_guard_get_pathbias_state(entry_guard_t *guard) { return &guard->pb; } HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC) /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past, * chosen uniformly at random. We use this before recording persistent * dates, so that we aren't leaking exactly when we recorded it. */ MOCK_IMPL(STATIC time_t, randomize_time,(time_t now, time_t max_backdate)) { tor_assert(max_backdate > 0); time_t earliest = now - max_backdate; time_t latest = now; if (earliest <= 0) earliest = 1; if (latest <= earliest) latest = earliest + 1; return crypto_rand_time_range(earliest, latest); } /** * @name parameters for networkstatus algorithm * * These parameters are taken from the consensus; some are overrideable in * the torrc. */ /**@{*/ /** * We never let our sampled guard set grow larger than this fraction * of the guards on the network. */ STATIC double get_max_sample_threshold(void) { int32_t pct = networkstatus_get_param(NULL, "guard-max-sample-threshold-percent", DFLT_MAX_SAMPLE_THRESHOLD_PERCENT, 1, 100); return pct / 100.0; } /** * We never let our sampled guard set grow larger than this number. */ STATIC int get_max_sample_size_absolute(void) { return (int) networkstatus_get_param(NULL, "guard-max-sample-size", DFLT_MAX_SAMPLE_SIZE, 1, INT32_MAX); } /** * We always try to make our sample contain at least this many guards. */ STATIC int get_min_filtered_sample_size(void) { return networkstatus_get_param(NULL, "guard-min-filtered-sample-size", DFLT_MIN_FILTERED_SAMPLE_SIZE, 1, INT32_MAX); } /** * If a guard is unlisted for this many days in a row, we remove it. */ STATIC int get_remove_unlisted_guards_after_days(void) { return networkstatus_get_param(NULL, "guard-remove-unlisted-guards-after-days", DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS, 1, 365*10); } /** * We remove unconfirmed guards from the sample after this many days, * regardless of whether they are listed or unlisted. */ STATIC int get_guard_lifetime(void) { if (get_options()->GuardLifetime >= 86400) return get_options()->GuardLifetime; int32_t days; days = networkstatus_get_param(NULL, "guard-lifetime-days", DFLT_GUARD_LIFETIME_DAYS, 1, 365*10); return days * 86400; } /** * We remove confirmed guards from the sample if they were sampled * GUARD_LIFETIME_DAYS ago and confirmed this many days ago. */ STATIC int get_guard_confirmed_min_lifetime(void) { if (get_options()->GuardLifetime >= 86400) return get_options()->GuardLifetime; int32_t days; days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days", DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS, 1, 365*10); return days * 86400; } /** * How many guards do we try to keep on our primary guard list? */ STATIC int get_n_primary_guards(void) { const int n = get_options()->NumEntryGuards; const int n_dir = get_options()->NumDirectoryGuards; if (n > 5) { return MAX(n_dir, n + n / 2); } else if (n >= 1) { return MAX(n_dir, n * 2); } return networkstatus_get_param(NULL, "guard-n-primary-guards", DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX); } /** * Return the number of the live primary guards we should look at when * making a circuit. */ STATIC int get_n_primary_guards_to_use(guard_usage_t usage) { int configured; const char *param_name; int param_default; if (usage == GUARD_USAGE_DIRGUARD) { configured = get_options()->NumDirectoryGuards; param_name = "guard-n-primary-dir-guards-to-use"; param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE; } else { configured = get_options()->NumEntryGuards; param_name = "guard-n-primary-guards-to-use"; param_default = DFLT_N_PRIMARY_GUARDS_TO_USE; } if (configured >= 1) { return configured; } return networkstatus_get_param(NULL, param_name, param_default, 1, INT32_MAX); } /** * If we haven't successfully built or used a circuit in this long, then * consider that the internet is probably down. */ STATIC int get_internet_likely_down_interval(void) { return networkstatus_get_param(NULL, "guard-internet-likely-down-interval", DFLT_INTERNET_LIKELY_DOWN_INTERVAL, 1, INT32_MAX); } /** * If we're trying to connect to a nonprimary guard for at least this * many seconds, and we haven't gotten the connection to work, we will treat * lower-priority guards as usable. */ STATIC int get_nonprimary_guard_connect_timeout(void) { return networkstatus_get_param(NULL, "guard-nonprimary-guard-connect-timeout", DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT, 1, INT32_MAX); } /** * If a circuit has been sitting around in 'waiting for better guard' state * for at least this long, we'll expire it. */ STATIC int get_nonprimary_guard_idle_timeout(void) { return networkstatus_get_param(NULL, "guard-nonprimary-guard-idle-timeout", DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT, 1, INT32_MAX); } /** * If our configuration retains fewer than this fraction of guards from the * torrc, we are in a restricted setting. */ STATIC double get_meaningful_restriction_threshold(void) { int32_t pct = networkstatus_get_param(NULL, "guard-meaningful-restriction-percent", DFLT_MEANINGFUL_RESTRICTION_PERCENT, 1, INT32_MAX); return pct / 100.0; } /** * If our configuration retains fewer than this fraction of guards from the * torrc, we are in an extremely restricted setting, and should warn. */ STATIC double get_extreme_restriction_threshold(void) { int32_t pct = networkstatus_get_param(NULL, "guard-extreme-restriction-percent", DFLT_EXTREME_RESTRICTION_PERCENT, 1, INT32_MAX); return pct / 100.0; } /* Mark <b>guard</b> as maybe reachable again. */ static void mark_guard_maybe_reachable(entry_guard_t *guard) { if (guard->is_reachable != GUARD_REACHABLE_NO) { return; } /* Note that we do not clear failing_since: this guard is now only * _maybe-reachable_. */ guard->is_reachable = GUARD_REACHABLE_MAYBE; if (guard->is_filtered_guard) guard->is_usable_filtered_guard = 1; } /** * Called when the network comes up after having seemed to be down for * a while: Mark the primary guards as maybe-reachable so that we'll * try them again. */ STATIC void mark_primary_guards_maybe_reachable(guard_selection_t *gs) { tor_assert(gs); if (!gs->primary_guards_up_to_date) entry_guards_update_primary(gs); SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) { mark_guard_maybe_reachable(guard); } SMARTLIST_FOREACH_END(guard); } /* Called when we exhaust all guards in our sampled set: Marks all guards as maybe-reachable so that we 'll try them again. */ static void mark_all_guards_maybe_reachable(guard_selection_t *gs) { tor_assert(gs); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { mark_guard_maybe_reachable(guard); } SMARTLIST_FOREACH_END(guard); } /**@}*/ /** * Given our options and our list of nodes, return the name of the * guard selection that we should use. Return NULL for "use the * same selection you were using before. */ STATIC const char * choose_guard_selection(const or_options_t *options, const networkstatus_t *live_ns, const guard_selection_t *old_selection, guard_selection_type_t *type_out) { tor_assert(options); tor_assert(type_out); if (options->UseBridges) { *type_out = GS_TYPE_BRIDGE; return "bridges"; } if (! live_ns) { /* without a networkstatus, we can't tell any more than that. */ *type_out = GS_TYPE_NORMAL; return "default"; } const smartlist_t *nodes = nodelist_get_list(); int n_guards = 0, n_passing_filter = 0; SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) { if (node_is_possible_guard(node)) { ++n_guards; if (node_passes_guard_filter(options, node)) { ++n_passing_filter; } } } SMARTLIST_FOREACH_END(node); /* We use separate 'high' and 'low' thresholds here to prevent flapping * back and forth */ const int meaningful_threshold_high = (int)(n_guards * get_meaningful_restriction_threshold() * 1.05); const int meaningful_threshold_mid = (int)(n_guards * get_meaningful_restriction_threshold()); const int meaningful_threshold_low = (int)(n_guards * get_meaningful_restriction_threshold() * .95); const int extreme_threshold = (int)(n_guards * get_extreme_restriction_threshold()); /* If we have no previous selection, then we're "restricted" iff we are below the meaningful restriction threshold. That's easy enough. But if we _do_ have a previous selection, we make it a little "sticky": we only move from "restricted" to "default" when we find that we're above the threshold plus 5%, and we only move from "default" to "restricted" when we're below the threshold minus 5%. That should prevent us from flapping back and forth if we happen to be hovering very close to the default. The extreme threshold is for warning only. */ static int have_warned_extreme_threshold = 0; if (n_guards && n_passing_filter < extreme_threshold && ! have_warned_extreme_threshold) { have_warned_extreme_threshold = 1; const double exclude_frac = (n_guards - n_passing_filter) / (double)n_guards; log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible " "guards. That's likely to make you stand out from the " "rest of the world.", (int)(exclude_frac * 100)); } /* Easy case: no previous selection. Just check if we are in restricted or normal guard selection. */ if (old_selection == NULL) { if (n_passing_filter >= meaningful_threshold_mid) { *type_out = GS_TYPE_NORMAL; return "default"; } else { *type_out = GS_TYPE_RESTRICTED; return "restricted"; } } /* Trickier case: we do have a previous guard selection context. */ tor_assert(old_selection); /* Use high and low thresholds to decide guard selection, and if we fall in the middle then keep the current guard selection context. */ if (n_passing_filter >= meaningful_threshold_high) { *type_out = GS_TYPE_NORMAL; return "default"; } else if (n_passing_filter < meaningful_threshold_low) { *type_out = GS_TYPE_RESTRICTED; return "restricted"; } else { /* we are in the middle: maintain previous guard selection */ *type_out = old_selection->type; return old_selection->name; } } /** * Check whether we should switch from our current guard selection to a * different one. If so, switch and return 1. Return 0 otherwise. * * On a 1 return, the caller should mark all currently live circuits unusable * for new streams, by calling circuit_mark_all_unused_circs() and * circuit_mark_all_dirty_circs_as_unusable(). */ int update_guard_selection_choice(const or_options_t *options) { if (!curr_guard_context) { create_initial_guard_context(); return 1; } guard_selection_type_t type = GS_TYPE_INFER; const char *new_name = choose_guard_selection( options, networkstatus_get_live_consensus(approx_time()), curr_guard_context, &type); tor_assert(new_name); tor_assert(type != GS_TYPE_INFER); const char *cur_name = curr_guard_context->name; if (! strcmp(cur_name, new_name)) { log_debug(LD_GUARD, "Staying with guard context \"%s\" (no change)", new_name); return 0; // No change } log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")", new_name, cur_name); guard_selection_t *new_guard_context; new_guard_context = get_guard_selection_by_name(new_name, type, 1); tor_assert(new_guard_context); tor_assert(new_guard_context != curr_guard_context); curr_guard_context = new_guard_context; return 1; } /** * Return true iff <b>node</b> has all the flags needed for us to consider it * a possible guard when sampling guards. */ static int node_is_possible_guard(const node_t *node) { /* The "GUARDS" set is all nodes in the nodelist for which this predicate * holds. */ tor_assert(node); return (node->is_possible_guard && node->is_stable && node->is_fast && node->is_valid && node_is_dir(node)); } /** * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or * NULL if we don't have one. */ STATIC entry_guard_t * get_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id) { tor_assert(gs); tor_assert(rsa_id); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN)) return guard; } SMARTLIST_FOREACH_END(guard); return NULL; } /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>, * return that guard. Otherwise return NULL. */ static entry_guard_t * get_sampled_guard_for_bridge(guard_selection_t *gs, const bridge_info_t *bridge) { const uint8_t *id = bridge_get_rsa_id_digest(bridge); const tor_addr_port_t *addrport = bridge_get_addr_port(bridge); entry_guard_t *guard; if (BUG(!addrport)) return NULL; // LCOV_EXCL_LINE guard = get_sampled_guard_by_bridge_addr(gs, addrport); if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN))) return NULL; else return guard; } /** If we know a bridge_info_t matching <b>guard</b>, return that * bridge. Otherwise return NULL. */ static bridge_info_t * get_bridge_info_for_guard(const entry_guard_t *guard) { const uint8_t *identity = NULL; if (! tor_digest_is_zero(guard->identity)) { identity = (const uint8_t *)guard->identity; } if (BUG(guard->bridge_addr == NULL)) return NULL; return get_configured_bridge_by_exact_addr_port_digest( &guard->bridge_addr->addr, guard->bridge_addr->port, (const char*)identity); } /** * Return true iff we have a sampled guard with the RSA identity digest * <b>rsa_id</b>. */ static inline int have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id) { return get_sampled_guard_with_id(gs, rsa_id) != NULL; } /** * Allocate a new entry_guard_t object for <b>node</b>, add it to the * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must * not currently be a sampled guard in <b>gs</b>. */ STATIC entry_guard_t * entry_guard_add_to_sample(guard_selection_t *gs, const node_t *node) { log_info(LD_GUARD, "Adding %s as to the entry guard sample set.", node_describe(node)); /* make sure that the guard is not already sampled. */ if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity))) return NULL; // LCOV_EXCL_LINE return entry_guard_add_to_sample_impl(gs, (const uint8_t*)node->identity, node_get_nickname(node), NULL); } /** * Backend: adds a new sampled guard to <b>gs</b>, with given identity, * nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but * we need one of them. nickname is optional. The caller is responsible for * maintaining the size limit of the SAMPLED_GUARDS set. */ static entry_guard_t * entry_guard_add_to_sample_impl(guard_selection_t *gs, const uint8_t *rsa_id_digest, const char *nickname, const tor_addr_port_t *bridge_addrport) { const int GUARD_LIFETIME = get_guard_lifetime(); tor_assert(gs); // XXXX #20827 take ed25519 identity here too. /* Make sure we can actually identify the guard. */ if (BUG(!rsa_id_digest && !bridge_addrport)) return NULL; // LCOV_EXCL_LINE entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t)); /* persistent fields */ guard->is_persistent = (rsa_id_digest != NULL); guard->selection_name = tor_strdup(gs->name); if (rsa_id_digest) memcpy(guard->identity, rsa_id_digest, DIGEST_LEN); if (nickname) strlcpy(guard->nickname, nickname, sizeof(guard->nickname)); guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10); tor_free(guard->sampled_by_version); guard->sampled_by_version = tor_strdup(VERSION); guard->currently_listed = 1; guard->confirmed_idx = -1; /* non-persistent fields */ guard->is_reachable = GUARD_REACHABLE_MAYBE; if (bridge_addrport) guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport)); smartlist_add(gs->sampled_entry_guards, guard); guard->in_selection = gs; entry_guard_set_filtered_flags(get_options(), gs, guard); entry_guards_changed_for_guard_selection(gs); return guard; } /** * Add an entry guard to the "bridges" guard selection sample, with * information taken from <b>bridge</b>. Return that entry guard. */ static entry_guard_t * entry_guard_add_bridge_to_sample(guard_selection_t *gs, const bridge_info_t *bridge) { const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge); const tor_addr_port_t *addrport = bridge_get_addr_port(bridge); tor_assert(addrport); /* make sure that the guard is not already sampled. */ if (BUG(get_sampled_guard_for_bridge(gs, bridge))) return NULL; // LCOV_EXCL_LINE return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport); } /** * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>, * or NULL if none exists. */ static entry_guard_t * get_sampled_guard_by_bridge_addr(guard_selection_t *gs, const tor_addr_port_t *addrport) { if (! gs) return NULL; if (BUG(!addrport)) return NULL; SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) { if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr)) return g; } SMARTLIST_FOREACH_END(g); return NULL; } /** Update the guard subsystem's knowledge of the identity of the bridge * at <b>addrport</b>. Idempotent. */ void entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport, const uint8_t *rsa_id_digest) { guard_selection_t *gs = get_guard_selection_by_name("bridges", GS_TYPE_BRIDGE, 0); if (!gs) return; entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport); if (!g) return; int make_persistent = 0; if (tor_digest_is_zero(g->identity)) { memcpy(g->identity, rsa_id_digest, DIGEST_LEN); make_persistent = 1; } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) { /* Nothing to see here; we learned something we already knew. */ if (BUG(! g->is_persistent)) make_persistent = 1; } else { char old_id[HEX_DIGEST_LEN+1]; base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity)); log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but " "we already knew a different one (%s). Ignoring the new info as " "possibly bogus.", hex_str((const char *)rsa_id_digest, DIGEST_LEN), fmt_and_decorate_addr(&addrport->addr), addrport->port, old_id); return; // redundant, but let's be clear: we're not making this persistent. } if (make_persistent) { g->is_persistent = 1; entry_guards_changed_for_guard_selection(gs); } } /** * Return the number of sampled guards in <b>gs</b> that are "filtered" * (that is, we're willing to connect to them) and that are "usable" * (that is, either "reachable" or "maybe reachable"). * * If a restriction is provided in <b>rst</b>, do not count any guards that * violate it. */ STATIC int num_reachable_filtered_guards(guard_selection_t *gs, const entry_guard_restriction_t *rst) { int n_reachable_filtered_guards = 0; SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { entry_guard_consider_retry(guard); if (! entry_guard_obeys_restriction(guard, rst)) continue; if (guard->is_usable_filtered_guard) ++n_reachable_filtered_guards; } SMARTLIST_FOREACH_END(guard); return n_reachable_filtered_guards; } /** Return the actual maximum size for the sample in <b>gs</b>, * given that we know about <b>n_guards</b> total. */ static int get_max_sample_size(guard_selection_t *gs, int n_guards) { const int using_bridges = (gs->type == GS_TYPE_BRIDGE); const int min_sample = get_min_filtered_sample_size(); /* If we are in bridge mode, expand our sample set as needed without worrying * about max size. We should respect the user's wishes to use many bridges if * that's what they have specified in their configuration file. */ if (using_bridges) return INT_MAX; const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold()); const int max_sample_absolute = get_max_sample_size_absolute(); const int max_sample = MIN(max_sample_by_pct, max_sample_absolute); if (max_sample < min_sample) return min_sample; else return max_sample; } /** * Return a smartlist of the all the guards that are not currently * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of * this list are node_t pointers in the non-bridge case, and * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b> * to the number of guards that we found in GUARDS, including those * that were already sampled. */ static smartlist_t * get_eligible_guards(const or_options_t *options, guard_selection_t *gs, int *n_guards_out) { /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */ smartlist_t *eligible_guards = smartlist_new(); int n_guards = 0; // total size of "GUARDS" if (gs->type == GS_TYPE_BRIDGE) { const smartlist_t *bridges = bridge_list_get(); SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) { ++n_guards; if (NULL != get_sampled_guard_for_bridge(gs, bridge)) { continue; } smartlist_add(eligible_guards, bridge); } SMARTLIST_FOREACH_END(bridge); } else { const smartlist_t *nodes = nodelist_get_list(); const int n_sampled = smartlist_len(gs->sampled_entry_guards); /* Build a bloom filter of our current guards: let's keep this O(N). */ digestset_t *sampled_guard_ids = digestset_new(n_sampled); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *, guard) { digestset_add(sampled_guard_ids, guard->identity); } SMARTLIST_FOREACH_END(guard); SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) { if (! node_is_possible_guard(node)) continue; if (gs->type == GS_TYPE_RESTRICTED) { /* In restricted mode, we apply the filter BEFORE sampling, so * that we are sampling from the nodes that we might actually * select. If we sampled first, we might wind up with a sample * that didn't include any EntryNodes at all. */ if (! node_passes_guard_filter(options, node)) continue; } ++n_guards; if (digestset_contains(sampled_guard_ids, node->identity)) continue; smartlist_add(eligible_guards, (node_t*)node); } SMARTLIST_FOREACH_END(node); /* Now we can free that bloom filter. */ digestset_free(sampled_guard_ids); } *n_guards_out = n_guards; return eligible_guards; } /** Helper: given a smartlist of either bridge_info_t (if gs->type is * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard, * add it as a guard, remove it from the list, and return a new * entry_guard_t. Return NULL on failure. */ static entry_guard_t * select_and_add_guard_item_for_sample(guard_selection_t *gs, smartlist_t *eligible_guards) { entry_guard_t *added_guard; if (gs->type == GS_TYPE_BRIDGE) { const bridge_info_t *bridge = smartlist_choose(eligible_guards); if (BUG(!bridge)) return NULL; // LCOV_EXCL_LINE smartlist_remove(eligible_guards, bridge); added_guard = entry_guard_add_bridge_to_sample(gs, bridge); } else { const node_t *node = node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD); if (BUG(!node)) return NULL; // LCOV_EXCL_LINE smartlist_remove(eligible_guards, node); added_guard = entry_guard_add_to_sample(gs, node); } return added_guard; } /** Return true iff we need a consensus to maintain our */ static int live_consensus_is_missing(const guard_selection_t *gs) { tor_assert(gs); if (gs->type == GS_TYPE_BRIDGE) { /* We don't update bridges from the consensus; they aren't there. */ return 0; } return networkstatus_get_live_consensus(approx_time()) == NULL; } /** * Add new guards to the sampled guards in <b>gs</b> until there are * enough usable filtered guards, but never grow the sample beyond its * maximum size. Return the last guard added, or NULL if none were * added. */ STATIC entry_guard_t * entry_guards_expand_sample(guard_selection_t *gs) { tor_assert(gs); const or_options_t *options = get_options(); if (live_consensus_is_missing(gs)) { log_info(LD_GUARD, "Not expanding the sample guard set; we have " "no live consensus."); return NULL; } int n_sampled = smartlist_len(gs->sampled_entry_guards); entry_guard_t *added_guard = NULL; int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL); int n_guards = 0; smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards); const int max_sample = get_max_sample_size(gs, n_guards); const int min_filtered_sample = get_min_filtered_sample_size(); log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards " "in the sample, and %d eligible guards to extend it with.", n_sampled, smartlist_len(eligible_guards)); while (n_usable_filtered_guards < min_filtered_sample) { /* Has our sample grown too large to expand? */ if (n_sampled >= max_sample) { log_info(LD_GUARD, "Not expanding the guard sample any further; " "just hit the maximum sample threshold of %d", max_sample); goto done; } /* Did we run out of guards? */ if (smartlist_len(eligible_guards) == 0) { /* LCOV_EXCL_START As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to allow all guards to be sampled, this can't be reached. */ log_info(LD_GUARD, "Not expanding the guard sample any further; " "just ran out of eligible guards"); goto done; /* LCOV_EXCL_STOP */ } /* Otherwise we can add at least one new guard. */ added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards); if (!added_guard) goto done; // LCOV_EXCL_LINE -- only fails on BUG. ++n_sampled; if (added_guard->is_usable_filtered_guard) ++n_usable_filtered_guards; } done: smartlist_free(eligible_guards); return added_guard; } /** * Helper: <b>guard</b> has just been removed from the sampled guards: * also remove it from primary and confirmed. */ static void remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs, entry_guard_t *guard) { if (guard->is_primary) { guard->is_primary = 0; smartlist_remove_keeporder(gs->primary_entry_guards, guard); } else { if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) { smartlist_remove_keeporder(gs->primary_entry_guards, guard); } } if (guard->confirmed_idx >= 0) { smartlist_remove_keeporder(gs->confirmed_entry_guards, guard); guard->confirmed_idx = -1; guard->confirmed_on_date = 0; } else { if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) { // LCOV_EXCL_START smartlist_remove_keeporder(gs->confirmed_entry_guards, guard); // LCOV_EXCL_STOP } } } /** Return true iff <b>guard</b> is currently "listed" -- that is, it * appears in the consensus, or as a configured bridge (as * appropriate) */ MOCK_IMPL(STATIC int, entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard)) { if (gs->type == GS_TYPE_BRIDGE) { return NULL != get_bridge_info_for_guard(guard); } else { const node_t *node = node_get_by_id(guard->identity); return node && node_is_possible_guard(node); } } /** * Update the status of all sampled guards based on the arrival of a * new consensus networkstatus document. This will include marking * some guards as listed or unlisted, and removing expired guards. */ STATIC void sampled_guards_update_from_consensus(guard_selection_t *gs) { tor_assert(gs); const int REMOVE_UNLISTED_GUARDS_AFTER = (get_remove_unlisted_guards_after_days() * 86400); const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5; // It's important to use only a live consensus here; we don't want to // make changes based on anything expired or old. if (live_consensus_is_missing(gs)) { log_info(LD_GUARD, "Not updating the sample guard set; we have " "no live consensus."); return; } log_info(LD_GUARD, "Updating sampled guard status based on received " "consensus."); int n_changes = 0; /* First: Update listed/unlisted. */ SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { /* XXXX #20827 check ed ID too */ const int is_listed = entry_guard_is_listed(gs, guard); if (is_listed && ! guard->currently_listed) { ++n_changes; guard->currently_listed = 1; guard->unlisted_since_date = 0; log_info(LD_GUARD, "Sampled guard %s is now listed again.", entry_guard_describe(guard)); } else if (!is_listed && guard->currently_listed) { ++n_changes; guard->currently_listed = 0; guard->unlisted_since_date = randomize_time(approx_time(), unlisted_since_slop); log_info(LD_GUARD, "Sampled guard %s is now unlisted.", entry_guard_describe(guard)); } else if (is_listed && guard->currently_listed) { log_debug(LD_GUARD, "Sampled guard %s is still listed.", entry_guard_describe(guard)); } else { tor_assert(! is_listed && ! guard->currently_listed); log_debug(LD_GUARD, "Sampled guard %s is still unlisted.", entry_guard_describe(guard)); } /* Clean up unlisted_since_date, just in case. */ if (guard->currently_listed && guard->unlisted_since_date) { ++n_changes; guard->unlisted_since_date = 0; log_warn(LD_BUG, "Sampled guard %s was listed, but with " "unlisted_since_date set. Fixing.", entry_guard_describe(guard)); } else if (!guard->currently_listed && ! guard->unlisted_since_date) { ++n_changes; guard->unlisted_since_date = randomize_time(approx_time(), unlisted_since_slop); log_warn(LD_BUG, "Sampled guard %s was unlisted, but with " "unlisted_since_date unset. Fixing.", entry_guard_describe(guard)); } } SMARTLIST_FOREACH_END(guard); const time_t remove_if_unlisted_since = approx_time() - REMOVE_UNLISTED_GUARDS_AFTER; const time_t maybe_remove_if_sampled_before = approx_time() - get_guard_lifetime(); const time_t remove_if_confirmed_before = approx_time() - get_guard_confirmed_min_lifetime(); /* Then: remove the ones that have been junk for too long */ SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { int rmv = 0; if (guard->currently_listed == 0 && guard->unlisted_since_date < remove_if_unlisted_since) { /* "We have a live consensus, and {IS_LISTED} is false, and {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER} days in the past." */ log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted " "for over %d days", entry_guard_describe(guard), get_remove_unlisted_guards_after_days()); rmv = 1; } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) { /* We have a live consensus, and {ADDED_ON_DATE} is over {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago. */ if (guard->confirmed_on_date == 0) { rmv = 1; log_info(LD_GUARD, "Removing sampled guard %s: it was sampled " "over %d days ago, but never confirmed.", entry_guard_describe(guard), get_guard_lifetime() / 86400); } else if (guard->confirmed_on_date < remove_if_confirmed_before) { rmv = 1; log_info(LD_GUARD, "Removing sampled guard %s: it was sampled " "over %d days ago, and confirmed over %d days ago.", entry_guard_describe(guard), get_guard_lifetime() / 86400, get_guard_confirmed_min_lifetime() / 86400); } } if (rmv) { ++n_changes; SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard); remove_guard_from_confirmed_and_primary_lists(gs, guard); entry_guard_free(guard); } } SMARTLIST_FOREACH_END(guard); if (n_changes) { gs->primary_guards_up_to_date = 0; entry_guards_update_filtered_sets(gs); /* We don't need to rebuild the confirmed list right here -- we may have * removed confirmed guards above, but we can't have added any new * confirmed guards. */ entry_guards_changed_for_guard_selection(gs); } } /** * Return true iff <b>node</b> is a Tor relay that we are configured to * be able to connect to. */ static int node_passes_guard_filter(const or_options_t *options, const node_t *node) { /* NOTE: Make sure that this function stays in sync with * options_transition_affects_entry_guards */ if (routerset_contains_node(options->ExcludeNodes, node)) return 0; if (options->EntryNodes && !routerset_contains_node(options->EntryNodes, node)) return 0; if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0)) return 0; if (node_is_a_configured_bridge(node)) return 0; return 1; } /** Helper: Return true iff <b>bridge</b> passes our configuration * filter-- if it is a relay that we are configured to be able to * connect to. */ static int bridge_passes_guard_filter(const or_options_t *options, const bridge_info_t *bridge) { tor_assert(bridge); if (!bridge) return 0; if (routerset_contains_bridge(options->ExcludeNodes, bridge)) return 0; /* Ignore entrynodes */ const tor_addr_port_t *addrport = bridge_get_addr_port(bridge); if (!fascist_firewall_allows_address_addr(&addrport->addr, addrport->port, FIREWALL_OR_CONNECTION, 0, 0)) return 0; return 1; } /** * Return true iff <b>guard</b> is a Tor relay that we are configured to * be able to connect to, and we haven't disabled it for omission from * the consensus or path bias issues. */ static int entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs, entry_guard_t *guard) { if (guard->currently_listed == 0) return 0; if (guard->pb.path_bias_disabled) return 0; if (gs->type == GS_TYPE_BRIDGE) { const bridge_info_t *bridge = get_bridge_info_for_guard(guard); if (bridge == NULL) return 0; return bridge_passes_guard_filter(options, bridge); } else { const node_t *node = node_get_by_id(guard->identity); if (node == NULL) { // This can happen when currently_listed is true, and we're not updating // it because we don't have a live consensus. return 0; } return node_passes_guard_filter(options, node); } } /** Return true iff <b>guard</b> is in the same family as <b>node</b>. */ static int guard_in_node_family(const entry_guard_t *guard, const node_t *node) { const node_t *guard_node = node_get_by_id(guard->identity); if (guard_node) { return nodes_in_same_family(guard_node, node); } else { /* If we don't have a node_t for the guard node, we might have * a bridge_info_t for it. So let's check to see whether the bridge * address matches has any family issues. * * (Strictly speaking, I believe this check is unnecessary, since we only * use it to avoid the exit's family when building circuits, and we don't * build multihop circuits until we have a routerinfo_t for the * bridge... at which point, we'll also have a node_t for the * bridge. Nonetheless, it seems wise to include it, in case our * assumptions change down the road. -nickm.) */ if (get_options()->EnforceDistinctSubnets && guard->bridge_addr) { tor_addr_t node_addr; node_get_addr(node, &node_addr); if (addrs_in_same_network_family(&node_addr, &guard->bridge_addr->addr)) { return 1; } } return 0; } } /** * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>. * (If <b>rst</b> is NULL, there are no restrictions.) */ static int entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst) { tor_assert(guard); if (! rst) return 1; // No restriction? No problem. // Only one kind of restriction exists right now: excluding an exit // ID and all of its family. const node_t *node = node_get_by_id((const char*)rst->exclude_id); if (node && guard_in_node_family(guard, node)) return 0; return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN); } /** * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b> * flags on <b>guard</b>. */ void entry_guard_set_filtered_flags(const or_options_t *options, guard_selection_t *gs, entry_guard_t *guard) { unsigned was_filtered = guard->is_filtered_guard; guard->is_filtered_guard = 0; guard->is_usable_filtered_guard = 0; if (entry_guard_passes_filter(options, gs, guard)) { guard->is_filtered_guard = 1; if (guard->is_reachable != GUARD_REACHABLE_NO) guard->is_usable_filtered_guard = 1; entry_guard_consider_retry(guard); } log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; " "reachable_filtered=%d.", entry_guard_describe(guard), guard->is_filtered_guard, guard->is_usable_filtered_guard); if (!bool_eq(was_filtered, guard->is_filtered_guard)) { /* This guard might now be primary or nonprimary. */ gs->primary_guards_up_to_date = 0; } } /** * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b> * flag on every guard in <b>gs</b>. */ STATIC void entry_guards_update_filtered_sets(guard_selection_t *gs) { const or_options_t *options = get_options(); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { entry_guard_set_filtered_flags(options, gs, guard); } SMARTLIST_FOREACH_END(guard); } /** * Return a random guard from the reachable filtered sample guards * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>. * Return NULL if no such guard can be found. * * Make sure that the sample is big enough, and that all the filter flags * are set correctly, before calling this function. * * If a restriction is provided in <b>rst</b>, do not return any guards that * violate it. **/ STATIC entry_guard_t * sample_reachable_filtered_entry_guards(guard_selection_t *gs, const entry_guard_restriction_t *rst, unsigned flags) { tor_assert(gs); entry_guard_t *result = NULL; const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED; const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY; const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING; const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY; const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR; SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { entry_guard_consider_retry(guard); } SMARTLIST_FOREACH_END(guard); const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst); log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d " "in the USABLE_FILTERED set.", n_reachable_filtered); const int min_filtered_sample = get_min_filtered_sample_size(); if (n_reachable_filtered < min_filtered_sample) { log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)"); entry_guards_expand_sample(gs); } if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary) entry_guards_update_primary(gs); /* Build the set of reachable filtered guards. */ smartlist_t *reachable_filtered_sample = smartlist_new(); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { entry_guard_consider_retry(guard);// redundant, but cheap. if (! entry_guard_obeys_restriction(guard, rst)) continue; if (! guard->is_usable_filtered_guard) continue; if (exclude_confirmed && guard->confirmed_idx >= 0) continue; if (exclude_primary && guard->is_primary) continue; if (exclude_pending && guard->is_pending) continue; if (need_descriptor && !guard_has_descriptor(guard)) continue; smartlist_add(reachable_filtered_sample, guard); } SMARTLIST_FOREACH_END(guard); log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)", flags, smartlist_len(reachable_filtered_sample)); if (smartlist_len(reachable_filtered_sample)) { result = smartlist_choose(reachable_filtered_sample); log_info(LD_GUARD, " (Selected %s.)", result ? entry_guard_describe(result) : "<null>"); } smartlist_free(reachable_filtered_sample); return result; } /** * Helper: compare two entry_guard_t by their confirmed_idx values. * Used to sort the confirmed list. */ static int compare_guards_by_confirmed_idx(const void **a_, const void **b_) { const entry_guard_t *a = *a_, *b = *b_; if (a->confirmed_idx < b->confirmed_idx) return -1; else if (a->confirmed_idx > b->confirmed_idx) return 1; else return 0; } /** * Find the confirmed guards from among the sampled guards in <b>gs</b>, * and put them in confirmed_entry_guards in the correct * order. Recalculate their indices. */ STATIC void entry_guards_update_confirmed(guard_selection_t *gs) { smartlist_clear(gs->confirmed_entry_guards); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { if (guard->confirmed_idx >= 0) smartlist_add(gs->confirmed_entry_guards, guard); } SMARTLIST_FOREACH_END(guard); smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx); int any_changed = 0; SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) { if (guard->confirmed_idx != guard_sl_idx) { any_changed = 1; guard->confirmed_idx = guard_sl_idx; } } SMARTLIST_FOREACH_END(guard); gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards); if (any_changed) { entry_guards_changed_for_guard_selection(gs); } } /** * Mark <b>guard</b> as a confirmed guard -- that is, one that we have * connected to, and intend to use again. */ STATIC void make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard) { if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0)) return; // LCOV_EXCL_LINE if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) return; // LCOV_EXCL_LINE const int GUARD_LIFETIME = get_guard_lifetime(); guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10); log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)", entry_guard_describe(guard), gs->next_confirmed_idx); guard->confirmed_idx = gs->next_confirmed_idx++; smartlist_add(gs->confirmed_entry_guards, guard); // This confirmed guard might kick something else out of the primary // guards. gs->primary_guards_up_to_date = 0; entry_guards_changed_for_guard_selection(gs); } /** * Recalculate the list of primary guards (the ones we'd prefer to use) from * the filtered sample and the confirmed list. */ STATIC void entry_guards_update_primary(guard_selection_t *gs) { tor_assert(gs); // prevent recursion. Recursion is potentially very bad here. static int running = 0; tor_assert(!running); running = 1; const int N_PRIMARY_GUARDS = get_n_primary_guards(); smartlist_t *new_primary_guards = smartlist_new(); smartlist_t *old_primary_guards = smartlist_new(); smartlist_add_all(old_primary_guards, gs->primary_entry_guards); /* Set this flag now, to prevent the calls below from recursing. */ gs->primary_guards_up_to_date = 1; /* First, can we fill it up with confirmed guards? */ SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) { if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS) break; if (! guard->is_filtered_guard) continue; guard->is_primary = 1; smartlist_add(new_primary_guards, guard); } SMARTLIST_FOREACH_END(guard); /* Can we keep any older primary guards? First remove all the ones * that we already kept. */ SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) { if (smartlist_contains(new_primary_guards, guard)) { SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard); } } SMARTLIST_FOREACH_END(guard); /* Now add any that are still good. */ SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) { if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS) break; if (! guard->is_filtered_guard) continue; guard->is_primary = 1; smartlist_add(new_primary_guards, guard); SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard); } SMARTLIST_FOREACH_END(guard); /* Mark the remaining previous primary guards as non-primary */ SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) { guard->is_primary = 0; } SMARTLIST_FOREACH_END(guard); /* Finally, fill out the list with sampled guards. */ while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) { entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL, SAMPLE_EXCLUDE_CONFIRMED| SAMPLE_EXCLUDE_PRIMARY| SAMPLE_NO_UPDATE_PRIMARY); if (!guard) break; guard->is_primary = 1; smartlist_add(new_primary_guards, guard); } #if 1 /* Debugging. */ SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, { tor_assert_nonfatal( bool_eq(guard->is_primary, smartlist_contains(new_primary_guards, guard))); }); #endif int any_change = 0; if (smartlist_len(gs->primary_entry_guards) != smartlist_len(new_primary_guards)) { any_change = 1; } else { SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) { if (g != smartlist_get(new_primary_guards, g_sl_idx)) { any_change = 1; } } SMARTLIST_FOREACH_END(g); } if (any_change) { log_info(LD_GUARD, "Primary entry guards have changed. " "New primary guard list is: "); int n = smartlist_len(new_primary_guards); SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) { log_info(LD_GUARD, " %d/%d: %s%s%s", g_sl_idx+1, n, entry_guard_describe(g), g->confirmed_idx >= 0 ? " (confirmed)" : "", g->is_filtered_guard ? "" : " (excluded by filter)"); } SMARTLIST_FOREACH_END(g); } smartlist_free(old_primary_guards); smartlist_free(gs->primary_entry_guards); gs->primary_entry_guards = new_primary_guards; gs->primary_guards_up_to_date = 1; running = 0; } /** * Return the number of seconds after the last attempt at which we should * retry a guard that has been failing since <b>failing_since</b>. */ static int get_retry_schedule(time_t failing_since, time_t now, int is_primary) { const unsigned SIX_HOURS = 6 * 3600; const unsigned FOUR_DAYS = 4 * 86400; const unsigned SEVEN_DAYS = 7 * 86400; time_t tdiff; if (now > failing_since) { tdiff = now - failing_since; } else { tdiff = 0; } const struct { time_t maximum; int primary_delay; int nonprimary_delay; } delays[] = { { SIX_HOURS, 10*60, 1*60*60 }, { FOUR_DAYS, 90*60, 4*60*60 }, { SEVEN_DAYS, 4*60*60, 18*60*60 }, { TIME_MAX, 9*60*60, 36*60*60 } }; unsigned i; for (i = 0; i < ARRAY_LENGTH(delays); ++i) { if (tdiff <= delays[i].maximum) { return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay; } } /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */ tor_assert_nonfatal_unreached(); return 36*60*60; /* LCOV_EXCL_STOP */ } /** * If <b>guard</b> is unreachable, consider whether enough time has passed * to consider it maybe-reachable again. */ STATIC void entry_guard_consider_retry(entry_guard_t *guard) { if (guard->is_reachable != GUARD_REACHABLE_NO) return; /* No retry needed. */ const time_t now = approx_time(); const int delay = get_retry_schedule(guard->failing_since, now, guard->is_primary); const time_t last_attempt = guard->last_tried_to_connect; if (BUG(last_attempt == 0) || now >= last_attempt + delay) { /* We should mark this retriable. */ char tbuf[ISO_TIME_LEN+1]; format_local_iso_time(tbuf, last_attempt); log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we " "haven't tried to use it since %s.", guard->is_primary?"primary ":"", guard->confirmed_idx>=0?"confirmed ":"", entry_guard_describe(guard), tbuf); guard->is_reachable = GUARD_REACHABLE_MAYBE; if (guard->is_filtered_guard) guard->is_usable_filtered_guard = 1; } } /** Tell the entry guards subsystem that we have confirmed that as of * just now, we're on the internet. */ void entry_guards_note_internet_connectivity(guard_selection_t *gs) { gs->last_time_on_internet = approx_time(); } /** * Get a guard for use with a circuit. Prefer to pick a running primary * guard; then a non-pending running filtered confirmed guard; then a * non-pending runnable filtered guard. Update the * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the * guard as appropriate. Set <b>state_out</b> to the new guard-state * of the circuit. */ STATIC entry_guard_t * select_entry_guard_for_circuit(guard_selection_t *gs, guard_usage_t usage, const entry_guard_restriction_t *rst, unsigned *state_out) { const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC); tor_assert(gs); tor_assert(state_out); if (!gs->primary_guards_up_to_date) entry_guards_update_primary(gs); int num_entry_guards = get_n_primary_guards_to_use(usage); smartlist_t *usable_primary_guards = smartlist_new(); /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of <maybe> or <yes>, return the first such guard." */ SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) { entry_guard_consider_retry(guard); if (! entry_guard_obeys_restriction(guard, rst)) continue; if (guard->is_reachable != GUARD_REACHABLE_NO) { if (need_descriptor && !guard_has_descriptor(guard)) { continue; } *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION; guard->last_tried_to_connect = approx_time(); smartlist_add(usable_primary_guards, guard); if (smartlist_len(usable_primary_guards) >= num_entry_guards) break; } } SMARTLIST_FOREACH_END(guard); if (smartlist_len(usable_primary_guards)) { entry_guard_t *guard = smartlist_choose(usable_primary_guards); smartlist_free(usable_primary_guards); log_info(LD_GUARD, "Selected primary guard %s for circuit.", entry_guard_describe(guard)); return guard; } smartlist_free(usable_primary_guards); /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS} and {USABLE_FILTERED_GUARDS} is nonempty, return the first entry in that intersection that has {is_pending} set to false." */ SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) { if (guard->is_primary) continue; /* we already considered this one. */ if (! entry_guard_obeys_restriction(guard, rst)) continue; entry_guard_consider_retry(guard); if (guard->is_usable_filtered_guard && ! guard->is_pending) { if (need_descriptor && !guard_has_descriptor(guard)) continue; /* not a bug */ guard->is_pending = 1; guard->last_tried_to_connect = approx_time(); *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD; log_info(LD_GUARD, "No primary guards available. Selected confirmed " "guard %s for circuit. Will try other guards before using " "this circuit.", entry_guard_describe(guard)); return guard; } } SMARTLIST_FOREACH_END(guard); /* "Otherwise, if there is no such entry, select a member at random from {USABLE_FILTERED_GUARDS}." */ { entry_guard_t *guard; unsigned flags = 0; if (need_descriptor) flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR; guard = sample_reachable_filtered_entry_guards(gs, rst, SAMPLE_EXCLUDE_CONFIRMED | SAMPLE_EXCLUDE_PRIMARY | SAMPLE_EXCLUDE_PENDING | flags); if (guard == NULL) { log_info(LD_GUARD, "Absolutely no sampled guards were available. " "Marking all guards for retry and starting from top again."); mark_all_guards_maybe_reachable(gs); return NULL; } guard->is_pending = 1; guard->last_tried_to_connect = approx_time(); *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD; log_info(LD_GUARD, "No primary or confirmed guards available. Selected " "random guard %s for circuit. Will try other guards before " "using this circuit.", entry_guard_describe(guard)); return guard; } } /** * Note that we failed to connect to or build circuits through <b>guard</b>. * Use with a guard returned by select_entry_guard_for_circuit(). */ STATIC void entry_guards_note_guard_failure(guard_selection_t *gs, entry_guard_t *guard) { tor_assert(gs); guard->is_reachable = GUARD_REACHABLE_NO; guard->is_usable_filtered_guard = 0; guard->is_pending = 0; if (guard->failing_since == 0) guard->failing_since = approx_time(); log_info(LD_GUARD, "Recorded failure for %s%sguard %s", guard->is_primary?"primary ":"", guard->confirmed_idx>=0?"confirmed ":"", entry_guard_describe(guard)); } /** * Note that we successfully connected to, and built a circuit through * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>, * return the new guard-state of the circuit. * * Be aware: the circuit is only usable when its guard-state becomes * GUARD_CIRC_STATE_COMPLETE. **/ STATIC unsigned entry_guards_note_guard_success(guard_selection_t *gs, entry_guard_t *guard, unsigned old_state) { tor_assert(gs); /* Save this, since we're about to overwrite it. */ const time_t last_time_on_internet = gs->last_time_on_internet; gs->last_time_on_internet = approx_time(); guard->is_reachable = GUARD_REACHABLE_YES; guard->failing_since = 0; guard->is_pending = 0; if (guard->is_filtered_guard) guard->is_usable_filtered_guard = 1; if (guard->confirmed_idx < 0) { make_guard_confirmed(gs, guard); if (!gs->primary_guards_up_to_date) entry_guards_update_primary(gs); } unsigned new_state; switch (old_state) { case GUARD_CIRC_STATE_COMPLETE: case GUARD_CIRC_STATE_USABLE_ON_COMPLETION: new_state = GUARD_CIRC_STATE_COMPLETE; break; default: tor_assert_nonfatal_unreached(); /* Fall through. */ case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD: if (guard->is_primary) { /* XXXX #20832 -- I don't actually like this logic. It seems to make * us a little more susceptible to evil-ISP attacks. The mitigations * I'm thinking of, however, aren't local to this point, so I'll leave * it alone. */ /* This guard may have become primary by virtue of being confirmed. * If so, the circuit for it is now complete. */ new_state = GUARD_CIRC_STATE_COMPLETE; } else { new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD; } break; } if (! guard->is_primary) { if (last_time_on_internet + get_internet_likely_down_interval() < approx_time()) { mark_primary_guards_maybe_reachable(gs); } } log_info(LD_GUARD, "Recorded success for %s%sguard %s", guard->is_primary?"primary ":"", guard->confirmed_idx>=0?"confirmed ":"", entry_guard_describe(guard)); return new_state; } /** * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>. */ STATIC int entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b) { tor_assert(a && b); if (a == b) return 0; /* Confirmed is always better than unconfirmed; lower index better than higher */ if (a->confirmed_idx < 0) { if (b->confirmed_idx >= 0) return 0; } else { if (b->confirmed_idx < 0) return 1; /* Lower confirmed_idx is better than higher. */ return (a->confirmed_idx < b->confirmed_idx); } /* If we reach this point, both are unconfirmed. If one is pending, it * has higher priority. */ if (a->is_pending) { if (! b->is_pending) return 1; /* Both are pending: earlier last_tried_connect wins. */ return a->last_tried_to_connect < b->last_tried_to_connect; } else { if (b->is_pending) return 0; /* Neither is pending: priorities are equal. */ return 0; } } /** Release all storage held in <b>restriction</b> */ static void entry_guard_restriction_free(entry_guard_restriction_t *rst) { tor_free(rst); } /** * Release all storage held in <b>state</b>. */ void circuit_guard_state_free(circuit_guard_state_t *state) { if (!state) return; entry_guard_restriction_free(state->restrictions); entry_guard_handle_free(state->guard); tor_free(state); } /** * Pick a suitable entry guard for a circuit in, and place that guard * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque * state object that will record whether the circuit is ready to be used * or not. Return 0 on success; on failure, return -1. * * If a restriction is provided in <b>rst</b>, do not return any guards that * violate it, and remember that restriction in <b>guard_state_out</b> for * later use. (Takes ownership of the <b>rst</b> object.) */ int entry_guard_pick_for_circuit(guard_selection_t *gs, guard_usage_t usage, entry_guard_restriction_t *rst, const node_t **chosen_node_out, circuit_guard_state_t **guard_state_out) { tor_assert(gs); tor_assert(chosen_node_out); tor_assert(guard_state_out); *chosen_node_out = NULL; *guard_state_out = NULL; unsigned state = 0; entry_guard_t *guard = select_entry_guard_for_circuit(gs, usage, rst, &state); if (! guard) goto fail; if (BUG(state == 0)) goto fail; const node_t *node = node_get_by_id(guard->identity); // XXXX #20827 check Ed ID. if (! node) goto fail; if (BUG(usage != GUARD_USAGE_DIRGUARD && !node_has_descriptor(node))) goto fail; *chosen_node_out = node; *guard_state_out = tor_malloc_zero(sizeof(circuit_guard_state_t)); (*guard_state_out)->guard = entry_guard_handle_new(guard); (*guard_state_out)->state = state; (*guard_state_out)->state_set_at = approx_time(); (*guard_state_out)->restrictions = rst; return 0; fail: entry_guard_restriction_free(rst); return -1; } /** * Called by the circuit building module when a circuit has succeeded: informs * the guards code that the guard in *<b>guard_state_p</b> is working, and * advances the state of the guard module. On a GUARD_USABLE_NEVER return * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER * return value, the circuit should not be used until we find out whether * preferred guards will work for us. */ guard_usable_t entry_guard_succeeded(circuit_guard_state_t **guard_state_p) { if (BUG(*guard_state_p == NULL)) return GUARD_USABLE_NEVER; entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard); if (! guard || BUG(guard->in_selection == NULL)) return GUARD_USABLE_NEVER; unsigned newstate = entry_guards_note_guard_success(guard->in_selection, guard, (*guard_state_p)->state); (*guard_state_p)->state = newstate; (*guard_state_p)->state_set_at = approx_time(); if (newstate == GUARD_CIRC_STATE_COMPLETE) { return GUARD_USABLE_NOW; } else { return GUARD_MAYBE_USABLE_LATER; } } /** Cancel the selection of *<b>guard_state_p</b> without declaring * success or failure. It is safe to call this function if success or * failure _has_ already been declared. */ void entry_guard_cancel(circuit_guard_state_t **guard_state_p) { if (BUG(*guard_state_p == NULL)) return; entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard); if (! guard) return; /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this * function will only get called in "bug" cases anyway. */ guard->is_pending = 0; circuit_guard_state_free(*guard_state_p); *guard_state_p = NULL; } /** * Called by the circuit building module when a circuit has succeeded: * informs the guards code that the guard in *<b>guard_state_p</b> is * not working, and advances the state of the guard module. */ void entry_guard_failed(circuit_guard_state_t **guard_state_p) { if (BUG(*guard_state_p == NULL)) return; entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard); if (! guard || BUG(guard->in_selection == NULL)) return; entry_guards_note_guard_failure(guard->in_selection, guard); (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD; (*guard_state_p)->state_set_at = approx_time(); } /** * Run the entry_guard_failed() function on every circuit that is * pending on <b>chan</b>. */ void entry_guard_chan_failed(channel_t *chan) { if (!chan) return; smartlist_t *pending = smartlist_new(); circuit_get_all_pending_on_channel(pending, chan); SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) { if (!CIRCUIT_IS_ORIGIN(circ)) continue; origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ); if (origin_circ->guard_state) { /* We might have no guard state if we didn't use a guard on this * circuit (eg it's for a fallback directory). */ entry_guard_failed(&origin_circ->guard_state); } } SMARTLIST_FOREACH_END(circ); smartlist_free(pending); } /** * Return true iff every primary guard in <b>gs</b> is believed to * be unreachable. */ STATIC int entry_guards_all_primary_guards_are_down(guard_selection_t *gs) { tor_assert(gs); if (!gs->primary_guards_up_to_date) entry_guards_update_primary(gs); SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) { entry_guard_consider_retry(guard); if (guard->is_reachable != GUARD_REACHABLE_NO) return 0; } SMARTLIST_FOREACH_END(guard); return 1; } /** Wrapper for entry_guard_has_higher_priority that compares the * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher * priority than <b>b</b>. * * If a restriction is provided in <b>rst</b>, then do not consider * <b>a</b> to have higher priority if it violates the restriction. */ static int circ_state_has_higher_priority(origin_circuit_t *a, const entry_guard_restriction_t *rst, origin_circuit_t *b) { circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a); circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b); tor_assert(state_a); tor_assert(state_b); entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard); entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard); if (! guard_a) { /* Unknown guard -- never higher priority. */ return 0; } else if (! guard_b) { /* Known guard -- higher priority than any unknown guard. */ return 1; } else if (! entry_guard_obeys_restriction(guard_a, rst)) { /* Restriction violated; guard_a cannot have higher priority. */ return 0; } else { /* Both known -- compare.*/ return entry_guard_has_higher_priority(guard_a, guard_b); } } /** * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>, * and see if any of them that were previously not ready to use for * guard-related reasons are now ready to use. Place those circuits * in <b>newly_complete_out</b>, and mark them COMPLETE. * * Return 1 if we upgraded any circuits, and 0 otherwise. */ int entry_guards_upgrade_waiting_circuits(guard_selection_t *gs, const smartlist_t *all_circuits_in, smartlist_t *newly_complete_out) { tor_assert(gs); tor_assert(all_circuits_in); tor_assert(newly_complete_out); if (! entry_guards_all_primary_guards_are_down(gs)) { /* We only upgrade a waiting circuit if the primary guards are all * down. */ log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, " "but not all primary guards were definitely down."); return 0; } int n_waiting = 0; int n_complete = 0; int n_complete_blocking = 0; origin_circuit_t *best_waiting_circuit = NULL; smartlist_t *all_circuits = smartlist_new(); SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) { // We filter out circuits that aren't ours, or which we can't // reason about. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ); if (state == NULL) continue; entry_guard_t *guard = entry_guard_handle_get(state->guard); if (!guard || guard->in_selection != gs) continue; smartlist_add(all_circuits, circ); } SMARTLIST_FOREACH_END(circ); SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) { circuit_guard_state_t *state = origin_circuit_get_guard_state(circ); if BUG((state == NULL)) continue; if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) { ++n_waiting; if (! best_waiting_circuit || circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) { best_waiting_circuit = circ; } } } SMARTLIST_FOREACH_END(circ); if (! best_waiting_circuit) { log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, " "but didn't find any."); goto no_change; } /* We'll need to keep track of what restrictions were used when picking this * circuit, so that we don't allow any circuit without those restrictions to * block it. */ const entry_guard_restriction_t *rst_on_best_waiting = origin_circuit_get_guard_state(best_waiting_circuit)->restrictions; /* First look at the complete circuits: Do any block this circuit? */ SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) { /* "C2 "blocks" C1 if: * C2 obeys all the restrictions that C1 had to obey, AND * C2 has higher priority than C1, AND * Either C2 is <complete>, or C2 is <waiting_for_better_guard>, or C2 has been <usable_if_no_better_guard> for no more than {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds." */ circuit_guard_state_t *state = origin_circuit_get_guard_state(circ); if BUG((state == NULL)) continue; if (state->state != GUARD_CIRC_STATE_COMPLETE) continue; ++n_complete; if (circ_state_has_higher_priority(circ, rst_on_best_waiting, best_waiting_circuit)) ++n_complete_blocking; } SMARTLIST_FOREACH_END(circ); if (n_complete_blocking) { log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found " "%d complete and %d guard-stalled. At least one complete " "circuit had higher priority, so not upgrading.", n_complete, n_waiting); goto no_change; } /* " * If any circuit C1 is <waiting_for_better_guard>, AND: * All primary guards have reachable status of <no>. * There is no circuit C2 that "blocks" C1. Then, upgrade C1 to <complete>."" */ int n_blockers_found = 0; const time_t state_set_at_cutoff = approx_time() - get_nonprimary_guard_connect_timeout(); SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) { circuit_guard_state_t *state = origin_circuit_get_guard_state(circ); if (BUG(state == NULL)) continue; if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD) continue; if (state->state_set_at <= state_set_at_cutoff) continue; if (circ_state_has_higher_priority(circ, rst_on_best_waiting, best_waiting_circuit)) ++n_blockers_found; } SMARTLIST_FOREACH_END(circ); if (n_blockers_found) { log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found " "%d guard-stalled, but %d pending circuit(s) had higher " "guard priority, so not upgrading.", n_waiting, n_blockers_found); goto no_change; } /* Okay. We have a best waiting circuit, and we aren't waiting for anything better. Add all circuits with that priority to the list, and call them COMPLETE. */ int n_succeeded = 0; SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) { circuit_guard_state_t *state = origin_circuit_get_guard_state(circ); if (BUG(state == NULL)) continue; if (circ != best_waiting_circuit && rst_on_best_waiting) { /* Can't upgrade other circ with same priority as best; might be blocked. */ continue; } if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) continue; if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ)) continue; state->state = GUARD_CIRC_STATE_COMPLETE; state->state_set_at = approx_time(); smartlist_add(newly_complete_out, circ); ++n_succeeded; } SMARTLIST_FOREACH_END(circ); log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found " "%d guard-stalled, %d complete. %d of the guard-stalled " "circuit(s) had high enough priority to upgrade.", n_waiting, n_complete, n_succeeded); tor_assert_nonfatal(n_succeeded >= 1); smartlist_free(all_circuits); return 1; no_change: smartlist_free(all_circuits); return 0; } /** * Return true iff the circuit whose state is <b>guard_state</b> should * expire. */ int entry_guard_state_should_expire(circuit_guard_state_t *guard_state) { if (guard_state == NULL) return 0; const time_t expire_if_waiting_since = approx_time() - get_nonprimary_guard_idle_timeout(); return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD && guard_state->state_set_at < expire_if_waiting_since); } /** * Update all derived pieces of the guard selection state in <b>gs</b>. * Return true iff we should stop using all previously generated circuits. */ int entry_guards_update_all(guard_selection_t *gs) { sampled_guards_update_from_consensus(gs); entry_guards_update_filtered_sets(gs); entry_guards_update_confirmed(gs); entry_guards_update_primary(gs); return 0; } /** * Return a newly allocated string for encoding the persistent parts of * <b>guard</b> to the state file. */ STATIC char * entry_guard_encode_for_state(entry_guard_t *guard) { /* * The meta-format we use is K=V K=V K=V... where K can be any * characters excepts space and =, and V can be any characters except * space. The order of entries is not allowed to matter. * Unrecognized K=V entries are persisted; recognized but erroneous * entries are corrected. */ smartlist_t *result = smartlist_new(); char tbuf[ISO_TIME_LEN+1]; tor_assert(guard); smartlist_add_asprintf(result, "in=%s", guard->selection_name); smartlist_add_asprintf(result, "rsa_id=%s", hex_str(guard->identity, DIGEST_LEN)); if (guard->bridge_addr) { smartlist_add_asprintf(result, "bridge_addr=%s:%d", fmt_and_decorate_addr(&guard->bridge_addr->addr), guard->bridge_addr->port); } if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) { smartlist_add_asprintf(result, "nickname=%s", guard->nickname); } format_iso_time_nospace(tbuf, guard->sampled_on_date); smartlist_add_asprintf(result, "sampled_on=%s", tbuf); if (guard->sampled_by_version) { smartlist_add_asprintf(result, "sampled_by=%s", guard->sampled_by_version); } if (guard->unlisted_since_date > 0) { format_iso_time_nospace(tbuf, guard->unlisted_since_date); smartlist_add_asprintf(result, "unlisted_since=%s", tbuf); } smartlist_add_asprintf(result, "listed=%d", (int)guard->currently_listed); if (guard->confirmed_idx >= 0) { format_iso_time_nospace(tbuf, guard->confirmed_on_date); smartlist_add_asprintf(result, "confirmed_on=%s", tbuf); smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx); } const double EPSILON = 1.0e-6; /* Make a copy of the pathbias object, since we will want to update some of them */ guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb)); pb->use_successes = pathbias_get_use_success_count(guard); pb->successful_circuits_closed = pathbias_get_close_success_count(guard); #define PB_FIELD(field) do { \ if (pb->field >= EPSILON) { \ smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \ } \ } while (0) PB_FIELD(use_attempts); PB_FIELD(use_successes); PB_FIELD(circ_attempts); PB_FIELD(circ_successes); PB_FIELD(successful_circuits_closed); PB_FIELD(collapsed_circuits); PB_FIELD(unusable_circuits); PB_FIELD(timeouts); tor_free(pb); #undef PB_FIELD if (guard->extra_state_fields) smartlist_add_strdup(result, guard->extra_state_fields); char *joined = smartlist_join_strings(result, " ", 0, NULL); SMARTLIST_FOREACH(result, char *, cp, tor_free(cp)); smartlist_free(result); return joined; } /** * Given a string generated by entry_guard_encode_for_state(), parse it * (if possible) and return an entry_guard_t object for it. Return NULL * on complete failure. */ STATIC entry_guard_t * entry_guard_parse_from_state(const char *s) { /* Unrecognized entries get put in here. */ smartlist_t *extra = smartlist_new(); /* These fields get parsed from the string. */ char *in = NULL; char *rsa_id = NULL; char *nickname = NULL; char *sampled_on = NULL; char *sampled_by = NULL; char *unlisted_since = NULL; char *listed = NULL; char *confirmed_on = NULL; char *confirmed_idx = NULL; char *bridge_addr = NULL; // pathbias char *pb_use_attempts = NULL; char *pb_use_successes = NULL; char *pb_circ_attempts = NULL; char *pb_circ_successes = NULL; char *pb_successful_circuits_closed = NULL; char *pb_collapsed_circuits = NULL; char *pb_unusable_circuits = NULL; char *pb_timeouts = NULL; /* Split up the entries. Put the ones we know about in strings and the * rest in "extra". */ { smartlist_t *entries = smartlist_new(); strmap_t *vals = strmap_new(); // Maps keyword to location #define FIELD(f) \ strmap_set(vals, #f, &f); FIELD(in); FIELD(rsa_id); FIELD(nickname); FIELD(sampled_on); FIELD(sampled_by); FIELD(unlisted_since); FIELD(listed); FIELD(confirmed_on); FIELD(confirmed_idx); FIELD(bridge_addr); FIELD(pb_use_attempts); FIELD(pb_use_successes); FIELD(pb_circ_attempts); FIELD(pb_circ_successes); FIELD(pb_successful_circuits_closed); FIELD(pb_collapsed_circuits); FIELD(pb_unusable_circuits); FIELD(pb_timeouts); #undef FIELD smartlist_split_string(entries, s, " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0); SMARTLIST_FOREACH_BEGIN(entries, char *, entry) { const char *eq = strchr(entry, '='); if (!eq) { smartlist_add(extra, entry); continue; } char *key = tor_strndup(entry, eq-entry); char **target = strmap_get(vals, key); if (target == NULL || *target != NULL) { /* unrecognized or already set */ smartlist_add(extra, entry); tor_free(key); continue; } *target = tor_strdup(eq+1); tor_free(key); tor_free(entry); } SMARTLIST_FOREACH_END(entry); smartlist_free(entries); strmap_free(vals, NULL); } entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t)); guard->is_persistent = 1; if (in == NULL) { log_warn(LD_CIRC, "Guard missing 'in' field"); goto err; } guard->selection_name = in; in = NULL; if (rsa_id == NULL) { log_warn(LD_CIRC, "Guard missing RSA ID field"); goto err; } /* Process the identity and nickname. */ if (base16_decode(guard->identity, sizeof(guard->identity), rsa_id, strlen(rsa_id)) != DIGEST_LEN) { log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id)); goto err; } if (nickname) { strlcpy(guard->nickname, nickname, sizeof(guard->nickname)); } else { guard->nickname[0]='$'; base16_encode(guard->nickname+1, sizeof(guard->nickname)-1, guard->identity, DIGEST_LEN); } if (bridge_addr) { tor_addr_port_t res; memset(&res, 0, sizeof(res)); int r = tor_addr_port_parse(LOG_WARN, bridge_addr, &res.addr, &res.port, -1); if (r == 0) guard->bridge_addr = tor_memdup(&res, sizeof(res)); /* On error, we already warned. */ } /* Process the various time fields. */ #define HANDLE_TIME(field) do { \ if (field) { \ int r = parse_iso_time_nospace(field, &field ## _time); \ if (r < 0) { \ log_warn(LD_CIRC, "Unable to parse %s %s from guard", \ #field, escaped(field)); \ field##_time = -1; \ } \ } \ } while (0) time_t sampled_on_time = 0; time_t unlisted_since_time = 0; time_t confirmed_on_time = 0; HANDLE_TIME(sampled_on); HANDLE_TIME(unlisted_since); HANDLE_TIME(confirmed_on); if (sampled_on_time <= 0) sampled_on_time = approx_time(); if (unlisted_since_time < 0) unlisted_since_time = 0; if (confirmed_on_time < 0) confirmed_on_time = 0; #undef HANDLE_TIME guard->sampled_on_date = sampled_on_time; guard->unlisted_since_date = unlisted_since_time; guard->confirmed_on_date = confirmed_on_time; /* Take sampled_by_version verbatim. */ guard->sampled_by_version = sampled_by; sampled_by = NULL; /* prevent free */ /* Listed is a boolean */ if (listed && strcmp(listed, "0")) guard->currently_listed = 1; /* The index is a nonnegative integer. */ guard->confirmed_idx = -1; if (confirmed_idx) { int ok=1; long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL); if (! ok) { log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s", escaped(confirmed_idx)); } else { guard->confirmed_idx = (int)idx; } } /* Anything we didn't recognize gets crammed together */ if (smartlist_len(extra) > 0) { guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL); } /* initialize non-persistent fields */ guard->is_reachable = GUARD_REACHABLE_MAYBE; #define PB_FIELD(field) \ do { \ if (pb_ ## field) { \ int ok = 1; \ double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \ if (! ok) { \ log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \ #field, pb_ ## field); \ } else { \ guard->pb.field = r; \ } \ } \ } while (0) PB_FIELD(use_attempts); PB_FIELD(use_successes); PB_FIELD(circ_attempts); PB_FIELD(circ_successes); PB_FIELD(successful_circuits_closed); PB_FIELD(collapsed_circuits); PB_FIELD(unusable_circuits); PB_FIELD(timeouts); #undef PB_FIELD pathbias_check_use_success_count(guard); pathbias_check_close_success_count(guard); /* We update everything on this guard later, after we've parsed * everything. */ goto done; err: // only consider it an error if the guard state was totally unparseable. entry_guard_free(guard); guard = NULL; done: tor_free(in); tor_free(rsa_id); tor_free(nickname); tor_free(sampled_on); tor_free(sampled_by); tor_free(unlisted_since); tor_free(listed); tor_free(confirmed_on); tor_free(confirmed_idx); tor_free(bridge_addr); tor_free(pb_use_attempts); tor_free(pb_use_successes); tor_free(pb_circ_attempts); tor_free(pb_circ_successes); tor_free(pb_successful_circuits_closed); tor_free(pb_collapsed_circuits); tor_free(pb_unusable_circuits); tor_free(pb_timeouts); SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp)); smartlist_free(extra); return guard; } /** * Replace the Guards entries in <b>state</b> with a list of all our sampled * guards. */ static void entry_guards_update_guards_in_state(or_state_t *state) { if (!guard_contexts) return; config_line_t *lines = NULL; config_line_t **nextline = &lines; SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) { SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { if (guard->is_persistent == 0) continue; *nextline = tor_malloc_zero(sizeof(config_line_t)); (*nextline)->key = tor_strdup("Guard"); (*nextline)->value = entry_guard_encode_for_state(guard); nextline = &(*nextline)->next; } SMARTLIST_FOREACH_END(guard); } SMARTLIST_FOREACH_END(gs); config_free_lines(state->Guard); state->Guard = lines; } /** * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0 * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only * check whether replacing would work.) */ static int entry_guards_load_guards_from_state(or_state_t *state, int set) { const config_line_t *line = state->Guard; int n_errors = 0; if (!guard_contexts) guard_contexts = smartlist_new(); /* Wipe all our existing guard info. (we shouldn't have any, but * let's be safe.) */ if (set) { SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) { guard_selection_free(gs); if (curr_guard_context == gs) curr_guard_context = NULL; SMARTLIST_DEL_CURRENT(guard_contexts, gs); } SMARTLIST_FOREACH_END(gs); } for ( ; line != NULL; line = line->next) { entry_guard_t *guard = entry_guard_parse_from_state(line->value); if (guard == NULL) { ++n_errors; continue; } tor_assert(guard->selection_name); if (!strcmp(guard->selection_name, "legacy")) { ++n_errors; entry_guard_free(guard); continue; } if (set) { guard_selection_t *gs; gs = get_guard_selection_by_name(guard->selection_name, GS_TYPE_INFER, 1); tor_assert(gs); smartlist_add(gs->sampled_entry_guards, guard); guard->in_selection = gs; } else { entry_guard_free(guard); } } if (set) { SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) { entry_guards_update_all(gs); } SMARTLIST_FOREACH_END(gs); } return n_errors ? -1 : 0; } /** If <b>digest</b> matches the identity of any node in the * entry_guards list for the provided guard selection state, return that node. Else return NULL. */ entry_guard_t * entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs, const char *digest) { return get_sampled_guard_with_id(gs, (const uint8_t*)digest); } /** Return the node_t associated with a single entry_guard_t. May * return NULL if the guard is not currently in the consensus. */ const node_t * entry_guard_find_node(const entry_guard_t *guard) { tor_assert(guard); return node_get_by_id(guard->identity); } /** If <b>digest</b> matches the identity of any node in the * entry_guards list for the default guard selection state, return that node. Else return NULL. */ entry_guard_t * entry_guard_get_by_id_digest(const char *digest) { return entry_guard_get_by_id_digest_for_guard_selection( get_guard_selection_info(), digest); } /** Release all storage held by <b>e</b>. */ STATIC void entry_guard_free(entry_guard_t *e) { if (!e) return; entry_guard_handles_clear(e); tor_free(e->sampled_by_version); tor_free(e->extra_state_fields); tor_free(e->selection_name); tor_free(e->bridge_addr); tor_free(e); } /** Return 0 if we're fine adding arbitrary routers out of the * directory to our entry guard list, or return 1 if we have a * list already and we must stick to it. */ int entry_list_is_constrained(const or_options_t *options) { // XXXX #21425 look at the current selection. if (options->EntryNodes) return 1; if (options->UseBridges) return 1; return 0; } /** Return the number of bridges that have descriptors that are marked with * purpose 'bridge' and are running. */ int num_bridges_usable(void) { int n_options = 0; tor_assert(get_options()->UseBridges); guard_selection_t *gs = get_guard_selection_info(); tor_assert(gs->type == GS_TYPE_BRIDGE); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { if (guard->is_reachable == GUARD_REACHABLE_NO) continue; if (tor_digest_is_zero(guard->identity)) continue; const node_t *node = node_get_by_id(guard->identity); if (node && node->ri) ++n_options; } SMARTLIST_FOREACH_END(guard); return n_options; } /** Check the pathbias use success count of <b>node</b> and disable it if it * goes over our thresholds. */ static void pathbias_check_use_success_count(entry_guard_t *node) { const or_options_t *options = get_options(); const double EPSILON = 1.0e-9; /* Note: We rely on the < comparison here to allow us to set a 0 * rate and disable the feature entirely. If refactoring, don't * change to <= */ if (node->pb.use_attempts > EPSILON && pathbias_get_use_success_count(node)/node->pb.use_attempts < pathbias_get_extreme_use_rate(options) && pathbias_get_dropguards(options)) { node->pb.path_bias_disabled = 1; log_info(LD_GENERAL, "Path use bias is too high (%f/%f); disabling node %s", node->pb.circ_successes, node->pb.circ_attempts, node->nickname); } } /** Check the pathbias close count of <b>node</b> and disable it if it goes * over our thresholds. */ static void pathbias_check_close_success_count(entry_guard_t *node) { const or_options_t *options = get_options(); const double EPSILON = 1.0e-9; /* Note: We rely on the < comparison here to allow us to set a 0 * rate and disable the feature entirely. If refactoring, don't * change to <= */ if (node->pb.circ_attempts > EPSILON && pathbias_get_close_success_count(node)/node->pb.circ_attempts < pathbias_get_extreme_rate(options) && pathbias_get_dropguards(options)) { node->pb.path_bias_disabled = 1; log_info(LD_GENERAL, "Path bias is too high (%f/%f); disabling node %s", node->pb.circ_successes, node->pb.circ_attempts, node->nickname); } } /** Parse <b>state</b> and learn about the entry guards it describes. * If <b>set</b> is true, and there are no errors, replace the guard * list in the default guard selection context with what we find. * On success, return 0. On failure, alloc into *<b>msg</b> a string * describing the error, and return -1. */ int entry_guards_parse_state(or_state_t *state, int set, char **msg) { entry_guards_dirty = 0; int r1 = entry_guards_load_guards_from_state(state, set); entry_guards_dirty = 0; if (r1 < 0) { if (msg && *msg == NULL) { *msg = tor_strdup("parsing error"); } return -1; } return 0; } /** How long will we let a change in our guard nodes stay un-saved * when we are trying to avoid disk writes? */ #define SLOW_GUARD_STATE_FLUSH_TIME 600 /** How long will we let a change in our guard nodes stay un-saved * when we are not trying to avoid disk writes? */ #define FAST_GUARD_STATE_FLUSH_TIME 30 /** Our list of entry guards has changed for a particular guard selection * context, or some element of one of our entry guards has changed for one. * Write the changes to disk within the next few minutes. */ void entry_guards_changed_for_guard_selection(guard_selection_t *gs) { time_t when; tor_assert(gs != NULL); entry_guards_dirty = 1; if (get_options()->AvoidDiskWrites) when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME; else when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME; /* or_state_save() will call entry_guards_update_state() and entry_guards_update_guards_in_state() */ or_state_mark_dirty(get_or_state(), when); } /** Our list of entry guards has changed for the default guard selection * context, or some element of one of our entry guards has changed. Write * the changes to disk within the next few minutes. */ void entry_guards_changed(void) { entry_guards_changed_for_guard_selection(get_guard_selection_info()); } /** If the entry guard info has not changed, do nothing and return. * Otherwise, free the EntryGuards piece of <b>state</b> and create * a new one out of the global entry_guards list, and then mark * <b>state</b> dirty so it will get saved to disk. */ void entry_guards_update_state(or_state_t *state) { entry_guards_dirty = 0; // Handles all guard info. entry_guards_update_guards_in_state(state); entry_guards_dirty = 0; if (!get_options()->AvoidDiskWrites) or_state_mark_dirty(get_or_state(), 0); entry_guards_dirty = 0; } /** * Format a single entry guard in the format expected by the controller. * Return a newly allocated string. */ STATIC char * getinfo_helper_format_single_entry_guard(const entry_guard_t *e) { const char *status = NULL; time_t when = 0; const node_t *node; char tbuf[ISO_TIME_LEN+1]; char nbuf[MAX_VERBOSE_NICKNAME_LEN+1]; /* This is going to be a bit tricky, since the status * codes weren't really intended for prop271 guards. * * XXXX use a more appropriate format for exporting this information */ if (e->confirmed_idx < 0) { status = "never-connected"; } else if (! e->currently_listed) { when = e->unlisted_since_date; status = "unusable"; } else if (! e->is_filtered_guard) { status = "unusable"; } else if (e->is_reachable == GUARD_REACHABLE_NO) { when = e->failing_since; status = "down"; } else { status = "up"; } node = entry_guard_find_node(e); if (node) { node_get_verbose_nickname(node, nbuf); } else { nbuf[0] = '$'; base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN); /* e->nickname field is not very reliable if we don't know about * this router any longer; don't include it. */ } char *result = NULL; if (when) { format_iso_time(tbuf, when); tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf); } else { tor_asprintf(&result, "%s %s\n", nbuf, status); } return result; } /** If <b>question</b> is the string "entry-guards", then dump * to *<b>answer</b> a newly allocated string describing all of * the nodes in the global entry_guards list. See control-spec.txt * for details. * For backward compatibility, we also handle the string "helper-nodes". * * XXX this should be totally redesigned after prop 271 too, and that's * going to take some control spec work. * */ int getinfo_helper_entry_guards(control_connection_t *conn, const char *question, char **answer, const char **errmsg) { guard_selection_t *gs = get_guard_selection_info(); tor_assert(gs != NULL); (void) conn; (void) errmsg; if (!strcmp(question,"entry-guards") || !strcmp(question,"helper-nodes")) { const smartlist_t *guards; guards = gs->sampled_entry_guards; smartlist_t *sl = smartlist_new(); SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) { char *cp = getinfo_helper_format_single_entry_guard(e); smartlist_add(sl, cp); } SMARTLIST_FOREACH_END(e); *answer = smartlist_join_strings(sl, "", 0, NULL); SMARTLIST_FOREACH(sl, char *, c, tor_free(c)); smartlist_free(sl); } return 0; } /* Given the original bandwidth of a guard and its guardfraction, * calculate how much bandwidth the guard should have as a guard and * as a non-guard. * * Quoting from proposal236: * * Let Wpf denote the weight from the 'bandwidth-weights' line a * client would apply to N for position p if it had the guard * flag, Wpn the weight if it did not have the guard flag, and B the * measured bandwidth of N in the consensus. Then instead of choosing * N for position p proportionally to Wpf*B or Wpn*B, clients should * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B. * * This function fills the <b>guardfraction_bw</b> structure. It sets * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B. */ void guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw, int orig_bandwidth, uint32_t guardfraction_percentage) { double guardfraction_fraction; /* Turn the percentage into a fraction. */ tor_assert(guardfraction_percentage <= 100); guardfraction_fraction = guardfraction_percentage / 100.0; long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth); tor_assert(guard_bw <= INT_MAX); guardfraction_bw->guard_bw = (int) guard_bw; guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw; } /** Helper: Update the status of all entry guards, in whatever algorithm * is used. Return true if we should stop using all previously generated * circuits, by calling circuit_mark_all_unused_circs() and * circuit_mark_all_dirty_circs_as_unusable(). */ int guards_update_all(void) { int mark_circuits = 0; if (update_guard_selection_choice(get_options())) mark_circuits = 1; tor_assert(curr_guard_context); if (entry_guards_update_all(curr_guard_context)) mark_circuits = 1; return mark_circuits; } /** Helper: pick a guard for a circuit, with whatever algorithm is used. */ const node_t * guards_choose_guard(cpath_build_state_t *state, circuit_guard_state_t **guard_state_out) { const node_t *r = NULL; const uint8_t *exit_id = NULL; entry_guard_restriction_t *rst = NULL; if (state && (exit_id = build_state_get_exit_rsa_id(state))) { /* We're building to a targeted exit node, so that node can't be * chosen as our guard for this circuit. Remember that fact in a * restriction. */ rst = tor_malloc_zero(sizeof(entry_guard_restriction_t)); memcpy(rst->exclude_id, exit_id, DIGEST_LEN); } if (entry_guard_pick_for_circuit(get_guard_selection_info(), GUARD_USAGE_TRAFFIC, rst, &r, guard_state_out) < 0) { tor_assert(r == NULL); } return r; } /** Remove all currently listed entry guards for a given guard selection * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b> * after calling this function. */ void remove_all_entry_guards_for_guard_selection(guard_selection_t *gs) { // This function shouldn't exist. XXXX tor_assert(gs != NULL); char *old_name = tor_strdup(gs->name); guard_selection_type_t old_type = gs->type; SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, { control_event_guard(entry->nickname, entry->identity, "DROPPED"); }); if (gs == curr_guard_context) { curr_guard_context = NULL; } smartlist_remove(guard_contexts, gs); guard_selection_free(gs); gs = get_guard_selection_by_name(old_name, old_type, 1); entry_guards_changed_for_guard_selection(gs); tor_free(old_name); } /** Remove all currently listed entry guards, so new ones will be chosen. * * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS * command, which is deprecated. */ void remove_all_entry_guards(void) { remove_all_entry_guards_for_guard_selection(get_guard_selection_info()); } /** Helper: pick a directory guard, with whatever algorithm is used. */ const node_t * guards_choose_dirguard(circuit_guard_state_t **guard_state_out) { const node_t *r = NULL; if (entry_guard_pick_for_circuit(get_guard_selection_info(), GUARD_USAGE_DIRGUARD, NULL, &r, guard_state_out) < 0) { tor_assert(r == NULL); } return r; } /** * If we're running with a constrained guard set, then maybe mark our guards * usable. Return 1 if we do; 0 if we don't. */ int guards_retry_optimistic(const or_options_t *options) { if (! entry_list_is_constrained(options)) return 0; mark_primary_guards_maybe_reachable(get_guard_selection_info()); return 1; } /** * Return true iff we know enough directory information to construct * circuits through all of the primary guards we'd currently use. */ int guard_selection_have_enough_dir_info_to_build_circuits(guard_selection_t *gs) { if (!gs->primary_guards_up_to_date) entry_guards_update_primary(gs); int n_missing_descriptors = 0; int n_considered = 0; int num_primary_to_check; /* We want to check for the descriptor of at least the first two primary * guards in our list, since these are the guards that we typically use for * circuits. */ num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC); num_primary_to_check++; SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) { entry_guard_consider_retry(guard); if (guard->is_reachable == GUARD_REACHABLE_NO) continue; n_considered++; if (!guard_has_descriptor(guard)) n_missing_descriptors++; if (n_considered >= num_primary_to_check) break; } SMARTLIST_FOREACH_END(guard); return n_missing_descriptors == 0; } /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses * the default guard selection. */ int entry_guards_have_enough_dir_info_to_build_circuits(void) { return guard_selection_have_enough_dir_info_to_build_circuits( get_guard_selection_info()); } /** Free one guard selection context */ STATIC void guard_selection_free(guard_selection_t *gs) { if (!gs) return; tor_free(gs->name); if (gs->sampled_entry_guards) { SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e, entry_guard_free(e)); smartlist_free(gs->sampled_entry_guards); gs->sampled_entry_guards = NULL; } smartlist_free(gs->confirmed_entry_guards); smartlist_free(gs->primary_entry_guards); tor_free(gs); } /** Release all storage held by the list of entry guards and related * memory structs. */ void entry_guards_free_all(void) { /* Null out the default */ curr_guard_context = NULL; /* Free all the guard contexts */ if (guard_contexts != NULL) { SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) { guard_selection_free(gs); } SMARTLIST_FOREACH_END(gs); smartlist_free(guard_contexts); guard_contexts = NULL; } circuit_build_times_free_timeouts(get_circuit_build_times_mutable()); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2490_1
crossvul-cpp_data_good_3568_6
/* -*- Mode: c; c-basic-offset: 2 -*- * * raptor_libxml.c - Raptor libxml functions * * Copyright (C) 2000-2009, David Beckett http://www.dajobe.org/ * Copyright (C) 2000-2004, 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 /* Raptor includes */ #include "raptor2.h" #include "raptor_internal.h" #ifdef RAPTOR_XML_LIBXML /* prototypes */ static void raptor_libxml_warning(void* user_data, const char *msg, ...) RAPTOR_PRINTF_FORMAT(2, 3); static void raptor_libxml_error_common(void* user_data, const char *msg, va_list args, const char *prefix, int is_fatal) RAPTOR_PRINTF_FORMAT(2, 0); static void raptor_libxml_error(void *context, const char *msg, ...) RAPTOR_PRINTF_FORMAT(2, 3); static void raptor_libxml_fatal_error(void *context, const char *msg, ...) RAPTOR_PRINTF_FORMAT(2, 3); static void raptor_libxml_xmlStructuredError_handler_global(void *user_data, xmlErrorPtr err); static void raptor_libxml_xmlStructuredError_handler_parsing(void *user_data, xmlErrorPtr err); static const char* const xml_warning_prefix="XML parser warning - "; static const char* const xml_error_prefix="XML parser error - "; static const char* const xml_generic_error_prefix="XML error - "; static const char* const xml_fatal_error_prefix="XML parser fatal error - "; static const char* const xml_validation_error_prefix="XML parser validation error - "; static const char* const xml_validation_warning_prefix="XML parser validation warning - "; #ifdef HAVE_XMLSAX2INTERNALSUBSET /* SAX2 - 2.6.0 or later */ #define libxml2_internalSubset xmlSAX2InternalSubset #define libxml2_externalSubset xmlSAX2ExternalSubset #define libxml2_isStandalone xmlSAX2IsStandalone #define libxml2_hasInternalSubset xmlSAX2HasInternalSubset #define libxml2_hasExternalSubset xmlSAX2HasExternalSubset #define libxml2_resolveEntity xmlSAX2ResolveEntity #define libxml2_getEntity xmlSAX2GetEntity #define libxml2_getParameterEntity xmlSAX2GetParameterEntity #define libxml2_entityDecl xmlSAX2EntityDecl #define libxml2_unparsedEntityDecl xmlSAX2UnparsedEntityDecl #define libxml2_startDocument xmlSAX2StartDocument #define libxml2_endDocument xmlSAX2EndDocument #else /* SAX1 - before libxml2 2.6.0 */ #define libxml2_internalSubset internalSubset #define libxml2_externalSubset externalSubset #define libxml2_isStandalone isStandalone #define libxml2_hasInternalSubset hasInternalSubset #define libxml2_hasExternalSubset hasExternalSubset #define libxml2_resolveEntity resolveEntity #define libxml2_getEntity getEntity #define libxml2_getParameterEntity getParameterEntity #define libxml2_entityDecl entityDecl #define libxml2_unparsedEntityDecl unparsedEntityDecl #define libxml2_startDocument startDocument #define libxml2_endDocument endDocument #endif static void raptor_libxml_internalSubset(void* user_data, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { raptor_sax2* sax2 = (raptor_sax2*)user_data; libxml2_internalSubset(sax2->xc, name, ExternalID, SystemID); } #ifdef RAPTOR_LIBXML_XMLSAXHANDLER_EXTERNALSUBSET static void raptor_libxml_externalSubset(void* user_data, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { raptor_sax2* sax2 = (raptor_sax2*)user_data; libxml2_externalSubset(sax2->xc, name, ExternalID, SystemID); } #endif static int raptor_libxml_isStandalone (void* user_data) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_isStandalone(sax2->xc); } static int raptor_libxml_hasInternalSubset (void* user_data) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_hasInternalSubset(sax2->xc); } static int raptor_libxml_hasExternalSubset (void* user_data) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_hasExternalSubset(sax2->xc); } static xmlParserInputPtr raptor_libxml_resolveEntity(void* user_data, const xmlChar *publicId, const xmlChar *systemId) { raptor_sax2* sax2 = (raptor_sax2*)user_data; xmlParserCtxtPtr ctxt = sax2->xc; const unsigned char *uri_string = NULL; xmlParserInputPtr entity_input; int load_entity = 0; if(ctxt->input) uri_string = RAPTOR_GOOD_CAST(const unsigned char *, ctxt->input->filename); if(!uri_string) uri_string = RAPTOR_GOOD_CAST(const unsigned char *, ctxt->directory); load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES); if(load_entity) load_entity = raptor_sax2_check_load_uri_string(sax2, uri_string); if(load_entity) { entity_input = xmlLoadExternalEntity(RAPTOR_GOOD_CAST(const char*, uri_string), RAPTOR_GOOD_CAST(const char*, publicId), ctxt); } else { RAPTOR_DEBUG4("Not loading entity URI %s by policy for publicId '%s' systemId '%s'\n", uri_string, publicId, systemId); } return entity_input; } static xmlEntityPtr raptor_libxml_getEntity(void* user_data, const xmlChar *name) { raptor_sax2* sax2 = (raptor_sax2*)user_data; xmlParserCtxtPtr xc = sax2->xc; xmlEntityPtr ret = NULL; if(!xc) return NULL; if(!xc->inSubset) { /* looks for hardcoded set of entity names - lt, gt etc. */ ret = xmlGetPredefinedEntity(name); if(ret) { RAPTOR_DEBUG2("Entity '%s' found in predefined set\n", name); return ret; } } /* This section uses xmlGetDocEntity which looks for entities in * memory only, never from a file or URI */ if(xc->myDoc && (xc->myDoc->standalone == 1)) { RAPTOR_DEBUG2("Entity '%s' document is standalone\n", name); /* Document is standalone: no entities are required to interpret doc */ if(xc->inSubset == 2) { xc->myDoc->standalone = 0; ret = xmlGetDocEntity(xc->myDoc, name); xc->myDoc->standalone = 1; } else { ret = xmlGetDocEntity(xc->myDoc, name); if(!ret) { xc->myDoc->standalone = 0; ret = xmlGetDocEntity(xc->myDoc, name); xc->myDoc->standalone = 1; } } } else { ret = xmlGetDocEntity(xc->myDoc, name); } if(ret && !ret->children && (ret->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { /* Entity is an external general parsed entity. It may be in a * catalog file, user file or user URI */ int val = 0; xmlNodePtr children; int load_entity = 0; load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES); if(load_entity) load_entity = raptor_sax2_check_load_uri_string(sax2, ret->URI); if(!load_entity) { RAPTOR_DEBUG2("Not getting entity URI %s by policy\n", ret->URI); children = xmlNewText((const xmlChar*)""); } else { /* Disable SAX2 handlers so that the SAX2 events do not all get * sent to callbacks during dealing with the entity parsing. */ sax2->enabled = 0; val = xmlParseCtxtExternalEntity(xc, ret->URI, ret->ExternalID, &children); sax2->enabled = 1; } if(!val) { xmlAddChildList((xmlNodePtr)ret, children); } else { xc->validate = 0; return NULL; } ret->owner = 1; /* Mark this entity as having been checked - never do this again */ if(!ret->checked) ret->checked = 1; } return ret; } static xmlEntityPtr raptor_libxml_getParameterEntity(void* user_data, const xmlChar *name) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_getParameterEntity(sax2->xc, name); } static void raptor_libxml_entityDecl(void* user_data, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content) { raptor_sax2* sax2 = (raptor_sax2*)user_data; libxml2_entityDecl(sax2->xc, name, type, publicId, systemId, content); } static void raptor_libxml_unparsedEntityDecl(void* user_data, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName) { raptor_sax2* sax2 = (raptor_sax2*)user_data; libxml2_unparsedEntityDecl(sax2->xc, name, publicId, systemId, notationName); } static void raptor_libxml_startDocument(void* user_data) { raptor_sax2* sax2 = (raptor_sax2*)user_data; libxml2_startDocument(sax2->xc); } static void raptor_libxml_endDocument(void* user_data) { raptor_sax2* sax2 = (raptor_sax2*)user_data; xmlParserCtxtPtr xc = sax2->xc; libxml2_endDocument(sax2->xc); if(xc->myDoc) { xmlFreeDoc(xc->myDoc); xc->myDoc = NULL; } } static void raptor_libxml_set_document_locator(void* user_data, xmlSAXLocatorPtr loc) { raptor_sax2* sax2 = (raptor_sax2*)user_data; sax2->loc = loc; } void raptor_libxml_update_document_locator(raptor_sax2* sax2, raptor_locator* locator) { /* for storing error info */ xmlSAXLocatorPtr loc = sax2 ? sax2->loc : NULL; xmlParserCtxtPtr xc= sax2 ? sax2->xc : NULL; if(xc && xc->inSubset) return; if(!locator) return; locator->line= -1; locator->column= -1; if(!xc) return; if(loc) { locator->line = loc->getLineNumber(xc); /* Seems to be broken */ /* locator->column = loc->getColumnNumber(xc); */ } } static void raptor_libxml_warning(void* user_data, const char *msg, ...) { raptor_sax2* sax2 = NULL; va_list args; int prefix_length = RAPTOR_BAD_CAST(int, strlen(xml_warning_prefix)); int length; char *nmsg; int msg_len; /* Work around libxml2 bug - sometimes the sax2->error * returns a ctx, sometimes the userdata */ if(((raptor_sax2*)user_data)->magic == RAPTOR_LIBXML_MAGIC) sax2 = (raptor_sax2*)user_data; else /* user_data is not userData */ sax2 = (raptor_sax2*)((xmlParserCtxtPtr)user_data)->userData; va_start(args, msg); raptor_libxml_update_document_locator(sax2, sax2->locator); msg_len = RAPTOR_BAD_CAST(int, strlen(msg)); length = prefix_length + msg_len + 1; nmsg = RAPTOR_MALLOC(char*, length); if(nmsg) { memcpy(nmsg, xml_warning_prefix, prefix_length); /* Do not copy NUL */ memcpy(nmsg + prefix_length, msg, msg_len + 1); /* Copy NUL */ if(nmsg[length-2] == '\n') nmsg[length-2]='\0'; } raptor_log_error_varargs(sax2->world, RAPTOR_LOG_LEVEL_WARN, sax2->locator, nmsg ? nmsg : msg, args); if(nmsg) RAPTOR_FREE(char*, nmsg); va_end(args); } static void raptor_libxml_error_common(void* user_data, const char *msg, va_list args, const char *prefix, int is_fatal) { raptor_sax2* sax2 = NULL; int prefix_length = RAPTOR_BAD_CAST(int, strlen(prefix)); int length; char *nmsg; int msg_len; raptor_world* world = NULL; raptor_locator* locator = NULL; if(user_data) { /* Work around libxml2 bug - sometimes the sax2->error * returns a user_data, sometimes the userdata */ if(((raptor_sax2*)user_data)->magic == RAPTOR_LIBXML_MAGIC) sax2 = (raptor_sax2*)user_data; else /* user_data is not userData */ sax2 = (raptor_sax2*)((xmlParserCtxtPtr)user_data)->userData; } if(sax2) { world = sax2->world; locator = sax2->locator; if(locator) raptor_libxml_update_document_locator(sax2, sax2->locator); } msg_len = RAPTOR_BAD_CAST(int, strlen(msg)); length = prefix_length + msg_len + 1; nmsg = RAPTOR_MALLOC(char*, length); if(nmsg) { memcpy(nmsg, prefix, prefix_length); /* Do not copy NUL */ memcpy(nmsg + prefix_length, msg, msg_len + 1); /* Copy NUL */ if(nmsg[length-1] == '\n') nmsg[length-1]='\0'; } if(is_fatal) raptor_log_error_varargs(world, RAPTOR_LOG_LEVEL_FATAL, locator, nmsg ? nmsg : msg, args); else raptor_log_error_varargs(world, RAPTOR_LOG_LEVEL_ERROR, locator, nmsg ? nmsg : msg, args); if(nmsg) RAPTOR_FREE(char*, nmsg); } static void raptor_libxml_error(void* user_data, const char *msg, ...) { va_list args; va_start(args, msg); raptor_libxml_error_common(user_data, msg, args, xml_error_prefix, 0); va_end(args); } void raptor_libxml_generic_error(void* user_data, const char *msg, ...) { raptor_world* world = (raptor_world*)user_data; va_list args; const char* prefix = xml_generic_error_prefix; int prefix_length = RAPTOR_BAD_CAST(int, strlen(prefix)); int length; char *nmsg; int msg_len; va_start(args, msg); msg_len = RAPTOR_BAD_CAST(int, strlen(msg)); length = prefix_length + msg_len + 1; nmsg = RAPTOR_MALLOC(char*, length); if(nmsg) { memcpy(nmsg, prefix, prefix_length); /* Do not copy NUL */ memcpy(nmsg + prefix_length, msg, msg_len + 1); /* Copy NUL */ if(nmsg[length-1] == '\n') nmsg[length-1]='\0'; } raptor_log_error_varargs(world, RAPTOR_LOG_LEVEL_ERROR, /* locator */ NULL, nmsg ? nmsg : msg, args); if(nmsg) RAPTOR_FREE(char*, nmsg); va_end(args); } static void raptor_libxml_fatal_error(void* user_data, const char *msg, ...) { va_list args; va_start(args, msg); raptor_libxml_error_common(user_data, msg, args, xml_fatal_error_prefix, 1); va_end(args); } void raptor_libxml_validation_error(void* user_data, const char *msg, ...) { va_list args; va_start(args, msg); raptor_libxml_error_common(user_data, msg, args, xml_validation_error_prefix, 1); va_end(args); } void raptor_libxml_validation_warning(void* user_data, const char *msg, ...) { va_list args; raptor_sax2* sax2 = (raptor_sax2*)user_data; int prefix_length = RAPTOR_GOOD_CAST(int, strlen(xml_validation_warning_prefix)); int length; char *nmsg; int msg_len; va_start(args, msg); raptor_libxml_update_document_locator(sax2, sax2->locator); msg_len = RAPTOR_BAD_CAST(int, strlen(msg)); length = prefix_length + msg_len + 1; nmsg = RAPTOR_MALLOC(char*, length); if(nmsg) { memcpy(nmsg, xml_validation_warning_prefix, prefix_length); /* Do not copy NUL */ memcpy(nmsg + prefix_length, msg, msg_len + 1); /* Copy NUL */ if(nmsg[length-2] == '\n') nmsg[length-2]='\0'; } raptor_log_error_varargs(sax2->world, RAPTOR_LOG_LEVEL_WARN, sax2->locator, nmsg ? nmsg : msg, args); if(nmsg) RAPTOR_FREE(char*, nmsg); va_end(args); } /* * Initialise libxml for a particular SAX2 setup */ void raptor_libxml_sax_init(raptor_sax2* sax2) { xmlSAXHandler *sax = &sax2->sax; sax->internalSubset = raptor_libxml_internalSubset; sax->isStandalone = raptor_libxml_isStandalone; sax->hasInternalSubset = raptor_libxml_hasInternalSubset; sax->hasExternalSubset = raptor_libxml_hasExternalSubset; sax->resolveEntity = raptor_libxml_resolveEntity; sax->getEntity = raptor_libxml_getEntity; sax->getParameterEntity = raptor_libxml_getParameterEntity; sax->entityDecl = raptor_libxml_entityDecl; sax->attributeDecl = NULL; /* attributeDecl */ sax->elementDecl = NULL; /* elementDecl */ sax->notationDecl = NULL; /* notationDecl */ sax->unparsedEntityDecl = raptor_libxml_unparsedEntityDecl; sax->setDocumentLocator = raptor_libxml_set_document_locator; sax->startDocument = raptor_libxml_startDocument; sax->endDocument = raptor_libxml_endDocument; sax->startElement= raptor_sax2_start_element; sax->endElement= raptor_sax2_end_element; sax->reference = NULL; /* reference */ sax->characters= raptor_sax2_characters; sax->cdataBlock= raptor_sax2_cdata; /* like <![CDATA[...]> */ sax->ignorableWhitespace= raptor_sax2_cdata; sax->processingInstruction = NULL; /* processingInstruction */ sax->comment = raptor_sax2_comment; /* comment */ sax->warning = (warningSAXFunc)raptor_libxml_warning; sax->error = (errorSAXFunc)raptor_libxml_error; sax->fatalError = (fatalErrorSAXFunc)raptor_libxml_fatal_error; sax->serror = (xmlStructuredErrorFunc)raptor_libxml_xmlStructuredError_handler_parsing; #ifdef RAPTOR_LIBXML_XMLSAXHANDLER_EXTERNALSUBSET sax->externalSubset = raptor_libxml_externalSubset; #endif #ifdef RAPTOR_LIBXML_XMLSAXHANDLER_INITIALIZED sax->initialized = 1; #endif } void raptor_libxml_free(xmlParserCtxtPtr xc) { libxml2_endDocument(xc); if(xc->myDoc) { xmlFreeDoc(xc->myDoc); xc->myDoc = NULL; } xmlFreeParserCtxt(xc); } int raptor_libxml_init(raptor_world* world) { xmlInitParser(); if(world->libxml_flags & RAPTOR_WORLD_FLAG_LIBXML_STRUCTURED_ERROR_SAVE) { world->libxml_saved_structured_error_context = xmlGenericErrorContext; world->libxml_saved_structured_error_handler = xmlStructuredError; /* sets xmlGenericErrorContext and xmlStructuredError */ xmlSetStructuredErrorFunc(world, (xmlStructuredErrorFunc)raptor_libxml_xmlStructuredError_handler_global); } if(world->libxml_flags & RAPTOR_WORLD_FLAG_LIBXML_GENERIC_ERROR_SAVE) { world->libxml_saved_generic_error_context = xmlGenericErrorContext; world->libxml_saved_generic_error_handler = xmlGenericError; /* sets xmlGenericErrorContext and xmlGenericError */ xmlSetGenericErrorFunc(world, (xmlGenericErrorFunc)raptor_libxml_generic_error); } return 0; } void raptor_libxml_finish(raptor_world* world) { if(world->libxml_flags & RAPTOR_WORLD_FLAG_LIBXML_STRUCTURED_ERROR_SAVE) xmlSetStructuredErrorFunc(world->libxml_saved_structured_error_context, world->libxml_saved_structured_error_handler); if(world->libxml_flags & RAPTOR_WORLD_FLAG_LIBXML_GENERIC_ERROR_SAVE) xmlSetGenericErrorFunc(world->libxml_saved_generic_error_context, world->libxml_saved_generic_error_handler); xmlCleanupParser(); } #if LIBXML_VERSION >= 20632 #define XML_LAST_DL XML_FROM_SCHEMATRONV #else #if LIBXML_VERSION >= 20621 #define XML_LAST_DL XML_FROM_I18N #else #if LIBXML_VERSION >= 20617 #define XML_LAST_DL XML_FROM_WRITER #else #if LIBXML_VERSION >= 20616 #define XML_LAST_DL XML_FROM_CHECK #else #if LIBXML_VERSION >= 20615 #define XML_LAST_DL XML_FROM_VALID #else #define XML_LAST_DL XML_FROM_XSLT #endif #endif #endif #endif #endif /* All other symbols not specifically below noted were added during * the period 2-10 October 2003 which is before the minimum libxml2 * version 2.6.8 release date of Mar 23 2004. * * When the minimum libxml2 version goes up, the #ifdefs for * older versions can be removed. */ static const char* const raptor_libxml_domain_labels[XML_LAST_DL+2]= { NULL, /* XML_FROM_NONE */ "parser", /* XML_FROM_PARSER */ "tree", /* XML_FROM_TREE */ "namespace", /* XML_FROM_NAMESPACE */ "validity", /* XML_FROM_DTD */ "HTML parser", /* XML_FROM_HTML */ "memory", /* XML_FROM_MEMORY */ "output", /* XML_FROM_OUTPUT */ "I/O" , /* XML_FROM_IO */ "FTP", /* XML_FROM_FTP */ #if LIBXML_VERSION >= 20618 /* 2005-02-13 - v2.6.18 */ "HTTP", /* XML_FROM_HTTP */ #endif "XInclude", /* XML_FROM_XINCLUDE */ "XPath", /* XML_FROM_XPATH */ "parser", /* XML_FROM_XPOINTER */ "regexp", /* XML_FROM_REGEXP */ "Schemas datatype", /* XML_FROM_DATATYPE */ "Schemas parser", /* XML_FROM_SCHEMASP */ "Schemas validity", /* XML_FROM_SCHEMASV */ "Relax-NG parser", /* XML_FROM_RELAXNGP */ "Relax-NG validity", /* XML_FROM_RELAXNGV */ "Catalog", /* XML_FROM_CATALOG */ "C14", /* XML_FROM_C14N */ "XSLT", /* XML_FROM_XSLT */ #if LIBXML_VERSION >= 20615 /* 2004-10-07 - v2.6.15 */ "validity", /* XML_FROM_VALID */ #endif #if LIBXML_VERSION >= 20616 /* 2004-11-04 - v2.6.16 */ "checking", /* XML_FROM_CHECK */ #endif #if LIBXML_VERSION >= 20617 /* 2005-01-04 - v2.6.17 */ "writer", /* XML_FROM_WRITER */ #endif #if LIBXML_VERSION >= 20621 /* 2005-08-24 - v2.6.21 */ "module", /* XML_FROM_MODULE */ "encoding", /* XML_FROM_I18N */ #endif #if LIBXML_VERSION >= 20632 /* 2008-04-08 - v2.6.32 */ "schematronv", /* XML_FROM_SCHEMATRONV */ #endif NULL }; static void raptor_libxml_xmlStructuredError_handler_common(raptor_world *world, raptor_locator *locator, xmlErrorPtr err) { raptor_stringbuffer* sb; char *nmsg; raptor_log_level level = RAPTOR_LOG_LEVEL_ERROR; if(err == NULL || err->code == XML_ERR_OK || err->level == XML_ERR_NONE) return; /* Do not warn about things with no location */ if(err->level == XML_ERR_WARNING && !err->file) return; /* XML fatal errors never cause an abort */ if(err->level == XML_ERR_FATAL) err->level = XML_ERR_ERROR; sb = raptor_new_stringbuffer(); if(err->domain != XML_FROM_HTML) raptor_stringbuffer_append_counted_string(sb, (const unsigned char*)"XML ", 4, 1); if(err->domain != XML_FROM_NONE && err->domain < XML_LAST_DL) { const unsigned char* label; label = (const unsigned char*)raptor_libxml_domain_labels[(int)err->domain]; raptor_stringbuffer_append_string(sb, label, 1); raptor_stringbuffer_append_counted_string(sb, (const unsigned char*)" ", 1, 1); } if(err->level == XML_ERR_WARNING) raptor_stringbuffer_append_counted_string(sb, (const unsigned char*)"warning: ", 9, 1); else /* XML_ERR_ERROR or XML_ERR_FATAL */ raptor_stringbuffer_append_counted_string(sb, (const unsigned char*)"error: ", 7, 1); if(err->message) { unsigned char* msg; size_t len; msg = (unsigned char*)err->message; len= strlen((const char*)msg); if(len && msg[len-1] == '\n') msg[--len]='\0'; raptor_stringbuffer_append_counted_string(sb, msg, len, 1); } #if LIBXML_VERSION >= 20618 /* 2005-02-13 - v2.6.18 */ /* str1 has the detailed HTTP error */ if(err->domain == XML_FROM_HTTP && err->str1) { unsigned char* msg; size_t len; msg = (unsigned char*)err->str1; len= strlen((const char*)msg); if(len && msg[len-1] == '\n') msg[--len]='\0'; raptor_stringbuffer_append_counted_string(sb, (const unsigned char*)" - ", 3, 1); raptor_stringbuffer_append_counted_string(sb, msg, len, 1); } #endif /* When err->domain == XML_FROM_XPATH then err->int1 is * the offset into err->str1, the line with the error */ if(err->domain == XML_FROM_XPATH && err->str1) { raptor_stringbuffer_append_counted_string(sb, (const unsigned char*)" in ", 4, 1); raptor_stringbuffer_append_string(sb, (const unsigned char*)err->str1, 1); } nmsg = (char*)raptor_stringbuffer_as_string(sb); if(err->level == XML_ERR_FATAL) level = RAPTOR_LOG_LEVEL_FATAL; else if(err->level == XML_ERR_ERROR) level = RAPTOR_LOG_LEVEL_ERROR; else level = RAPTOR_LOG_LEVEL_WARN; raptor_log_error(world, level, locator, nmsg); raptor_free_stringbuffer(sb); } /* user_data is a raptor_world* */ static void raptor_libxml_xmlStructuredError_handler_global(void *user_data, xmlErrorPtr err) { raptor_world *world = NULL; /* user_data may point to a raptor_world* */ if(user_data) { world = (raptor_world*)user_data; if(world->magic != RAPTOR2_WORLD_MAGIC) world = NULL; } raptor_libxml_xmlStructuredError_handler_common(world, NULL, err); } /* user_data may be a raptor_sax2; err->ctxt->userData may point to a * raptor_sax2* */ static void raptor_libxml_xmlStructuredError_handler_parsing(void *user_data, xmlErrorPtr err) { raptor_sax2* sax2 = NULL; /* user_data may point to a raptor_sax2* */ if(user_data) { sax2 = (raptor_sax2*)user_data; if(sax2->magic != RAPTOR_LIBXML_MAGIC) sax2 = NULL; } /* err->ctxt->userData may point to a raptor_sax2* */ if(err && err->ctxt) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)err->ctxt; if(ctxt->userData) { sax2 = (raptor_sax2*)ctxt->userData; if(sax2->magic != RAPTOR_LIBXML_MAGIC) sax2 = NULL; } } if(sax2) raptor_libxml_xmlStructuredError_handler_common(sax2->world, sax2->locator, err); else raptor_libxml_xmlStructuredError_handler_common(NULL, NULL, err); } /* end if RAPTOR_XML_LIBXML */ #endif
./CrossVul/dataset_final_sorted/CWE-200/c/good_3568_6
crossvul-cpp_data_good_3485_0
/* comedi/comedi_fops.c comedi kernel module COMEDI - Linux Control and Measurement Device Interface Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org> 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #undef DEBUG #define __NO_VERSION__ #include "comedi_fops.h" #include "comedi_compat32.h" #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/fcntl.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/kmod.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/device.h> #include <linux/vmalloc.h> #include <linux/fs.h> #include "comedidev.h" #include <linux/cdev.h> #include <linux/stat.h> #include <linux/io.h> #include <linux/uaccess.h> #include "internal.h" MODULE_AUTHOR("http://www.comedi.org"); MODULE_DESCRIPTION("Comedi core module"); MODULE_LICENSE("GPL"); #ifdef CONFIG_COMEDI_DEBUG int comedi_debug; EXPORT_SYMBOL(comedi_debug); module_param(comedi_debug, int, 0644); #endif int comedi_autoconfig = 1; module_param(comedi_autoconfig, bool, 0444); static int comedi_num_legacy_minors; module_param(comedi_num_legacy_minors, int, 0444); static DEFINE_SPINLOCK(comedi_file_info_table_lock); static struct comedi_device_file_info *comedi_file_info_table[COMEDI_NUM_MINORS]; static int do_devconfig_ioctl(struct comedi_device *dev, struct comedi_devconfig __user *arg); static int do_bufconfig_ioctl(struct comedi_device *dev, struct comedi_bufconfig __user *arg); static int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file); static int do_subdinfo_ioctl(struct comedi_device *dev, struct comedi_subdinfo __user *arg, void *file); static int do_chaninfo_ioctl(struct comedi_device *dev, struct comedi_chaninfo __user *arg); static int do_bufinfo_ioctl(struct comedi_device *dev, struct comedi_bufinfo __user *arg, void *file); static int do_cmd_ioctl(struct comedi_device *dev, struct comedi_cmd __user *arg, void *file); static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg, void *file); static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg, void *file); static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg, void *file); static int do_cmdtest_ioctl(struct comedi_device *dev, struct comedi_cmd __user *arg, void *file); static int do_insnlist_ioctl(struct comedi_device *dev, struct comedi_insnlist __user *arg, void *file); static int do_insn_ioctl(struct comedi_device *dev, struct comedi_insn __user *arg, void *file); static int do_poll_ioctl(struct comedi_device *dev, unsigned int subd, void *file); extern void do_become_nonbusy(struct comedi_device *dev, struct comedi_subdevice *s); static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s); static int comedi_fasync(int fd, struct file *file, int on); static int is_device_busy(struct comedi_device *dev); static int resize_async_buffer(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_async *async, unsigned new_size); /* declarations for sysfs attribute files */ static struct device_attribute dev_attr_max_read_buffer_kb; static struct device_attribute dev_attr_read_buffer_kb; static struct device_attribute dev_attr_max_write_buffer_kb; static struct device_attribute dev_attr_write_buffer_kb; static long comedi_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev; int rc; if (dev_file_info == NULL || dev_file_info->device == NULL) return -ENODEV; dev = dev_file_info->device; mutex_lock(&dev->mutex); /* Device config is special, because it must work on * an unconfigured device. */ if (cmd == COMEDI_DEVCONFIG) { rc = do_devconfig_ioctl(dev, (struct comedi_devconfig __user *)arg); goto done; } if (!dev->attached) { DPRINTK("no driver configured on /dev/comedi%i\n", dev->minor); rc = -ENODEV; goto done; } switch (cmd) { case COMEDI_BUFCONFIG: rc = do_bufconfig_ioctl(dev, (struct comedi_bufconfig __user *)arg); break; case COMEDI_DEVINFO: rc = do_devinfo_ioctl(dev, (struct comedi_devinfo __user *)arg, file); break; case COMEDI_SUBDINFO: rc = do_subdinfo_ioctl(dev, (struct comedi_subdinfo __user *)arg, file); break; case COMEDI_CHANINFO: rc = do_chaninfo_ioctl(dev, (void __user *)arg); break; case COMEDI_RANGEINFO: rc = do_rangeinfo_ioctl(dev, (void __user *)arg); break; case COMEDI_BUFINFO: rc = do_bufinfo_ioctl(dev, (struct comedi_bufinfo __user *)arg, file); break; case COMEDI_LOCK: rc = do_lock_ioctl(dev, arg, file); break; case COMEDI_UNLOCK: rc = do_unlock_ioctl(dev, arg, file); break; case COMEDI_CANCEL: rc = do_cancel_ioctl(dev, arg, file); break; case COMEDI_CMD: rc = do_cmd_ioctl(dev, (struct comedi_cmd __user *)arg, file); break; case COMEDI_CMDTEST: rc = do_cmdtest_ioctl(dev, (struct comedi_cmd __user *)arg, file); break; case COMEDI_INSNLIST: rc = do_insnlist_ioctl(dev, (struct comedi_insnlist __user *)arg, file); break; case COMEDI_INSN: rc = do_insn_ioctl(dev, (struct comedi_insn __user *)arg, file); break; case COMEDI_POLL: rc = do_poll_ioctl(dev, arg, file); break; default: rc = -ENOTTY; break; } done: mutex_unlock(&dev->mutex); return rc; } /* COMEDI_DEVCONFIG device config ioctl arg: pointer to devconfig structure reads: devconfig structure at arg writes: none */ static int do_devconfig_ioctl(struct comedi_device *dev, struct comedi_devconfig __user *arg) { struct comedi_devconfig it; int ret; unsigned char *aux_data = NULL; int aux_len; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (arg == NULL) { if (is_device_busy(dev)) return -EBUSY; if (dev->attached) { struct module *driver_module = dev->driver->module; comedi_device_detach(dev); module_put(driver_module); } return 0; } if (copy_from_user(&it, arg, sizeof(struct comedi_devconfig))) return -EFAULT; it.board_name[COMEDI_NAMELEN - 1] = 0; if (comedi_aux_data(it.options, 0) && it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) { int bit_shift; aux_len = it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH]; if (aux_len < 0) return -EFAULT; aux_data = vmalloc(aux_len); if (!aux_data) return -ENOMEM; if (copy_from_user(aux_data, comedi_aux_data(it.options, 0), aux_len)) { vfree(aux_data); return -EFAULT; } it.options[COMEDI_DEVCONF_AUX_DATA_LO] = (unsigned long)aux_data; if (sizeof(void *) > sizeof(int)) { bit_shift = sizeof(int) * 8; it.options[COMEDI_DEVCONF_AUX_DATA_HI] = ((unsigned long)aux_data) >> bit_shift; } else it.options[COMEDI_DEVCONF_AUX_DATA_HI] = 0; } ret = comedi_device_attach(dev, &it); if (ret == 0) { if (!try_module_get(dev->driver->module)) { comedi_device_detach(dev); return -ENOSYS; } } if (aux_data) vfree(aux_data); return ret; } /* COMEDI_BUFCONFIG buffer configuration ioctl arg: pointer to bufconfig structure reads: bufconfig at arg writes: modified bufconfig at arg */ static int do_bufconfig_ioctl(struct comedi_device *dev, struct comedi_bufconfig __user *arg) { struct comedi_bufconfig bc; struct comedi_async *async; struct comedi_subdevice *s; int retval = 0; if (copy_from_user(&bc, arg, sizeof(struct comedi_bufconfig))) return -EFAULT; if (bc.subdevice >= dev->n_subdevices || bc.subdevice < 0) return -EINVAL; s = dev->subdevices + bc.subdevice; async = s->async; if (!async) { DPRINTK("subdevice does not have async capability\n"); bc.size = 0; bc.maximum_size = 0; goto copyback; } if (bc.maximum_size) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; async->max_bufsize = bc.maximum_size; } if (bc.size) { retval = resize_async_buffer(dev, s, async, bc.size); if (retval < 0) return retval; } bc.size = async->prealloc_bufsz; bc.maximum_size = async->max_bufsize; copyback: if (copy_to_user(arg, &bc, sizeof(struct comedi_bufconfig))) return -EFAULT; return 0; } /* COMEDI_DEVINFO device info ioctl arg: pointer to devinfo structure reads: none writes: devinfo structure */ static int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; } /* COMEDI_SUBDINFO subdevice info ioctl arg: pointer to array of subdevice info structures reads: none writes: array of subdevice info structures at arg */ static int do_subdinfo_ioctl(struct comedi_device *dev, struct comedi_subdinfo __user *arg, void *file) { int ret, i; struct comedi_subdinfo *tmp, *us; struct comedi_subdevice *s; tmp = kcalloc(dev->n_subdevices, sizeof(struct comedi_subdinfo), GFP_KERNEL); if (!tmp) return -ENOMEM; /* fill subdinfo structs */ for (i = 0; i < dev->n_subdevices; i++) { s = dev->subdevices + i; us = tmp + i; us->type = s->type; us->n_chan = s->n_chan; us->subd_flags = s->subdev_flags; if (comedi_get_subdevice_runflags(s) & SRF_RUNNING) us->subd_flags |= SDF_RUNNING; #define TIMER_nanosec 5 /* backwards compatibility */ us->timer_type = TIMER_nanosec; us->len_chanlist = s->len_chanlist; us->maxdata = s->maxdata; if (s->range_table) { us->range_type = (i << 24) | (0 << 16) | (s->range_table->length); } else { us->range_type = 0; /* XXX */ } us->flags = s->flags; if (s->busy) us->subd_flags |= SDF_BUSY; if (s->busy == file) us->subd_flags |= SDF_BUSY_OWNER; if (s->lock) us->subd_flags |= SDF_LOCKED; if (s->lock == file) us->subd_flags |= SDF_LOCK_OWNER; if (!s->maxdata && s->maxdata_list) us->subd_flags |= SDF_MAXDATA; if (s->flaglist) us->subd_flags |= SDF_FLAGS; if (s->range_table_list) us->subd_flags |= SDF_RANGETYPE; if (s->do_cmd) us->subd_flags |= SDF_CMD; if (s->insn_bits != &insn_inval) us->insn_bits_support = COMEDI_SUPPORTED; else us->insn_bits_support = COMEDI_UNSUPPORTED; us->settling_time_0 = s->settling_time_0; } ret = copy_to_user(arg, tmp, dev->n_subdevices * sizeof(struct comedi_subdinfo)); kfree(tmp); return ret ? -EFAULT : 0; } /* COMEDI_CHANINFO subdevice info ioctl arg: pointer to chaninfo structure reads: chaninfo structure at arg writes: arrays at elements of chaninfo structure */ static int do_chaninfo_ioctl(struct comedi_device *dev, struct comedi_chaninfo __user *arg) { struct comedi_subdevice *s; struct comedi_chaninfo it; if (copy_from_user(&it, arg, sizeof(struct comedi_chaninfo))) return -EFAULT; if (it.subdev >= dev->n_subdevices) return -EINVAL; s = dev->subdevices + it.subdev; if (it.maxdata_list) { if (s->maxdata || !s->maxdata_list) return -EINVAL; if (copy_to_user(it.maxdata_list, s->maxdata_list, s->n_chan * sizeof(unsigned int))) return -EFAULT; } if (it.flaglist) { if (!s->flaglist) return -EINVAL; if (copy_to_user(it.flaglist, s->flaglist, s->n_chan * sizeof(unsigned int))) return -EFAULT; } if (it.rangelist) { int i; if (!s->range_table_list) return -EINVAL; for (i = 0; i < s->n_chan; i++) { int x; x = (dev->minor << 28) | (it.subdev << 24) | (i << 16) | (s->range_table_list[i]->length); if (put_user(x, it.rangelist + i)) return -EFAULT; } #if 0 if (copy_to_user(it.rangelist, s->range_type_list, s->n_chan * sizeof(unsigned int))) return -EFAULT; #endif } return 0; } /* COMEDI_BUFINFO buffer information ioctl arg: pointer to bufinfo structure reads: bufinfo at arg writes: modified bufinfo at arg */ static int do_bufinfo_ioctl(struct comedi_device *dev, struct comedi_bufinfo __user *arg, void *file) { struct comedi_bufinfo bi; struct comedi_subdevice *s; struct comedi_async *async; if (copy_from_user(&bi, arg, sizeof(struct comedi_bufinfo))) return -EFAULT; if (bi.subdevice >= dev->n_subdevices || bi.subdevice < 0) return -EINVAL; s = dev->subdevices + bi.subdevice; if (s->lock && s->lock != file) return -EACCES; async = s->async; if (!async) { DPRINTK("subdevice does not have async capability\n"); bi.buf_write_ptr = 0; bi.buf_read_ptr = 0; bi.buf_write_count = 0; bi.buf_read_count = 0; bi.bytes_read = 0; bi.bytes_written = 0; goto copyback; } if (!s->busy) { bi.bytes_read = 0; bi.bytes_written = 0; goto copyback_position; } if (s->busy != file) return -EACCES; if (bi.bytes_read && (s->subdev_flags & SDF_CMD_READ)) { bi.bytes_read = comedi_buf_read_alloc(async, bi.bytes_read); comedi_buf_read_free(async, bi.bytes_read); if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR | SRF_RUNNING)) && async->buf_write_count == async->buf_read_count) { do_become_nonbusy(dev, s); } } if (bi.bytes_written && (s->subdev_flags & SDF_CMD_WRITE)) { bi.bytes_written = comedi_buf_write_alloc(async, bi.bytes_written); comedi_buf_write_free(async, bi.bytes_written); } copyback_position: bi.buf_write_count = async->buf_write_count; bi.buf_write_ptr = async->buf_write_ptr; bi.buf_read_count = async->buf_read_count; bi.buf_read_ptr = async->buf_read_ptr; copyback: if (copy_to_user(arg, &bi, sizeof(struct comedi_bufinfo))) return -EFAULT; return 0; } static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn, unsigned int *data, void *file); /* * COMEDI_INSNLIST * synchronous instructions * * arg: * pointer to sync cmd structure * * reads: * sync cmd struct at arg * instruction list * data (for writes) * * writes: * data (for reads) */ /* arbitrary limits */ #define MAX_SAMPLES 256 static int do_insnlist_ioctl(struct comedi_device *dev, struct comedi_insnlist __user *arg, void *file) { struct comedi_insnlist insnlist; struct comedi_insn *insns = NULL; unsigned int *data = NULL; int i = 0; int ret = 0; if (copy_from_user(&insnlist, arg, sizeof(struct comedi_insnlist))) return -EFAULT; data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL); if (!data) { DPRINTK("kmalloc failed\n"); ret = -ENOMEM; goto error; } insns = kmalloc(sizeof(struct comedi_insn) * insnlist.n_insns, GFP_KERNEL); if (!insns) { DPRINTK("kmalloc failed\n"); ret = -ENOMEM; goto error; } if (copy_from_user(insns, insnlist.insns, sizeof(struct comedi_insn) * insnlist.n_insns)) { DPRINTK("copy_from_user failed\n"); ret = -EFAULT; goto error; } for (i = 0; i < insnlist.n_insns; i++) { if (insns[i].n > MAX_SAMPLES) { DPRINTK("number of samples too large\n"); ret = -EINVAL; goto error; } if (insns[i].insn & INSN_MASK_WRITE) { if (copy_from_user(data, insns[i].data, insns[i].n * sizeof(unsigned int))) { DPRINTK("copy_from_user failed\n"); ret = -EFAULT; goto error; } } ret = parse_insn(dev, insns + i, data, file); if (ret < 0) goto error; if (insns[i].insn & INSN_MASK_READ) { if (copy_to_user(insns[i].data, data, insns[i].n * sizeof(unsigned int))) { DPRINTK("copy_to_user failed\n"); ret = -EFAULT; goto error; } } if (need_resched()) schedule(); } error: kfree(insns); kfree(data); if (ret < 0) return ret; return i; } static int check_insn_config_length(struct comedi_insn *insn, unsigned int *data) { if (insn->n < 1) return -EINVAL; switch (data[0]) { case INSN_CONFIG_DIO_OUTPUT: case INSN_CONFIG_DIO_INPUT: case INSN_CONFIG_DISARM: case INSN_CONFIG_RESET: if (insn->n == 1) return 0; break; case INSN_CONFIG_ARM: case INSN_CONFIG_DIO_QUERY: case INSN_CONFIG_BLOCK_SIZE: case INSN_CONFIG_FILTER: case INSN_CONFIG_SERIAL_CLOCK: case INSN_CONFIG_BIDIRECTIONAL_DATA: case INSN_CONFIG_ALT_SOURCE: case INSN_CONFIG_SET_COUNTER_MODE: case INSN_CONFIG_8254_READ_STATUS: case INSN_CONFIG_SET_ROUTING: case INSN_CONFIG_GET_ROUTING: case INSN_CONFIG_GET_PWM_STATUS: case INSN_CONFIG_PWM_SET_PERIOD: case INSN_CONFIG_PWM_GET_PERIOD: if (insn->n == 2) return 0; break; case INSN_CONFIG_SET_GATE_SRC: case INSN_CONFIG_GET_GATE_SRC: case INSN_CONFIG_SET_CLOCK_SRC: case INSN_CONFIG_GET_CLOCK_SRC: case INSN_CONFIG_SET_OTHER_SRC: case INSN_CONFIG_GET_COUNTER_STATUS: case INSN_CONFIG_PWM_SET_H_BRIDGE: case INSN_CONFIG_PWM_GET_H_BRIDGE: case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE: if (insn->n == 3) return 0; break; case INSN_CONFIG_PWM_OUTPUT: case INSN_CONFIG_ANALOG_TRIG: if (insn->n == 5) return 0; break; /* by default we allow the insn since we don't have checks for * all possible cases yet */ default: printk(KERN_WARNING "comedi: no check for data length of config insn id " "%i is implemented.\n" " Add a check to %s in %s.\n" " Assuming n=%i is correct.\n", data[0], __func__, __FILE__, insn->n); return 0; break; } return -EINVAL; } static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn, unsigned int *data, void *file) { struct comedi_subdevice *s; int ret = 0; int i; if (insn->insn & INSN_MASK_SPECIAL) { /* a non-subdevice instruction */ switch (insn->insn) { case INSN_GTOD: { struct timeval tv; if (insn->n != 2) { ret = -EINVAL; break; } do_gettimeofday(&tv); data[0] = tv.tv_sec; data[1] = tv.tv_usec; ret = 2; break; } case INSN_WAIT: if (insn->n != 1 || data[0] >= 100000) { ret = -EINVAL; break; } udelay(data[0] / 1000); ret = 1; break; case INSN_INTTRIG: if (insn->n != 1) { ret = -EINVAL; break; } if (insn->subdev >= dev->n_subdevices) { DPRINTK("%d not usable subdevice\n", insn->subdev); ret = -EINVAL; break; } s = dev->subdevices + insn->subdev; if (!s->async) { DPRINTK("no async\n"); ret = -EINVAL; break; } if (!s->async->inttrig) { DPRINTK("no inttrig\n"); ret = -EAGAIN; break; } ret = s->async->inttrig(dev, s, insn->data[0]); if (ret >= 0) ret = 1; break; default: DPRINTK("invalid insn\n"); ret = -EINVAL; break; } } else { /* a subdevice instruction */ unsigned int maxdata; if (insn->subdev >= dev->n_subdevices) { DPRINTK("subdevice %d out of range\n", insn->subdev); ret = -EINVAL; goto out; } s = dev->subdevices + insn->subdev; if (s->type == COMEDI_SUBD_UNUSED) { DPRINTK("%d not usable subdevice\n", insn->subdev); ret = -EIO; goto out; } /* are we locked? (ioctl lock) */ if (s->lock && s->lock != file) { DPRINTK("device locked\n"); ret = -EACCES; goto out; } ret = comedi_check_chanlist(s, 1, &insn->chanspec); if (ret < 0) { ret = -EINVAL; DPRINTK("bad chanspec\n"); goto out; } if (s->busy) { ret = -EBUSY; goto out; } /* This looks arbitrary. It is. */ s->busy = &parse_insn; switch (insn->insn) { case INSN_READ: ret = s->insn_read(dev, s, insn, data); break; case INSN_WRITE: maxdata = s->maxdata_list ? s->maxdata_list[CR_CHAN(insn->chanspec)] : s->maxdata; for (i = 0; i < insn->n; ++i) { if (data[i] > maxdata) { ret = -EINVAL; DPRINTK("bad data value(s)\n"); break; } } if (ret == 0) ret = s->insn_write(dev, s, insn, data); break; case INSN_BITS: if (insn->n != 2) { ret = -EINVAL; } else { /* Most drivers ignore the base channel in * insn->chanspec. Fix this here if * the subdevice has <= 32 channels. */ unsigned int shift; unsigned int orig_mask; orig_mask = data[0]; if (s->n_chan <= 32) { shift = CR_CHAN(insn->chanspec); if (shift > 0) { insn->chanspec = 0; data[0] <<= shift; data[1] <<= shift; } } else shift = 0; ret = s->insn_bits(dev, s, insn, data); data[0] = orig_mask; if (shift > 0) data[1] >>= shift; } break; case INSN_CONFIG: ret = check_insn_config_length(insn, data); if (ret) break; ret = s->insn_config(dev, s, insn, data); break; default: ret = -EINVAL; break; } s->busy = NULL; } out: return ret; } /* * COMEDI_INSN * synchronous instructions * * arg: * pointer to insn * * reads: * struct comedi_insn struct at arg * data (for writes) * * writes: * data (for reads) */ static int do_insn_ioctl(struct comedi_device *dev, struct comedi_insn __user *arg, void *file) { struct comedi_insn insn; unsigned int *data = NULL; int ret = 0; data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL); if (!data) { ret = -ENOMEM; goto error; } if (copy_from_user(&insn, arg, sizeof(struct comedi_insn))) { ret = -EFAULT; goto error; } /* This is where the behavior of insn and insnlist deviate. */ if (insn.n > MAX_SAMPLES) insn.n = MAX_SAMPLES; if (insn.insn & INSN_MASK_WRITE) { if (copy_from_user(data, insn.data, insn.n * sizeof(unsigned int))) { ret = -EFAULT; goto error; } } ret = parse_insn(dev, &insn, data, file); if (ret < 0) goto error; if (insn.insn & INSN_MASK_READ) { if (copy_to_user(insn.data, data, insn.n * sizeof(unsigned int))) { ret = -EFAULT; goto error; } } ret = insn.n; error: kfree(data); return ret; } static void comedi_set_subdevice_runflags(struct comedi_subdevice *s, unsigned mask, unsigned bits) { unsigned long flags; spin_lock_irqsave(&s->spin_lock, flags); s->runflags &= ~mask; s->runflags |= (bits & mask); spin_unlock_irqrestore(&s->spin_lock, flags); } static int do_cmd_ioctl(struct comedi_device *dev, struct comedi_cmd __user *cmd, void *file) { struct comedi_cmd user_cmd; struct comedi_subdevice *s; struct comedi_async *async; int ret = 0; unsigned int __user *chanlist_saver = NULL; if (copy_from_user(&user_cmd, cmd, sizeof(struct comedi_cmd))) { DPRINTK("bad cmd address\n"); return -EFAULT; } /* save user's chanlist pointer so it can be restored later */ chanlist_saver = user_cmd.chanlist; if (user_cmd.subdev >= dev->n_subdevices) { DPRINTK("%d no such subdevice\n", user_cmd.subdev); return -ENODEV; } s = dev->subdevices + user_cmd.subdev; async = s->async; if (s->type == COMEDI_SUBD_UNUSED) { DPRINTK("%d not valid subdevice\n", user_cmd.subdev); return -EIO; } if (!s->do_cmd || !s->do_cmdtest || !s->async) { DPRINTK("subdevice %i does not support commands\n", user_cmd.subdev); return -EIO; } /* are we locked? (ioctl lock) */ if (s->lock && s->lock != file) { DPRINTK("subdevice locked\n"); return -EACCES; } /* are we busy? */ if (s->busy) { DPRINTK("subdevice busy\n"); return -EBUSY; } s->busy = file; /* make sure channel/gain list isn't too long */ if (user_cmd.chanlist_len > s->len_chanlist) { DPRINTK("channel/gain list too long %u > %d\n", user_cmd.chanlist_len, s->len_chanlist); ret = -EINVAL; goto cleanup; } /* make sure channel/gain list isn't too short */ if (user_cmd.chanlist_len < 1) { DPRINTK("channel/gain list too short %u < 1\n", user_cmd.chanlist_len); ret = -EINVAL; goto cleanup; } kfree(async->cmd.chanlist); async->cmd = user_cmd; async->cmd.data = NULL; /* load channel/gain list */ async->cmd.chanlist = kmalloc(async->cmd.chanlist_len * sizeof(int), GFP_KERNEL); if (!async->cmd.chanlist) { DPRINTK("allocation failed\n"); ret = -ENOMEM; goto cleanup; } if (copy_from_user(async->cmd.chanlist, user_cmd.chanlist, async->cmd.chanlist_len * sizeof(int))) { DPRINTK("fault reading chanlist\n"); ret = -EFAULT; goto cleanup; } /* make sure each element in channel/gain list is valid */ ret = comedi_check_chanlist(s, async->cmd.chanlist_len, async->cmd.chanlist); if (ret < 0) { DPRINTK("bad chanlist\n"); goto cleanup; } ret = s->do_cmdtest(dev, s, &async->cmd); if (async->cmd.flags & TRIG_BOGUS || ret) { DPRINTK("test returned %d\n", ret); user_cmd = async->cmd; /* restore chanlist pointer before copying back */ user_cmd.chanlist = chanlist_saver; user_cmd.data = NULL; if (copy_to_user(cmd, &user_cmd, sizeof(struct comedi_cmd))) { DPRINTK("fault writing cmd\n"); ret = -EFAULT; goto cleanup; } ret = -EAGAIN; goto cleanup; } if (!async->prealloc_bufsz) { ret = -ENOMEM; DPRINTK("no buffer (?)\n"); goto cleanup; } comedi_reset_async_buf(async); async->cb_mask = COMEDI_CB_EOA | COMEDI_CB_BLOCK | COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW; if (async->cmd.flags & TRIG_WAKE_EOS) async->cb_mask |= COMEDI_CB_EOS; comedi_set_subdevice_runflags(s, ~0, SRF_USER | SRF_RUNNING); ret = s->do_cmd(dev, s); if (ret == 0) return 0; cleanup: do_become_nonbusy(dev, s); return ret; } /* COMEDI_CMDTEST command testing ioctl arg: pointer to cmd structure reads: cmd structure at arg channel/range list writes: modified cmd structure at arg */ static int do_cmdtest_ioctl(struct comedi_device *dev, struct comedi_cmd __user *arg, void *file) { struct comedi_cmd user_cmd; struct comedi_subdevice *s; int ret = 0; unsigned int *chanlist = NULL; unsigned int __user *chanlist_saver = NULL; if (copy_from_user(&user_cmd, arg, sizeof(struct comedi_cmd))) { DPRINTK("bad cmd address\n"); return -EFAULT; } /* save user's chanlist pointer so it can be restored later */ chanlist_saver = user_cmd.chanlist; if (user_cmd.subdev >= dev->n_subdevices) { DPRINTK("%d no such subdevice\n", user_cmd.subdev); return -ENODEV; } s = dev->subdevices + user_cmd.subdev; if (s->type == COMEDI_SUBD_UNUSED) { DPRINTK("%d not valid subdevice\n", user_cmd.subdev); return -EIO; } if (!s->do_cmd || !s->do_cmdtest) { DPRINTK("subdevice %i does not support commands\n", user_cmd.subdev); return -EIO; } /* make sure channel/gain list isn't too long */ if (user_cmd.chanlist_len > s->len_chanlist) { DPRINTK("channel/gain list too long %d > %d\n", user_cmd.chanlist_len, s->len_chanlist); ret = -EINVAL; goto cleanup; } /* load channel/gain list */ if (user_cmd.chanlist) { chanlist = kmalloc(user_cmd.chanlist_len * sizeof(int), GFP_KERNEL); if (!chanlist) { DPRINTK("allocation failed\n"); ret = -ENOMEM; goto cleanup; } if (copy_from_user(chanlist, user_cmd.chanlist, user_cmd.chanlist_len * sizeof(int))) { DPRINTK("fault reading chanlist\n"); ret = -EFAULT; goto cleanup; } /* make sure each element in channel/gain list is valid */ ret = comedi_check_chanlist(s, user_cmd.chanlist_len, chanlist); if (ret < 0) { DPRINTK("bad chanlist\n"); goto cleanup; } user_cmd.chanlist = chanlist; } ret = s->do_cmdtest(dev, s, &user_cmd); /* restore chanlist pointer before copying back */ user_cmd.chanlist = chanlist_saver; if (copy_to_user(arg, &user_cmd, sizeof(struct comedi_cmd))) { DPRINTK("bad cmd address\n"); ret = -EFAULT; goto cleanup; } cleanup: kfree(chanlist); return ret; } /* COMEDI_LOCK lock subdevice arg: subdevice number reads: none writes: none */ static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg, void *file) { int ret = 0; unsigned long flags; struct comedi_subdevice *s; if (arg >= dev->n_subdevices) return -EINVAL; s = dev->subdevices + arg; spin_lock_irqsave(&s->spin_lock, flags); if (s->busy || s->lock) ret = -EBUSY; else s->lock = file; spin_unlock_irqrestore(&s->spin_lock, flags); #if 0 if (ret < 0) return ret; if (s->lock_f) ret = s->lock_f(dev, s); #endif return ret; } /* COMEDI_UNLOCK unlock subdevice arg: subdevice number reads: none writes: none This function isn't protected by the semaphore, since we already own the lock. */ static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg, void *file) { struct comedi_subdevice *s; if (arg >= dev->n_subdevices) return -EINVAL; s = dev->subdevices + arg; if (s->busy) return -EBUSY; if (s->lock && s->lock != file) return -EACCES; if (s->lock == file) { #if 0 if (s->unlock) s->unlock(dev, s); #endif s->lock = NULL; } return 0; } /* COMEDI_CANCEL cancel acquisition ioctl arg: subdevice number reads: nothing writes: nothing */ static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg, void *file) { struct comedi_subdevice *s; if (arg >= dev->n_subdevices) return -EINVAL; s = dev->subdevices + arg; if (s->async == NULL) return -EINVAL; if (s->lock && s->lock != file) return -EACCES; if (!s->busy) return 0; if (s->busy != file) return -EBUSY; return do_cancel(dev, s); } /* COMEDI_POLL ioctl instructs driver to synchronize buffers arg: subdevice number reads: nothing writes: nothing */ static int do_poll_ioctl(struct comedi_device *dev, unsigned int arg, void *file) { struct comedi_subdevice *s; if (arg >= dev->n_subdevices) return -EINVAL; s = dev->subdevices + arg; if (s->lock && s->lock != file) return -EACCES; if (!s->busy) return 0; if (s->busy != file) return -EBUSY; if (s->poll) return s->poll(dev, s); return -EINVAL; } static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s) { int ret = 0; if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) && s->cancel) ret = s->cancel(dev, s); do_become_nonbusy(dev, s); return ret; } static void comedi_unmap(struct vm_area_struct *area) { struct comedi_async *async; struct comedi_device *dev; async = area->vm_private_data; dev = async->subdevice->device; mutex_lock(&dev->mutex); async->mmap_count--; mutex_unlock(&dev->mutex); } static struct vm_operations_struct comedi_vm_ops = { .close = comedi_unmap, }; static int comedi_mmap(struct file *file, struct vm_area_struct *vma) { const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; struct comedi_async *async = NULL; unsigned long start = vma->vm_start; unsigned long size; int n_pages; int i; int retval; struct comedi_subdevice *s; mutex_lock(&dev->mutex); if (!dev->attached) { DPRINTK("no driver configured on comedi%i\n", dev->minor); retval = -ENODEV; goto done; } if (vma->vm_flags & VM_WRITE) s = comedi_get_write_subdevice(dev_file_info); else s = comedi_get_read_subdevice(dev_file_info); if (s == NULL) { retval = -EINVAL; goto done; } async = s->async; if (async == NULL) { retval = -EINVAL; goto done; } if (vma->vm_pgoff != 0) { DPRINTK("comedi: mmap() offset must be 0.\n"); retval = -EINVAL; goto done; } size = vma->vm_end - vma->vm_start; if (size > async->prealloc_bufsz) { retval = -EFAULT; goto done; } if (size & (~PAGE_MASK)) { retval = -EFAULT; goto done; } n_pages = size >> PAGE_SHIFT; for (i = 0; i < n_pages; ++i) { if (remap_pfn_range(vma, start, page_to_pfn(virt_to_page (async->buf_page_list [i].virt_addr)), PAGE_SIZE, PAGE_SHARED)) { retval = -EAGAIN; goto done; } start += PAGE_SIZE; } vma->vm_ops = &comedi_vm_ops; vma->vm_private_data = async; async->mmap_count++; retval = 0; done: mutex_unlock(&dev->mutex); return retval; } static unsigned int comedi_poll(struct file *file, poll_table * wait) { unsigned int mask = 0; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; struct comedi_subdevice *read_subdev; struct comedi_subdevice *write_subdev; mutex_lock(&dev->mutex); if (!dev->attached) { DPRINTK("no driver configured on comedi%i\n", dev->minor); mutex_unlock(&dev->mutex); return 0; } mask = 0; read_subdev = comedi_get_read_subdevice(dev_file_info); if (read_subdev) { poll_wait(file, &read_subdev->async->wait_head, wait); if (!read_subdev->busy || comedi_buf_read_n_available(read_subdev->async) > 0 || !(comedi_get_subdevice_runflags(read_subdev) & SRF_RUNNING)) { mask |= POLLIN | POLLRDNORM; } } write_subdev = comedi_get_write_subdevice(dev_file_info); if (write_subdev) { poll_wait(file, &write_subdev->async->wait_head, wait); comedi_buf_write_alloc(write_subdev->async, write_subdev->async->prealloc_bufsz); if (!write_subdev->busy || !(comedi_get_subdevice_runflags(write_subdev) & SRF_RUNNING) || comedi_buf_write_n_allocated(write_subdev->async) >= bytes_per_sample(write_subdev->async->subdevice)) { mask |= POLLOUT | POLLWRNORM; } } mutex_unlock(&dev->mutex); return mask; } static ssize_t comedi_write(struct file *file, const char __user *buf, size_t nbytes, loff_t *offset) { struct comedi_subdevice *s; struct comedi_async *async; int n, m, count = 0, retval = 0; DECLARE_WAITQUEUE(wait, current); const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; if (!dev->attached) { DPRINTK("no driver configured on comedi%i\n", dev->minor); retval = -ENODEV; goto done; } s = comedi_get_write_subdevice(dev_file_info); if (s == NULL) { retval = -EIO; goto done; } async = s->async; if (!nbytes) { retval = 0; goto done; } if (!s->busy) { retval = 0; goto done; } if (s->busy != file) { retval = -EACCES; goto done; } add_wait_queue(&async->wait_head, &wait); while (nbytes > 0 && !retval) { set_current_state(TASK_INTERRUPTIBLE); if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) { if (count == 0) { if (comedi_get_subdevice_runflags(s) & SRF_ERROR) { retval = -EPIPE; } else { retval = 0; } do_become_nonbusy(dev, s); } break; } n = nbytes; m = n; if (async->buf_write_ptr + m > async->prealloc_bufsz) m = async->prealloc_bufsz - async->buf_write_ptr; comedi_buf_write_alloc(async, async->prealloc_bufsz); if (m > comedi_buf_write_n_allocated(async)) m = comedi_buf_write_n_allocated(async); if (m < n) n = m; if (n == 0) { if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } if (signal_pending(current)) { retval = -ERESTARTSYS; break; } schedule(); if (!s->busy) break; if (s->busy != file) { retval = -EACCES; break; } continue; } m = copy_from_user(async->prealloc_buf + async->buf_write_ptr, buf, n); if (m) { n -= m; retval = -EFAULT; } comedi_buf_write_free(async, n); count += n; nbytes -= n; buf += n; break; /* makes device work like a pipe */ } set_current_state(TASK_RUNNING); remove_wait_queue(&async->wait_head, &wait); done: return count ? count : retval; } static ssize_t comedi_read(struct file *file, char __user *buf, size_t nbytes, loff_t *offset) { struct comedi_subdevice *s; struct comedi_async *async; int n, m, count = 0, retval = 0; DECLARE_WAITQUEUE(wait, current); const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; if (!dev->attached) { DPRINTK("no driver configured on comedi%i\n", dev->minor); retval = -ENODEV; goto done; } s = comedi_get_read_subdevice(dev_file_info); if (s == NULL) { retval = -EIO; goto done; } async = s->async; if (!nbytes) { retval = 0; goto done; } if (!s->busy) { retval = 0; goto done; } if (s->busy != file) { retval = -EACCES; goto done; } add_wait_queue(&async->wait_head, &wait); while (nbytes > 0 && !retval) { set_current_state(TASK_INTERRUPTIBLE); n = nbytes; m = comedi_buf_read_n_available(async); /* printk("%d available\n",m); */ if (async->buf_read_ptr + m > async->prealloc_bufsz) m = async->prealloc_bufsz - async->buf_read_ptr; /* printk("%d contiguous\n",m); */ if (m < n) n = m; if (n == 0) { if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) { do_become_nonbusy(dev, s); if (comedi_get_subdevice_runflags(s) & SRF_ERROR) { retval = -EPIPE; } else { retval = 0; } break; } if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } if (signal_pending(current)) { retval = -ERESTARTSYS; break; } schedule(); if (!s->busy) { retval = 0; break; } if (s->busy != file) { retval = -EACCES; break; } continue; } m = copy_to_user(buf, async->prealloc_buf + async->buf_read_ptr, n); if (m) { n -= m; retval = -EFAULT; } comedi_buf_read_alloc(async, n); comedi_buf_read_free(async, n); count += n; nbytes -= n; buf += n; break; /* makes device work like a pipe */ } if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR | SRF_RUNNING)) && async->buf_read_count - async->buf_write_count == 0) { do_become_nonbusy(dev, s); } set_current_state(TASK_RUNNING); remove_wait_queue(&async->wait_head, &wait); done: return count ? count : retval; } /* This function restores a subdevice to an idle state. */ void do_become_nonbusy(struct comedi_device *dev, struct comedi_subdevice *s) { struct comedi_async *async = s->async; comedi_set_subdevice_runflags(s, SRF_RUNNING, 0); if (async) { comedi_reset_async_buf(async); async->inttrig = NULL; } else { printk(KERN_ERR "BUG: (?) do_become_nonbusy called with async=0\n"); } s->busy = NULL; } static int comedi_open(struct inode *inode, struct file *file) { const unsigned minor = iminor(inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info ? dev_file_info->device : NULL; if (dev == NULL) { DPRINTK("invalid minor number\n"); return -ENODEV; } /* This is slightly hacky, but we want module autoloading * to work for root. * case: user opens device, attached -> ok * case: user opens device, unattached, in_request_module=0 -> autoload * case: user opens device, unattached, in_request_module=1 -> fail * case: root opens device, attached -> ok * case: root opens device, unattached, in_request_module=1 -> ok * (typically called from modprobe) * case: root opens device, unattached, in_request_module=0 -> autoload * * The last could be changed to "-> ok", which would deny root * autoloading. */ mutex_lock(&dev->mutex); if (dev->attached) goto ok; if (!capable(CAP_NET_ADMIN) && dev->in_request_module) { DPRINTK("in request module\n"); mutex_unlock(&dev->mutex); return -ENODEV; } if (capable(CAP_NET_ADMIN) && dev->in_request_module) goto ok; dev->in_request_module = 1; #ifdef CONFIG_KMOD mutex_unlock(&dev->mutex); request_module("char-major-%i-%i", COMEDI_MAJOR, dev->minor); mutex_lock(&dev->mutex); #endif dev->in_request_module = 0; if (!dev->attached && !capable(CAP_NET_ADMIN)) { DPRINTK("not attached and not CAP_NET_ADMIN\n"); mutex_unlock(&dev->mutex); return -ENODEV; } ok: __module_get(THIS_MODULE); if (dev->attached) { if (!try_module_get(dev->driver->module)) { module_put(THIS_MODULE); mutex_unlock(&dev->mutex); return -ENOSYS; } } if (dev->attached && dev->use_count == 0 && dev->open) { int rc = dev->open(dev); if (rc < 0) { module_put(dev->driver->module); module_put(THIS_MODULE); mutex_unlock(&dev->mutex); return rc; } } dev->use_count++; mutex_unlock(&dev->mutex); return 0; } static int comedi_close(struct inode *inode, struct file *file) { const unsigned minor = iminor(inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; struct comedi_subdevice *s = NULL; int i; mutex_lock(&dev->mutex); if (dev->subdevices) { for (i = 0; i < dev->n_subdevices; i++) { s = dev->subdevices + i; if (s->busy == file) do_cancel(dev, s); if (s->lock == file) s->lock = NULL; } } if (dev->attached && dev->use_count == 1 && dev->close) dev->close(dev); module_put(THIS_MODULE); if (dev->attached) module_put(dev->driver->module); dev->use_count--; mutex_unlock(&dev->mutex); if (file->f_flags & FASYNC) comedi_fasync(-1, file, 0); return 0; } static int comedi_fasync(int fd, struct file *file, int on) { const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; return fasync_helper(fd, file, on, &dev->async_queue); } const struct file_operations comedi_fops = { .owner = THIS_MODULE, .unlocked_ioctl = comedi_unlocked_ioctl, .compat_ioctl = comedi_compat_ioctl, .open = comedi_open, .release = comedi_close, .read = comedi_read, .write = comedi_write, .mmap = comedi_mmap, .poll = comedi_poll, .fasync = comedi_fasync, .llseek = noop_llseek, }; struct class *comedi_class; static struct cdev comedi_cdev; static void comedi_cleanup_legacy_minors(void) { unsigned i; for (i = 0; i < comedi_num_legacy_minors; i++) comedi_free_board_minor(i); } static int __init comedi_init(void) { int i; int retval; printk(KERN_INFO "comedi: version " COMEDI_RELEASE " - http://www.comedi.org\n"); if (comedi_num_legacy_minors < 0 || comedi_num_legacy_minors > COMEDI_NUM_BOARD_MINORS) { printk(KERN_ERR "comedi: error: invalid value for module " "parameter \"comedi_num_legacy_minors\". Valid values " "are 0 through %i.\n", COMEDI_NUM_BOARD_MINORS); return -EINVAL; } /* * comedi is unusable if both comedi_autoconfig and * comedi_num_legacy_minors are zero, so we might as well adjust the * defaults in that case */ if (comedi_autoconfig == 0 && comedi_num_legacy_minors == 0) comedi_num_legacy_minors = 16; memset(comedi_file_info_table, 0, sizeof(struct comedi_device_file_info *) * COMEDI_NUM_MINORS); retval = register_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS, "comedi"); if (retval) return -EIO; cdev_init(&comedi_cdev, &comedi_fops); comedi_cdev.owner = THIS_MODULE; kobject_set_name(&comedi_cdev.kobj, "comedi"); if (cdev_add(&comedi_cdev, MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS)) { unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS); return -EIO; } comedi_class = class_create(THIS_MODULE, "comedi"); if (IS_ERR(comedi_class)) { printk(KERN_ERR "comedi: failed to create class"); cdev_del(&comedi_cdev); unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS); return PTR_ERR(comedi_class); } /* XXX requires /proc interface */ comedi_proc_init(); /* create devices files for legacy/manual use */ for (i = 0; i < comedi_num_legacy_minors; i++) { int minor; minor = comedi_alloc_board_minor(NULL); if (minor < 0) { comedi_cleanup_legacy_minors(); cdev_del(&comedi_cdev); unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS); return minor; } } return 0; } static void __exit comedi_cleanup(void) { int i; comedi_cleanup_legacy_minors(); for (i = 0; i < COMEDI_NUM_MINORS; ++i) BUG_ON(comedi_file_info_table[i]); class_destroy(comedi_class); cdev_del(&comedi_cdev); unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS); comedi_proc_cleanup(); } module_init(comedi_init); module_exit(comedi_cleanup); void comedi_error(const struct comedi_device *dev, const char *s) { printk(KERN_ERR "comedi%d: %s: %s\n", dev->minor, dev->driver->driver_name, s); } EXPORT_SYMBOL(comedi_error); void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s) { struct comedi_async *async = s->async; unsigned runflags = 0; unsigned runflags_mask = 0; /* DPRINTK("comedi_event 0x%x\n",mask); */ if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) == 0) return; if (s-> async->events & (COMEDI_CB_EOA | COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)) { runflags_mask |= SRF_RUNNING; } /* remember if an error event has occurred, so an error * can be returned the next time the user does a read() */ if (s->async->events & (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)) { runflags_mask |= SRF_ERROR; runflags |= SRF_ERROR; } if (runflags_mask) { /*sets SRF_ERROR and SRF_RUNNING together atomically */ comedi_set_subdevice_runflags(s, runflags_mask, runflags); } if (async->cb_mask & s->async->events) { if (comedi_get_subdevice_runflags(s) & SRF_USER) { wake_up_interruptible(&async->wait_head); if (s->subdev_flags & SDF_CMD_READ) kill_fasync(&dev->async_queue, SIGIO, POLL_IN); if (s->subdev_flags & SDF_CMD_WRITE) kill_fasync(&dev->async_queue, SIGIO, POLL_OUT); } else { if (async->cb_func) async->cb_func(s->async->events, async->cb_arg); } } s->async->events = 0; } EXPORT_SYMBOL(comedi_event); unsigned comedi_get_subdevice_runflags(struct comedi_subdevice *s) { unsigned long flags; unsigned runflags; spin_lock_irqsave(&s->spin_lock, flags); runflags = s->runflags; spin_unlock_irqrestore(&s->spin_lock, flags); return runflags; } EXPORT_SYMBOL(comedi_get_subdevice_runflags); static int is_device_busy(struct comedi_device *dev) { struct comedi_subdevice *s; int i; if (!dev->attached) return 0; for (i = 0; i < dev->n_subdevices; i++) { s = dev->subdevices + i; if (s->busy) return 1; if (s->async && s->async->mmap_count) return 1; } return 0; } static void comedi_device_init(struct comedi_device *dev) { memset(dev, 0, sizeof(struct comedi_device)); spin_lock_init(&dev->spinlock); mutex_init(&dev->mutex); dev->minor = -1; } static void comedi_device_cleanup(struct comedi_device *dev) { if (dev == NULL) return; mutex_lock(&dev->mutex); comedi_device_detach(dev); mutex_unlock(&dev->mutex); mutex_destroy(&dev->mutex); } int comedi_alloc_board_minor(struct device *hardware_device) { unsigned long flags; struct comedi_device_file_info *info; struct device *csdev; unsigned i; int retval; info = kzalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL); if (info == NULL) return -ENOMEM; info->device = kzalloc(sizeof(struct comedi_device), GFP_KERNEL); if (info->device == NULL) { kfree(info); return -ENOMEM; } comedi_device_init(info->device); spin_lock_irqsave(&comedi_file_info_table_lock, flags); for (i = 0; i < COMEDI_NUM_BOARD_MINORS; ++i) { if (comedi_file_info_table[i] == NULL) { comedi_file_info_table[i] = info; break; } } spin_unlock_irqrestore(&comedi_file_info_table_lock, flags); if (i == COMEDI_NUM_BOARD_MINORS) { comedi_device_cleanup(info->device); kfree(info->device); kfree(info); printk(KERN_ERR "comedi: error: " "ran out of minor numbers for board device files.\n"); return -EBUSY; } info->device->minor = i; csdev = COMEDI_DEVICE_CREATE(comedi_class, NULL, MKDEV(COMEDI_MAJOR, i), NULL, hardware_device, "comedi%i", i); if (!IS_ERR(csdev)) info->device->class_dev = csdev; dev_set_drvdata(csdev, info); retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_max_read_buffer_kb.attr.name); comedi_free_board_minor(i); return retval; } retval = device_create_file(csdev, &dev_attr_read_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_read_buffer_kb.attr.name); comedi_free_board_minor(i); return retval; } retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_max_write_buffer_kb.attr.name); comedi_free_board_minor(i); return retval; } retval = device_create_file(csdev, &dev_attr_write_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_write_buffer_kb.attr.name); comedi_free_board_minor(i); return retval; } return i; } void comedi_free_board_minor(unsigned minor) { unsigned long flags; struct comedi_device_file_info *info; BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS); spin_lock_irqsave(&comedi_file_info_table_lock, flags); info = comedi_file_info_table[minor]; comedi_file_info_table[minor] = NULL; spin_unlock_irqrestore(&comedi_file_info_table_lock, flags); if (info) { struct comedi_device *dev = info->device; if (dev) { if (dev->class_dev) { device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, dev->minor)); } comedi_device_cleanup(dev); kfree(dev); } kfree(info); } } int comedi_alloc_subdevice_minor(struct comedi_device *dev, struct comedi_subdevice *s) { unsigned long flags; struct comedi_device_file_info *info; struct device *csdev; unsigned i; int retval; info = kmalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL); if (info == NULL) return -ENOMEM; info->device = dev; info->read_subdevice = s; info->write_subdevice = s; spin_lock_irqsave(&comedi_file_info_table_lock, flags); for (i = COMEDI_FIRST_SUBDEVICE_MINOR; i < COMEDI_NUM_MINORS; ++i) { if (comedi_file_info_table[i] == NULL) { comedi_file_info_table[i] = info; break; } } spin_unlock_irqrestore(&comedi_file_info_table_lock, flags); if (i == COMEDI_NUM_MINORS) { kfree(info); printk(KERN_ERR "comedi: error: " "ran out of minor numbers for board device files.\n"); return -EBUSY; } s->minor = i; csdev = COMEDI_DEVICE_CREATE(comedi_class, dev->class_dev, MKDEV(COMEDI_MAJOR, i), NULL, NULL, "comedi%i_subd%i", dev->minor, (int)(s - dev->subdevices)); if (!IS_ERR(csdev)) s->class_dev = csdev; dev_set_drvdata(csdev, info); retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_max_read_buffer_kb.attr.name); comedi_free_subdevice_minor(s); return retval; } retval = device_create_file(csdev, &dev_attr_read_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_read_buffer_kb.attr.name); comedi_free_subdevice_minor(s); return retval; } retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_max_write_buffer_kb.attr.name); comedi_free_subdevice_minor(s); return retval; } retval = device_create_file(csdev, &dev_attr_write_buffer_kb); if (retval) { printk(KERN_ERR "comedi: " "failed to create sysfs attribute file \"%s\".\n", dev_attr_write_buffer_kb.attr.name); comedi_free_subdevice_minor(s); return retval; } return i; } void comedi_free_subdevice_minor(struct comedi_subdevice *s) { unsigned long flags; struct comedi_device_file_info *info; if (s == NULL) return; if (s->minor < 0) return; BUG_ON(s->minor >= COMEDI_NUM_MINORS); BUG_ON(s->minor < COMEDI_FIRST_SUBDEVICE_MINOR); spin_lock_irqsave(&comedi_file_info_table_lock, flags); info = comedi_file_info_table[s->minor]; comedi_file_info_table[s->minor] = NULL; spin_unlock_irqrestore(&comedi_file_info_table_lock, flags); if (s->class_dev) { device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, s->minor)); s->class_dev = NULL; } kfree(info); } struct comedi_device_file_info *comedi_get_device_file_info(unsigned minor) { unsigned long flags; struct comedi_device_file_info *info; BUG_ON(minor >= COMEDI_NUM_MINORS); spin_lock_irqsave(&comedi_file_info_table_lock, flags); info = comedi_file_info_table[minor]; spin_unlock_irqrestore(&comedi_file_info_table_lock, flags); return info; } EXPORT_SYMBOL_GPL(comedi_get_device_file_info); static int resize_async_buffer(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_async *async, unsigned new_size) { int retval; if (new_size > async->max_bufsize) return -EPERM; if (s->busy) { DPRINTK("subdevice is busy, cannot resize buffer\n"); return -EBUSY; } if (async->mmap_count) { DPRINTK("subdevice is mmapped, cannot resize buffer\n"); return -EBUSY; } if (!async->prealloc_buf) return -EINVAL; /* make sure buffer is an integral number of pages * (we round up) */ new_size = (new_size + PAGE_SIZE - 1) & PAGE_MASK; retval = comedi_buf_alloc(dev, s, new_size); if (retval < 0) return retval; if (s->buf_change) { retval = s->buf_change(dev, s, new_size); if (retval < 0) return retval; } DPRINTK("comedi%i subd %d buffer resized to %i bytes\n", dev->minor, (int)(s - dev->subdevices), async->prealloc_bufsz); return 0; } /* sysfs attribute files */ static const unsigned bytes_per_kibi = 1024; static ssize_t show_max_read_buffer_kb(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t retval; struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned max_buffer_size_kb = 0; struct comedi_subdevice *const read_subdevice = comedi_get_read_subdevice(info); mutex_lock(&info->device->mutex); if (read_subdevice && (read_subdevice->subdev_flags & SDF_CMD_READ) && read_subdevice->async) { max_buffer_size_kb = read_subdevice->async->max_bufsize / bytes_per_kibi; } retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb); mutex_unlock(&info->device->mutex); return retval; } static ssize_t store_max_read_buffer_kb(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned long new_max_size_kb; uint64_t new_max_size; struct comedi_subdevice *const read_subdevice = comedi_get_read_subdevice(info); if (strict_strtoul(buf, 10, &new_max_size_kb)) return -EINVAL; if (new_max_size_kb != (uint32_t) new_max_size_kb) return -EINVAL; new_max_size = ((uint64_t) new_max_size_kb) * bytes_per_kibi; if (new_max_size != (uint32_t) new_max_size) return -EINVAL; mutex_lock(&info->device->mutex); if (read_subdevice == NULL || (read_subdevice->subdev_flags & SDF_CMD_READ) == 0 || read_subdevice->async == NULL) { mutex_unlock(&info->device->mutex); return -EINVAL; } read_subdevice->async->max_bufsize = new_max_size; mutex_unlock(&info->device->mutex); return count; } static struct device_attribute dev_attr_max_read_buffer_kb = { .attr = { .name = "max_read_buffer_kb", .mode = S_IRUGO | S_IWUSR}, .show = &show_max_read_buffer_kb, .store = &store_max_read_buffer_kb }; static ssize_t show_read_buffer_kb(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t retval; struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned buffer_size_kb = 0; struct comedi_subdevice *const read_subdevice = comedi_get_read_subdevice(info); mutex_lock(&info->device->mutex); if (read_subdevice && (read_subdevice->subdev_flags & SDF_CMD_READ) && read_subdevice->async) { buffer_size_kb = read_subdevice->async->prealloc_bufsz / bytes_per_kibi; } retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb); mutex_unlock(&info->device->mutex); return retval; } static ssize_t store_read_buffer_kb(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned long new_size_kb; uint64_t new_size; int retval; struct comedi_subdevice *const read_subdevice = comedi_get_read_subdevice(info); if (strict_strtoul(buf, 10, &new_size_kb)) return -EINVAL; if (new_size_kb != (uint32_t) new_size_kb) return -EINVAL; new_size = ((uint64_t) new_size_kb) * bytes_per_kibi; if (new_size != (uint32_t) new_size) return -EINVAL; mutex_lock(&info->device->mutex); if (read_subdevice == NULL || (read_subdevice->subdev_flags & SDF_CMD_READ) == 0 || read_subdevice->async == NULL) { mutex_unlock(&info->device->mutex); return -EINVAL; } retval = resize_async_buffer(info->device, read_subdevice, read_subdevice->async, new_size); mutex_unlock(&info->device->mutex); if (retval < 0) return retval; return count; } static struct device_attribute dev_attr_read_buffer_kb = { .attr = { .name = "read_buffer_kb", .mode = S_IRUGO | S_IWUSR | S_IWGRP}, .show = &show_read_buffer_kb, .store = &store_read_buffer_kb }; static ssize_t show_max_write_buffer_kb(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t retval; struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned max_buffer_size_kb = 0; struct comedi_subdevice *const write_subdevice = comedi_get_write_subdevice(info); mutex_lock(&info->device->mutex); if (write_subdevice && (write_subdevice->subdev_flags & SDF_CMD_WRITE) && write_subdevice->async) { max_buffer_size_kb = write_subdevice->async->max_bufsize / bytes_per_kibi; } retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb); mutex_unlock(&info->device->mutex); return retval; } static ssize_t store_max_write_buffer_kb(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned long new_max_size_kb; uint64_t new_max_size; struct comedi_subdevice *const write_subdevice = comedi_get_write_subdevice(info); if (strict_strtoul(buf, 10, &new_max_size_kb)) return -EINVAL; if (new_max_size_kb != (uint32_t) new_max_size_kb) return -EINVAL; new_max_size = ((uint64_t) new_max_size_kb) * bytes_per_kibi; if (new_max_size != (uint32_t) new_max_size) return -EINVAL; mutex_lock(&info->device->mutex); if (write_subdevice == NULL || (write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 || write_subdevice->async == NULL) { mutex_unlock(&info->device->mutex); return -EINVAL; } write_subdevice->async->max_bufsize = new_max_size; mutex_unlock(&info->device->mutex); return count; } static struct device_attribute dev_attr_max_write_buffer_kb = { .attr = { .name = "max_write_buffer_kb", .mode = S_IRUGO | S_IWUSR}, .show = &show_max_write_buffer_kb, .store = &store_max_write_buffer_kb }; static ssize_t show_write_buffer_kb(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t retval; struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned buffer_size_kb = 0; struct comedi_subdevice *const write_subdevice = comedi_get_write_subdevice(info); mutex_lock(&info->device->mutex); if (write_subdevice && (write_subdevice->subdev_flags & SDF_CMD_WRITE) && write_subdevice->async) { buffer_size_kb = write_subdevice->async->prealloc_bufsz / bytes_per_kibi; } retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb); mutex_unlock(&info->device->mutex); return retval; } static ssize_t store_write_buffer_kb(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct comedi_device_file_info *info = dev_get_drvdata(dev); unsigned long new_size_kb; uint64_t new_size; int retval; struct comedi_subdevice *const write_subdevice = comedi_get_write_subdevice(info); if (strict_strtoul(buf, 10, &new_size_kb)) return -EINVAL; if (new_size_kb != (uint32_t) new_size_kb) return -EINVAL; new_size = ((uint64_t) new_size_kb) * bytes_per_kibi; if (new_size != (uint32_t) new_size) return -EINVAL; mutex_lock(&info->device->mutex); if (write_subdevice == NULL || (write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 || write_subdevice->async == NULL) { mutex_unlock(&info->device->mutex); return -EINVAL; } retval = resize_async_buffer(info->device, write_subdevice, write_subdevice->async, new_size); mutex_unlock(&info->device->mutex); if (retval < 0) return retval; return count; } static struct device_attribute dev_attr_write_buffer_kb = { .attr = { .name = "write_buffer_kb", .mode = S_IRUGO | S_IWUSR | S_IWGRP}, .show = &show_write_buffer_kb, .store = &store_write_buffer_kb };
./CrossVul/dataset_final_sorted/CWE-200/c/good_3485_0
crossvul-cpp_data_bad_1829_4
/***********************************************************************/ /* */ /* OCaml */ /* */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* */ /* Copyright 1996 Institut National de Recherche en Informatique et */ /* en Automatique. All rights reserved. This file is distributed */ /* under the terms of the GNU Library General Public License, with */ /* the special exception on linking described in file ../LICENSE. */ /* */ /***********************************************************************/ /* Operations on strings */ #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "caml/alloc.h" #include "caml/fail.h" #include "caml/mlvalues.h" #include "caml/misc.h" /* returns a number of bytes (chars) */ CAMLexport mlsize_t caml_string_length(value s) { mlsize_t temp; temp = Bosize_val(s) - 1; Assert (Byte (s, temp - Byte (s, temp)) == 0); return temp - Byte (s, temp); } /* returns a value that represents a number of bytes (chars) */ CAMLprim value caml_ml_string_length(value s) { mlsize_t temp; temp = Bosize_val(s) - 1; Assert (Byte (s, temp - Byte (s, temp)) == 0); return Val_long(temp - Byte (s, temp)); } /* [len] is a value that represents a number of bytes (chars) */ CAMLprim value caml_create_string(value len) { mlsize_t size = Long_val(len); if (size > Bsize_wsize (Max_wosize) - 1){ caml_invalid_argument("String.create"); } return caml_alloc_string(size); } CAMLprim value caml_string_get(value str, value index) { intnat idx = Long_val(index); if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error(); return Val_int(Byte_u(str, idx)); } CAMLprim value caml_string_set(value str, value index, value newval) { intnat idx = Long_val(index); if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error(); Byte_u(str, idx) = Int_val(newval); return Val_unit; } CAMLprim value caml_string_get16(value str, value index) { intnat res; unsigned char b1, b2; intnat idx = Long_val(index); if (idx < 0 || idx + 1 >= caml_string_length(str)) caml_array_bound_error(); b1 = Byte_u(str, idx); b2 = Byte_u(str, idx + 1); #ifdef ARCH_BIG_ENDIAN res = b1 << 8 | b2; #else res = b2 << 8 | b1; #endif return Val_int(res); } CAMLprim value caml_string_get32(value str, value index) { intnat res; unsigned char b1, b2, b3, b4; intnat idx = Long_val(index); if (idx < 0 || idx + 3 >= caml_string_length(str)) caml_array_bound_error(); b1 = Byte_u(str, idx); b2 = Byte_u(str, idx + 1); b3 = Byte_u(str, idx + 2); b4 = Byte_u(str, idx + 3); #ifdef ARCH_BIG_ENDIAN res = b1 << 24 | b2 << 16 | b3 << 8 | b4; #else res = b4 << 24 | b3 << 16 | b2 << 8 | b1; #endif return caml_copy_int32(res); } CAMLprim value caml_string_get64(value str, value index) { uint64_t res; unsigned char b1, b2, b3, b4, b5, b6, b7, b8; intnat idx = Long_val(index); if (idx < 0 || idx + 7 >= caml_string_length(str)) caml_array_bound_error(); b1 = Byte_u(str, idx); b2 = Byte_u(str, idx + 1); b3 = Byte_u(str, idx + 2); b4 = Byte_u(str, idx + 3); b5 = Byte_u(str, idx + 4); b6 = Byte_u(str, idx + 5); b7 = Byte_u(str, idx + 6); b8 = Byte_u(str, idx + 7); #ifdef ARCH_BIG_ENDIAN res = (uint64_t) b1 << 56 | (uint64_t) b2 << 48 | (uint64_t) b3 << 40 | (uint64_t) b4 << 32 | (uint64_t) b5 << 24 | (uint64_t) b6 << 16 | (uint64_t) b7 << 8 | (uint64_t) b8; #else res = (uint64_t) b8 << 56 | (uint64_t) b7 << 48 | (uint64_t) b6 << 40 | (uint64_t) b5 << 32 | (uint64_t) b4 << 24 | (uint64_t) b3 << 16 | (uint64_t) b2 << 8 | (uint64_t) b1; #endif return caml_copy_int64(res); } CAMLprim value caml_string_set16(value str, value index, value newval) { unsigned char b1, b2; intnat val; intnat idx = Long_val(index); if (idx < 0 || idx + 1 >= caml_string_length(str)) caml_array_bound_error(); val = Long_val(newval); #ifdef ARCH_BIG_ENDIAN b1 = 0xFF & val >> 8; b2 = 0xFF & val; #else b2 = 0xFF & val >> 8; b1 = 0xFF & val; #endif Byte_u(str, idx) = b1; Byte_u(str, idx + 1) = b2; return Val_unit; } CAMLprim value caml_string_set32(value str, value index, value newval) { unsigned char b1, b2, b3, b4; intnat val; intnat idx = Long_val(index); if (idx < 0 || idx + 3 >= caml_string_length(str)) caml_array_bound_error(); val = Int32_val(newval); #ifdef ARCH_BIG_ENDIAN b1 = 0xFF & val >> 24; b2 = 0xFF & val >> 16; b3 = 0xFF & val >> 8; b4 = 0xFF & val; #else b4 = 0xFF & val >> 24; b3 = 0xFF & val >> 16; b2 = 0xFF & val >> 8; b1 = 0xFF & val; #endif Byte_u(str, idx) = b1; Byte_u(str, idx + 1) = b2; Byte_u(str, idx + 2) = b3; Byte_u(str, idx + 3) = b4; return Val_unit; } CAMLprim value caml_string_set64(value str, value index, value newval) { unsigned char b1, b2, b3, b4, b5, b6, b7, b8; int64_t val; intnat idx = Long_val(index); if (idx < 0 || idx + 7 >= caml_string_length(str)) caml_array_bound_error(); val = Int64_val(newval); #ifdef ARCH_BIG_ENDIAN b1 = 0xFF & val >> 56; b2 = 0xFF & val >> 48; b3 = 0xFF & val >> 40; b4 = 0xFF & val >> 32; b5 = 0xFF & val >> 24; b6 = 0xFF & val >> 16; b7 = 0xFF & val >> 8; b8 = 0xFF & val; #else b8 = 0xFF & val >> 56; b7 = 0xFF & val >> 48; b6 = 0xFF & val >> 40; b5 = 0xFF & val >> 32; b4 = 0xFF & val >> 24; b3 = 0xFF & val >> 16; b2 = 0xFF & val >> 8; b1 = 0xFF & val; #endif Byte_u(str, idx) = b1; Byte_u(str, idx + 1) = b2; Byte_u(str, idx + 2) = b3; Byte_u(str, idx + 3) = b4; Byte_u(str, idx + 4) = b5; Byte_u(str, idx + 5) = b6; Byte_u(str, idx + 6) = b7; Byte_u(str, idx + 7) = b8; return Val_unit; } CAMLprim value caml_string_equal(value s1, value s2) { mlsize_t sz1, sz2; value * p1, * p2; if (s1 == s2) return Val_true; sz1 = Wosize_val(s1); sz2 = Wosize_val(s2); if (sz1 != sz2) return Val_false; for(p1 = Op_val(s1), p2 = Op_val(s2); sz1 > 0; sz1--, p1++, p2++) if (*p1 != *p2) return Val_false; return Val_true; } CAMLprim value caml_string_notequal(value s1, value s2) { return Val_not(caml_string_equal(s1, s2)); } CAMLprim value caml_string_compare(value s1, value s2) { mlsize_t len1, len2; int res; if (s1 == s2) return Val_int(0); len1 = caml_string_length(s1); len2 = caml_string_length(s2); res = memcmp(String_val(s1), String_val(s2), len1 <= len2 ? len1 : len2); if (res < 0) return Val_int(-1); if (res > 0) return Val_int(1); if (len1 < len2) return Val_int(-1); if (len1 > len2) return Val_int(1); return Val_int(0); } CAMLprim value caml_string_lessthan(value s1, value s2) { return caml_string_compare(s1, s2) < Val_int(0) ? Val_true : Val_false; } CAMLprim value caml_string_lessequal(value s1, value s2) { return caml_string_compare(s1, s2) <= Val_int(0) ? Val_true : Val_false; } CAMLprim value caml_string_greaterthan(value s1, value s2) { return caml_string_compare(s1, s2) > Val_int(0) ? Val_true : Val_false; } CAMLprim value caml_string_greaterequal(value s1, value s2) { return caml_string_compare(s1, s2) >= Val_int(0) ? Val_true : Val_false; } CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2, value n) { memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n)); return Val_unit; } CAMLprim value caml_fill_string(value s, value offset, value len, value init) { memset(&Byte(s, Long_val(offset)), Int_val(init), Long_val(len)); return Val_unit; } CAMLprim value caml_bitvect_test(value bv, value n) { int pos = Int_val(n); return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7))); } CAMLexport value caml_alloc_sprintf(const char * format, ...) { va_list args; char buf[64]; int n; value res; #ifndef _WIN32 /* C99-compliant implementation */ va_start(args, format); /* "vsnprintf(dest, sz, format, args)" writes at most "sz" characters into "dest", including the terminating '\0'. It returns the number of characters of the formatted string, excluding the terminating '\0'. */ n = vsnprintf(buf, sizeof(buf), format, args); va_end(args); /* Allocate a Caml string with length "n" as computed by vsnprintf. */ res = caml_alloc_string(n); if (n < sizeof(buf)) { /* All output characters were written to buf, including the terminating '\0'. Just copy them to the result. */ memcpy(String_val(res), buf, n); } else { /* Re-do the formatting, outputting directly in the Caml string. Note that caml_alloc_string left room for a '\0' at position n, so the size passed to vsnprintf is n+1. */ va_start(args, format); vsnprintf(String_val(res), n + 1, format, args); va_end(args); } return res; #else /* Implementation specific to the Microsoft CRT library */ va_start(args, format); /* "_vsnprintf(dest, sz, format, args)" writes at most "sz" characters into "dest". Let "len" be the number of characters of the formatted string. If "len" < "sz", a null terminator was appended, and "len" is returned. If "len" == "sz", no null termination, and "len" is returned. If "len" > "sz", a negative value is returned. */ n = _vsnprintf(buf, sizeof(buf), format, args); va_end(args); if (n >= 0 && n <= sizeof(buf)) { /* All output characters were written to buf. "n" is the actual length of the output. Copy the characters to a Caml string of length n. */ res = caml_alloc_string(n); memcpy(String_val(res), buf, n); } else { /* Determine actual length of output, excluding final '\0' */ va_start(args, format); n = _vscprintf(format, args); va_end(args); res = caml_alloc_string(n); /* Re-do the formatting, outputting directly in the Caml string. Note that caml_alloc_string left room for a '\0' at position n, so the size passed to _vsnprintf is n+1. */ va_start(args, format); _vsnprintf(String_val(res), n + 1, format, args); va_end(args); } return res; #endif }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1829_4
crossvul-cpp_data_good_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; strncpy(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; strncpy(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; strncpy(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; strncpy(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; strncpy(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) { strncpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name)); strncpy(ualg->cru_driver_name, alg->cra_driver_name, sizeof(ualg->cru_driver_name)); strncpy(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; strncpy(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/good_460_0
crossvul-cpp_data_good_1394_0
// SPDX-License-Identifier: GPL-2.0 /* * linux/mm/mincore.c * * Copyright (C) 1994-2006 Linus Torvalds */ /* * The mincore() system call. */ #include <linux/pagemap.h> #include <linux/gfp.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/syscalls.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/shmem_fs.h> #include <linux/hugetlb.h> #include <linux/uaccess.h> #include <asm/pgtable.h> static int mincore_hugetlb(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { #ifdef CONFIG_HUGETLB_PAGE unsigned char present; unsigned char *vec = walk->private; /* * Hugepages under user process are always in RAM and never * swapped out, but theoretically it needs to be checked. */ present = pte && !huge_pte_none(huge_ptep_get(pte)); for (; addr != end; vec++, addr += PAGE_SIZE) *vec = present; walk->private = vec; #else BUG(); #endif return 0; } static int mincore_unmapped_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { unsigned char *vec = walk->private; unsigned long nr = (end - addr) >> PAGE_SHIFT; memset(vec, 0, nr); walk->private += nr; return 0; } static int mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { spinlock_t *ptl; struct vm_area_struct *vma = walk->vma; pte_t *ptep; unsigned char *vec = walk->private; int nr = (end - addr) >> PAGE_SHIFT; ptl = pmd_trans_huge_lock(pmd, vma); if (ptl) { memset(vec, 1, nr); spin_unlock(ptl); goto out; } /* We'll consider a THP page under construction to be there */ if (pmd_trans_unstable(pmd)) { memset(vec, 1, nr); goto out; } ptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); for (; addr != end; ptep++, addr += PAGE_SIZE) { pte_t pte = *ptep; if (pte_none(pte)) *vec = 0; else if (pte_present(pte)) *vec = 1; else { /* pte is a swap entry */ swp_entry_t entry = pte_to_swp_entry(pte); /* * migration or hwpoison entries are always * uptodate */ *vec = !!non_swap_entry(entry); } vec++; } pte_unmap_unlock(ptep - 1, ptl); out: walk->private += nr; cond_resched(); return 0; } /* * Do a chunk of "sys_mincore()". We've already checked * all the arguments, we hold the mmap semaphore: we should * just return the amount of info we're asked for. */ static long do_mincore(unsigned long addr, unsigned long pages, unsigned char *vec) { struct vm_area_struct *vma; unsigned long end; int err; struct mm_walk mincore_walk = { .pmd_entry = mincore_pte_range, .pte_hole = mincore_unmapped_range, .hugetlb_entry = mincore_hugetlb, .private = vec, }; vma = find_vma(current->mm, addr); if (!vma || addr < vma->vm_start) return -ENOMEM; mincore_walk.mm = vma->vm_mm; end = min(vma->vm_end, addr + (pages << PAGE_SHIFT)); err = walk_page_range(addr, end, &mincore_walk); if (err < 0) return err; return (end - addr) >> PAGE_SHIFT; } /* * The mincore(2) system call. * * mincore() returns the memory residency status of the pages in the * current process's address space specified by [addr, addr + len). * The status is returned in a vector of bytes. The least significant * bit of each byte is 1 if the referenced page is in memory, otherwise * it is zero. * * Because the status of a page can change after mincore() checks it * but before it returns to the application, the returned vector may * contain stale information. Only locked pages are guaranteed to * remain in memory. * * return values: * zero - success * -EFAULT - vec points to an illegal address * -EINVAL - addr is not a multiple of PAGE_SIZE * -ENOMEM - Addresses in the range [addr, addr + len] are * invalid for the address space of this process, or * specify one or more pages which are not currently * mapped * -EAGAIN - A kernel resource was temporarily unavailable. */ SYSCALL_DEFINE3(mincore, unsigned long, start, size_t, len, unsigned char __user *, vec) { long retval; unsigned long pages; unsigned char *tmp; /* Check the start address: needs to be page-aligned.. */ if (start & ~PAGE_MASK) return -EINVAL; /* ..and we need to be passed a valid user-space range */ if (!access_ok((void __user *) start, len)) return -ENOMEM; /* This also avoids any overflows on PAGE_ALIGN */ pages = len >> PAGE_SHIFT; pages += (offset_in_page(len)) != 0; if (!access_ok(vec, pages)) return -EFAULT; tmp = (void *) __get_free_page(GFP_USER); if (!tmp) return -EAGAIN; retval = 0; while (pages) { /* * Do at most PAGE_SIZE entries per iteration, due to * the temporary buffer size. */ down_read(&current->mm->mmap_sem); retval = do_mincore(start, min(pages, PAGE_SIZE), tmp); up_read(&current->mm->mmap_sem); if (retval <= 0) break; if (copy_to_user(vec, tmp, retval)) { retval = -EFAULT; break; } pages -= retval; vec += retval; start += retval << PAGE_SHIFT; retval = 0; } free_page((unsigned long) tmp); return retval; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_1394_0
crossvul-cpp_data_bad_5686_0
/* * Copyright (C) ST-Ericsson AB 2010 * Author: Sjur Brendeland sjur.brandeland@stericsson.com * License terms: GNU General Public License (GPL) version 2 */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__ #include <linux/fs.h> #include <linux/init.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/list.h> #include <linux/wait.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/uaccess.h> #include <linux/debugfs.h> #include <linux/caif/caif_socket.h> #include <linux/pkt_sched.h> #include <net/sock.h> #include <net/tcp_states.h> #include <net/caif/caif_layer.h> #include <net/caif/caif_dev.h> #include <net/caif/cfpkt.h> MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(AF_CAIF); /* * CAIF state is re-using the TCP socket states. * caif_states stored in sk_state reflect the state as reported by * the CAIF stack, while sk_socket->state is the state of the socket. */ enum caif_states { CAIF_CONNECTED = TCP_ESTABLISHED, CAIF_CONNECTING = TCP_SYN_SENT, CAIF_DISCONNECTED = TCP_CLOSE }; #define TX_FLOW_ON_BIT 1 #define RX_FLOW_ON_BIT 2 struct caifsock { struct sock sk; /* must be first member */ struct cflayer layer; u32 flow_state; struct caif_connect_request conn_req; struct mutex readlock; struct dentry *debugfs_socket_dir; int headroom, tailroom, maxframe; }; static int rx_flow_is_on(struct caifsock *cf_sk) { return test_bit(RX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static int tx_flow_is_on(struct caifsock *cf_sk) { return test_bit(TX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_rx_flow_off(struct caifsock *cf_sk) { clear_bit(RX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_rx_flow_on(struct caifsock *cf_sk) { set_bit(RX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_tx_flow_off(struct caifsock *cf_sk) { clear_bit(TX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_tx_flow_on(struct caifsock *cf_sk) { set_bit(TX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void caif_read_lock(struct sock *sk) { struct caifsock *cf_sk; cf_sk = container_of(sk, struct caifsock, sk); mutex_lock(&cf_sk->readlock); } static void caif_read_unlock(struct sock *sk) { struct caifsock *cf_sk; cf_sk = container_of(sk, struct caifsock, sk); mutex_unlock(&cf_sk->readlock); } static int sk_rcvbuf_lowwater(struct caifsock *cf_sk) { /* A quarter of full buffer is used a low water mark */ return cf_sk->sk.sk_rcvbuf / 4; } static void caif_flow_ctrl(struct sock *sk, int mode) { struct caifsock *cf_sk; cf_sk = container_of(sk, struct caifsock, sk); if (cf_sk->layer.dn && cf_sk->layer.dn->modemcmd) cf_sk->layer.dn->modemcmd(cf_sk->layer.dn, mode); } /* * Copied from sock.c:sock_queue_rcv_skb(), but changed so packets are * not dropped, but CAIF is sending flow off instead. */ static int caif_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; int skb_len; unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned int)sk->sk_rcvbuf && rx_flow_is_on(cf_sk)) { net_dbg_ratelimited("sending flow OFF (queue len = %d %d)\n", atomic_read(&cf_sk->sk.sk_rmem_alloc), sk_rcvbuf_lowwater(cf_sk)); set_rx_flow_off(cf_sk); caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ); } err = sk_filter(sk, skb); if (err) return err; if (!sk_rmem_schedule(sk, skb, skb->truesize) && rx_flow_is_on(cf_sk)) { set_rx_flow_off(cf_sk); net_dbg_ratelimited("sending flow OFF due to rmem_schedule\n"); caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ); } skb->dev = NULL; skb_set_owner_r(skb, sk); /* Cache the SKB length before we tack it onto the receive * queue. Once it is added it no longer belongs to us and * may be freed by other threads of control pulling packets * from the queue. */ skb_len = skb->len; spin_lock_irqsave(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb_len); else kfree_skb(skb); return 0; } /* Packet Receive Callback function called from CAIF Stack */ static int caif_sktrecv_cb(struct cflayer *layr, struct cfpkt *pkt) { struct caifsock *cf_sk; struct sk_buff *skb; cf_sk = container_of(layr, struct caifsock, layer); skb = cfpkt_tonative(pkt); if (unlikely(cf_sk->sk.sk_state != CAIF_CONNECTED)) { kfree_skb(skb); return 0; } caif_queue_rcv_skb(&cf_sk->sk, skb); return 0; } static void cfsk_hold(struct cflayer *layr) { struct caifsock *cf_sk = container_of(layr, struct caifsock, layer); sock_hold(&cf_sk->sk); } static void cfsk_put(struct cflayer *layr) { struct caifsock *cf_sk = container_of(layr, struct caifsock, layer); sock_put(&cf_sk->sk); } /* Packet Control Callback function called from CAIF */ static void caif_ctrl_cb(struct cflayer *layr, enum caif_ctrlcmd flow, int phyid) { struct caifsock *cf_sk = container_of(layr, struct caifsock, layer); switch (flow) { case CAIF_CTRLCMD_FLOW_ON_IND: /* OK from modem to start sending again */ set_tx_flow_on(cf_sk); cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_FLOW_OFF_IND: /* Modem asks us to shut up */ set_tx_flow_off(cf_sk); cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_INIT_RSP: /* We're now connected */ caif_client_register_refcnt(&cf_sk->layer, cfsk_hold, cfsk_put); cf_sk->sk.sk_state = CAIF_CONNECTED; set_tx_flow_on(cf_sk); cf_sk->sk.sk_shutdown = 0; cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_DEINIT_RSP: /* We're now disconnected */ cf_sk->sk.sk_state = CAIF_DISCONNECTED; cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_INIT_FAIL_RSP: /* Connect request failed */ cf_sk->sk.sk_err = ECONNREFUSED; cf_sk->sk.sk_state = CAIF_DISCONNECTED; cf_sk->sk.sk_shutdown = SHUTDOWN_MASK; /* * Socket "standards" seems to require POLLOUT to * be set at connect failure. */ set_tx_flow_on(cf_sk); cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_REMOTE_SHUTDOWN_IND: /* Modem has closed this connection, or device is down. */ cf_sk->sk.sk_shutdown = SHUTDOWN_MASK; cf_sk->sk.sk_err = ECONNRESET; set_rx_flow_on(cf_sk); cf_sk->sk.sk_error_report(&cf_sk->sk); break; default: pr_debug("Unexpected flow command %d\n", flow); } } static void caif_check_flow_release(struct sock *sk) { struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); if (rx_flow_is_on(cf_sk)) return; if (atomic_read(&sk->sk_rmem_alloc) <= sk_rcvbuf_lowwater(cf_sk)) { set_rx_flow_on(cf_sk); caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_ON_REQ); } } /* * Copied from unix_dgram_recvmsg, but removed credit checks, * changed locking, address handling and added MSG_TRUNC. */ static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int ret; int copylen; ret = -EOPNOTSUPP; if (m->msg_flags&MSG_OOB) goto read_error; skb = skb_recv_datagram(sk, flags, 0 , &ret); if (!skb) goto read_error; copylen = skb->len; if (len < copylen) { m->msg_flags |= MSG_TRUNC; copylen = len; } ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen); if (ret) goto out_free; ret = (flags & MSG_TRUNC) ? skb->len : copylen; out_free: skb_free_datagram(sk, skb); caif_check_flow_release(sk); return ret; read_error: return ret; } /* Copied from unix_stream_wait_data, identical except for lock call. */ static long caif_stream_data_wait(struct sock *sk, long timeo) { DEFINE_WAIT(wait); lock_sock(sk); for (;;) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (!skb_queue_empty(&sk->sk_receive_queue) || sk->sk_err || sk->sk_state != CAIF_CONNECTED || sock_flag(sk, SOCK_DEAD) || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current) || !timeo) break; set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); } finish_wait(sk_sleep(sk), &wait); release_sock(sk); return timeo; } /* * Copied from unix_stream_recvmsg, but removed credit checks, * changed locking calls, changed address handling. */ static int caif_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int copied = 0; int target; int err = 0; long timeo; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; msg->msg_namelen = 0; /* * Lock the socket to prevent queue disordering * while sleeps in memcpy_tomsg */ err = -EAGAIN; if (sk->sk_state == CAIF_CONNECTING) goto out; caif_read_lock(sk); target = sock_rcvlowat(sk, flags&MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT); do { int chunk; struct sk_buff *skb; lock_sock(sk); skb = skb_dequeue(&sk->sk_receive_queue); caif_check_flow_release(sk); if (skb == NULL) { if (copied >= target) goto unlock; /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) goto unlock; err = -ECONNRESET; if (sk->sk_shutdown & RCV_SHUTDOWN) goto unlock; err = -EPIPE; if (sk->sk_state != CAIF_CONNECTED) goto unlock; if (sock_flag(sk, SOCK_DEAD)) goto unlock; release_sock(sk); err = -EAGAIN; if (!timeo) break; caif_read_unlock(sk); timeo = caif_stream_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } caif_read_lock(sk); continue; unlock: release_sock(sk); break; } release_sock(sk); chunk = min_t(unsigned int, skb->len, size); if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { skb_pull(skb, chunk); /* put the skb back if we didn't use it up. */ if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* * It is questionable, see note in unix_dgram_recvmsg. */ /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); caif_read_unlock(sk); out: return copied ? : err; } /* * Copied from sock.c:sock_wait_for_wmem, but change to wait for * CAIF flow-on and sock_writable. */ static long caif_wait_for_flow_on(struct caifsock *cf_sk, int wait_writeable, long timeo, int *err) { struct sock *sk = &cf_sk->sk; DEFINE_WAIT(wait); for (;;) { *err = 0; if (tx_flow_is_on(cf_sk) && (!wait_writeable || sock_writeable(&cf_sk->sk))) break; *err = -ETIMEDOUT; if (!timeo) break; *err = -ERESTARTSYS; if (signal_pending(current)) break; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); *err = -ECONNRESET; if (sk->sk_shutdown & SHUTDOWN_MASK) break; *err = -sk->sk_err; if (sk->sk_err) break; *err = -EPIPE; if (cf_sk->sk.sk_state != CAIF_CONNECTED) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Transmit a SKB. The device may temporarily request re-transmission * by returning EAGAIN. */ static int transmit_skb(struct sk_buff *skb, struct caifsock *cf_sk, int noblock, long timeo) { struct cfpkt *pkt; pkt = cfpkt_fromnative(CAIF_DIR_OUT, skb); memset(skb->cb, 0, sizeof(struct caif_payload_info)); cfpkt_set_prio(pkt, cf_sk->sk.sk_priority); if (cf_sk->layer.dn == NULL) { kfree_skb(skb); return -EINVAL; } return cf_sk->layer.dn->transmit(cf_sk->layer.dn, pkt); } /* Copied from af_unix:unix_dgram_sendmsg, and adapted to CAIF */ static int caif_seqpkt_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); int buffer_size; int ret = 0; struct sk_buff *skb = NULL; int noblock; long timeo; caif_assert(cf_sk); ret = sock_error(sk); if (ret) goto err; ret = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto err; ret = -EOPNOTSUPP; if (msg->msg_namelen) goto err; ret = -EINVAL; if (unlikely(msg->msg_iov->iov_base == NULL)) goto err; noblock = msg->msg_flags & MSG_DONTWAIT; timeo = sock_sndtimeo(sk, noblock); timeo = caif_wait_for_flow_on(container_of(sk, struct caifsock, sk), 1, timeo, &ret); if (ret) goto err; ret = -EPIPE; if (cf_sk->sk.sk_state != CAIF_CONNECTED || sock_flag(sk, SOCK_DEAD) || (sk->sk_shutdown & RCV_SHUTDOWN)) goto err; /* Error if trying to write more than maximum frame size. */ ret = -EMSGSIZE; if (len > cf_sk->maxframe && cf_sk->sk.sk_protocol != CAIFPROTO_RFM) goto err; buffer_size = len + cf_sk->headroom + cf_sk->tailroom; ret = -ENOMEM; skb = sock_alloc_send_skb(sk, buffer_size, noblock, &ret); if (!skb || skb_tailroom(skb) < buffer_size) goto err; skb_reserve(skb, cf_sk->headroom); ret = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len); if (ret) goto err; ret = transmit_skb(skb, cf_sk, noblock, timeo); if (ret < 0) /* skb is already freed */ return ret; return len; err: kfree_skb(skb); return ret; } /* * Copied from unix_stream_sendmsg and adapted to CAIF: * Changed removed permission handling and added waiting for flow on * and other minor adaptations. */ static int caif_stream_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); int err, size; struct sk_buff *skb; int sent = 0; long timeo; err = -EOPNOTSUPP; if (unlikely(msg->msg_flags&MSG_OOB)) goto out_err; if (unlikely(msg->msg_namelen)) goto out_err; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); timeo = caif_wait_for_flow_on(cf_sk, 1, timeo, &err); if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN)) goto pipe_err; while (sent < len) { size = len-sent; if (size > cf_sk->maxframe) size = cf_sk->maxframe; /* If size is more than half of sndbuf, chop up message */ if (size > ((sk->sk_sndbuf >> 1) - 64)) size = (sk->sk_sndbuf >> 1) - 64; if (size > SKB_MAX_ALLOC) size = SKB_MAX_ALLOC; skb = sock_alloc_send_skb(sk, size + cf_sk->headroom + cf_sk->tailroom, msg->msg_flags&MSG_DONTWAIT, &err); if (skb == NULL) goto out_err; skb_reserve(skb, cf_sk->headroom); /* * If you pass two values to the sock_alloc_send_skb * it tries to grab the large buffer with GFP_NOFS * (which can fail easily), and if it fails grab the * fallback size buffer which is under a page and will * succeed. [Alan] */ size = min_t(int, size, skb_tailroom(skb)); err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size); if (err) { kfree_skb(skb); goto out_err; } err = transmit_skb(skb, cf_sk, msg->msg_flags&MSG_DONTWAIT, timeo); if (err < 0) /* skb is already freed */ goto pipe_err; sent += size; } return sent; pipe_err: if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL)) send_sig(SIGPIPE, current, 0); err = -EPIPE; out_err: return sent ? : err; } static int setsockopt(struct socket *sock, int lvl, int opt, char __user *ov, unsigned int ol) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); int linksel; if (cf_sk->sk.sk_socket->state != SS_UNCONNECTED) return -ENOPROTOOPT; switch (opt) { case CAIFSO_LINK_SELECT: if (ol < sizeof(int)) return -EINVAL; if (lvl != SOL_CAIF) goto bad_sol; if (copy_from_user(&linksel, ov, sizeof(int))) return -EINVAL; lock_sock(&(cf_sk->sk)); cf_sk->conn_req.link_selector = linksel; release_sock(&cf_sk->sk); return 0; case CAIFSO_REQ_PARAM: if (lvl != SOL_CAIF) goto bad_sol; if (cf_sk->sk.sk_protocol != CAIFPROTO_UTIL) return -ENOPROTOOPT; lock_sock(&(cf_sk->sk)); if (ol > sizeof(cf_sk->conn_req.param.data) || copy_from_user(&cf_sk->conn_req.param.data, ov, ol)) { release_sock(&cf_sk->sk); return -EINVAL; } cf_sk->conn_req.param.size = ol; release_sock(&cf_sk->sk); return 0; default: return -ENOPROTOOPT; } return 0; bad_sol: return -ENOPROTOOPT; } /* * caif_connect() - Connect a CAIF Socket * Copied and modified af_irda.c:irda_connect(). * * Note : by consulting "errno", the user space caller may learn the cause * of the failure. Most of them are visible in the function, others may come * from subroutines called and are listed here : * o -EAFNOSUPPORT: bad socket family or type. * o -ESOCKTNOSUPPORT: bad socket type or protocol * o -EINVAL: bad socket address, or CAIF link type * o -ECONNREFUSED: remote end refused the connection. * o -EINPROGRESS: connect request sent but timed out (or non-blocking) * o -EISCONN: already connected. * o -ETIMEDOUT: Connection timed out (send timeout) * o -ENODEV: No link layer to send request * o -ECONNRESET: Received Shutdown indication or lost link layer * o -ENOMEM: Out of memory * * State Strategy: * o sk_state: holds the CAIF_* protocol state, it's updated by * caif_ctrl_cb. * o sock->state: holds the SS_* socket state and is updated by connect and * disconnect. */ static int caif_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); long timeo; int err; int ifindex, headroom, tailroom; unsigned int mtu; struct net_device *dev; lock_sock(sk); err = -EAFNOSUPPORT; if (uaddr->sa_family != AF_CAIF) goto out; switch (sock->state) { case SS_UNCONNECTED: /* Normal case, a fresh connect */ caif_assert(sk->sk_state == CAIF_DISCONNECTED); break; case SS_CONNECTING: switch (sk->sk_state) { case CAIF_CONNECTED: sock->state = SS_CONNECTED; err = -EISCONN; goto out; case CAIF_DISCONNECTED: /* Reconnect allowed */ break; case CAIF_CONNECTING: err = -EALREADY; if (flags & O_NONBLOCK) goto out; goto wait_connect; } break; case SS_CONNECTED: caif_assert(sk->sk_state == CAIF_CONNECTED || sk->sk_state == CAIF_DISCONNECTED); if (sk->sk_shutdown & SHUTDOWN_MASK) { /* Allow re-connect after SHUTDOWN_IND */ caif_disconnect_client(sock_net(sk), &cf_sk->layer); caif_free_client(&cf_sk->layer); break; } /* No reconnect on a seqpacket socket */ err = -EISCONN; goto out; case SS_DISCONNECTING: case SS_FREE: caif_assert(1); /*Should never happen */ break; } sk->sk_state = CAIF_DISCONNECTED; sock->state = SS_UNCONNECTED; sk_stream_kill_queues(&cf_sk->sk); err = -EINVAL; if (addr_len != sizeof(struct sockaddr_caif)) goto out; memcpy(&cf_sk->conn_req.sockaddr, uaddr, sizeof(struct sockaddr_caif)); /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = CAIF_CONNECTING; /* Check priority value comming from socket */ /* if priority value is out of range it will be ajusted */ if (cf_sk->sk.sk_priority > CAIF_PRIO_MAX) cf_sk->conn_req.priority = CAIF_PRIO_MAX; else if (cf_sk->sk.sk_priority < CAIF_PRIO_MIN) cf_sk->conn_req.priority = CAIF_PRIO_MIN; else cf_sk->conn_req.priority = cf_sk->sk.sk_priority; /*ifindex = id of the interface.*/ cf_sk->conn_req.ifindex = cf_sk->sk.sk_bound_dev_if; cf_sk->layer.receive = caif_sktrecv_cb; err = caif_connect_client(sock_net(sk), &cf_sk->conn_req, &cf_sk->layer, &ifindex, &headroom, &tailroom); if (err < 0) { cf_sk->sk.sk_socket->state = SS_UNCONNECTED; cf_sk->sk.sk_state = CAIF_DISCONNECTED; goto out; } err = -ENODEV; rcu_read_lock(); dev = dev_get_by_index_rcu(sock_net(sk), ifindex); if (!dev) { rcu_read_unlock(); goto out; } cf_sk->headroom = LL_RESERVED_SPACE_EXTRA(dev, headroom); mtu = dev->mtu; rcu_read_unlock(); cf_sk->tailroom = tailroom; cf_sk->maxframe = mtu - (headroom + tailroom); if (cf_sk->maxframe < 1) { pr_warn("CAIF Interface MTU too small (%d)\n", dev->mtu); err = -ENODEV; goto out; } err = -EINPROGRESS; wait_connect: if (sk->sk_state != CAIF_CONNECTED && (flags & O_NONBLOCK)) goto out; timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); release_sock(sk); err = -ERESTARTSYS; timeo = wait_event_interruptible_timeout(*sk_sleep(sk), sk->sk_state != CAIF_CONNECTING, timeo); lock_sock(sk); if (timeo < 0) goto out; /* -ERESTARTSYS */ err = -ETIMEDOUT; if (timeo == 0 && sk->sk_state != CAIF_CONNECTED) goto out; if (sk->sk_state != CAIF_CONNECTED) { sock->state = SS_UNCONNECTED; err = sock_error(sk); if (!err) err = -ECONNREFUSED; goto out; } sock->state = SS_CONNECTED; err = 0; out: release_sock(sk); return err; } /* * caif_release() - Disconnect a CAIF Socket * Copied and modified af_irda.c:irda_release(). */ static int caif_release(struct socket *sock) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); if (!sk) return 0; set_tx_flow_off(cf_sk); /* * Ensure that packets are not queued after this point in time. * caif_queue_rcv_skb checks SOCK_DEAD holding the queue lock, * this ensures no packets when sock is dead. */ spin_lock_bh(&sk->sk_receive_queue.lock); sock_set_flag(sk, SOCK_DEAD); spin_unlock_bh(&sk->sk_receive_queue.lock); sock->sk = NULL; WARN_ON(IS_ERR(cf_sk->debugfs_socket_dir)); if (cf_sk->debugfs_socket_dir != NULL) debugfs_remove_recursive(cf_sk->debugfs_socket_dir); lock_sock(&(cf_sk->sk)); sk->sk_state = CAIF_DISCONNECTED; sk->sk_shutdown = SHUTDOWN_MASK; caif_disconnect_client(sock_net(sk), &cf_sk->layer); cf_sk->sk.sk_socket->state = SS_DISCONNECTING; wake_up_interruptible_poll(sk_sleep(sk), POLLERR|POLLHUP); sock_orphan(sk); sk_stream_kill_queues(&cf_sk->sk); release_sock(sk); sock_put(sk); return 0; } /* Copied from af_unix.c:unix_poll(), added CAIF tx_flow handling */ static unsigned int caif_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); sock_poll_wait(file, sk_sleep(sk), wait); mask = 0; /* exceptional events? */ if (sk->sk_err) mask |= POLLERR; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP; /* readable? */ if (!skb_queue_empty(&sk->sk_receive_queue) || (sk->sk_shutdown & RCV_SHUTDOWN)) mask |= POLLIN | POLLRDNORM; /* * we set writable also when the other side has shut down the * connection. This prevents stuck sockets. */ if (sock_writeable(sk) && tx_flow_is_on(cf_sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; return mask; } static const struct proto_ops caif_seqpacket_ops = { .family = PF_CAIF, .owner = THIS_MODULE, .release = caif_release, .bind = sock_no_bind, .connect = caif_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = caif_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = caif_seqpkt_sendmsg, .recvmsg = caif_seqpkt_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const struct proto_ops caif_stream_ops = { .family = PF_CAIF, .owner = THIS_MODULE, .release = caif_release, .bind = sock_no_bind, .connect = caif_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = caif_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = caif_stream_sendmsg, .recvmsg = caif_stream_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; /* This function is called when a socket is finally destroyed. */ static void caif_sock_destructor(struct sock *sk) { struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); caif_assert(!atomic_read(&sk->sk_wmem_alloc)); caif_assert(sk_unhashed(sk)); caif_assert(!sk->sk_socket); if (!sock_flag(sk, SOCK_DEAD)) { pr_debug("Attempt to release alive CAIF socket: %p\n", sk); return; } sk_stream_kill_queues(&cf_sk->sk); caif_free_client(&cf_sk->layer); } static int caif_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk = NULL; struct caifsock *cf_sk = NULL; static struct proto prot = {.name = "PF_CAIF", .owner = THIS_MODULE, .obj_size = sizeof(struct caifsock), }; if (!capable(CAP_SYS_ADMIN) && !capable(CAP_NET_ADMIN)) return -EPERM; /* * The sock->type specifies the socket type to use. * The CAIF socket is a packet stream in the sense * that it is packet based. CAIF trusts the reliability * of the link, no resending is implemented. */ if (sock->type == SOCK_SEQPACKET) sock->ops = &caif_seqpacket_ops; else if (sock->type == SOCK_STREAM) sock->ops = &caif_stream_ops; else return -ESOCKTNOSUPPORT; if (protocol < 0 || protocol >= CAIFPROTO_MAX) return -EPROTONOSUPPORT; /* * Set the socket state to unconnected. The socket state * is really not used at all in the net/core or socket.c but the * initialization makes sure that sock->state is not uninitialized. */ sk = sk_alloc(net, PF_CAIF, GFP_KERNEL, &prot); if (!sk) return -ENOMEM; cf_sk = container_of(sk, struct caifsock, sk); /* Store the protocol */ sk->sk_protocol = (unsigned char) protocol; /* Initialize default priority for well-known cases */ switch (protocol) { case CAIFPROTO_AT: sk->sk_priority = TC_PRIO_CONTROL; break; case CAIFPROTO_RFM: sk->sk_priority = TC_PRIO_INTERACTIVE_BULK; break; default: sk->sk_priority = TC_PRIO_BESTEFFORT; } /* * Lock in order to try to stop someone from opening the socket * too early. */ lock_sock(&(cf_sk->sk)); /* Initialize the nozero default sock structure data. */ sock_init_data(sock, sk); sk->sk_destruct = caif_sock_destructor; mutex_init(&cf_sk->readlock); /* single task reading lock */ cf_sk->layer.ctrlcmd = caif_ctrl_cb; cf_sk->sk.sk_socket->state = SS_UNCONNECTED; cf_sk->sk.sk_state = CAIF_DISCONNECTED; set_tx_flow_off(cf_sk); set_rx_flow_on(cf_sk); /* Set default options on configuration */ cf_sk->conn_req.link_selector = CAIF_LINK_LOW_LATENCY; cf_sk->conn_req.protocol = protocol; release_sock(&cf_sk->sk); return 0; } static struct net_proto_family caif_family_ops = { .family = PF_CAIF, .create = caif_create, .owner = THIS_MODULE, }; static int __init caif_sktinit_module(void) { int err = sock_register(&caif_family_ops); if (!err) return err; return 0; } static void __exit caif_sktexit_module(void) { sock_unregister(PF_CAIF); } module_init(caif_sktinit_module); module_exit(caif_sktexit_module);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5686_0
crossvul-cpp_data_bad_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/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(); } /** * __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/bad_4240_2
crossvul-cpp_data_good_5683_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 address family and sockets. */ #include <linux/module.h> #include <asm/ioctls.h> #include <net/bluetooth/bluetooth.h> #include <linux/proc_fs.h> #define VERSION "2.16" /* Bluetooth sockets */ #define BT_MAX_PROTO 8 static const struct net_proto_family *bt_proto[BT_MAX_PROTO]; static DEFINE_RWLOCK(bt_proto_lock); static struct lock_class_key bt_lock_key[BT_MAX_PROTO]; static const char *const bt_key_strings[BT_MAX_PROTO] = { "sk_lock-AF_BLUETOOTH-BTPROTO_L2CAP", "sk_lock-AF_BLUETOOTH-BTPROTO_HCI", "sk_lock-AF_BLUETOOTH-BTPROTO_SCO", "sk_lock-AF_BLUETOOTH-BTPROTO_RFCOMM", "sk_lock-AF_BLUETOOTH-BTPROTO_BNEP", "sk_lock-AF_BLUETOOTH-BTPROTO_CMTP", "sk_lock-AF_BLUETOOTH-BTPROTO_HIDP", "sk_lock-AF_BLUETOOTH-BTPROTO_AVDTP", }; static struct lock_class_key bt_slock_key[BT_MAX_PROTO]; static const char *const bt_slock_key_strings[BT_MAX_PROTO] = { "slock-AF_BLUETOOTH-BTPROTO_L2CAP", "slock-AF_BLUETOOTH-BTPROTO_HCI", "slock-AF_BLUETOOTH-BTPROTO_SCO", "slock-AF_BLUETOOTH-BTPROTO_RFCOMM", "slock-AF_BLUETOOTH-BTPROTO_BNEP", "slock-AF_BLUETOOTH-BTPROTO_CMTP", "slock-AF_BLUETOOTH-BTPROTO_HIDP", "slock-AF_BLUETOOTH-BTPROTO_AVDTP", }; void bt_sock_reclassify_lock(struct sock *sk, int proto) { BUG_ON(!sk); BUG_ON(sock_owned_by_user(sk)); sock_lock_init_class_and_name(sk, bt_slock_key_strings[proto], &bt_slock_key[proto], bt_key_strings[proto], &bt_lock_key[proto]); } EXPORT_SYMBOL(bt_sock_reclassify_lock); int bt_sock_register(int proto, const struct net_proto_family *ops) { int err = 0; if (proto < 0 || proto >= BT_MAX_PROTO) return -EINVAL; write_lock(&bt_proto_lock); if (bt_proto[proto]) err = -EEXIST; else bt_proto[proto] = ops; write_unlock(&bt_proto_lock); return err; } EXPORT_SYMBOL(bt_sock_register); int bt_sock_unregister(int proto) { int err = 0; if (proto < 0 || proto >= BT_MAX_PROTO) return -EINVAL; write_lock(&bt_proto_lock); if (!bt_proto[proto]) err = -ENOENT; else bt_proto[proto] = NULL; write_unlock(&bt_proto_lock); return err; } EXPORT_SYMBOL(bt_sock_unregister); static int bt_sock_create(struct net *net, struct socket *sock, int proto, int kern) { int err; if (net != &init_net) return -EAFNOSUPPORT; if (proto < 0 || proto >= BT_MAX_PROTO) return -EINVAL; if (!bt_proto[proto]) request_module("bt-proto-%d", proto); err = -EPROTONOSUPPORT; read_lock(&bt_proto_lock); if (bt_proto[proto] && try_module_get(bt_proto[proto]->owner)) { err = bt_proto[proto]->create(net, sock, proto, kern); if (!err) bt_sock_reclassify_lock(sock->sk, proto); module_put(bt_proto[proto]->owner); } read_unlock(&bt_proto_lock); return err; } void bt_sock_link(struct bt_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_add_node(sk, &l->head); write_unlock(&l->lock); } EXPORT_SYMBOL(bt_sock_link); void bt_sock_unlink(struct bt_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_del_node_init(sk); write_unlock(&l->lock); } EXPORT_SYMBOL(bt_sock_unlink); void bt_accept_enqueue(struct sock *parent, struct sock *sk) { BT_DBG("parent %p, sk %p", parent, sk); sock_hold(sk); list_add_tail(&bt_sk(sk)->accept_q, &bt_sk(parent)->accept_q); bt_sk(sk)->parent = parent; parent->sk_ack_backlog++; } EXPORT_SYMBOL(bt_accept_enqueue); void bt_accept_unlink(struct sock *sk) { BT_DBG("sk %p state %d", sk, sk->sk_state); list_del_init(&bt_sk(sk)->accept_q); bt_sk(sk)->parent->sk_ack_backlog--; bt_sk(sk)->parent = NULL; sock_put(sk); } EXPORT_SYMBOL(bt_accept_unlink); struct sock *bt_accept_dequeue(struct sock *parent, struct socket *newsock) { struct list_head *p, *n; struct sock *sk; BT_DBG("parent %p", parent); list_for_each_safe(p, n, &bt_sk(parent)->accept_q) { sk = (struct sock *) list_entry(p, struct bt_sock, accept_q); lock_sock(sk); /* FIXME: Is this check still needed */ if (sk->sk_state == BT_CLOSED) { release_sock(sk); bt_accept_unlink(sk); continue; } if (sk->sk_state == BT_CONNECTED || !newsock || test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) { bt_accept_unlink(sk); if (newsock) sock_graft(sk, newsock); release_sock(sk); return sk; } release_sock(sk); } return NULL; } EXPORT_SYMBOL(bt_accept_dequeue); int bt_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; size_t copied; int err; BT_DBG("sock %p sk %p len %zu", sock, sk, len); if (flags & (MSG_OOB)) return -EOPNOTSUPP; msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } 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); if (err == 0) sock_recv_ts_and_drops(msg, sk, skb); skb_free_datagram(sk, skb); return err ? : copied; } EXPORT_SYMBOL(bt_sock_recvmsg); static long bt_sock_data_wait(struct sock *sk, long timeo) { DECLARE_WAITQUEUE(wait, current); add_wait_queue(sk_sleep(sk), &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (!skb_queue_empty(&sk->sk_receive_queue)) break; if (sk->sk_err || (sk->sk_shutdown & RCV_SHUTDOWN)) break; if (signal_pending(current) || !timeo) break; set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); return timeo; } int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int err = 0; size_t target, copied = 0; long timeo; if (flags & MSG_OOB) return -EOPNOTSUPP; msg->msg_namelen = 0; BT_DBG("sk %p size %zu", sk, size); lock_sock(sk); target = sock_rcvlowat(sk, flags & MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); do { struct sk_buff *skb; int chunk; skb = skb_dequeue(&sk->sk_receive_queue); if (!skb) { if (copied >= target) break; err = sock_error(sk); if (err) break; if (sk->sk_shutdown & RCV_SHUTDOWN) break; err = -EAGAIN; if (!timeo) break; timeo = bt_sock_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } continue; } chunk = min_t(unsigned int, skb->len, size); if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (!copied) copied = -EFAULT; break; } copied += chunk; size -= chunk; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { int skb_len = skb_headlen(skb); if (chunk <= skb_len) { __skb_pull(skb, chunk); } else { struct sk_buff *frag; __skb_pull(skb, skb_len); chunk -= skb_len; skb_walk_frags(skb, frag) { if (chunk <= frag->len) { /* Pulling partial data */ skb->len -= chunk; skb->data_len -= chunk; __skb_pull(frag, chunk); break; } else if (frag->len) { /* Pulling all frag data */ chunk -= frag->len; skb->len -= frag->len; skb->data_len -= frag->len; __skb_pull(frag, frag->len); } } } if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); out: release_sock(sk); return copied ? : err; } EXPORT_SYMBOL(bt_sock_stream_recvmsg); static inline unsigned int bt_accept_poll(struct sock *parent) { struct list_head *p, *n; struct sock *sk; list_for_each_safe(p, n, &bt_sk(parent)->accept_q) { sk = (struct sock *) list_entry(p, struct bt_sock, accept_q); if (sk->sk_state == BT_CONNECTED || (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags) && sk->sk_state == BT_CONNECT2)) return POLLIN | POLLRDNORM; } return 0; } unsigned int bt_sock_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask = 0; BT_DBG("sock %p, sk %p", sock, sk); poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == BT_LISTEN) return bt_accept_poll(sk); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; if (sk->sk_state == BT_CLOSED) mask |= POLLHUP; if (sk->sk_state == BT_CONNECT || sk->sk_state == BT_CONNECT2 || sk->sk_state == BT_CONFIG) return mask; if (!test_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags) && sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); return mask; } EXPORT_SYMBOL(bt_sock_poll); int bt_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; struct sk_buff *skb; long amount; int err; BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg); switch (cmd) { case TIOCOUTQ: if (sk->sk_state == BT_LISTEN) return -EINVAL; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; err = put_user(amount, (int __user *) arg); break; case TIOCINQ: if (sk->sk_state == BT_LISTEN) return -EINVAL; lock_sock(sk); skb = skb_peek(&sk->sk_receive_queue); amount = skb ? skb->len : 0; release_sock(sk); err = put_user(amount, (int __user *) arg); break; case SIOCGSTAMP: err = sock_get_timestamp(sk, (struct timeval __user *) arg); break; case SIOCGSTAMPNS: err = sock_get_timestampns(sk, (struct timespec __user *) arg); break; default: err = -ENOIOCTLCMD; break; } return err; } EXPORT_SYMBOL(bt_sock_ioctl); int bt_sock_wait_state(struct sock *sk, int state, unsigned long timeo) { DECLARE_WAITQUEUE(wait, current); int err = 0; BT_DBG("sk %p", sk); add_wait_queue(sk_sleep(sk), &wait); set_current_state(TASK_INTERRUPTIBLE); while (sk->sk_state != state) { if (!timeo) { err = -EINPROGRESS; 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_INTERRUPTIBLE); err = sock_error(sk); if (err) break; } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); return err; } EXPORT_SYMBOL(bt_sock_wait_state); #ifdef CONFIG_PROC_FS struct bt_seq_state { struct bt_sock_list *l; }; static void *bt_seq_start(struct seq_file *seq, loff_t *pos) __acquires(seq->private->l->lock) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; read_lock(&l->lock); return seq_hlist_start_head(&l->head, *pos); } static void *bt_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; return seq_hlist_next(v, &l->head, pos); } static void bt_seq_stop(struct seq_file *seq, void *v) __releases(seq->private->l->lock) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; read_unlock(&l->lock); } static int bt_seq_show(struct seq_file *seq, void *v) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; if (v == SEQ_START_TOKEN) { seq_puts(seq ,"sk RefCnt Rmem Wmem User Inode Src Dst Parent"); if (l->custom_seq_show) { seq_putc(seq, ' '); l->custom_seq_show(seq, v); } seq_putc(seq, '\n'); } else { struct sock *sk = sk_entry(v); struct bt_sock *bt = bt_sk(sk); seq_printf(seq, "%pK %-6d %-6u %-6u %-6u %-6lu %pMR %pMR %-6lu", sk, atomic_read(&sk->sk_refcnt), sk_rmem_alloc_get(sk), sk_wmem_alloc_get(sk), from_kuid(seq_user_ns(seq), sock_i_uid(sk)), sock_i_ino(sk), &bt->src, &bt->dst, bt->parent? sock_i_ino(bt->parent): 0LU); if (l->custom_seq_show) { seq_putc(seq, ' '); l->custom_seq_show(seq, v); } seq_putc(seq, '\n'); } return 0; } static struct seq_operations bt_seq_ops = { .start = bt_seq_start, .next = bt_seq_next, .stop = bt_seq_stop, .show = bt_seq_show, }; static int bt_seq_open(struct inode *inode, struct file *file) { struct bt_sock_list *sk_list; struct bt_seq_state *s; sk_list = PDE(inode)->data; s = __seq_open_private(file, &bt_seq_ops, sizeof(struct bt_seq_state)); if (!s) return -ENOMEM; s->l = sk_list; return 0; } int bt_procfs_init(struct module* module, struct net *net, const char *name, struct bt_sock_list* sk_list, int (* seq_show)(struct seq_file *, void *)) { struct proc_dir_entry * pde; sk_list->custom_seq_show = seq_show; sk_list->fops.owner = module; sk_list->fops.open = bt_seq_open; sk_list->fops.read = seq_read; sk_list->fops.llseek = seq_lseek; sk_list->fops.release = seq_release_private; pde = proc_create(name, 0, net->proc_net, &sk_list->fops); if (!pde) return -ENOMEM; pde->data = sk_list; return 0; } void bt_procfs_cleanup(struct net *net, const char *name) { remove_proc_entry(name, net->proc_net); } #else int bt_procfs_init(struct module* module, struct net *net, const char *name, struct bt_sock_list* sk_list, int (* seq_show)(struct seq_file *, void *)) { return 0; } void bt_procfs_cleanup(struct net *net, const char *name) { } #endif EXPORT_SYMBOL(bt_procfs_init); EXPORT_SYMBOL(bt_procfs_cleanup); static struct net_proto_family bt_sock_family_ops = { .owner = THIS_MODULE, .family = PF_BLUETOOTH, .create = bt_sock_create, }; static int __init bt_init(void) { int err; BT_INFO("Core ver %s", VERSION); err = bt_sysfs_init(); if (err < 0) return err; err = sock_register(&bt_sock_family_ops); if (err < 0) { bt_sysfs_cleanup(); return err; } BT_INFO("HCI device and connection manager initialized"); err = hci_sock_init(); if (err < 0) goto error; err = l2cap_init(); if (err < 0) goto sock_err; err = sco_init(); if (err < 0) { l2cap_exit(); goto sock_err; } return 0; sock_err: hci_sock_cleanup(); error: sock_unregister(PF_BLUETOOTH); bt_sysfs_cleanup(); return err; } static void __exit bt_exit(void) { sco_exit(); l2cap_exit(); hci_sock_cleanup(); sock_unregister(PF_BLUETOOTH); bt_sysfs_cleanup(); } subsys_initcall(bt_init); module_exit(bt_exit); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Bluetooth Core ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_BLUETOOTH);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5683_0
crossvul-cpp_data_bad_3416_0
/* * Apple HTTP Live Streaming demuxer * Copyright (c) 2010 Martin Storsjo * Copyright (c) 2013 Anssi Hannula * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Apple HTTP Live Streaming demuxer * http://tools.ietf.org/html/draft-pantos-http-live-streaming */ #include "libavutil/avstring.h" #include "libavutil/avassert.h" #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/time.h" #include "avformat.h" #include "internal.h" #include "avio_internal.h" #include "id3v2.h" #define INITIAL_BUFFER_SIZE 32768 #define MAX_FIELD_LEN 64 #define MAX_CHARACTERISTICS_LEN 512 #define MPEG_TIME_BASE 90000 #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE} /* * An apple http stream consists of a playlist with media segment files, * played sequentially. There may be several playlists with the same * video content, in different bandwidth variants, that are played in * parallel (preferably only one bandwidth variant at a time). In this case, * the user supplied the url to a main playlist that only lists the variant * playlists. * * If the main playlist doesn't point at any variants, we still create * one anonymous toplevel variant for this, to maintain the structure. */ enum KeyType { KEY_NONE, KEY_AES_128, KEY_SAMPLE_AES }; struct segment { int64_t duration; int64_t url_offset; int64_t size; char *url; char *key; enum KeyType key_type; uint8_t iv[16]; /* associated Media Initialization Section, treated as a segment */ struct segment *init_section; }; struct rendition; enum PlaylistType { PLS_TYPE_UNSPECIFIED, PLS_TYPE_EVENT, PLS_TYPE_VOD }; /* * Each playlist has its own demuxer. If it currently is active, * it has an open AVIOContext too, and potentially an AVPacket * containing the next packet from this stream. */ struct playlist { char url[MAX_URL_SIZE]; AVIOContext pb; uint8_t* read_buffer; AVIOContext *input; AVFormatContext *parent; int index; AVFormatContext *ctx; AVPacket pkt; int has_noheader_flag; /* main demuxer streams associated with this playlist * indexed by the subdemuxer stream indexes */ AVStream **main_streams; int n_main_streams; int finished; enum PlaylistType type; int64_t target_duration; int start_seq_no; int n_segments; struct segment **segments; int needed, cur_needed; int cur_seq_no; int64_t cur_seg_offset; int64_t last_load_time; /* Currently active Media Initialization Section */ struct segment *cur_init_section; uint8_t *init_sec_buf; unsigned int init_sec_buf_size; unsigned int init_sec_data_len; unsigned int init_sec_buf_read_offset; char key_url[MAX_URL_SIZE]; uint8_t key[16]; /* ID3 timestamp handling (elementary audio streams have ID3 timestamps * (and possibly other ID3 tags) in the beginning of each segment) */ int is_id3_timestamped; /* -1: not yet known */ int64_t id3_mpegts_timestamp; /* in mpegts tb */ int64_t id3_offset; /* in stream original tb */ uint8_t* id3_buf; /* temp buffer for id3 parsing */ unsigned int id3_buf_size; AVDictionary *id3_initial; /* data from first id3 tag */ int id3_found; /* ID3 tag found at some point */ int id3_changed; /* ID3 tag data has changed at some point */ ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */ int64_t seek_timestamp; int seek_flags; int seek_stream_index; /* into subdemuxer stream array */ /* Renditions associated with this playlist, if any. * Alternative rendition playlists have a single rendition associated * with them, and variant main Media Playlists may have * multiple (playlist-less) renditions associated with them. */ int n_renditions; struct rendition **renditions; /* Media Initialization Sections (EXT-X-MAP) associated with this * playlist, if any. */ int n_init_sections; struct segment **init_sections; }; /* * Renditions are e.g. alternative subtitle or audio streams. * The rendition may either be an external playlist or it may be * contained in the main Media Playlist of the variant (in which case * playlist is NULL). */ struct rendition { enum AVMediaType type; struct playlist *playlist; char group_id[MAX_FIELD_LEN]; char language[MAX_FIELD_LEN]; char name[MAX_FIELD_LEN]; int disposition; }; struct variant { int bandwidth; /* every variant contains at least the main Media Playlist in index 0 */ int n_playlists; struct playlist **playlists; char audio_group[MAX_FIELD_LEN]; char video_group[MAX_FIELD_LEN]; char subtitles_group[MAX_FIELD_LEN]; }; typedef struct HLSContext { AVClass *class; AVFormatContext *ctx; int n_variants; struct variant **variants; int n_playlists; struct playlist **playlists; int n_renditions; struct rendition **renditions; int cur_seq_no; int live_start_index; int first_packet; int64_t first_timestamp; int64_t cur_timestamp; AVIOInterruptCB *interrupt_callback; char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context char *http_proxy; ///< holds the address of the HTTP proxy server AVDictionary *avio_opts; int strict_std_compliance; } HLSContext; static int read_chomp_line(AVIOContext *s, char *buf, int maxlen) { int len = ff_get_line(s, buf, maxlen); while (len > 0 && av_isspace(buf[len - 1])) buf[--len] = '\0'; return len; } static void free_segment_list(struct playlist *pls) { int i; for (i = 0; i < pls->n_segments; i++) { av_freep(&pls->segments[i]->key); av_freep(&pls->segments[i]->url); av_freep(&pls->segments[i]); } av_freep(&pls->segments); pls->n_segments = 0; } static void free_init_section_list(struct playlist *pls) { int i; for (i = 0; i < pls->n_init_sections; i++) { av_freep(&pls->init_sections[i]->url); av_freep(&pls->init_sections[i]); } av_freep(&pls->init_sections); pls->n_init_sections = 0; } static void free_playlist_list(HLSContext *c) { int i; for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; free_segment_list(pls); free_init_section_list(pls); av_freep(&pls->main_streams); av_freep(&pls->renditions); av_freep(&pls->id3_buf); av_dict_free(&pls->id3_initial); ff_id3v2_free_extra_meta(&pls->id3_deferred_extra); av_freep(&pls->init_sec_buf); av_packet_unref(&pls->pkt); av_freep(&pls->pb.buffer); if (pls->input) ff_format_io_close(c->ctx, &pls->input); if (pls->ctx) { pls->ctx->pb = NULL; avformat_close_input(&pls->ctx); } av_free(pls); } av_freep(&c->playlists); av_freep(&c->cookies); av_freep(&c->user_agent); av_freep(&c->headers); av_freep(&c->http_proxy); c->n_playlists = 0; } static void free_variant_list(HLSContext *c) { int i; for (i = 0; i < c->n_variants; i++) { struct variant *var = c->variants[i]; av_freep(&var->playlists); av_free(var); } av_freep(&c->variants); c->n_variants = 0; } static void free_rendition_list(HLSContext *c) { int i; for (i = 0; i < c->n_renditions; i++) av_freep(&c->renditions[i]); av_freep(&c->renditions); c->n_renditions = 0; } /* * Used to reset a statically allocated AVPacket to a clean slate, * containing no data. */ static void reset_packet(AVPacket *pkt) { av_init_packet(pkt); pkt->data = NULL; } static struct playlist *new_playlist(HLSContext *c, const char *url, const char *base) { struct playlist *pls = av_mallocz(sizeof(struct playlist)); if (!pls) return NULL; reset_packet(&pls->pkt); ff_make_absolute_url(pls->url, sizeof(pls->url), base, url); pls->seek_timestamp = AV_NOPTS_VALUE; pls->is_id3_timestamped = -1; pls->id3_mpegts_timestamp = AV_NOPTS_VALUE; dynarray_add(&c->playlists, &c->n_playlists, pls); return pls; } struct variant_info { char bandwidth[20]; /* variant group ids: */ char audio[MAX_FIELD_LEN]; char video[MAX_FIELD_LEN]; char subtitles[MAX_FIELD_LEN]; }; static struct variant *new_variant(HLSContext *c, struct variant_info *info, const char *url, const char *base) { struct variant *var; struct playlist *pls; pls = new_playlist(c, url, base); if (!pls) return NULL; var = av_mallocz(sizeof(struct variant)); if (!var) return NULL; if (info) { var->bandwidth = atoi(info->bandwidth); strcpy(var->audio_group, info->audio); strcpy(var->video_group, info->video); strcpy(var->subtitles_group, info->subtitles); } dynarray_add(&c->variants, &c->n_variants, var); dynarray_add(&var->playlists, &var->n_playlists, pls); return var; } static void handle_variant_args(struct variant_info *info, const char *key, int key_len, char **dest, int *dest_len) { if (!strncmp(key, "BANDWIDTH=", key_len)) { *dest = info->bandwidth; *dest_len = sizeof(info->bandwidth); } else if (!strncmp(key, "AUDIO=", key_len)) { *dest = info->audio; *dest_len = sizeof(info->audio); } else if (!strncmp(key, "VIDEO=", key_len)) { *dest = info->video; *dest_len = sizeof(info->video); } else if (!strncmp(key, "SUBTITLES=", key_len)) { *dest = info->subtitles; *dest_len = sizeof(info->subtitles); } } struct key_info { char uri[MAX_URL_SIZE]; char method[11]; char iv[35]; }; static void handle_key_args(struct key_info *info, const char *key, int key_len, char **dest, int *dest_len) { if (!strncmp(key, "METHOD=", key_len)) { *dest = info->method; *dest_len = sizeof(info->method); } else if (!strncmp(key, "URI=", key_len)) { *dest = info->uri; *dest_len = sizeof(info->uri); } else if (!strncmp(key, "IV=", key_len)) { *dest = info->iv; *dest_len = sizeof(info->iv); } } struct init_section_info { char uri[MAX_URL_SIZE]; char byterange[32]; }; static struct segment *new_init_section(struct playlist *pls, struct init_section_info *info, const char *url_base) { struct segment *sec; char *ptr; char tmp_str[MAX_URL_SIZE]; if (!info->uri[0]) return NULL; sec = av_mallocz(sizeof(*sec)); if (!sec) return NULL; ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri); sec->url = av_strdup(tmp_str); if (!sec->url) { av_free(sec); return NULL; } if (info->byterange[0]) { sec->size = strtoll(info->byterange, NULL, 10); ptr = strchr(info->byterange, '@'); if (ptr) sec->url_offset = strtoll(ptr+1, NULL, 10); } else { /* the entire file is the init section */ sec->size = -1; } dynarray_add(&pls->init_sections, &pls->n_init_sections, sec); return sec; } static void handle_init_section_args(struct init_section_info *info, const char *key, int key_len, char **dest, int *dest_len) { if (!strncmp(key, "URI=", key_len)) { *dest = info->uri; *dest_len = sizeof(info->uri); } else if (!strncmp(key, "BYTERANGE=", key_len)) { *dest = info->byterange; *dest_len = sizeof(info->byterange); } } struct rendition_info { char type[16]; char uri[MAX_URL_SIZE]; char group_id[MAX_FIELD_LEN]; char language[MAX_FIELD_LEN]; char assoc_language[MAX_FIELD_LEN]; char name[MAX_FIELD_LEN]; char defaultr[4]; char forced[4]; char characteristics[MAX_CHARACTERISTICS_LEN]; }; static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info, const char *url_base) { struct rendition *rend; enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN; char *characteristic; char *chr_ptr; char *saveptr; if (!strcmp(info->type, "AUDIO")) type = AVMEDIA_TYPE_AUDIO; else if (!strcmp(info->type, "VIDEO")) type = AVMEDIA_TYPE_VIDEO; else if (!strcmp(info->type, "SUBTITLES")) type = AVMEDIA_TYPE_SUBTITLE; else if (!strcmp(info->type, "CLOSED-CAPTIONS")) /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in * AVC SEI RBSP anyway */ return NULL; if (type == AVMEDIA_TYPE_UNKNOWN) return NULL; /* URI is mandatory for subtitles as per spec */ if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0]) return NULL; /* TODO: handle subtitles (each segment has to parsed separately) */ if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) if (type == AVMEDIA_TYPE_SUBTITLE) return NULL; rend = av_mallocz(sizeof(struct rendition)); if (!rend) return NULL; dynarray_add(&c->renditions, &c->n_renditions, rend); rend->type = type; strcpy(rend->group_id, info->group_id); strcpy(rend->language, info->language); strcpy(rend->name, info->name); /* add the playlist if this is an external rendition */ if (info->uri[0]) { rend->playlist = new_playlist(c, info->uri, url_base); if (rend->playlist) dynarray_add(&rend->playlist->renditions, &rend->playlist->n_renditions, rend); } if (info->assoc_language[0]) { int langlen = strlen(rend->language); if (langlen < sizeof(rend->language) - 3) { rend->language[langlen] = ','; strncpy(rend->language + langlen + 1, info->assoc_language, sizeof(rend->language) - langlen - 2); } } if (!strcmp(info->defaultr, "YES")) rend->disposition |= AV_DISPOSITION_DEFAULT; if (!strcmp(info->forced, "YES")) rend->disposition |= AV_DISPOSITION_FORCED; chr_ptr = info->characteristics; while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) { if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound")) rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; else if (!strcmp(characteristic, "public.accessibility.describes-video")) rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; chr_ptr = NULL; } return rend; } static void handle_rendition_args(struct rendition_info *info, const char *key, int key_len, char **dest, int *dest_len) { if (!strncmp(key, "TYPE=", key_len)) { *dest = info->type; *dest_len = sizeof(info->type); } else if (!strncmp(key, "URI=", key_len)) { *dest = info->uri; *dest_len = sizeof(info->uri); } else if (!strncmp(key, "GROUP-ID=", key_len)) { *dest = info->group_id; *dest_len = sizeof(info->group_id); } else if (!strncmp(key, "LANGUAGE=", key_len)) { *dest = info->language; *dest_len = sizeof(info->language); } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) { *dest = info->assoc_language; *dest_len = sizeof(info->assoc_language); } else if (!strncmp(key, "NAME=", key_len)) { *dest = info->name; *dest_len = sizeof(info->name); } else if (!strncmp(key, "DEFAULT=", key_len)) { *dest = info->defaultr; *dest_len = sizeof(info->defaultr); } else if (!strncmp(key, "FORCED=", key_len)) { *dest = info->forced; *dest_len = sizeof(info->forced); } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) { *dest = info->characteristics; *dest_len = sizeof(info->characteristics); } /* * ignored: * - AUTOSELECT: client may autoselect based on e.g. system language * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4") */ } /* used by parse_playlist to allocate a new variant+playlist when the * playlist is detected to be a Media Playlist (not Master Playlist) * and we have no parent Master Playlist (parsing of which would have * allocated the variant and playlist already) * *pls == NULL => Master Playlist or parentless Media Playlist * *pls != NULL => parented Media Playlist, playlist+variant allocated */ static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url) { if (*pls) return 0; if (!new_variant(c, NULL, url, NULL)) return AVERROR(ENOMEM); *pls = c->playlists[c->n_playlists - 1]; return 0; } static void update_options(char **dest, const char *name, void *src) { av_freep(dest); av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest); if (*dest && !strlen(*dest)) av_freep(dest); } static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary *opts, AVDictionary *opts2, int *is_http) { HLSContext *c = s->priv_data; AVDictionary *tmp = NULL; const char *proto_name = NULL; int ret; av_dict_copy(&tmp, opts, 0); av_dict_copy(&tmp, opts2, 0); if (av_strstart(url, "crypto", NULL)) { if (url[6] == '+' || url[6] == ':') proto_name = avio_find_protocol_name(url + 7); } if (!proto_name) proto_name = avio_find_protocol_name(url); if (!proto_name) return AVERROR_INVALIDDATA; // only http(s) & file are allowed if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL)) return AVERROR_INVALIDDATA; if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':') ; else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':') ; else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5)) return AVERROR_INVALIDDATA; ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp); if (ret >= 0) { // update cookies on http response with setcookies. char *new_cookies = NULL; if (!(s->flags & AVFMT_FLAG_CUSTOM_IO)) av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies); if (new_cookies) { av_free(c->cookies); c->cookies = new_cookies; } av_dict_set(&opts, "cookies", c->cookies, 0); } av_dict_free(&tmp); if (is_http) *is_http = av_strstart(proto_name, "http", NULL); return ret; } static int parse_playlist(HLSContext *c, const char *url, struct playlist *pls, AVIOContext *in) { int ret = 0, is_segment = 0, is_variant = 0; int64_t duration = 0; enum KeyType key_type = KEY_NONE; uint8_t iv[16] = ""; int has_iv = 0; char key[MAX_URL_SIZE] = ""; char line[MAX_URL_SIZE]; const char *ptr; int close_in = 0; int64_t seg_offset = 0; int64_t seg_size = -1; uint8_t *new_url = NULL; struct variant_info variant_info; char tmp_str[MAX_URL_SIZE]; struct segment *cur_init_section = NULL; if (!in) { #if 1 AVDictionary *opts = NULL; close_in = 1; /* Some HLS servers don't like being sent the range header */ av_dict_set(&opts, "seekable", "0", 0); // broker prior HTTP options that should be consistent across requests av_dict_set(&opts, "user_agent", c->user_agent, 0); av_dict_set(&opts, "cookies", c->cookies, 0); av_dict_set(&opts, "headers", c->headers, 0); av_dict_set(&opts, "http_proxy", c->http_proxy, 0); ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts); av_dict_free(&opts); if (ret < 0) return ret; #else ret = open_in(c, &in, url); if (ret < 0) return ret; close_in = 1; #endif } if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) url = new_url; read_chomp_line(in, line, sizeof(line)); if (strcmp(line, "#EXTM3U")) { ret = AVERROR_INVALIDDATA; goto fail; } if (pls) { free_segment_list(pls); pls->finished = 0; pls->type = PLS_TYPE_UNSPECIFIED; } while (!avio_feof(in)) { read_chomp_line(in, line, sizeof(line)); if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) { is_variant = 1; memset(&variant_info, 0, sizeof(variant_info)); ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args, &variant_info); } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) { struct key_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args, &info); key_type = KEY_NONE; has_iv = 0; if (!strcmp(info.method, "AES-128")) key_type = KEY_AES_128; if (!strcmp(info.method, "SAMPLE-AES")) key_type = KEY_SAMPLE_AES; if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) { ff_hex_to_data(iv, info.iv + 2); has_iv = 1; } av_strlcpy(key, info.uri, sizeof(key)); } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) { struct rendition_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args, &info); new_rendition(c, &info, url); } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE; } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->start_seq_no = atoi(ptr); } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; if (!strcmp(ptr, "EVENT")) pls->type = PLS_TYPE_EVENT; else if (!strcmp(ptr, "VOD")) pls->type = PLS_TYPE_VOD; } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) { struct init_section_info info = {{0}}; ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args, &info); cur_init_section = new_init_section(pls, &info, url); } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) { if (pls) pls->finished = 1; } else if (av_strstart(line, "#EXTINF:", &ptr)) { is_segment = 1; duration = atof(ptr) * AV_TIME_BASE; } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) { seg_size = strtoll(ptr, NULL, 10); ptr = strchr(ptr, '@'); if (ptr) seg_offset = strtoll(ptr+1, NULL, 10); } else if (av_strstart(line, "#", NULL)) { continue; } else if (line[0]) { if (is_variant) { if (!new_variant(c, &variant_info, line, url)) { ret = AVERROR(ENOMEM); goto fail; } is_variant = 0; } if (is_segment) { struct segment *seg; if (!pls) { if (!new_variant(c, 0, url, NULL)) { ret = AVERROR(ENOMEM); goto fail; } pls = c->playlists[c->n_playlists - 1]; } seg = av_malloc(sizeof(struct segment)); if (!seg) { ret = AVERROR(ENOMEM); goto fail; } seg->duration = duration; seg->key_type = key_type; if (has_iv) { memcpy(seg->iv, iv, sizeof(iv)); } else { int seq = pls->start_seq_no + pls->n_segments; memset(seg->iv, 0, sizeof(seg->iv)); AV_WB32(seg->iv + 12, seq); } if (key_type != KEY_NONE) { ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key); seg->key = av_strdup(tmp_str); if (!seg->key) { av_free(seg); ret = AVERROR(ENOMEM); goto fail; } } else { seg->key = NULL; } ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line); seg->url = av_strdup(tmp_str); if (!seg->url) { av_free(seg->key); av_free(seg); ret = AVERROR(ENOMEM); goto fail; } dynarray_add(&pls->segments, &pls->n_segments, seg); is_segment = 0; seg->size = seg_size; if (seg_size >= 0) { seg->url_offset = seg_offset; seg_offset += seg_size; seg_size = -1; } else { seg->url_offset = 0; seg_offset = 0; } seg->init_section = cur_init_section; } } } if (pls) pls->last_load_time = av_gettime_relative(); fail: av_free(new_url); if (close_in) ff_format_io_close(c->ctx, &in); return ret; } static struct segment *current_segment(struct playlist *pls) { return pls->segments[pls->cur_seq_no - pls->start_seq_no]; } enum ReadFromURLMode { READ_NORMAL, READ_COMPLETE, }; static int read_from_url(struct playlist *pls, struct segment *seg, uint8_t *buf, int buf_size, enum ReadFromURLMode mode) { int ret; /* limit read if the segment was only a part of a file */ if (seg->size >= 0) buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset); if (mode == READ_COMPLETE) { ret = avio_read(pls->input, buf, buf_size); if (ret != buf_size) av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n"); } else ret = avio_read(pls->input, buf, buf_size); if (ret > 0) pls->cur_seg_offset += ret; return ret; } /* Parse the raw ID3 data and pass contents to caller */ static void parse_id3(AVFormatContext *s, AVIOContext *pb, AVDictionary **metadata, int64_t *dts, ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta) { static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp"; ID3v2ExtraMeta *meta; ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta); for (meta = *extra_meta; meta; meta = meta->next) { if (!strcmp(meta->tag, "PRIV")) { ID3v2ExtraMetaPRIV *priv = meta->data; if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) { /* 33-bit MPEG timestamp */ int64_t ts = AV_RB64(priv->data); av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts); if ((ts & ~((1ULL << 33) - 1)) == 0) *dts = ts; else av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts); } } else if (!strcmp(meta->tag, "APIC") && apic) *apic = meta->data; } } /* Check if the ID3 metadata contents have changed */ static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata, ID3v2ExtraMetaAPIC *apic) { AVDictionaryEntry *entry = NULL; AVDictionaryEntry *oldentry; /* check that no keys have changed values */ while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) { oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE); if (!oldentry || strcmp(oldentry->value, entry->value) != 0) return 1; } /* check if apic appeared */ if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data)) return 1; if (apic) { int size = pls->ctx->streams[1]->attached_pic.size; if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE) return 1; if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0) return 1; } return 0; } /* Parse ID3 data and handle the found data */ static void handle_id3(AVIOContext *pb, struct playlist *pls) { AVDictionary *metadata = NULL; ID3v2ExtraMetaAPIC *apic = NULL; ID3v2ExtraMeta *extra_meta = NULL; int64_t timestamp = AV_NOPTS_VALUE; parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta); if (timestamp != AV_NOPTS_VALUE) { pls->id3_mpegts_timestamp = timestamp; pls->id3_offset = 0; } if (!pls->id3_found) { /* initial ID3 tags */ av_assert0(!pls->id3_deferred_extra); pls->id3_found = 1; /* get picture attachment and set text metadata */ if (pls->ctx->nb_streams) ff_id3v2_parse_apic(pls->ctx, &extra_meta); else /* demuxer not yet opened, defer picture attachment */ pls->id3_deferred_extra = extra_meta; av_dict_copy(&pls->ctx->metadata, metadata, 0); pls->id3_initial = metadata; } else { if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) { avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream"); pls->id3_changed = 1; } av_dict_free(&metadata); } if (!pls->id3_deferred_extra) ff_id3v2_free_extra_meta(&extra_meta); } static void intercept_id3(struct playlist *pls, uint8_t *buf, int buf_size, int *len) { /* intercept id3 tags, we do not want to pass them to the raw * demuxer on all segment switches */ int bytes; int id3_buf_pos = 0; int fill_buf = 0; struct segment *seg = current_segment(pls); /* gather all the id3 tags */ while (1) { /* see if we can retrieve enough data for ID3 header */ if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) { bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE); if (bytes > 0) { if (bytes == ID3v2_HEADER_SIZE - *len) /* no EOF yet, so fill the caller buffer again after * we have stripped the ID3 tags */ fill_buf = 1; *len += bytes; } else if (*len <= 0) { /* error/EOF */ *len = bytes; fill_buf = 0; } } if (*len < ID3v2_HEADER_SIZE) break; if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) { int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024; int taglen = ff_id3v2_tag_len(buf); int tag_got_bytes = FFMIN(taglen, *len); int remaining = taglen - tag_got_bytes; if (taglen > maxsize) { av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n", taglen, maxsize); break; } /* * Copy the id3 tag to our temporary id3 buffer. * We could read a small id3 tag directly without memcpy, but * we would still need to copy the large tags, and handling * both of those cases together with the possibility for multiple * tags would make the handling a bit complex. */ pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen); if (!pls->id3_buf) break; memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes); id3_buf_pos += tag_got_bytes; /* strip the intercepted bytes */ *len -= tag_got_bytes; memmove(buf, buf + tag_got_bytes, *len); av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes); if (remaining > 0) { /* read the rest of the tag in */ if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining) break; id3_buf_pos += remaining; av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining); } } else { /* no more ID3 tags */ break; } } /* re-fill buffer for the caller unless EOF */ if (*len >= 0 && (fill_buf || *len == 0)) { bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL); /* ignore error if we already had some data */ if (bytes >= 0) *len += bytes; else if (*len == 0) *len = bytes; } if (pls->id3_buf) { /* Now parse all the ID3 tags */ AVIOContext id3ioctx; ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL); handle_id3(&id3ioctx, pls); } if (pls->is_id3_timestamped == -1) pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE); } static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg) { AVDictionary *opts = NULL; int ret; int is_http = 0; // broker prior HTTP options that should be consistent across requests av_dict_set(&opts, "user_agent", c->user_agent, 0); av_dict_set(&opts, "cookies", c->cookies, 0); av_dict_set(&opts, "headers", c->headers, 0); av_dict_set(&opts, "http_proxy", c->http_proxy, 0); av_dict_set(&opts, "seekable", "0", 0); if (seg->size >= 0) { /* try to restrict the HTTP request to the part we want * (if this is in fact a HTTP request) */ av_dict_set_int(&opts, "offset", seg->url_offset, 0); av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0); } av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n", seg->url, seg->url_offset, pls->index); if (seg->key_type == KEY_NONE) { ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts, &is_http); } else if (seg->key_type == KEY_AES_128) { AVDictionary *opts2 = NULL; char iv[33], key[33], url[MAX_URL_SIZE]; if (strcmp(seg->key, pls->key_url)) { AVIOContext *pb; if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) { ret = avio_read(pb, pls->key, sizeof(pls->key)); if (ret != sizeof(pls->key)) { av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n", seg->key); } ff_format_io_close(pls->parent, &pb); } else { av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n", seg->key); } av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url)); } ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0); ff_data_to_hex(key, pls->key, sizeof(pls->key), 0); iv[32] = key[32] = '\0'; if (strstr(seg->url, "://")) snprintf(url, sizeof(url), "crypto+%s", seg->url); else snprintf(url, sizeof(url), "crypto:%s", seg->url); av_dict_copy(&opts2, c->avio_opts, 0); av_dict_set(&opts2, "key", key, 0); av_dict_set(&opts2, "iv", iv, 0); ret = open_url(pls->parent, &pls->input, url, opts2, opts, &is_http); av_dict_free(&opts2); if (ret < 0) { goto cleanup; } ret = 0; } else if (seg->key_type == KEY_SAMPLE_AES) { av_log(pls->parent, AV_LOG_ERROR, "SAMPLE-AES encryption is not supported yet\n"); ret = AVERROR_PATCHWELCOME; } else ret = AVERROR(ENOSYS); /* Seek to the requested position. If this was a HTTP request, the offset * should already be where want it to, but this allows e.g. local testing * without a HTTP server. * * This is not done for HTTP at all as avio_seek() does internal bookkeeping * of file offset which is out-of-sync with the actual offset when "offset" * AVOption is used with http protocol, causing the seek to not be a no-op * as would be expected. Wrong offset received from the server will not be * noticed without the call, though. */ if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) { int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET); if (seekret < 0) { av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url); ret = seekret; ff_format_io_close(pls->parent, &pls->input); } } cleanup: av_dict_free(&opts); pls->cur_seg_offset = 0; return ret; } static int update_init_section(struct playlist *pls, struct segment *seg) { static const int max_init_section_size = 1024*1024; HLSContext *c = pls->parent->priv_data; int64_t sec_size; int64_t urlsize; int ret; if (seg->init_section == pls->cur_init_section) return 0; pls->cur_init_section = NULL; if (!seg->init_section) return 0; ret = open_input(c, pls, seg->init_section); if (ret < 0) { av_log(pls->parent, AV_LOG_WARNING, "Failed to open an initialization section in playlist %d\n", pls->index); return ret; } if (seg->init_section->size >= 0) sec_size = seg->init_section->size; else if ((urlsize = avio_size(pls->input)) >= 0) sec_size = urlsize; else sec_size = max_init_section_size; av_log(pls->parent, AV_LOG_DEBUG, "Downloading an initialization section of size %"PRId64"\n", sec_size); sec_size = FFMIN(sec_size, max_init_section_size); av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size); ret = read_from_url(pls, seg->init_section, pls->init_sec_buf, pls->init_sec_buf_size, READ_COMPLETE); ff_format_io_close(pls->parent, &pls->input); if (ret < 0) return ret; pls->cur_init_section = seg->init_section; pls->init_sec_data_len = ret; pls->init_sec_buf_read_offset = 0; /* spec says audio elementary streams do not have media initialization * sections, so there should be no ID3 timestamps */ pls->is_id3_timestamped = 0; return 0; } static int64_t default_reload_interval(struct playlist *pls) { return pls->n_segments > 0 ? pls->segments[pls->n_segments - 1]->duration : pls->target_duration; } static int read_data(void *opaque, uint8_t *buf, int buf_size) { struct playlist *v = opaque; HLSContext *c = v->parent->priv_data; int ret, i; int just_opened = 0; restart: if (!v->needed) return AVERROR_EOF; if (!v->input) { int64_t reload_interval; struct segment *seg; /* Check that the playlist is still needed before opening a new * segment. */ if (v->ctx && v->ctx->nb_streams) { v->needed = 0; for (i = 0; i < v->n_main_streams; i++) { if (v->main_streams[i]->discard < AVDISCARD_ALL) { v->needed = 1; break; } } } if (!v->needed) { av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n", v->index); return AVERROR_EOF; } /* If this is a live stream and the reload interval has elapsed since * the last playlist reload, reload the playlists now. */ reload_interval = default_reload_interval(v); reload: if (!v->finished && av_gettime_relative() - v->last_load_time >= reload_interval) { if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) { av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n", v->index); return ret; } /* If we need to reload the playlist again below (if * there's still no more segments), switch to a reload * interval of half the target duration. */ reload_interval = v->target_duration / 2; } if (v->cur_seq_no < v->start_seq_no) { av_log(NULL, AV_LOG_WARNING, "skipping %d segments ahead, expired from playlists\n", v->start_seq_no - v->cur_seq_no); v->cur_seq_no = v->start_seq_no; } if (v->cur_seq_no >= v->start_seq_no + v->n_segments) { if (v->finished) return AVERROR_EOF; while (av_gettime_relative() - v->last_load_time < reload_interval) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_usleep(100*1000); } /* Enough time has elapsed since the last reload */ goto reload; } seg = current_segment(v); /* load/update Media Initialization Section, if any */ ret = update_init_section(v, seg); if (ret) return ret; ret = open_input(c, v, seg); if (ret < 0) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n", v->index); v->cur_seq_no += 1; goto reload; } just_opened = 1; } if (v->init_sec_buf_read_offset < v->init_sec_data_len) { /* Push init section out first before first actual segment */ int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size); memcpy(buf, v->init_sec_buf, copy_size); v->init_sec_buf_read_offset += copy_size; return copy_size; } ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL); if (ret > 0) { if (just_opened && v->is_id3_timestamped != 0) { /* Intercept ID3 tags here, elementary audio streams are required * to convey timestamps using them in the beginning of each segment. */ intercept_id3(v, buf, buf_size, &ret); } return ret; } ff_format_io_close(v->parent, &v->input); v->cur_seq_no++; c->cur_seq_no = v->cur_seq_no; goto restart; } static void add_renditions_to_variant(HLSContext *c, struct variant *var, enum AVMediaType type, const char *group_id) { int i; for (i = 0; i < c->n_renditions; i++) { struct rendition *rend = c->renditions[i]; if (rend->type == type && !strcmp(rend->group_id, group_id)) { if (rend->playlist) /* rendition is an external playlist * => add the playlist to the variant */ dynarray_add(&var->playlists, &var->n_playlists, rend->playlist); else /* rendition is part of the variant main Media Playlist * => add the rendition to the main Media Playlist */ dynarray_add(&var->playlists[0]->renditions, &var->playlists[0]->n_renditions, rend); } } } static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls, enum AVMediaType type) { int rend_idx = 0; int i; for (i = 0; i < pls->n_main_streams; i++) { AVStream *st = pls->main_streams[i]; if (st->codecpar->codec_type != type) continue; for (; rend_idx < pls->n_renditions; rend_idx++) { struct rendition *rend = pls->renditions[rend_idx]; if (rend->type != type) continue; if (rend->language[0]) av_dict_set(&st->metadata, "language", rend->language, 0); if (rend->name[0]) av_dict_set(&st->metadata, "comment", rend->name, 0); st->disposition |= rend->disposition; } if (rend_idx >=pls->n_renditions) break; } } /* if timestamp was in valid range: returns 1 and sets seq_no * if not: returns 0 and sets seq_no to closest segment */ static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls, int64_t timestamp, int *seq_no) { int i; int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ? 0 : c->first_timestamp; if (timestamp < pos) { *seq_no = pls->start_seq_no; return 0; } for (i = 0; i < pls->n_segments; i++) { int64_t diff = pos + pls->segments[i]->duration - timestamp; if (diff > 0) { *seq_no = pls->start_seq_no + i; return 1; } pos += pls->segments[i]->duration; } *seq_no = pls->start_seq_no + pls->n_segments - 1; return 0; } static int select_cur_seq_no(HLSContext *c, struct playlist *pls) { int seq_no; if (!pls->finished && !c->first_packet && av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls)) /* reload the playlist since it was suspended */ parse_playlist(c, pls->url, pls, NULL); /* If playback is already in progress (we are just selecting a new * playlist) and this is a complete file, find the matching segment * by counting durations. */ if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) { find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no); return seq_no; } if (!pls->finished) { if (!c->first_packet && /* we are doing a segment selection during playback */ c->cur_seq_no >= pls->start_seq_no && c->cur_seq_no < pls->start_seq_no + pls->n_segments) /* While spec 3.4.3 says that we cannot assume anything about the * content at the same sequence number on different playlists, * in practice this seems to work and doing it otherwise would * require us to download a segment to inspect its timestamps. */ return c->cur_seq_no; /* If this is a live stream, start live_start_index segments from the * start or end */ if (c->live_start_index < 0) return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0); else return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1); } /* Otherwise just start on the first segment. */ return pls->start_seq_no; } static int save_avio_options(AVFormatContext *s) { HLSContext *c = s->priv_data; static const char *opts[] = { "headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL }; const char **opt = opts; uint8_t *buf; int ret = 0; while (*opt) { if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) { ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL); if (ret < 0) return ret; } opt++; } return ret; } static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **opts) { av_log(s, AV_LOG_ERROR, "A HLS playlist item '%s' referred to an external file '%s'. " "Opening this file was forbidden for security reasons\n", s->filename, url); return AVERROR(EPERM); } static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream) { HLSContext *c = s->priv_data; int i, j; int bandwidth = -1; for (i = 0; i < c->n_variants; i++) { struct variant *v = c->variants[i]; for (j = 0; j < v->n_playlists; j++) { if (v->playlists[j] != pls) continue; av_program_add_stream_index(s, i, stream->index); if (bandwidth < 0) bandwidth = v->bandwidth; else if (bandwidth != v->bandwidth) bandwidth = -1; /* stream in multiple variants with different bandwidths */ } } if (bandwidth >= 0) av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0); } static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist) { int err; err = avcodec_parameters_copy(st->codecpar, ist->codecpar); if (err < 0) return err; if (pls->is_id3_timestamped) /* custom timestamps via id3 */ avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE); else avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den); st->internal->need_context_update = 1; return 0; } /* add new subdemuxer streams to our context, if any */ static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls) { int err; while (pls->n_main_streams < pls->ctx->nb_streams) { int ist_idx = pls->n_main_streams; AVStream *st = avformat_new_stream(s, NULL); AVStream *ist = pls->ctx->streams[ist_idx]; if (!st) return AVERROR(ENOMEM); st->id = pls->index; dynarray_add(&pls->main_streams, &pls->n_main_streams, st); add_stream_to_programs(s, pls, st); err = set_stream_info_from_input_stream(st, pls, ist); if (err < 0) return err; } return 0; } static void update_noheader_flag(AVFormatContext *s) { HLSContext *c = s->priv_data; int flag_needed = 0; int i; for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; if (pls->has_noheader_flag) { flag_needed = 1; break; } } if (flag_needed) s->ctx_flags |= AVFMTCTX_NOHEADER; else s->ctx_flags &= ~AVFMTCTX_NOHEADER; } static int hls_close(AVFormatContext *s) { HLSContext *c = s->priv_data; free_playlist_list(c); free_variant_list(c); free_rendition_list(c); av_dict_free(&c->avio_opts); return 0; } static int hls_read_header(AVFormatContext *s) { void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb; HLSContext *c = s->priv_data; int ret = 0, i; int highest_cur_seq_no = 0; c->ctx = s; c->interrupt_callback = &s->interrupt_callback; c->strict_std_compliance = s->strict_std_compliance; c->first_packet = 1; c->first_timestamp = AV_NOPTS_VALUE; c->cur_timestamp = AV_NOPTS_VALUE; if (u) { // get the previous user agent & set back to null if string size is zero update_options(&c->user_agent, "user_agent", u); // get the previous cookies & set back to null if string size is zero update_options(&c->cookies, "cookies", u); // get the previous headers & set back to null if string size is zero update_options(&c->headers, "headers", u); // get the previous http proxt & set back to null if string size is zero update_options(&c->http_proxy, "http_proxy", u); } if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0) goto fail; if ((ret = save_avio_options(s)) < 0) goto fail; /* Some HLS servers don't like being sent the range header */ av_dict_set(&c->avio_opts, "seekable", "0", 0); if (c->n_variants == 0) { av_log(NULL, AV_LOG_WARNING, "Empty playlist\n"); ret = AVERROR_EOF; goto fail; } /* If the playlist only contained playlists (Master Playlist), * parse each individual playlist. */ if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) { for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0) goto fail; } } if (c->variants[0]->playlists[0]->n_segments == 0) { av_log(NULL, AV_LOG_WARNING, "Empty playlist\n"); ret = AVERROR_EOF; goto fail; } /* If this isn't a live stream, calculate the total duration of the * stream. */ if (c->variants[0]->playlists[0]->finished) { int64_t duration = 0; for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++) duration += c->variants[0]->playlists[0]->segments[i]->duration; s->duration = duration; } /* Associate renditions with variants */ for (i = 0; i < c->n_variants; i++) { struct variant *var = c->variants[i]; if (var->audio_group[0]) add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group); if (var->video_group[0]) add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group); if (var->subtitles_group[0]) add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group); } /* Create a program for each variant */ for (i = 0; i < c->n_variants; i++) { struct variant *v = c->variants[i]; AVProgram *program; program = av_new_program(s, i); if (!program) goto fail; av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0); } /* Select the starting segments */ for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; if (pls->n_segments == 0) continue; pls->cur_seq_no = select_cur_seq_no(c, pls); highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no); } /* Open the demuxer for each playlist */ for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; AVInputFormat *in_fmt = NULL; if (!(pls->ctx = avformat_alloc_context())) { ret = AVERROR(ENOMEM); goto fail; } if (pls->n_segments == 0) continue; pls->index = i; pls->needed = 1; pls->parent = s; /* * If this is a live stream and this playlist looks like it is one segment * behind, try to sync it up so that every substream starts at the same * time position (so e.g. avformat_find_stream_info() will see packets from * all active streams within the first few seconds). This is not very generic, * though, as the sequence numbers are technically independent. */ if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 && highest_cur_seq_no < pls->start_seq_no + pls->n_segments) { pls->cur_seq_no = highest_cur_seq_no; } pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE); if (!pls->read_buffer){ ret = AVERROR(ENOMEM); avformat_free_context(pls->ctx); pls->ctx = NULL; goto fail; } ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL); pls->pb.seekable = 0; ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url, NULL, 0, 0); if (ret < 0) { /* Free the ctx - it isn't initialized properly at this point, * so avformat_close_input shouldn't be called. If * avformat_open_input fails below, it frees and zeros the * context, so it doesn't need any special treatment like this. */ av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url); avformat_free_context(pls->ctx); pls->ctx = NULL; goto fail; } pls->ctx->pb = &pls->pb; pls->ctx->io_open = nested_io_open; pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO; if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0) goto fail; ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL); if (ret < 0) goto fail; if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) { ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra); avformat_queue_attached_pictures(pls->ctx); ff_id3v2_free_extra_meta(&pls->id3_deferred_extra); pls->id3_deferred_extra = NULL; } if (pls->is_id3_timestamped == -1) av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n"); /* * For ID3 timestamped raw audio streams we need to detect the packet * durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(), * but for other streams we can rely on our user calling avformat_find_stream_info() * on us if they want to. */ if (pls->is_id3_timestamped) { ret = avformat_find_stream_info(pls->ctx, NULL); if (ret < 0) goto fail; } pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER); /* Create new AVStreams for each stream in this playlist */ ret = update_streams_from_subdemuxer(s, pls); if (ret < 0) goto fail; add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO); add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO); add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE); } update_noheader_flag(s); return 0; fail: hls_close(s); return ret; } static int recheck_discard_flags(AVFormatContext *s, int first) { HLSContext *c = s->priv_data; int i, changed = 0; /* Check if any new streams are needed */ for (i = 0; i < c->n_playlists; i++) c->playlists[i]->cur_needed = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; struct playlist *pls = c->playlists[s->streams[i]->id]; if (st->discard < AVDISCARD_ALL) pls->cur_needed = 1; } for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; if (pls->cur_needed && !pls->needed) { pls->needed = 1; changed = 1; pls->cur_seq_no = select_cur_seq_no(c, pls); pls->pb.eof_reached = 0; if (c->cur_timestamp != AV_NOPTS_VALUE) { /* catch up */ pls->seek_timestamp = c->cur_timestamp; pls->seek_flags = AVSEEK_FLAG_ANY; pls->seek_stream_index = -1; } av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no); } else if (first && !pls->cur_needed && pls->needed) { if (pls->input) ff_format_io_close(pls->parent, &pls->input); pls->needed = 0; changed = 1; av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i); } } return changed; } static void fill_timing_for_id3_timestamped_stream(struct playlist *pls) { if (pls->id3_offset >= 0) { pls->pkt.dts = pls->id3_mpegts_timestamp + av_rescale_q(pls->id3_offset, pls->ctx->streams[pls->pkt.stream_index]->time_base, MPEG_TIME_BASE_Q); if (pls->pkt.duration) pls->id3_offset += pls->pkt.duration; else pls->id3_offset = -1; } else { /* there have been packets with unknown duration * since the last id3 tag, should not normally happen */ pls->pkt.dts = AV_NOPTS_VALUE; } if (pls->pkt.duration) pls->pkt.duration = av_rescale_q(pls->pkt.duration, pls->ctx->streams[pls->pkt.stream_index]->time_base, MPEG_TIME_BASE_Q); pls->pkt.pts = AV_NOPTS_VALUE; } static AVRational get_timebase(struct playlist *pls) { if (pls->is_id3_timestamped) return MPEG_TIME_BASE_Q; return pls->ctx->streams[pls->pkt.stream_index]->time_base; } static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a, int64_t ts_b, struct playlist *pls_b) { int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q); int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q); return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33); } static int hls_read_packet(AVFormatContext *s, AVPacket *pkt) { HLSContext *c = s->priv_data; int ret, i, minplaylist = -1; recheck_discard_flags(s, c->first_packet); c->first_packet = 0; for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; /* Make sure we've got one buffered packet from each open playlist * stream */ if (pls->needed && !pls->pkt.data) { while (1) { int64_t ts_diff; AVRational tb; ret = av_read_frame(pls->ctx, &pls->pkt); if (ret < 0) { if (!avio_feof(&pls->pb) && ret != AVERROR_EOF) return ret; reset_packet(&pls->pkt); break; } else { /* stream_index check prevents matching picture attachments etc. */ if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) { /* audio elementary streams are id3 timestamped */ fill_timing_for_id3_timestamped_stream(pls); } if (c->first_timestamp == AV_NOPTS_VALUE && pls->pkt.dts != AV_NOPTS_VALUE) c->first_timestamp = av_rescale_q(pls->pkt.dts, get_timebase(pls), AV_TIME_BASE_Q); } if (pls->seek_timestamp == AV_NOPTS_VALUE) break; if (pls->seek_stream_index < 0 || pls->seek_stream_index == pls->pkt.stream_index) { if (pls->pkt.dts == AV_NOPTS_VALUE) { pls->seek_timestamp = AV_NOPTS_VALUE; break; } tb = get_timebase(pls); ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE, tb.den, AV_ROUND_DOWN) - pls->seek_timestamp; if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY || pls->pkt.flags & AV_PKT_FLAG_KEY)) { pls->seek_timestamp = AV_NOPTS_VALUE; break; } } av_packet_unref(&pls->pkt); reset_packet(&pls->pkt); } } /* Check if this stream has the packet with the lowest dts */ if (pls->pkt.data) { struct playlist *minpls = minplaylist < 0 ? NULL : c->playlists[minplaylist]; if (minplaylist < 0) { minplaylist = i; } else { int64_t dts = pls->pkt.dts; int64_t mindts = minpls->pkt.dts; if (dts == AV_NOPTS_VALUE || (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0)) minplaylist = i; } } } /* If we got a packet, return it */ if (minplaylist >= 0) { struct playlist *pls = c->playlists[minplaylist]; AVStream *ist; AVStream *st; ret = update_streams_from_subdemuxer(s, pls); if (ret < 0) { av_packet_unref(&pls->pkt); reset_packet(&pls->pkt); return ret; } /* check if noheader flag has been cleared by the subdemuxer */ if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) { pls->has_noheader_flag = 0; update_noheader_flag(s); } if (pls->pkt.stream_index >= pls->n_main_streams) { av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n", pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams); av_packet_unref(&pls->pkt); reset_packet(&pls->pkt); return AVERROR_BUG; } ist = pls->ctx->streams[pls->pkt.stream_index]; st = pls->main_streams[pls->pkt.stream_index]; *pkt = pls->pkt; pkt->stream_index = st->index; reset_packet(&c->playlists[minplaylist]->pkt); if (pkt->dts != AV_NOPTS_VALUE) c->cur_timestamp = av_rescale_q(pkt->dts, ist->time_base, AV_TIME_BASE_Q); /* There may be more situations where this would be useful, but this at least * handles newly probed codecs properly (i.e. request_probe by mpegts). */ if (ist->codecpar->codec_id != st->codecpar->codec_id) { ret = set_stream_info_from_input_stream(st, pls, ist); if (ret < 0) { av_packet_unref(pkt); return ret; } } return 0; } return AVERROR_EOF; } static int hls_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { HLSContext *c = s->priv_data; struct playlist *seek_pls = NULL; int i, seq_no; int j; int stream_subdemuxer_index; int64_t first_timestamp, seek_timestamp, duration; if ((flags & AVSEEK_FLAG_BYTE) || !(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT)) return AVERROR(ENOSYS); first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ? 0 : c->first_timestamp; seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE, s->streams[stream_index]->time_base.den, flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP); duration = s->duration == AV_NOPTS_VALUE ? 0 : s->duration; if (0 < duration && duration < seek_timestamp - first_timestamp) return AVERROR(EIO); /* find the playlist with the specified stream */ for (i = 0; i < c->n_playlists; i++) { struct playlist *pls = c->playlists[i]; for (j = 0; j < pls->n_main_streams; j++) { if (pls->main_streams[j] == s->streams[stream_index]) { seek_pls = pls; stream_subdemuxer_index = j; break; } } } /* check if the timestamp is valid for the playlist with the * specified stream index */ if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no)) return AVERROR(EIO); /* set segment now so we do not need to search again below */ seek_pls->cur_seq_no = seq_no; seek_pls->seek_stream_index = stream_subdemuxer_index; for (i = 0; i < c->n_playlists; i++) { /* Reset reading */ struct playlist *pls = c->playlists[i]; if (pls->input) ff_format_io_close(pls->parent, &pls->input); av_packet_unref(&pls->pkt); reset_packet(&pls->pkt); pls->pb.eof_reached = 0; /* Clear any buffered data */ pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer; /* Reset the pos, to let the mpegts demuxer know we've seeked. */ pls->pb.pos = 0; /* Flush the packet queue of the subdemuxer. */ ff_read_frame_flush(pls->ctx); pls->seek_timestamp = seek_timestamp; pls->seek_flags = flags; if (pls != seek_pls) { /* set closest segment seq_no for playlists not handled above */ find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no); /* seek the playlist to the given position without taking * keyframes into account since this playlist does not have the * specified stream where we should look for the keyframes */ pls->seek_stream_index = -1; pls->seek_flags |= AVSEEK_FLAG_ANY; } } c->cur_timestamp = seek_timestamp; return 0; } static int hls_probe(AVProbeData *p) { /* Require #EXTM3U at the start, and either one of the ones below * somewhere for a proper match. */ if (strncmp(p->buf, "#EXTM3U", 7)) return 0; if (strstr(p->buf, "#EXT-X-STREAM-INF:") || strstr(p->buf, "#EXT-X-TARGETDURATION:") || strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:")) return AVPROBE_SCORE_MAX; return 0; } #define OFFSET(x) offsetof(HLSContext, x) #define FLAGS AV_OPT_FLAG_DECODING_PARAM static const AVOption hls_options[] = { {"live_start_index", "segment index to start live streams at (negative values are from the end)", OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS}, {NULL} }; static const AVClass hls_class = { .class_name = "hls,applehttp", .item_name = av_default_item_name, .option = hls_options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_hls_demuxer = { .name = "hls,applehttp", .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"), .priv_class = &hls_class, .priv_data_size = sizeof(HLSContext), .read_probe = hls_probe, .read_header = hls_read_header, .read_packet = hls_read_packet, .read_close = hls_close, .read_seek = hls_read_seek, };
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3416_0
crossvul-cpp_data_bad_1860_0
#include <linux/types.h> #include <linux/errno.h> #include <linux/kmod.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/file.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/device.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/seq_file.h> #include <linux/uaccess.h> #include <linux/ratelimit.h> #undef LDISC_DEBUG_HANGUP #ifdef LDISC_DEBUG_HANGUP #define tty_ldisc_debug(tty, f, args...) tty_debug(tty, f, ##args) #else #define tty_ldisc_debug(tty, f, args...) #endif /* lockdep nested classes for tty->ldisc_sem */ enum { LDISC_SEM_NORMAL, LDISC_SEM_OTHER, }; /* * This guards the refcounted line discipline lists. The lock * must be taken with irqs off because there are hangup path * callers who will do ldisc lookups and cannot sleep. */ static DEFINE_RAW_SPINLOCK(tty_ldiscs_lock); /* Line disc dispatch table */ static struct tty_ldisc_ops *tty_ldiscs[NR_LDISCS]; /** * tty_register_ldisc - install a line discipline * @disc: ldisc number * @new_ldisc: pointer to the ldisc object * * Installs a new line discipline into the kernel. The discipline * is set up as unreferenced and then made available to the kernel * from this point onwards. * * Locking: * takes tty_ldiscs_lock to guard against ldisc races */ int tty_register_ldisc(int disc, struct tty_ldisc_ops *new_ldisc) { unsigned long flags; int ret = 0; if (disc < N_TTY || disc >= NR_LDISCS) return -EINVAL; raw_spin_lock_irqsave(&tty_ldiscs_lock, flags); tty_ldiscs[disc] = new_ldisc; new_ldisc->num = disc; new_ldisc->refcount = 0; raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags); return ret; } EXPORT_SYMBOL(tty_register_ldisc); /** * tty_unregister_ldisc - unload a line discipline * @disc: ldisc number * @new_ldisc: pointer to the ldisc object * * Remove a line discipline from the kernel providing it is not * currently in use. * * Locking: * takes tty_ldiscs_lock to guard against ldisc races */ int tty_unregister_ldisc(int disc) { unsigned long flags; int ret = 0; if (disc < N_TTY || disc >= NR_LDISCS) return -EINVAL; raw_spin_lock_irqsave(&tty_ldiscs_lock, flags); if (tty_ldiscs[disc]->refcount) ret = -EBUSY; else tty_ldiscs[disc] = NULL; raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags); return ret; } EXPORT_SYMBOL(tty_unregister_ldisc); static struct tty_ldisc_ops *get_ldops(int disc) { unsigned long flags; struct tty_ldisc_ops *ldops, *ret; raw_spin_lock_irqsave(&tty_ldiscs_lock, flags); ret = ERR_PTR(-EINVAL); ldops = tty_ldiscs[disc]; if (ldops) { ret = ERR_PTR(-EAGAIN); if (try_module_get(ldops->owner)) { ldops->refcount++; ret = ldops; } } raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags); return ret; } static void put_ldops(struct tty_ldisc_ops *ldops) { unsigned long flags; raw_spin_lock_irqsave(&tty_ldiscs_lock, flags); ldops->refcount--; module_put(ldops->owner); raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags); } /** * tty_ldisc_get - take a reference to an ldisc * @disc: ldisc number * * Takes a reference to a line discipline. Deals with refcounts and * module locking counts. Returns NULL if the discipline is not available. * Returns a pointer to the discipline and bumps the ref count if it is * available * * Locking: * takes tty_ldiscs_lock to guard against ldisc races */ static struct tty_ldisc *tty_ldisc_get(struct tty_struct *tty, int disc) { struct tty_ldisc *ld; struct tty_ldisc_ops *ldops; if (disc < N_TTY || disc >= NR_LDISCS) return ERR_PTR(-EINVAL); /* * Get the ldisc ops - we may need to request them to be loaded * dynamically and try again. */ ldops = get_ldops(disc); if (IS_ERR(ldops)) { request_module("tty-ldisc-%d", disc); ldops = get_ldops(disc); if (IS_ERR(ldops)) return ERR_CAST(ldops); } ld = kmalloc(sizeof(struct tty_ldisc), GFP_KERNEL); if (ld == NULL) { put_ldops(ldops); return ERR_PTR(-ENOMEM); } ld->ops = ldops; ld->tty = tty; return ld; } /** * tty_ldisc_put - release the ldisc * * Complement of tty_ldisc_get(). */ static void tty_ldisc_put(struct tty_ldisc *ld) { if (WARN_ON_ONCE(!ld)) return; put_ldops(ld->ops); kfree(ld); } static void *tty_ldiscs_seq_start(struct seq_file *m, loff_t *pos) { return (*pos < NR_LDISCS) ? pos : NULL; } static void *tty_ldiscs_seq_next(struct seq_file *m, void *v, loff_t *pos) { (*pos)++; return (*pos < NR_LDISCS) ? pos : NULL; } static void tty_ldiscs_seq_stop(struct seq_file *m, void *v) { } static int tty_ldiscs_seq_show(struct seq_file *m, void *v) { int i = *(loff_t *)v; struct tty_ldisc_ops *ldops; ldops = get_ldops(i); if (IS_ERR(ldops)) return 0; seq_printf(m, "%-10s %2d\n", ldops->name ? ldops->name : "???", i); put_ldops(ldops); return 0; } static const struct seq_operations tty_ldiscs_seq_ops = { .start = tty_ldiscs_seq_start, .next = tty_ldiscs_seq_next, .stop = tty_ldiscs_seq_stop, .show = tty_ldiscs_seq_show, }; static int proc_tty_ldiscs_open(struct inode *inode, struct file *file) { return seq_open(file, &tty_ldiscs_seq_ops); } const struct file_operations tty_ldiscs_proc_fops = { .owner = THIS_MODULE, .open = proc_tty_ldiscs_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /** * tty_ldisc_ref_wait - wait for the tty ldisc * @tty: tty device * * Dereference the line discipline for the terminal and take a * reference to it. If the line discipline is in flux then * wait patiently until it changes. * * Note: Must not be called from an IRQ/timer context. The caller * must also be careful not to hold other locks that will deadlock * against a discipline change, such as an existing ldisc reference * (which we check for) * * Note: only callable from a file_operations routine (which * guarantees tty->ldisc != NULL when the lock is acquired). */ struct tty_ldisc *tty_ldisc_ref_wait(struct tty_struct *tty) { ldsem_down_read(&tty->ldisc_sem, MAX_SCHEDULE_TIMEOUT); WARN_ON(!tty->ldisc); return tty->ldisc; } EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait); /** * tty_ldisc_ref - get the tty ldisc * @tty: tty device * * Dereference the line discipline for the terminal and take a * reference to it. If the line discipline is in flux then * return NULL. Can be called from IRQ and timer functions. */ struct tty_ldisc *tty_ldisc_ref(struct tty_struct *tty) { struct tty_ldisc *ld = NULL; if (ldsem_down_read_trylock(&tty->ldisc_sem)) { ld = tty->ldisc; if (!ld) ldsem_up_read(&tty->ldisc_sem); } return ld; } EXPORT_SYMBOL_GPL(tty_ldisc_ref); /** * tty_ldisc_deref - free a tty ldisc reference * @ld: reference to free up * * Undoes the effect of tty_ldisc_ref or tty_ldisc_ref_wait. May * be called in IRQ context. */ void tty_ldisc_deref(struct tty_ldisc *ld) { ldsem_up_read(&ld->tty->ldisc_sem); } EXPORT_SYMBOL_GPL(tty_ldisc_deref); static inline int __lockfunc __tty_ldisc_lock(struct tty_struct *tty, unsigned long timeout) { return ldsem_down_write(&tty->ldisc_sem, timeout); } static inline int __lockfunc __tty_ldisc_lock_nested(struct tty_struct *tty, unsigned long timeout) { return ldsem_down_write_nested(&tty->ldisc_sem, LDISC_SEM_OTHER, timeout); } static inline void __tty_ldisc_unlock(struct tty_struct *tty) { ldsem_up_write(&tty->ldisc_sem); } static int __lockfunc tty_ldisc_lock(struct tty_struct *tty, unsigned long timeout) { int ret; ret = __tty_ldisc_lock(tty, timeout); if (!ret) return -EBUSY; set_bit(TTY_LDISC_HALTED, &tty->flags); return 0; } static void tty_ldisc_unlock(struct tty_struct *tty) { clear_bit(TTY_LDISC_HALTED, &tty->flags); __tty_ldisc_unlock(tty); } static int __lockfunc tty_ldisc_lock_pair_timeout(struct tty_struct *tty, struct tty_struct *tty2, unsigned long timeout) { int ret; if (tty < tty2) { ret = __tty_ldisc_lock(tty, timeout); if (ret) { ret = __tty_ldisc_lock_nested(tty2, timeout); if (!ret) __tty_ldisc_unlock(tty); } } else { /* if this is possible, it has lots of implications */ WARN_ON_ONCE(tty == tty2); if (tty2 && tty != tty2) { ret = __tty_ldisc_lock(tty2, timeout); if (ret) { ret = __tty_ldisc_lock_nested(tty, timeout); if (!ret) __tty_ldisc_unlock(tty2); } } else ret = __tty_ldisc_lock(tty, timeout); } if (!ret) return -EBUSY; set_bit(TTY_LDISC_HALTED, &tty->flags); if (tty2) set_bit(TTY_LDISC_HALTED, &tty2->flags); return 0; } static void __lockfunc tty_ldisc_lock_pair(struct tty_struct *tty, struct tty_struct *tty2) { tty_ldisc_lock_pair_timeout(tty, tty2, MAX_SCHEDULE_TIMEOUT); } static void __lockfunc tty_ldisc_unlock_pair(struct tty_struct *tty, struct tty_struct *tty2) { __tty_ldisc_unlock(tty); if (tty2) __tty_ldisc_unlock(tty2); } /** * tty_ldisc_flush - flush line discipline queue * @tty: tty * * Flush the line discipline queue (if any) and the tty flip buffers * for this tty. */ void tty_ldisc_flush(struct tty_struct *tty) { struct tty_ldisc *ld = tty_ldisc_ref(tty); tty_buffer_flush(tty, ld); if (ld) tty_ldisc_deref(ld); } EXPORT_SYMBOL_GPL(tty_ldisc_flush); /** * tty_set_termios_ldisc - set ldisc field * @tty: tty structure * @num: line discipline number * * This is probably overkill for real world processors but * they are not on hot paths so a little discipline won't do * any harm. * * Locking: takes termios_rwsem */ static void tty_set_termios_ldisc(struct tty_struct *tty, int num) { down_write(&tty->termios_rwsem); tty->termios.c_line = num; up_write(&tty->termios_rwsem); } /** * tty_ldisc_open - open a line discipline * @tty: tty we are opening the ldisc on * @ld: discipline to open * * A helper opening method. Also a convenient debugging and check * point. * * Locking: always called with BTM already held. */ static int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld) { WARN_ON(test_and_set_bit(TTY_LDISC_OPEN, &tty->flags)); if (ld->ops->open) { int ret; /* BTM here locks versus a hangup event */ ret = ld->ops->open(tty); if (ret) clear_bit(TTY_LDISC_OPEN, &tty->flags); tty_ldisc_debug(tty, "%p: opened\n", tty->ldisc); return ret; } return 0; } /** * tty_ldisc_close - close a line discipline * @tty: tty we are opening the ldisc on * @ld: discipline to close * * A helper close method. Also a convenient debugging and check * point. */ static void tty_ldisc_close(struct tty_struct *tty, struct tty_ldisc *ld) { WARN_ON(!test_bit(TTY_LDISC_OPEN, &tty->flags)); clear_bit(TTY_LDISC_OPEN, &tty->flags); if (ld->ops->close) ld->ops->close(tty); tty_ldisc_debug(tty, "%p: closed\n", tty->ldisc); } /** * tty_ldisc_restore - helper for tty ldisc change * @tty: tty to recover * @old: previous ldisc * * Restore the previous line discipline or N_TTY when a line discipline * change fails due to an open error */ static void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old) { struct tty_ldisc *new_ldisc; int r; /* There is an outstanding reference here so this is safe */ old = tty_ldisc_get(tty, old->ops->num); WARN_ON(IS_ERR(old)); tty->ldisc = old; tty_set_termios_ldisc(tty, old->ops->num); if (tty_ldisc_open(tty, old) < 0) { tty_ldisc_put(old); /* This driver is always present */ new_ldisc = tty_ldisc_get(tty, N_TTY); if (IS_ERR(new_ldisc)) panic("n_tty: get"); tty->ldisc = new_ldisc; tty_set_termios_ldisc(tty, N_TTY); r = tty_ldisc_open(tty, new_ldisc); if (r < 0) panic("Couldn't open N_TTY ldisc for " "%s --- error %d.", tty_name(tty), r); } } /** * tty_set_ldisc - set line discipline * @tty: the terminal to set * @ldisc: the line discipline * * Set the discipline of a tty line. Must be called from a process * context. The ldisc change logic has to protect itself against any * overlapping ldisc change (including on the other end of pty pairs), * the close of one side of a tty/pty pair, and eventually hangup. */ int tty_set_ldisc(struct tty_struct *tty, int ldisc) { int retval; struct tty_ldisc *old_ldisc, *new_ldisc; new_ldisc = tty_ldisc_get(tty, ldisc); if (IS_ERR(new_ldisc)) return PTR_ERR(new_ldisc); tty_lock(tty); retval = tty_ldisc_lock(tty, 5 * HZ); if (retval) goto err; /* Check the no-op case */ if (tty->ldisc->ops->num == ldisc) goto out; if (test_bit(TTY_HUPPED, &tty->flags)) { /* We were raced by hangup */ retval = -EIO; goto out; } old_ldisc = tty->ldisc; /* Shutdown the old discipline. */ tty_ldisc_close(tty, old_ldisc); /* Now set up the new line discipline. */ tty->ldisc = new_ldisc; tty_set_termios_ldisc(tty, ldisc); retval = tty_ldisc_open(tty, new_ldisc); if (retval < 0) { /* Back to the old one or N_TTY if we can't */ tty_ldisc_put(new_ldisc); tty_ldisc_restore(tty, old_ldisc); } if (tty->ldisc->ops->num != old_ldisc->ops->num && tty->ops->set_ldisc) { down_read(&tty->termios_rwsem); tty->ops->set_ldisc(tty); up_read(&tty->termios_rwsem); } /* At this point we hold a reference to the new ldisc and a reference to the old ldisc, or we hold two references to the old ldisc (if it was restored as part of error cleanup above). In either case, releasing a single reference from the old ldisc is correct. */ new_ldisc = old_ldisc; out: tty_ldisc_unlock(tty); /* Restart the work queue in case no characters kick it off. Safe if already running */ tty_buffer_restart_work(tty->port); err: tty_ldisc_put(new_ldisc); /* drop the extra reference */ tty_unlock(tty); return retval; } /** * tty_reset_termios - reset terminal state * @tty: tty to reset * * Restore a terminal to the driver default state. */ static void tty_reset_termios(struct tty_struct *tty) { down_write(&tty->termios_rwsem); tty->termios = tty->driver->init_termios; tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios); tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios); up_write(&tty->termios_rwsem); } /** * tty_ldisc_reinit - reinitialise the tty ldisc * @tty: tty to reinit * @ldisc: line discipline to reinitialize * * Switch the tty to a line discipline and leave the ldisc * state closed */ static int tty_ldisc_reinit(struct tty_struct *tty, int ldisc) { struct tty_ldisc *ld = tty_ldisc_get(tty, ldisc); if (IS_ERR(ld)) return -1; tty_ldisc_close(tty, tty->ldisc); tty_ldisc_put(tty->ldisc); /* * Switch the line discipline back */ tty->ldisc = ld; tty_set_termios_ldisc(tty, ldisc); return 0; } /** * tty_ldisc_hangup - hangup ldisc reset * @tty: tty being hung up * * Some tty devices reset their termios when they receive a hangup * event. In that situation we must also switch back to N_TTY properly * before we reset the termios data. * * Locking: We can take the ldisc mutex as the rest of the code is * careful to allow for this. * * In the pty pair case this occurs in the close() path of the * tty itself so we must be careful about locking rules. */ void tty_ldisc_hangup(struct tty_struct *tty) { struct tty_ldisc *ld; int reset = tty->driver->flags & TTY_DRIVER_RESET_TERMIOS; int err = 0; tty_ldisc_debug(tty, "%p: closing\n", tty->ldisc); ld = tty_ldisc_ref(tty); if (ld != NULL) { if (ld->ops->flush_buffer) ld->ops->flush_buffer(tty); tty_driver_flush_buffer(tty); if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) && ld->ops->write_wakeup) ld->ops->write_wakeup(tty); if (ld->ops->hangup) ld->ops->hangup(tty); tty_ldisc_deref(ld); } wake_up_interruptible_poll(&tty->write_wait, POLLOUT); wake_up_interruptible_poll(&tty->read_wait, POLLIN); /* * Shutdown the current line discipline, and reset it to * N_TTY if need be. * * Avoid racing set_ldisc or tty_ldisc_release */ tty_ldisc_lock(tty, MAX_SCHEDULE_TIMEOUT); if (tty->ldisc) { /* At this point we have a halted ldisc; we want to close it and reopen a new ldisc. We could defer the reopen to the next open but it means auditing a lot of other paths so this is a FIXME */ if (reset == 0) { if (!tty_ldisc_reinit(tty, tty->termios.c_line)) err = tty_ldisc_open(tty, tty->ldisc); else err = 1; } /* If the re-open fails or we reset then go to N_TTY. The N_TTY open cannot fail */ if (reset || err) { BUG_ON(tty_ldisc_reinit(tty, N_TTY)); WARN_ON(tty_ldisc_open(tty, tty->ldisc)); } } tty_ldisc_unlock(tty); if (reset) tty_reset_termios(tty); tty_ldisc_debug(tty, "%p: re-opened\n", tty->ldisc); } /** * tty_ldisc_setup - open line discipline * @tty: tty being shut down * @o_tty: pair tty for pty/tty pairs * * Called during the initial open of a tty/pty pair in order to set up the * line disciplines and bind them to the tty. This has no locking issues * as the device isn't yet active. */ int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty) { struct tty_ldisc *ld = tty->ldisc; int retval; retval = tty_ldisc_open(tty, ld); if (retval) return retval; if (o_tty) { retval = tty_ldisc_open(o_tty, o_tty->ldisc); if (retval) { tty_ldisc_close(tty, ld); return retval; } } return 0; } static void tty_ldisc_kill(struct tty_struct *tty) { /* * Now kill off the ldisc */ tty_ldisc_close(tty, tty->ldisc); tty_ldisc_put(tty->ldisc); /* Force an oops if we mess this up */ tty->ldisc = NULL; /* Ensure the next open requests the N_TTY ldisc */ tty_set_termios_ldisc(tty, N_TTY); } /** * tty_ldisc_release - release line discipline * @tty: tty being shut down (or one end of pty pair) * * Called during the final close of a tty or a pty pair in order to shut * down the line discpline layer. On exit, each ldisc assigned is N_TTY and * each ldisc has not been opened. */ void tty_ldisc_release(struct tty_struct *tty) { struct tty_struct *o_tty = tty->link; /* * Shutdown this line discipline. As this is the final close, * it does not race with the set_ldisc code path. */ tty_ldisc_lock_pair(tty, o_tty); tty_ldisc_kill(tty); if (o_tty) tty_ldisc_kill(o_tty); tty_ldisc_unlock_pair(tty, o_tty); /* And the memory resources remaining (buffers, termios) will be disposed of when the kref hits zero */ tty_ldisc_debug(tty, "released\n"); } /** * tty_ldisc_init - ldisc setup for new tty * @tty: tty being allocated * * Set up the line discipline objects for a newly allocated tty. Note that * the tty structure is not completely set up when this call is made. */ void tty_ldisc_init(struct tty_struct *tty) { struct tty_ldisc *ld = tty_ldisc_get(tty, N_TTY); if (IS_ERR(ld)) panic("n_tty: init_tty"); tty->ldisc = ld; } /** * tty_ldisc_init - ldisc cleanup for new tty * @tty: tty that was allocated recently * * The tty structure must not becompletely set up (tty_ldisc_setup) when * this call is made. */ void tty_ldisc_deinit(struct tty_struct *tty) { tty_ldisc_put(tty->ldisc); tty->ldisc = NULL; } void tty_ldisc_begin(void) { /* Setup the default TTY line discipline. */ (void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1860_0
crossvul-cpp_data_bad_3696_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 "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; } 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); 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) { 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; } return 0; } int rds_recvmsg(struct kiocb *iocb, 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; struct sockaddr_in *sin; 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) { /* 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)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); 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); 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)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; 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)); } 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; } rds_info_copy(iter, &minfo, sizeof(minfo)); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3696_0
crossvul-cpp_data_good_151_0
/* * linux/kernel/compat.c * * Kernel compatibililty routines for e.g. 32 bit syscall support * on 64 bit kernels. * * Copyright (C) 2002-2003 Stephen Rothwell, IBM Corporation * * 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. */ #include <linux/linkage.h> #include <linux/compat.h> #include <linux/errno.h> #include <linux/time.h> #include <linux/signal.h> #include <linux/sched.h> /* for MAX_SCHEDULE_TIMEOUT */ #include <linux/syscalls.h> #include <linux/unistd.h> #include <linux/security.h> #include <linux/timex.h> #include <linux/export.h> #include <linux/migrate.h> #include <linux/posix-timers.h> #include <linux/times.h> #include <linux/ptrace.h> #include <linux/gfp.h> #include <linux/uaccess.h> int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp) { struct compat_timex tx32; memset(txc, 0, sizeof(struct timex)); if (copy_from_user(&tx32, utp, sizeof(struct compat_timex))) return -EFAULT; txc->modes = tx32.modes; txc->offset = tx32.offset; txc->freq = tx32.freq; txc->maxerror = tx32.maxerror; txc->esterror = tx32.esterror; txc->status = tx32.status; txc->constant = tx32.constant; txc->precision = tx32.precision; txc->tolerance = tx32.tolerance; txc->time.tv_sec = tx32.time.tv_sec; txc->time.tv_usec = tx32.time.tv_usec; txc->tick = tx32.tick; txc->ppsfreq = tx32.ppsfreq; txc->jitter = tx32.jitter; txc->shift = tx32.shift; txc->stabil = tx32.stabil; txc->jitcnt = tx32.jitcnt; txc->calcnt = tx32.calcnt; txc->errcnt = tx32.errcnt; txc->stbcnt = tx32.stbcnt; return 0; } int compat_put_timex(struct compat_timex __user *utp, const struct timex *txc) { struct compat_timex tx32; memset(&tx32, 0, sizeof(struct compat_timex)); tx32.modes = txc->modes; tx32.offset = txc->offset; tx32.freq = txc->freq; tx32.maxerror = txc->maxerror; tx32.esterror = txc->esterror; tx32.status = txc->status; tx32.constant = txc->constant; tx32.precision = txc->precision; tx32.tolerance = txc->tolerance; tx32.time.tv_sec = txc->time.tv_sec; tx32.time.tv_usec = txc->time.tv_usec; tx32.tick = txc->tick; tx32.ppsfreq = txc->ppsfreq; tx32.jitter = txc->jitter; tx32.shift = txc->shift; tx32.stabil = txc->stabil; tx32.jitcnt = txc->jitcnt; tx32.calcnt = txc->calcnt; tx32.errcnt = txc->errcnt; tx32.stbcnt = txc->stbcnt; tx32.tai = txc->tai; if (copy_to_user(utp, &tx32, sizeof(struct compat_timex))) return -EFAULT; return 0; } static int __compat_get_timeval(struct timeval *tv, const struct compat_timeval __user *ctv) { return (!access_ok(VERIFY_READ, ctv, sizeof(*ctv)) || __get_user(tv->tv_sec, &ctv->tv_sec) || __get_user(tv->tv_usec, &ctv->tv_usec)) ? -EFAULT : 0; } static int __compat_put_timeval(const struct timeval *tv, struct compat_timeval __user *ctv) { return (!access_ok(VERIFY_WRITE, ctv, sizeof(*ctv)) || __put_user(tv->tv_sec, &ctv->tv_sec) || __put_user(tv->tv_usec, &ctv->tv_usec)) ? -EFAULT : 0; } static int __compat_get_timespec(struct timespec *ts, const struct compat_timespec __user *cts) { return (!access_ok(VERIFY_READ, cts, sizeof(*cts)) || __get_user(ts->tv_sec, &cts->tv_sec) || __get_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0; } static int __compat_put_timespec(const struct timespec *ts, struct compat_timespec __user *cts) { return (!access_ok(VERIFY_WRITE, cts, sizeof(*cts)) || __put_user(ts->tv_sec, &cts->tv_sec) || __put_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0; } static int __compat_get_timespec64(struct timespec64 *ts64, const struct compat_timespec __user *cts) { struct compat_timespec ts; int ret; ret = copy_from_user(&ts, cts, sizeof(ts)); if (ret) return -EFAULT; ts64->tv_sec = ts.tv_sec; ts64->tv_nsec = ts.tv_nsec; return 0; } static int __compat_put_timespec64(const struct timespec64 *ts64, struct compat_timespec __user *cts) { struct compat_timespec ts = { .tv_sec = ts64->tv_sec, .tv_nsec = ts64->tv_nsec }; return copy_to_user(cts, &ts, sizeof(ts)) ? -EFAULT : 0; } int compat_get_timespec64(struct timespec64 *ts, const void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_from_user(ts, uts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_get_timespec64(ts, uts); } EXPORT_SYMBOL_GPL(compat_get_timespec64); int compat_put_timespec64(const struct timespec64 *ts, void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_to_user(uts, ts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_put_timespec64(ts, uts); } EXPORT_SYMBOL_GPL(compat_put_timespec64); int compat_get_timeval(struct timeval *tv, const void __user *utv) { if (COMPAT_USE_64BIT_TIME) return copy_from_user(tv, utv, sizeof(*tv)) ? -EFAULT : 0; else return __compat_get_timeval(tv, utv); } EXPORT_SYMBOL_GPL(compat_get_timeval); int compat_put_timeval(const struct timeval *tv, void __user *utv) { if (COMPAT_USE_64BIT_TIME) return copy_to_user(utv, tv, sizeof(*tv)) ? -EFAULT : 0; else return __compat_put_timeval(tv, utv); } EXPORT_SYMBOL_GPL(compat_put_timeval); int compat_get_timespec(struct timespec *ts, const void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_from_user(ts, uts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_get_timespec(ts, uts); } EXPORT_SYMBOL_GPL(compat_get_timespec); int compat_put_timespec(const struct timespec *ts, void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_to_user(uts, ts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_put_timespec(ts, uts); } EXPORT_SYMBOL_GPL(compat_put_timespec); int get_compat_itimerval(struct itimerval *o, const struct compat_itimerval __user *i) { struct compat_itimerval v32; if (copy_from_user(&v32, i, sizeof(struct compat_itimerval))) return -EFAULT; o->it_interval.tv_sec = v32.it_interval.tv_sec; o->it_interval.tv_usec = v32.it_interval.tv_usec; o->it_value.tv_sec = v32.it_value.tv_sec; o->it_value.tv_usec = v32.it_value.tv_usec; return 0; } int put_compat_itimerval(struct compat_itimerval __user *o, const struct itimerval *i) { struct compat_itimerval v32; v32.it_interval.tv_sec = i->it_interval.tv_sec; v32.it_interval.tv_usec = i->it_interval.tv_usec; v32.it_value.tv_sec = i->it_value.tv_sec; v32.it_value.tv_usec = i->it_value.tv_usec; return copy_to_user(o, &v32, sizeof(struct compat_itimerval)) ? -EFAULT : 0; } #ifdef __ARCH_WANT_SYS_SIGPROCMASK /* * sys_sigprocmask SIG_SETMASK sets the first (compat) word of the * blocked set of signals to the supplied signal set */ static inline void compat_sig_setmask(sigset_t *blocked, compat_sigset_word set) { memcpy(blocked->sig, &set, sizeof(set)); } COMPAT_SYSCALL_DEFINE3(sigprocmask, int, how, compat_old_sigset_t __user *, nset, compat_old_sigset_t __user *, oset) { old_sigset_t old_set, new_set; sigset_t new_blocked; old_set = current->blocked.sig[0]; if (nset) { if (get_user(new_set, nset)) return -EFAULT; new_set &= ~(sigmask(SIGKILL) | sigmask(SIGSTOP)); new_blocked = current->blocked; switch (how) { case SIG_BLOCK: sigaddsetmask(&new_blocked, new_set); break; case SIG_UNBLOCK: sigdelsetmask(&new_blocked, new_set); break; case SIG_SETMASK: compat_sig_setmask(&new_blocked, new_set); break; default: return -EINVAL; } set_current_blocked(&new_blocked); } if (oset) { if (put_user(old_set, oset)) return -EFAULT; } return 0; } #endif int put_compat_rusage(const struct rusage *r, struct compat_rusage __user *ru) { struct compat_rusage r32; memset(&r32, 0, sizeof(r32)); r32.ru_utime.tv_sec = r->ru_utime.tv_sec; r32.ru_utime.tv_usec = r->ru_utime.tv_usec; r32.ru_stime.tv_sec = r->ru_stime.tv_sec; r32.ru_stime.tv_usec = r->ru_stime.tv_usec; r32.ru_maxrss = r->ru_maxrss; r32.ru_ixrss = r->ru_ixrss; r32.ru_idrss = r->ru_idrss; r32.ru_isrss = r->ru_isrss; r32.ru_minflt = r->ru_minflt; r32.ru_majflt = r->ru_majflt; r32.ru_nswap = r->ru_nswap; r32.ru_inblock = r->ru_inblock; r32.ru_oublock = r->ru_oublock; r32.ru_msgsnd = r->ru_msgsnd; r32.ru_msgrcv = r->ru_msgrcv; r32.ru_nsignals = r->ru_nsignals; r32.ru_nvcsw = r->ru_nvcsw; r32.ru_nivcsw = r->ru_nivcsw; if (copy_to_user(ru, &r32, sizeof(r32))) return -EFAULT; return 0; } static int compat_get_user_cpu_mask(compat_ulong_t __user *user_mask_ptr, unsigned len, struct cpumask *new_mask) { unsigned long *k; if (len < cpumask_size()) memset(new_mask, 0, cpumask_size()); else if (len > cpumask_size()) len = cpumask_size(); k = cpumask_bits(new_mask); return compat_get_bitmap(k, user_mask_ptr, len * 8); } COMPAT_SYSCALL_DEFINE3(sched_setaffinity, compat_pid_t, pid, unsigned int, len, compat_ulong_t __user *, user_mask_ptr) { cpumask_var_t new_mask; int retval; if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) return -ENOMEM; retval = compat_get_user_cpu_mask(user_mask_ptr, len, new_mask); if (retval) goto out; retval = sched_setaffinity(pid, new_mask); out: free_cpumask_var(new_mask); return retval; } COMPAT_SYSCALL_DEFINE3(sched_getaffinity, compat_pid_t, pid, unsigned int, len, compat_ulong_t __user *, user_mask_ptr) { int ret; cpumask_var_t mask; if ((len * BITS_PER_BYTE) < nr_cpu_ids) return -EINVAL; if (len & (sizeof(compat_ulong_t)-1)) return -EINVAL; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; ret = sched_getaffinity(pid, mask); if (ret == 0) { unsigned int retlen = min(len, cpumask_size()); if (compat_put_bitmap(user_mask_ptr, cpumask_bits(mask), retlen * 8)) ret = -EFAULT; else ret = retlen; } free_cpumask_var(mask); return ret; } int get_compat_itimerspec64(struct itimerspec64 *its, const struct compat_itimerspec __user *uits) { if (__compat_get_timespec64(&its->it_interval, &uits->it_interval) || __compat_get_timespec64(&its->it_value, &uits->it_value)) return -EFAULT; return 0; } EXPORT_SYMBOL_GPL(get_compat_itimerspec64); int put_compat_itimerspec64(const struct itimerspec64 *its, struct compat_itimerspec __user *uits) { if (__compat_put_timespec64(&its->it_interval, &uits->it_interval) || __compat_put_timespec64(&its->it_value, &uits->it_value)) return -EFAULT; return 0; } EXPORT_SYMBOL_GPL(put_compat_itimerspec64); /* * We currently only need the following fields from the sigevent * structure: sigev_value, sigev_signo, sig_notify and (sometimes * sigev_notify_thread_id). The others are handled in user mode. * We also assume that copying sigev_value.sival_int is sufficient * to keep all the bits of sigev_value.sival_ptr intact. */ int get_compat_sigevent(struct sigevent *event, const struct compat_sigevent __user *u_event) { memset(event, 0, sizeof(*event)); return (!access_ok(VERIFY_READ, u_event, sizeof(*u_event)) || __get_user(event->sigev_value.sival_int, &u_event->sigev_value.sival_int) || __get_user(event->sigev_signo, &u_event->sigev_signo) || __get_user(event->sigev_notify, &u_event->sigev_notify) || __get_user(event->sigev_notify_thread_id, &u_event->sigev_notify_thread_id)) ? -EFAULT : 0; } long compat_get_bitmap(unsigned long *mask, const compat_ulong_t __user *umask, unsigned long bitmap_size) { unsigned long nr_compat_longs; /* align bitmap up to nearest compat_long_t boundary */ bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG); nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size); if (!access_ok(VERIFY_READ, umask, bitmap_size / 8)) return -EFAULT; user_access_begin(); while (nr_compat_longs > 1) { compat_ulong_t l1, l2; unsafe_get_user(l1, umask++, Efault); unsafe_get_user(l2, umask++, Efault); *mask++ = ((unsigned long)l2 << BITS_PER_COMPAT_LONG) | l1; nr_compat_longs -= 2; } if (nr_compat_longs) unsafe_get_user(*mask, umask++, Efault); user_access_end(); return 0; Efault: user_access_end(); return -EFAULT; } long compat_put_bitmap(compat_ulong_t __user *umask, unsigned long *mask, unsigned long bitmap_size) { unsigned long nr_compat_longs; /* align bitmap up to nearest compat_long_t boundary */ bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG); nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size); if (!access_ok(VERIFY_WRITE, umask, bitmap_size / 8)) return -EFAULT; user_access_begin(); while (nr_compat_longs > 1) { unsigned long m = *mask++; unsafe_put_user((compat_ulong_t)m, umask++, Efault); unsafe_put_user(m >> BITS_PER_COMPAT_LONG, umask++, Efault); nr_compat_longs -= 2; } if (nr_compat_longs) unsafe_put_user((compat_ulong_t)*mask, umask++, Efault); user_access_end(); return 0; Efault: user_access_end(); return -EFAULT; } int get_compat_sigset(sigset_t *set, const compat_sigset_t __user *compat) { #ifdef __BIG_ENDIAN compat_sigset_t v; if (copy_from_user(&v, compat, sizeof(compat_sigset_t))) return -EFAULT; switch (_NSIG_WORDS) { case 4: set->sig[3] = v.sig[6] | (((long)v.sig[7]) << 32 ); case 3: set->sig[2] = v.sig[4] | (((long)v.sig[5]) << 32 ); case 2: set->sig[1] = v.sig[2] | (((long)v.sig[3]) << 32 ); case 1: set->sig[0] = v.sig[0] | (((long)v.sig[1]) << 32 ); } #else if (copy_from_user(set, compat, sizeof(compat_sigset_t))) return -EFAULT; #endif return 0; } EXPORT_SYMBOL_GPL(get_compat_sigset); /* * Allocate user-space memory for the duration of a single system call, * in order to marshall parameters inside a compat thunk. */ void __user *compat_alloc_user_space(unsigned long len) { void __user *ptr; /* If len would occupy more than half of the entire compat space... */ if (unlikely(len > (((compat_uptr_t)~0) >> 1))) return NULL; ptr = arch_compat_alloc_user_space(len); if (unlikely(!access_ok(VERIFY_WRITE, ptr, len))) return NULL; return ptr; } EXPORT_SYMBOL_GPL(compat_alloc_user_space);
./CrossVul/dataset_final_sorted/CWE-200/c/good_151_0
crossvul-cpp_data_good_335_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % X X BBBB M M % % X X B B MM MM % % X BBBB M M M % % X X B B M M % % X X BBBB M M % % % % % % Read/Write X Windows System Bitmap Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 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-private.h" #include "MagickCore/colormap.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/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/utility.h" /* Forward declarations. */ static MagickBooleanType WriteXBMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s X B M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsXBM() returns MagickTrue if the image format type, identified by the % magick string, is XBM. % % The format of the IsXBM method is: % % MagickBooleanType IsXBM(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 IsXBM(const unsigned char *magick,const size_t length) { if (length < 7) return(MagickFalse); if (memcmp(magick,"#define",7) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXBMImage() reads an X11 bitmap 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 ReadXBMImage method is: % % Image *ReadXBMImage(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 int XBMInteger(Image *image,short int *hex_digits) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(-1); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); /* Evaluate number. */ value=0; do { if (value > (unsigned int) (INT_MAX/10)) break; value*=16; c&=0xff; if (value > (unsigned int) (INT_MAX-hex_digits[c])) break; value+=hex_digits[c]; c=ReadBlobByte(image); if (c == EOF) return(-1); } while (hex_digits[c] >= 0); return((int) value); } static Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MagickPathExtent], name[MagickPathExtent]; Image *image; int c; MagickBooleanType status; register ssize_t i, x; register Quantum *q; register unsigned char *p; short int hex_digits[256]; ssize_t y; unsigned char *data; unsigned int bit, byte, bytes_per_line, height, length, padding, version, width; /* 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); } /* Read X bitmap header. */ width=0; height=0; *name='\0'; while (ReadBlobString(image,buffer) != (char *) NULL) if (sscanf(buffer,"#define %1024s %u",name,&width) == 2) if ((strlen(name) >= 6) && (LocaleCompare(name+strlen(name)-6,"_width") == 0)) break; while (ReadBlobString(image,buffer) != (char *) NULL) if (sscanf(buffer,"#define %1024s %u",name,&height) == 2) if ((strlen(name) >= 7) && (LocaleCompare(name+strlen(name)-7,"_height") == 0)) break; image->columns=width; image->rows=height; image->depth=8; image->storage_class=PseudoClass; image->colors=2; /* Scan until hex digits. */ version=11; while (ReadBlobString(image,buffer) != (char *) NULL) { if (sscanf(buffer,"static short %1024s = {",name) == 1) version=10; else if (sscanf(buffer,"static unsigned char %1024s = {",name) == 1) version=11; else if (sscanf(buffer,"static char %1024s = {",name) == 1) version=11; else continue; p=(unsigned char *) strrchr(name,'_'); if (p == (unsigned char *) NULL) p=(unsigned char *) name; else p++; if (LocaleCompare("bits[]",(char *) p) == 0) break; } if ((image->columns == 0) || (image->rows == 0) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize colormap. */ image->colormap[0].red=(MagickRealType) QuantumRange; image->colormap[0].green=(MagickRealType) QuantumRange; image->colormap[0].blue=(MagickRealType) QuantumRange; image->colormap[1].red=0.0; image->colormap[1].green=0.0; image->colormap[1].blue=0.0; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Initialize hex values. */ for (i=0; i < (ssize_t) (sizeof(hex_digits)/sizeof(*hex_digits)); i++) hex_digits[i]=(-1); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'x']=0; hex_digits[(int) ' ']=(-1); hex_digits[(int) ',']=(-1); hex_digits[(int) '}']=(-1); hex_digits[(int) '\n']=(-1); hex_digits[(int) '\t']=(-1); /* Read hex image data. */ padding=0; if (((image->columns % 16) != 0) && ((image->columns % 16) < 9) && (version == 10)) padding=1; bytes_per_line=(unsigned int) (image->columns+7)/8+padding; length=(unsigned int) image->rows; data=(unsigned char *) AcquireQuantumMemory(length,bytes_per_line* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; if (version == 10) for (i=0; i < (ssize_t) (bytes_per_line*image->rows); (i+=2)) { c=XBMInteger(image,hex_digits); if (c < 0) { data=(unsigned char *) RelinquishMagickMemory(data); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } *p++=(unsigned char) c; if ((padding == 0) || (((i+2) % bytes_per_line) != 0)) *p++=(unsigned char) (c >> 8); } else for (i=0; i < (ssize_t) (bytes_per_line*image->rows); i++) { c=XBMInteger(image,hex_digits); if (c < 0) { data=(unsigned char *) RelinquishMagickMemory(data); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } *p++=(unsigned char) c; } if (EOFBlob(image) != MagickFalse) { data=(unsigned char *) RelinquishMagickMemory(data); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Convert X bitmap image to pixel packets. */ p=data; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(unsigned int) (*p++); SetPixelIndex(image,(Quantum) ((byte & 0x01) != 0 ? 0x01 : 0x00),q); bit++; byte>>=1; if (bit == 8) bit=0; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } data=(unsigned char *) RelinquishMagickMemory(data); (void) SyncImage(image,exception); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterXBMImage() adds attributes for the XBM image format to % the list of supported formats. The attributes 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 RegisterXBMImage method is: % % size_t RegisterXBMImage(void) % */ ModuleExport size_t RegisterXBMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("XBM","XBM", "X Windows system bitmap (black and white)"); entry->decoder=(DecodeImageHandler *) ReadXBMImage; entry->encoder=(EncodeImageHandler *) WriteXBMImage; entry->magick=(IsImageFormatHandler *) IsXBM; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterXBMImage() removes format registrations made by the % XBM module from the list of supported formats. % % The format of the UnregisterXBMImage method is: % % UnregisterXBMImage(void) % */ ModuleExport void UnregisterXBMImage(void) { (void) UnregisterMagickInfo("XBM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteXBMImage() writes an image to a file in the X bitmap format. % % The format of the WriteXBMImage method is: % % MagickBooleanType WriteXBMImage(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 WriteXBMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char basename[MagickPathExtent], buffer[MagickPathExtent]; MagickBooleanType status; register const Quantum *p; register ssize_t x; size_t bit, byte; ssize_t count, y; /* 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); (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Write X bitmap header. */ GetPathComponent(image->filename,BasePath,basename); (void) FormatLocaleString(buffer,MagickPathExtent,"#define %s_width %.20g\n", basename,(double) image->columns); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"#define %s_height %.20g\n", basename,(double) image->rows); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "static char %s_bits[] = {\n",basename); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) CopyMagickString(buffer," ",MagickPathExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); /* Convert MIFF to X bitmap pixels. */ (void) SetImageType(image,BilevelType,exception); bit=0; byte=0; count=0; x=0; y=0; (void) CopyMagickString(buffer," ",MagickPathExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2)) byte|=0x80; bit++; if (bit == 8) { /* Write a bitmap byte to the image file. */ (void) FormatLocaleString(buffer,MagickPathExtent,"0x%02X, ", (unsigned int) (byte & 0xff)); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count++; if (count == 12) { (void) CopyMagickString(buffer,"\n ",MagickPathExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count=0; }; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { /* Write a bitmap byte to the image file. */ byte>>=(8-bit); (void) FormatLocaleString(buffer,MagickPathExtent,"0x%02X, ", (unsigned int) (byte & 0xff)); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count++; if (count == 12) { (void) CopyMagickString(buffer,"\n ",MagickPathExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count=0; }; bit=0; byte=0; }; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) CopyMagickString(buffer,"};\n",MagickPathExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_335_0
crossvul-cpp_data_bad_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; /* 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; msg->msg_namelen = 0; 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/bad_5696_0
crossvul-cpp_data_bad_5687_0
/********************************************************************* * * Filename: af_irda.c * Version: 0.9 * Description: IrDA sockets implementation * Status: Stable * Author: Dag Brattli <dagb@cs.uit.no> * Created at: Sun May 31 10:12:43 1998 * Modified at: Sat Dec 25 21:10:23 1999 * Modified by: Dag Brattli <dag@brattli.net> * Sources: af_netroom.c, af_ax25.c, af_rose.c, af_x25.c etc. * * Copyright (c) 1999 Dag Brattli <dagb@cs.uit.no> * Copyright (c) 1999-2003 Jean Tourrilhes <jt@hpl.hp.com> * 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; 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 * * Linux-IrDA now supports four different types of IrDA sockets: * * o SOCK_STREAM: TinyTP connections with SAR disabled. The * max SDU size is 0 for conn. of this type * o SOCK_SEQPACKET: TinyTP connections with SAR enabled. TTP may * fragment the messages, but will preserve * the message boundaries * o SOCK_DGRAM: IRDAPROTO_UNITDATA: TinyTP connections with Unitdata * (unreliable) transfers * IRDAPROTO_ULTRA: Connectionless and unreliable data * ********************************************************************/ #include <linux/capability.h> #include <linux/module.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/net.h> #include <linux/irda.h> #include <linux/poll.h> #include <asm/ioctls.h> /* TIOCOUTQ, TIOCINQ */ #include <asm/uaccess.h> #include <net/sock.h> #include <net/tcp_states.h> #include <net/irda/af_irda.h> static int irda_create(struct net *net, struct socket *sock, int protocol, int kern); static const struct proto_ops irda_stream_ops; static const struct proto_ops irda_seqpacket_ops; static const struct proto_ops irda_dgram_ops; #ifdef CONFIG_IRDA_ULTRA static const struct proto_ops irda_ultra_ops; #define ULTRA_MAX_DATA 382 #endif /* CONFIG_IRDA_ULTRA */ #define IRDA_MAX_HEADER (TTP_MAX_HEADER) /* * Function irda_data_indication (instance, sap, skb) * * Received some data from TinyTP. Just queue it on the receive queue * */ static int irda_data_indication(void *instance, void *sap, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; int err; IRDA_DEBUG(3, "%s()\n", __func__); self = instance; sk = instance; err = sock_queue_rcv_skb(sk, skb); if (err) { IRDA_DEBUG(1, "%s(), error: no more mem!\n", __func__); self->rx_flow = FLOW_STOP; /* When we return error, TTP will need to requeue the skb */ return err; } return 0; } /* * Function irda_disconnect_indication (instance, sap, reason, skb) * * Connection has been closed. Check reason to find out why * */ static void irda_disconnect_indication(void *instance, void *sap, LM_REASON reason, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; self = instance; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); /* Don't care about it, but let's not leak it */ if(skb) dev_kfree_skb(skb); sk = instance; if (sk == NULL) { IRDA_DEBUG(0, "%s(%p) : BUG : sk is NULL\n", __func__, self); return; } /* Prevent race conditions with irda_release() and irda_shutdown() */ bh_lock_sock(sk); if (!sock_flag(sk, SOCK_DEAD) && sk->sk_state != TCP_CLOSE) { sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); /* Close our TSAP. * If we leave it open, IrLMP put it back into the list of * unconnected LSAPs. The problem is that any incoming request * can then be matched to this socket (and it will be, because * it is at the head of the list). This would prevent any * listening socket waiting on the same TSAP to get those * requests. Some apps forget to close sockets, or hang to it * a bit too long, so we may stay in this dead state long * enough to be noticed... * Note : all socket function do check sk->sk_state, so we are * safe... * Jean II */ if (self->tsap) { irttp_close_tsap(self->tsap); self->tsap = NULL; } } bh_unlock_sock(sk); /* Note : once we are there, there is not much you want to do * with the socket anymore, apart from closing it. * For example, bind() and connect() won't reset sk->sk_err, * sk->sk_shutdown and sk->sk_flags to valid values... * Jean II */ } /* * Function irda_connect_confirm (instance, sap, qos, max_sdu_size, skb) * * Connections has been confirmed by the remote device * */ static void irda_connect_confirm(void *instance, void *sap, struct qos_info *qos, __u32 max_sdu_size, __u8 max_header_size, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; self = instance; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); sk = instance; if (sk == NULL) { dev_kfree_skb(skb); return; } dev_kfree_skb(skb); // Should be ??? skb_queue_tail(&sk->sk_receive_queue, skb); /* How much header space do we need to reserve */ self->max_header_size = max_header_size; /* IrTTP max SDU size in transmit direction */ self->max_sdu_size_tx = max_sdu_size; /* Find out what the largest chunk of data that we can transmit is */ switch (sk->sk_type) { case SOCK_STREAM: if (max_sdu_size != 0) { IRDA_ERROR("%s: max_sdu_size must be 0\n", __func__); return; } self->max_data_size = irttp_get_max_seg_size(self->tsap); break; case SOCK_SEQPACKET: if (max_sdu_size == 0) { IRDA_ERROR("%s: max_sdu_size cannot be 0\n", __func__); return; } self->max_data_size = max_sdu_size; break; default: self->max_data_size = irttp_get_max_seg_size(self->tsap); } IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__, self->max_data_size); memcpy(&self->qos_tx, qos, sizeof(struct qos_info)); /* We are now connected! */ sk->sk_state = TCP_ESTABLISHED; sk->sk_state_change(sk); } /* * Function irda_connect_indication(instance, sap, qos, max_sdu_size, userdata) * * Incoming connection * */ static void irda_connect_indication(void *instance, void *sap, struct qos_info *qos, __u32 max_sdu_size, __u8 max_header_size, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; self = instance; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); sk = instance; if (sk == NULL) { dev_kfree_skb(skb); return; } /* How much header space do we need to reserve */ self->max_header_size = max_header_size; /* IrTTP max SDU size in transmit direction */ self->max_sdu_size_tx = max_sdu_size; /* Find out what the largest chunk of data that we can transmit is */ switch (sk->sk_type) { case SOCK_STREAM: if (max_sdu_size != 0) { IRDA_ERROR("%s: max_sdu_size must be 0\n", __func__); kfree_skb(skb); return; } self->max_data_size = irttp_get_max_seg_size(self->tsap); break; case SOCK_SEQPACKET: if (max_sdu_size == 0) { IRDA_ERROR("%s: max_sdu_size cannot be 0\n", __func__); kfree_skb(skb); return; } self->max_data_size = max_sdu_size; break; default: self->max_data_size = irttp_get_max_seg_size(self->tsap); } IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__, self->max_data_size); memcpy(&self->qos_tx, qos, sizeof(struct qos_info)); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_state_change(sk); } /* * Function irda_connect_response (handle) * * Accept incoming connection * */ static void irda_connect_response(struct irda_sock *self) { struct sk_buff *skb; IRDA_DEBUG(2, "%s()\n", __func__); skb = alloc_skb(TTP_MAX_HEADER + TTP_SAR_HEADER, GFP_ATOMIC); if (skb == NULL) { IRDA_DEBUG(0, "%s() Unable to allocate sk_buff!\n", __func__); return; } /* Reserve space for MUX_CONTROL and LAP header */ skb_reserve(skb, IRDA_MAX_HEADER); irttp_connect_response(self->tsap, self->max_sdu_size_rx, skb); } /* * Function irda_flow_indication (instance, sap, flow) * * Used by TinyTP to tell us if it can accept more data or not * */ static void irda_flow_indication(void *instance, void *sap, LOCAL_FLOW flow) { struct irda_sock *self; struct sock *sk; IRDA_DEBUG(2, "%s()\n", __func__); self = instance; sk = instance; BUG_ON(sk == NULL); switch (flow) { case FLOW_STOP: IRDA_DEBUG(1, "%s(), IrTTP wants us to slow down\n", __func__); self->tx_flow = flow; break; case FLOW_START: self->tx_flow = flow; IRDA_DEBUG(1, "%s(), IrTTP wants us to start again\n", __func__); wake_up_interruptible(sk_sleep(sk)); break; default: IRDA_DEBUG(0, "%s(), Unknown flow command!\n", __func__); /* Unknown flow command, better stop */ self->tx_flow = flow; break; } } /* * Function irda_getvalue_confirm (obj_id, value, priv) * * Got answer from remote LM-IAS, just pass object to requester... * * Note : duplicate from above, but we need our own version that * doesn't touch the dtsap_sel and save the full value structure... */ static void irda_getvalue_confirm(int result, __u16 obj_id, struct ias_value *value, void *priv) { struct irda_sock *self; self = priv; if (!self) { IRDA_WARNING("%s: lost myself!\n", __func__); return; } IRDA_DEBUG(2, "%s(%p)\n", __func__, self); /* We probably don't need to make any more queries */ iriap_close(self->iriap); self->iriap = NULL; /* Check if request succeeded */ if (result != IAS_SUCCESS) { IRDA_DEBUG(1, "%s(), IAS query failed! (%d)\n", __func__, result); self->errno = result; /* We really need it later */ /* Wake up any processes waiting for result */ wake_up_interruptible(&self->query_wait); return; } /* Pass the object to the caller (so the caller must delete it) */ self->ias_result = value; self->errno = 0; /* Wake up any processes waiting for result */ wake_up_interruptible(&self->query_wait); } /* * Function irda_selective_discovery_indication (discovery) * * Got a selective discovery indication from IrLMP. * * IrLMP is telling us that this node is new and matching our hint bit * filter. Wake up any process waiting for answer... */ static void irda_selective_discovery_indication(discinfo_t *discovery, DISCOVERY_MODE mode, void *priv) { struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); self = priv; if (!self) { IRDA_WARNING("%s: lost myself!\n", __func__); return; } /* Pass parameter to the caller */ self->cachedaddr = discovery->daddr; /* Wake up process if its waiting for device to be discovered */ wake_up_interruptible(&self->query_wait); } /* * Function irda_discovery_timeout (priv) * * Timeout in the selective discovery process * * We were waiting for a node to be discovered, but nothing has come up * so far. Wake up the user and tell him that we failed... */ static void irda_discovery_timeout(u_long priv) { struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); self = (struct irda_sock *) priv; BUG_ON(self == NULL); /* Nothing for the caller */ self->cachelog = NULL; self->cachedaddr = 0; self->errno = -ETIME; /* Wake up process if its still waiting... */ wake_up_interruptible(&self->query_wait); } /* * Function irda_open_tsap (self) * * Open local Transport Service Access Point (TSAP) * */ static int irda_open_tsap(struct irda_sock *self, __u8 tsap_sel, char *name) { notify_t notify; if (self->tsap) { IRDA_DEBUG(0, "%s: busy!\n", __func__); return -EBUSY; } /* Initialize callbacks to be used by the IrDA stack */ irda_notify_init(&notify); notify.connect_confirm = irda_connect_confirm; notify.connect_indication = irda_connect_indication; notify.disconnect_indication = irda_disconnect_indication; notify.data_indication = irda_data_indication; notify.udata_indication = irda_data_indication; notify.flow_indication = irda_flow_indication; notify.instance = self; strncpy(notify.name, name, NOTIFY_MAX_NAME); self->tsap = irttp_open_tsap(tsap_sel, DEFAULT_INITIAL_CREDIT, &notify); if (self->tsap == NULL) { IRDA_DEBUG(0, "%s(), Unable to allocate TSAP!\n", __func__); return -ENOMEM; } /* Remember which TSAP selector we actually got */ self->stsap_sel = self->tsap->stsap_sel; return 0; } /* * Function irda_open_lsap (self) * * Open local Link Service Access Point (LSAP). Used for opening Ultra * sockets */ #ifdef CONFIG_IRDA_ULTRA static int irda_open_lsap(struct irda_sock *self, int pid) { notify_t notify; if (self->lsap) { IRDA_WARNING("%s(), busy!\n", __func__); return -EBUSY; } /* Initialize callbacks to be used by the IrDA stack */ irda_notify_init(&notify); notify.udata_indication = irda_data_indication; notify.instance = self; strncpy(notify.name, "Ultra", NOTIFY_MAX_NAME); self->lsap = irlmp_open_lsap(LSAP_CONNLESS, &notify, pid); if (self->lsap == NULL) { IRDA_DEBUG( 0, "%s(), Unable to allocate LSAP!\n", __func__); return -ENOMEM; } return 0; } #endif /* CONFIG_IRDA_ULTRA */ /* * Function irda_find_lsap_sel (self, name) * * Try to lookup LSAP selector in remote LM-IAS * * Basically, we start a IAP query, and then go to sleep. When the query * return, irda_getvalue_confirm will wake us up, and we can examine the * result of the query... * Note that in some case, the query fail even before we go to sleep, * creating some races... */ static int irda_find_lsap_sel(struct irda_sock *self, char *name) { IRDA_DEBUG(2, "%s(%p, %s)\n", __func__, self, name); if (self->iriap) { IRDA_WARNING("%s(): busy with a previous query\n", __func__); return -EBUSY; } self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self, irda_getvalue_confirm); if(self->iriap == NULL) return -ENOMEM; /* Treat unexpected wakeup as disconnect */ self->errno = -EHOSTUNREACH; /* Query remote LM-IAS */ iriap_getvaluebyclass_request(self->iriap, self->saddr, self->daddr, name, "IrDA:TinyTP:LsapSel"); /* Wait for answer, if not yet finished (or failed) */ if (wait_event_interruptible(self->query_wait, (self->iriap==NULL))) /* Treat signals as disconnect */ return -EHOSTUNREACH; /* Check what happened */ if (self->errno) { /* Requested object/attribute doesn't exist */ if((self->errno == IAS_CLASS_UNKNOWN) || (self->errno == IAS_ATTRIB_UNKNOWN)) return -EADDRNOTAVAIL; else return -EHOSTUNREACH; } /* Get the remote TSAP selector */ switch (self->ias_result->type) { case IAS_INTEGER: IRDA_DEBUG(4, "%s() int=%d\n", __func__, self->ias_result->t.integer); if (self->ias_result->t.integer != -1) self->dtsap_sel = self->ias_result->t.integer; else self->dtsap_sel = 0; break; default: self->dtsap_sel = 0; IRDA_DEBUG(0, "%s(), bad type!\n", __func__); break; } if (self->ias_result) irias_delete_value(self->ias_result); if (self->dtsap_sel) return 0; return -EADDRNOTAVAIL; } /* * Function irda_discover_daddr_and_lsap_sel (self, name) * * This try to find a device with the requested service. * * It basically look into the discovery log. For each address in the list, * it queries the LM-IAS of the device to find if this device offer * the requested service. * If there is more than one node supporting the service, we complain * to the user (it should move devices around). * The, we set both the destination address and the lsap selector to point * on the service on the unique device we have found. * * Note : this function fails if there is more than one device in range, * because IrLMP doesn't disconnect the LAP when the last LSAP is closed. * Moreover, we would need to wait the LAP disconnection... */ static int irda_discover_daddr_and_lsap_sel(struct irda_sock *self, char *name) { discinfo_t *discoveries; /* Copy of the discovery log */ int number; /* Number of nodes in the log */ int i; int err = -ENETUNREACH; __u32 daddr = DEV_ADDR_ANY; /* Address we found the service on */ __u8 dtsap_sel = 0x0; /* TSAP associated with it */ IRDA_DEBUG(2, "%s(), name=%s\n", __func__, name); /* Ask lmp for the current discovery log * Note : we have to use irlmp_get_discoveries(), as opposed * to play with the cachelog directly, because while we are * making our ias query, le log might change... */ discoveries = irlmp_get_discoveries(&number, self->mask.word, self->nslots); /* Check if the we got some results */ if (discoveries == NULL) return -ENETUNREACH; /* No nodes discovered */ /* * Now, check all discovered devices (if any), and connect * client only about the services that the client is * interested in... */ for(i = 0; i < number; i++) { /* Try the address in the log */ self->daddr = discoveries[i].daddr; self->saddr = 0x0; IRDA_DEBUG(1, "%s(), trying daddr = %08x\n", __func__, self->daddr); /* Query remote LM-IAS for this service */ err = irda_find_lsap_sel(self, name); switch (err) { case 0: /* We found the requested service */ if(daddr != DEV_ADDR_ANY) { IRDA_DEBUG(1, "%s(), discovered service ''%s'' in two different devices !!!\n", __func__, name); self->daddr = DEV_ADDR_ANY; kfree(discoveries); return -ENOTUNIQ; } /* First time we found that one, save it ! */ daddr = self->daddr; dtsap_sel = self->dtsap_sel; break; case -EADDRNOTAVAIL: /* Requested service simply doesn't exist on this node */ break; default: /* Something bad did happen :-( */ IRDA_DEBUG(0, "%s(), unexpected IAS query failure\n", __func__); self->daddr = DEV_ADDR_ANY; kfree(discoveries); return -EHOSTUNREACH; break; } } /* Cleanup our copy of the discovery log */ kfree(discoveries); /* Check out what we found */ if(daddr == DEV_ADDR_ANY) { IRDA_DEBUG(1, "%s(), cannot discover service ''%s'' in any device !!!\n", __func__, name); self->daddr = DEV_ADDR_ANY; return -EADDRNOTAVAIL; } /* Revert back to discovered device & service */ self->daddr = daddr; self->saddr = 0x0; self->dtsap_sel = dtsap_sel; IRDA_DEBUG(1, "%s(), discovered requested service ''%s'' at address %08x\n", __func__, name, self->daddr); return 0; } /* * Function irda_getname (sock, uaddr, uaddr_len, peer) * * Return the our own, or peers socket address (sockaddr_irda) * */ static int irda_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_irda saddr; struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); memset(&saddr, 0, sizeof(saddr)); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->dtsap_sel; saddr.sir_addr = self->daddr; } else { saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->stsap_sel; saddr.sir_addr = self->saddr; } IRDA_DEBUG(1, "%s(), tsap_sel = %#x\n", __func__, saddr.sir_lsap_sel); IRDA_DEBUG(1, "%s(), addr = %08x\n", __func__, saddr.sir_addr); /* uaddr_len come to us uninitialised */ *uaddr_len = sizeof (struct sockaddr_irda); memcpy(uaddr, &saddr, *uaddr_len); return 0; } /* * Function irda_listen (sock, backlog) * * Just move to the listen state * */ static int irda_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = -EOPNOTSUPP; IRDA_DEBUG(2, "%s()\n", __func__); lock_sock(sk); if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) && (sk->sk_type != SOCK_DGRAM)) goto out; if (sk->sk_state != TCP_LISTEN) { sk->sk_max_ack_backlog = backlog; sk->sk_state = TCP_LISTEN; err = 0; } out: release_sock(sk); return err; } /* * Function irda_bind (sock, uaddr, addr_len) * * Used by servers to register their well known TSAP * */ static int irda_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr; struct irda_sock *self = irda_sk(sk); int err; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); if (addr_len != sizeof(struct sockaddr_irda)) return -EINVAL; lock_sock(sk); #ifdef CONFIG_IRDA_ULTRA /* Special care for Ultra sockets */ if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA)) { self->pid = addr->sir_lsap_sel; err = -EOPNOTSUPP; if (self->pid & 0x80) { IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__); goto out; } err = irda_open_lsap(self, self->pid); if (err < 0) goto out; /* Pretend we are connected */ sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; err = 0; goto out; } #endif /* CONFIG_IRDA_ULTRA */ self->ias_obj = irias_new_object(addr->sir_name, jiffies); err = -ENOMEM; if (self->ias_obj == NULL) goto out; err = irda_open_tsap(self, addr->sir_lsap_sel, addr->sir_name); if (err < 0) { irias_delete_object(self->ias_obj); self->ias_obj = NULL; goto out; } /* Register with LM-IAS */ irias_add_integer_attrib(self->ias_obj, "IrDA:TinyTP:LsapSel", self->stsap_sel, IAS_KERNEL_ATTR); irias_insert_object(self->ias_obj); err = 0; out: release_sock(sk); return err; } /* * Function irda_accept (sock, newsock, flags) * * Wait for incoming connection * */ static int irda_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct irda_sock *new, *self = irda_sk(sk); struct sock *newsk; struct sk_buff *skb; int err; IRDA_DEBUG(2, "%s()\n", __func__); err = irda_create(sock_net(sk), newsock, sk->sk_protocol, 0); if (err) return err; err = -EINVAL; lock_sock(sk); if (sock->state != SS_UNCONNECTED) goto out; if ((sk = sock->sk) == NULL) goto out; err = -EOPNOTSUPP; if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) && (sk->sk_type != SOCK_DGRAM)) goto out; err = -EINVAL; if (sk->sk_state != TCP_LISTEN) goto out; /* * The read queue this time is holding sockets ready to use * hooked into the SABM we saved */ /* * We can perform the accept only if there is incoming data * on the listening socket. * So, we will block the caller until we receive any data. * If the caller was waiting on select() or poll() before * calling us, the data is waiting for us ;-) * Jean II */ while (1) { skb = skb_dequeue(&sk->sk_receive_queue); if (skb) break; /* Non blocking operation */ err = -EWOULDBLOCK; if (flags & O_NONBLOCK) goto out; err = wait_event_interruptible(*(sk_sleep(sk)), skb_peek(&sk->sk_receive_queue)); if (err) goto out; } newsk = newsock->sk; err = -EIO; if (newsk == NULL) goto out; newsk->sk_state = TCP_ESTABLISHED; new = irda_sk(newsk); /* Now attach up the new socket */ new->tsap = irttp_dup(self->tsap, new); err = -EPERM; /* value does not seem to make sense. -arnd */ if (!new->tsap) { IRDA_DEBUG(0, "%s(), dup failed!\n", __func__); kfree_skb(skb); goto out; } new->stsap_sel = new->tsap->stsap_sel; new->dtsap_sel = new->tsap->dtsap_sel; new->saddr = irttp_get_saddr(new->tsap); new->daddr = irttp_get_daddr(new->tsap); new->max_sdu_size_tx = self->max_sdu_size_tx; new->max_sdu_size_rx = self->max_sdu_size_rx; new->max_data_size = self->max_data_size; new->max_header_size = self->max_header_size; memcpy(&new->qos_tx, &self->qos_tx, sizeof(struct qos_info)); /* Clean up the original one to keep it in listen state */ irttp_listen(self->tsap); kfree_skb(skb); sk->sk_ack_backlog--; newsock->state = SS_CONNECTED; irda_connect_response(new); err = 0; out: release_sock(sk); return err; } /* * Function irda_connect (sock, uaddr, addr_len, flags) * * Connect to a IrDA device * * The main difference with a "standard" connect is that with IrDA we need * to resolve the service name into a TSAP selector (in TCP, port number * doesn't have to be resolved). * Because of this service name resolution, we can offer "auto-connect", * where we connect to a service without specifying a destination address. * * Note : by consulting "errno", the user space caller may learn the cause * of the failure. Most of them are visible in the function, others may come * from subroutines called and are listed here : * o EBUSY : already processing a connect * o EHOSTUNREACH : bad addr->sir_addr argument * o EADDRNOTAVAIL : bad addr->sir_name argument * o ENOTUNIQ : more than one node has addr->sir_name (auto-connect) * o ENETUNREACH : no node found on the network (auto-connect) */ static int irda_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr; struct irda_sock *self = irda_sk(sk); int err; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); lock_sock(sk); /* Don't allow connect for Ultra sockets */ err = -ESOCKTNOSUPPORT; if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA)) goto out; if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) { sock->state = SS_CONNECTED; err = 0; goto out; /* Connect completed during a ERESTARTSYS event */ } if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) { sock->state = SS_UNCONNECTED; err = -ECONNREFUSED; goto out; } err = -EISCONN; /* No reconnect on a seqpacket socket */ if (sk->sk_state == TCP_ESTABLISHED) goto out; sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; err = -EINVAL; if (addr_len != sizeof(struct sockaddr_irda)) goto out; /* Check if user supplied any destination device address */ if ((!addr->sir_addr) || (addr->sir_addr == DEV_ADDR_ANY)) { /* Try to find one suitable */ err = irda_discover_daddr_and_lsap_sel(self, addr->sir_name); if (err) { IRDA_DEBUG(0, "%s(), auto-connect failed!\n", __func__); goto out; } } else { /* Use the one provided by the user */ self->daddr = addr->sir_addr; IRDA_DEBUG(1, "%s(), daddr = %08x\n", __func__, self->daddr); /* If we don't have a valid service name, we assume the * user want to connect on a specific LSAP. Prevent * the use of invalid LSAPs (IrLMP 1.1 p10). Jean II */ if((addr->sir_name[0] != '\0') || (addr->sir_lsap_sel >= 0x70)) { /* Query remote LM-IAS using service name */ err = irda_find_lsap_sel(self, addr->sir_name); if (err) { IRDA_DEBUG(0, "%s(), connect failed!\n", __func__); goto out; } } else { /* Directly connect to the remote LSAP * specified by the sir_lsap field. * Please use with caution, in IrDA LSAPs are * dynamic and there is no "well-known" LSAP. */ self->dtsap_sel = addr->sir_lsap_sel; } } /* Check if we have opened a local TSAP */ if (!self->tsap) irda_open_tsap(self, LSAP_ANY, addr->sir_name); /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; /* Connect to remote device */ err = irttp_connect_request(self->tsap, self->dtsap_sel, self->saddr, self->daddr, NULL, self->max_sdu_size_rx, NULL); if (err) { IRDA_DEBUG(0, "%s(), connect failed!\n", __func__); goto out; } /* Now the loop */ err = -EINPROGRESS; if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) goto out; err = -ERESTARTSYS; if (wait_event_interruptible(*(sk_sleep(sk)), (sk->sk_state != TCP_SYN_SENT))) goto out; if (sk->sk_state != TCP_ESTABLISHED) { sock->state = SS_UNCONNECTED; if (sk->sk_prot->disconnect(sk, flags)) sock->state = SS_DISCONNECTING; err = sock_error(sk); if (!err) err = -ECONNRESET; goto out; } sock->state = SS_CONNECTED; /* At this point, IrLMP has assigned our source address */ self->saddr = irttp_get_saddr(self->tsap); err = 0; out: release_sock(sk); return err; } static struct proto irda_proto = { .name = "IRDA", .owner = THIS_MODULE, .obj_size = sizeof(struct irda_sock), }; /* * Function irda_create (sock, protocol) * * Create IrDA socket * */ static int irda_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); if (net != &init_net) return -EAFNOSUPPORT; /* Check for valid socket type */ switch (sock->type) { case SOCK_STREAM: /* For TTP connections with SAR disabled */ case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */ case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */ break; default: return -ESOCKTNOSUPPORT; } /* Allocate networking socket */ sk = sk_alloc(net, PF_IRDA, GFP_ATOMIC, &irda_proto); if (sk == NULL) return -ENOMEM; self = irda_sk(sk); IRDA_DEBUG(2, "%s() : self is %p\n", __func__, self); init_waitqueue_head(&self->query_wait); switch (sock->type) { case SOCK_STREAM: sock->ops = &irda_stream_ops; self->max_sdu_size_rx = TTP_SAR_DISABLE; break; case SOCK_SEQPACKET: sock->ops = &irda_seqpacket_ops; self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; case SOCK_DGRAM: switch (protocol) { #ifdef CONFIG_IRDA_ULTRA case IRDAPROTO_ULTRA: sock->ops = &irda_ultra_ops; /* Initialise now, because we may send on unbound * sockets. Jean II */ self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER; self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER; break; #endif /* CONFIG_IRDA_ULTRA */ case IRDAPROTO_UNITDATA: sock->ops = &irda_dgram_ops; /* We let Unitdata conn. be like seqpack conn. */ self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } /* Initialise networking socket struct */ sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */ sk->sk_family = PF_IRDA; sk->sk_protocol = protocol; /* Register as a client with IrLMP */ self->ckey = irlmp_register_client(0, NULL, NULL, NULL); self->mask.word = 0xffff; self->rx_flow = self->tx_flow = FLOW_START; self->nslots = DISCOVERY_DEFAULT_SLOTS; self->daddr = DEV_ADDR_ANY; /* Until we get connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ return 0; } /* * Function irda_destroy_socket (self) * * Destroy socket * */ static void irda_destroy_socket(struct irda_sock *self) { IRDA_DEBUG(2, "%s(%p)\n", __func__, self); /* Unregister with IrLMP */ irlmp_unregister_client(self->ckey); irlmp_unregister_service(self->skey); /* Unregister with LM-IAS */ if (self->ias_obj) { irias_delete_object(self->ias_obj); self->ias_obj = NULL; } if (self->iriap) { iriap_close(self->iriap); self->iriap = NULL; } if (self->tsap) { irttp_disconnect_request(self->tsap, NULL, P_NORMAL); irttp_close_tsap(self->tsap); self->tsap = NULL; } #ifdef CONFIG_IRDA_ULTRA if (self->lsap) { irlmp_close_lsap(self->lsap); self->lsap = NULL; } #endif /* CONFIG_IRDA_ULTRA */ } /* * Function irda_release (sock) */ static int irda_release(struct socket *sock) { struct sock *sk = sock->sk; IRDA_DEBUG(2, "%s()\n", __func__); if (sk == NULL) return 0; lock_sock(sk); sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); /* Destroy IrDA socket */ irda_destroy_socket(irda_sk(sk)); sock_orphan(sk); sock->sk = NULL; release_sock(sk); /* Purge queues (see sock_init_data()) */ skb_queue_purge(&sk->sk_receive_queue); /* Destroy networking socket if we are the last reference on it, * i.e. if(sk->sk_refcnt == 0) -> sk_free(sk) */ sock_put(sk); /* Notes on socket locking and deallocation... - Jean II * In theory we should put pairs of sock_hold() / sock_put() to * prevent the socket to be destroyed whenever there is an * outstanding request or outstanding incoming packet or event. * * 1) This may include IAS request, both in connect and getsockopt. * Unfortunately, the situation is a bit more messy than it looks, * because we close iriap and kfree(self) above. * * 2) This may include selective discovery in getsockopt. * Same stuff as above, irlmp registration and self are gone. * * Probably 1 and 2 may not matter, because it's all triggered * by a process and the socket layer already prevent the * socket to go away while a process is holding it, through * sockfd_put() and fput()... * * 3) This may include deferred TSAP closure. In particular, * we may receive a late irda_disconnect_indication() * Fortunately, (tsap_cb *)->close_pend should protect us * from that. * * I did some testing on SMP, and it looks solid. And the socket * memory leak is now gone... - Jean II */ return 0; } /* * Function irda_sendmsg (iocb, sock, msg, len) * * Send message down to TinyTP. This function is used for both STREAM and * SEQPACK services. This is possible since it forces the client to * fragment the message if necessary */ static int irda_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct irda_sock *self; struct sk_buff *skb; int err = -EPIPE; IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len); /* Note : socket.c set MSG_EOR on SEQPACKET sockets */ if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_EOR | MSG_CMSG_COMPAT | MSG_NOSIGNAL)) { return -EINVAL; } lock_sock(sk); if (sk->sk_shutdown & SEND_SHUTDOWN) goto out_err; if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } self = irda_sk(sk); /* Check if IrTTP is wants us to slow down */ if (wait_event_interruptible(*(sk_sleep(sk)), (self->tx_flow != FLOW_STOP || sk->sk_state != TCP_ESTABLISHED))) { err = -ERESTARTSYS; goto out; } /* Check if we are still connected */ if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Check that we don't send out too big frames */ if (len > self->max_data_size) { IRDA_DEBUG(2, "%s(), Chopping frame from %zd to %d bytes!\n", __func__, len, self->max_data_size); len = self->max_data_size; } skb = sock_alloc_send_skb(sk, len + self->max_header_size + 16, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) goto out_err; skb_reserve(skb, self->max_header_size + 16); skb_reset_transport_header(skb); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); goto out_err; } /* * Just send the message to TinyTP, and let it deal with possible * errors. No need to duplicate all that here */ err = irttp_data_request(self->tsap, skb); if (err) { IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err); goto out_err; } release_sock(sk); /* Tell client how much data we actually sent */ return len; out_err: err = sk_stream_error(sk, msg->msg_flags, err); out: release_sock(sk); return err; } /* * Function irda_recvmsg_dgram (iocb, sock, msg, size, flags) * * Try to receive message and copy it to user. The frame is discarded * after being read, regardless of how much the user actually read */ static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct sk_buff *skb; size_t copied; int err; IRDA_DEBUG(4, "%s()\n", __func__); skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) return err; skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n", __func__, copied, size); copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); skb_free_datagram(sk, skb); /* * Check if we have previously stopped IrTTP and we know * have more free space in our rx_queue. If so tell IrTTP * to start delivering frames again before our rx_queue gets * empty */ if (self->rx_flow == FLOW_STOP) { if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) { IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__); self->rx_flow = FLOW_START; irttp_flow_request(self->tsap, FLOW_START); } } return copied; } /* * Function irda_recvmsg_stream (iocb, sock, msg, size, flags) */ static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); int noblock = flags & MSG_DONTWAIT; size_t copied = 0; int target, err; long timeo; IRDA_DEBUG(3, "%s()\n", __func__); if ((err = sock_error(sk)) < 0) return err; if (sock->flags & __SO_ACCEPTCON) return -EINVAL; err =-EOPNOTSUPP; if (flags & MSG_OOB) return -EOPNOTSUPP; err = 0; target = sock_rcvlowat(sk, flags & MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, noblock); msg->msg_namelen = 0; do { int chunk; struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue); if (skb == NULL) { DEFINE_WAIT(wait); err = 0; if (copied >= target) break; prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) ; else if (sk->sk_shutdown & RCV_SHUTDOWN) ; else if (noblock) err = -EAGAIN; else if (signal_pending(current)) err = sock_intr_errno(timeo); else if (sk->sk_state != TCP_ESTABLISHED) err = -ENOTCONN; else if (skb_peek(&sk->sk_receive_queue) == NULL) /* Wait process until data arrives */ schedule(); finish_wait(sk_sleep(sk), &wait); if (err) return err; if (sk->sk_shutdown & RCV_SHUTDOWN) break; continue; } chunk = min_t(unsigned int, skb->len, size); if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { skb_pull(skb, chunk); /* put the skb back if we didn't use it up.. */ if (skb->len) { IRDA_DEBUG(1, "%s(), back on q!\n", __func__); skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { IRDA_DEBUG(0, "%s() questionable!?\n", __func__); /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); /* * Check if we have previously stopped IrTTP and we know * have more free space in our rx_queue. If so tell IrTTP * to start delivering frames again before our rx_queue gets * empty */ if (self->rx_flow == FLOW_STOP) { if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) { IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__); self->rx_flow = FLOW_START; irttp_flow_request(self->tsap, FLOW_START); } } return copied; } /* * Function irda_sendmsg_dgram (iocb, sock, msg, len) * * Send message down to TinyTP for the unreliable sequenced * packet service... * */ static int irda_sendmsg_dgram(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct irda_sock *self; struct sk_buff *skb; int err; IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len); if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); err = -EPIPE; goto out; } err = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; self = irda_sk(sk); /* * Check that we don't send out too big frames. This is an unreliable * service, so we have no fragmentation and no coalescence */ if (len > self->max_data_size) { IRDA_DEBUG(0, "%s(), Warning to much data! " "Chopping frame from %zd to %d bytes!\n", __func__, len, self->max_data_size); len = self->max_data_size; } skb = sock_alloc_send_skb(sk, len + self->max_header_size, msg->msg_flags & MSG_DONTWAIT, &err); err = -ENOBUFS; if (!skb) goto out; skb_reserve(skb, self->max_header_size); skb_reset_transport_header(skb); IRDA_DEBUG(4, "%s(), appending user data\n", __func__); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); goto out; } /* * Just send the message to TinyTP, and let it deal with possible * errors. No need to duplicate all that here */ err = irttp_udata_request(self->tsap, skb); if (err) { IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err); goto out; } release_sock(sk); return len; out: release_sock(sk); return err; } /* * Function irda_sendmsg_ultra (iocb, sock, msg, len) * * Send message down to IrLMP for the unreliable Ultra * packet service... */ #ifdef CONFIG_IRDA_ULTRA static int irda_sendmsg_ultra(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct irda_sock *self; __u8 pid = 0; int bound = 0; struct sk_buff *skb; int err; IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len); err = -EINVAL; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); goto out; } self = irda_sk(sk); /* Check if an address was specified with sendto. Jean II */ if (msg->msg_name) { struct sockaddr_irda *addr = (struct sockaddr_irda *) msg->msg_name; err = -EINVAL; /* Check address, extract pid. Jean II */ if (msg->msg_namelen < sizeof(*addr)) goto out; if (addr->sir_family != AF_IRDA) goto out; pid = addr->sir_lsap_sel; if (pid & 0x80) { IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__); err = -EOPNOTSUPP; goto out; } } else { /* Check that the socket is properly bound to an Ultra * port. Jean II */ if ((self->lsap == NULL) || (sk->sk_state != TCP_ESTABLISHED)) { IRDA_DEBUG(0, "%s(), socket not bound to Ultra PID.\n", __func__); err = -ENOTCONN; goto out; } /* Use PID from socket */ bound = 1; } /* * Check that we don't send out too big frames. This is an unreliable * service, so we have no fragmentation and no coalescence */ if (len > self->max_data_size) { IRDA_DEBUG(0, "%s(), Warning to much data! " "Chopping frame from %zd to %d bytes!\n", __func__, len, self->max_data_size); len = self->max_data_size; } skb = sock_alloc_send_skb(sk, len + self->max_header_size, msg->msg_flags & MSG_DONTWAIT, &err); err = -ENOBUFS; if (!skb) goto out; skb_reserve(skb, self->max_header_size); skb_reset_transport_header(skb); IRDA_DEBUG(4, "%s(), appending user data\n", __func__); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); goto out; } err = irlmp_connless_data_request((bound ? self->lsap : NULL), skb, pid); if (err) IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err); out: release_sock(sk); return err ? : len; } #endif /* CONFIG_IRDA_ULTRA */ /* * Function irda_shutdown (sk, how) */ static int irda_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); IRDA_DEBUG(1, "%s(%p)\n", __func__, self); lock_sock(sk); sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); if (self->iriap) { iriap_close(self->iriap); self->iriap = NULL; } if (self->tsap) { irttp_disconnect_request(self->tsap, NULL, P_NORMAL); irttp_close_tsap(self->tsap); self->tsap = NULL; } /* A few cleanup so the socket look as good as new... */ self->rx_flow = self->tx_flow = FLOW_START; /* needed ??? */ self->daddr = DEV_ADDR_ANY; /* Until we get re-connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ release_sock(sk); return 0; } /* * Function irda_poll (file, sock, wait) */ static unsigned int irda_poll(struct file * file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); unsigned int mask; IRDA_DEBUG(4, "%s()\n", __func__); poll_wait(file, sk_sleep(sk), wait); mask = 0; /* Exceptional events? */ if (sk->sk_err) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) { IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__); mask |= POLLHUP; } /* Readable? */ if (!skb_queue_empty(&sk->sk_receive_queue)) { IRDA_DEBUG(4, "Socket is readable\n"); mask |= POLLIN | POLLRDNORM; } /* Connection-based need to check for termination and startup */ switch (sk->sk_type) { case SOCK_STREAM: if (sk->sk_state == TCP_CLOSE) { IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__); mask |= POLLHUP; } if (sk->sk_state == TCP_ESTABLISHED) { if ((self->tx_flow == FLOW_START) && sock_writeable(sk)) { mask |= POLLOUT | POLLWRNORM | POLLWRBAND; } } break; case SOCK_SEQPACKET: if ((self->tx_flow == FLOW_START) && sock_writeable(sk)) { mask |= POLLOUT | POLLWRNORM | POLLWRBAND; } break; case SOCK_DGRAM: if (sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; break; default: break; } return mask; } /* * Function irda_ioctl (sock, cmd, arg) */ static int irda_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; int err; IRDA_DEBUG(4, "%s(), cmd=%#x\n", __func__, cmd); err = -EINVAL; switch (cmd) { case TIOCOUTQ: { long amount; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; err = put_user(amount, (unsigned int __user *)arg); break; } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; /* 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; err = put_user(amount, (unsigned int __user *)arg); break; } case SIOCGSTAMP: if (sk != NULL) err = sock_get_timestamp(sk, (struct timeval __user *)arg); break; case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFMETRIC: case SIOCSIFMETRIC: break; default: IRDA_DEBUG(1, "%s(), doing device ioctl!\n", __func__); err = -ENOIOCTLCMD; } return err; } #ifdef CONFIG_COMPAT /* * Function irda_ioctl (sock, cmd, arg) */ static int irda_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { /* * All IRDA's ioctl are standard ones. */ return -ENOIOCTLCMD; } #endif /* * Function irda_setsockopt (sock, level, optname, optval, optlen) * * Set some options for the socket * */ static int irda_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct irda_ias_set *ias_opt; struct ias_object *ias_obj; struct ias_attrib * ias_attr; /* Attribute in IAS object */ int opt, free_ias = 0, err = 0; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); if (level != SOL_IRLMP) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case IRLMP_IAS_SET: /* The user want to add an attribute to an existing IAS object * (in the IAS database) or to create a new object with this * attribute. * We first query IAS to know if the object exist, and then * create the right attribute... */ if (optlen != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, optlen)) { kfree(ias_opt); err = -EFAULT; goto out; } /* Find the object we target. * If the user gives us an empty string, we use the object * associated with this socket. This will workaround * duplicated class name - Jean II */ if(ias_opt->irda_class_name[0] == '\0') { if(self->ias_obj == NULL) { kfree(ias_opt); err = -EINVAL; goto out; } ias_obj = self->ias_obj; } else ias_obj = irias_find_object(ias_opt->irda_class_name); /* Only ROOT can mess with the global IAS database. * Users can only add attributes to the object associated * with the socket they own - Jean II */ if((!capable(CAP_NET_ADMIN)) && ((ias_obj == NULL) || (ias_obj != self->ias_obj))) { kfree(ias_opt); err = -EPERM; goto out; } /* If the object doesn't exist, create it */ if(ias_obj == (struct ias_object *) NULL) { /* Create a new object */ ias_obj = irias_new_object(ias_opt->irda_class_name, jiffies); if (ias_obj == NULL) { kfree(ias_opt); err = -ENOMEM; goto out; } free_ias = 1; } /* Do we have the attribute already ? */ if(irias_find_attrib(ias_obj, ias_opt->irda_attrib_name)) { kfree(ias_opt); if (free_ias) { kfree(ias_obj->name); kfree(ias_obj); } err = -EINVAL; goto out; } /* Look at the type */ switch(ias_opt->irda_attrib_type) { case IAS_INTEGER: /* Add an integer attribute */ irias_add_integer_attrib( ias_obj, ias_opt->irda_attrib_name, ias_opt->attribute.irda_attrib_int, IAS_USER_ATTR); break; case IAS_OCT_SEQ: /* Check length */ if(ias_opt->attribute.irda_attrib_octet_seq.len > IAS_MAX_OCTET_STRING) { kfree(ias_opt); if (free_ias) { kfree(ias_obj->name); kfree(ias_obj); } err = -EINVAL; goto out; } /* Add an octet sequence attribute */ irias_add_octseq_attrib( ias_obj, ias_opt->irda_attrib_name, ias_opt->attribute.irda_attrib_octet_seq.octet_seq, ias_opt->attribute.irda_attrib_octet_seq.len, IAS_USER_ATTR); break; case IAS_STRING: /* Should check charset & co */ /* Check length */ /* The length is encoded in a __u8, and * IAS_MAX_STRING == 256, so there is no way * userspace can pass us a string too large. * Jean II */ /* NULL terminate the string (avoid troubles) */ ias_opt->attribute.irda_attrib_string.string[ias_opt->attribute.irda_attrib_string.len] = '\0'; /* Add a string attribute */ irias_add_string_attrib( ias_obj, ias_opt->irda_attrib_name, ias_opt->attribute.irda_attrib_string.string, IAS_USER_ATTR); break; default : kfree(ias_opt); if (free_ias) { kfree(ias_obj->name); kfree(ias_obj); } err = -EINVAL; goto out; } irias_insert_object(ias_obj); kfree(ias_opt); break; case IRLMP_IAS_DEL: /* The user want to delete an object from our local IAS * database. We just need to query the IAS, check is the * object is not owned by the kernel and delete it. */ if (optlen != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, optlen)) { kfree(ias_opt); err = -EFAULT; goto out; } /* Find the object we target. * If the user gives us an empty string, we use the object * associated with this socket. This will workaround * duplicated class name - Jean II */ if(ias_opt->irda_class_name[0] == '\0') ias_obj = self->ias_obj; else ias_obj = irias_find_object(ias_opt->irda_class_name); if(ias_obj == (struct ias_object *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Only ROOT can mess with the global IAS database. * Users can only del attributes from the object associated * with the socket they own - Jean II */ if((!capable(CAP_NET_ADMIN)) && ((ias_obj == NULL) || (ias_obj != self->ias_obj))) { kfree(ias_opt); err = -EPERM; goto out; } /* Find the attribute (in the object) we target */ ias_attr = irias_find_attrib(ias_obj, ias_opt->irda_attrib_name); if(ias_attr == (struct ias_attrib *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Check is the user space own the object */ if(ias_attr->value->owner != IAS_USER_ATTR) { IRDA_DEBUG(1, "%s(), attempting to delete a kernel attribute\n", __func__); kfree(ias_opt); err = -EPERM; goto out; } /* Remove the attribute (and maybe the object) */ irias_delete_attrib(ias_obj, ias_attr, 1); kfree(ias_opt); break; case IRLMP_MAX_SDU_SIZE: if (optlen < sizeof(int)) { err = -EINVAL; goto out; } if (get_user(opt, (int __user *)optval)) { err = -EFAULT; goto out; } /* Only possible for a seqpacket service (TTP with SAR) */ if (sk->sk_type != SOCK_SEQPACKET) { IRDA_DEBUG(2, "%s(), setting max_sdu_size = %d\n", __func__, opt); self->max_sdu_size_rx = opt; } else { IRDA_WARNING("%s: not allowed to set MAXSDUSIZE for this socket type!\n", __func__); err = -ENOPROTOOPT; goto out; } break; case IRLMP_HINTS_SET: if (optlen < sizeof(int)) { err = -EINVAL; goto out; } /* The input is really a (__u8 hints[2]), easier as an int */ if (get_user(opt, (int __user *)optval)) { err = -EFAULT; goto out; } /* Unregister any old registration */ if (self->skey) irlmp_unregister_service(self->skey); self->skey = irlmp_register_service((__u16) opt); break; case IRLMP_HINT_MASK_SET: /* As opposed to the previous case which set the hint bits * that we advertise, this one set the filter we use when * making a discovery (nodes which don't match any hint * bit in the mask are not reported). */ if (optlen < sizeof(int)) { err = -EINVAL; goto out; } /* The input is really a (__u8 hints[2]), easier as an int */ if (get_user(opt, (int __user *)optval)) { err = -EFAULT; goto out; } /* Set the new hint mask */ self->mask.word = (__u16) opt; /* Mask out extension bits */ self->mask.word &= 0x7f7f; /* Check if no bits */ if(!self->mask.word) self->mask.word = 0xFFFF; break; default: err = -ENOPROTOOPT; break; } out: release_sock(sk); return err; } /* * Function irda_extract_ias_value(ias_opt, ias_value) * * Translate internal IAS value structure to the user space representation * * The external representation of IAS values, as we exchange them with * user space program is quite different from the internal representation, * as stored in the IAS database (because we need a flat structure for * crossing kernel boundary). * This function transform the former in the latter. We also check * that the value type is valid. */ static int irda_extract_ias_value(struct irda_ias_set *ias_opt, struct ias_value *ias_value) { /* Look at the type */ switch (ias_value->type) { case IAS_INTEGER: /* Copy the integer */ ias_opt->attribute.irda_attrib_int = ias_value->t.integer; break; case IAS_OCT_SEQ: /* Set length */ ias_opt->attribute.irda_attrib_octet_seq.len = ias_value->len; /* Copy over */ memcpy(ias_opt->attribute.irda_attrib_octet_seq.octet_seq, ias_value->t.oct_seq, ias_value->len); break; case IAS_STRING: /* Set length */ ias_opt->attribute.irda_attrib_string.len = ias_value->len; ias_opt->attribute.irda_attrib_string.charset = ias_value->charset; /* Copy over */ memcpy(ias_opt->attribute.irda_attrib_string.string, ias_value->t.string, ias_value->len); /* NULL terminate the string (avoid troubles) */ ias_opt->attribute.irda_attrib_string.string[ias_value->len] = '\0'; break; case IAS_MISSING: default : return -EINVAL; } /* Copy type over */ ias_opt->irda_attrib_type = ias_value->type; return 0; } /* * Function irda_getsockopt (sock, level, optname, optval, optlen) */ static int irda_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct irda_device_list list; struct irda_device_info *discoveries; struct irda_ias_set * ias_opt; /* IAS get/query params */ struct ias_object * ias_obj; /* Object in IAS */ struct ias_attrib * ias_attr; /* Attribute in IAS object */ int daddr = DEV_ADDR_ANY; /* Dest address for IAS queries */ int val = 0; int len = 0; int err = 0; int offset, total; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); if (level != SOL_IRLMP) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if(len < 0) return -EINVAL; lock_sock(sk); switch (optname) { case IRLMP_ENUMDEVICES: /* Offset to first device entry */ offset = sizeof(struct irda_device_list) - sizeof(struct irda_device_info); if (len < offset) { err = -EINVAL; goto out; } /* Ask lmp for the current discovery log */ discoveries = irlmp_get_discoveries(&list.len, self->mask.word, self->nslots); /* Check if the we got some results */ if (discoveries == NULL) { err = -EAGAIN; goto out; /* Didn't find any devices */ } /* Write total list length back to client */ if (copy_to_user(optval, &list, offset)) err = -EFAULT; /* Copy the list itself - watch for overflow */ if (list.len > 2048) { err = -EINVAL; goto bed; } total = offset + (list.len * sizeof(struct irda_device_info)); if (total > len) total = len; if (copy_to_user(optval+offset, discoveries, total - offset)) err = -EFAULT; /* Write total number of bytes used back to client */ if (put_user(total, optlen)) err = -EFAULT; bed: /* Free up our buffer */ kfree(discoveries); break; case IRLMP_MAX_SDU_SIZE: val = self->max_data_size; len = sizeof(int); if (put_user(len, optlen)) { err = -EFAULT; goto out; } if (copy_to_user(optval, &val, len)) { err = -EFAULT; goto out; } break; case IRLMP_IAS_GET: /* The user want an object from our local IAS database. * We just need to query the IAS and return the value * that we found */ /* Check that the user has allocated the right space for us */ if (len != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, len)) { kfree(ias_opt); err = -EFAULT; goto out; } /* Find the object we target. * If the user gives us an empty string, we use the object * associated with this socket. This will workaround * duplicated class name - Jean II */ if(ias_opt->irda_class_name[0] == '\0') ias_obj = self->ias_obj; else ias_obj = irias_find_object(ias_opt->irda_class_name); if(ias_obj == (struct ias_object *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Find the attribute (in the object) we target */ ias_attr = irias_find_attrib(ias_obj, ias_opt->irda_attrib_name); if(ias_attr == (struct ias_attrib *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Translate from internal to user structure */ err = irda_extract_ias_value(ias_opt, ias_attr->value); if(err) { kfree(ias_opt); goto out; } /* Copy reply to the user */ if (copy_to_user(optval, ias_opt, sizeof(struct irda_ias_set))) { kfree(ias_opt); err = -EFAULT; goto out; } /* Note : don't need to put optlen, we checked it */ kfree(ias_opt); break; case IRLMP_IAS_QUERY: /* The user want an object from a remote IAS database. * We need to use IAP to query the remote database and * then wait for the answer to come back. */ /* Check that the user has allocated the right space for us */ if (len != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, len)) { kfree(ias_opt); err = -EFAULT; goto out; } /* At this point, there are two cases... * 1) the socket is connected - that's the easy case, we * just query the device we are connected to... * 2) the socket is not connected - the user doesn't want * to connect and/or may not have a valid service name * (so can't create a fake connection). In this case, * we assume that the user pass us a valid destination * address in the requesting structure... */ if(self->daddr != DEV_ADDR_ANY) { /* We are connected - reuse known daddr */ daddr = self->daddr; } else { /* We are not connected, we must specify a valid * destination address */ daddr = ias_opt->daddr; if((!daddr) || (daddr == DEV_ADDR_ANY)) { kfree(ias_opt); err = -EINVAL; goto out; } } /* Check that we can proceed with IAP */ if (self->iriap) { IRDA_WARNING("%s: busy with a previous query\n", __func__); kfree(ias_opt); err = -EBUSY; goto out; } self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self, irda_getvalue_confirm); if (self->iriap == NULL) { kfree(ias_opt); err = -ENOMEM; goto out; } /* Treat unexpected wakeup as disconnect */ self->errno = -EHOSTUNREACH; /* Query remote LM-IAS */ iriap_getvaluebyclass_request(self->iriap, self->saddr, daddr, ias_opt->irda_class_name, ias_opt->irda_attrib_name); /* Wait for answer, if not yet finished (or failed) */ if (wait_event_interruptible(self->query_wait, (self->iriap == NULL))) { /* pending request uses copy of ias_opt-content * we can free it regardless! */ kfree(ias_opt); /* Treat signals as disconnect */ err = -EHOSTUNREACH; goto out; } /* Check what happened */ if (self->errno) { kfree(ias_opt); /* Requested object/attribute doesn't exist */ if((self->errno == IAS_CLASS_UNKNOWN) || (self->errno == IAS_ATTRIB_UNKNOWN)) err = -EADDRNOTAVAIL; else err = -EHOSTUNREACH; goto out; } /* Translate from internal to user structure */ err = irda_extract_ias_value(ias_opt, self->ias_result); if (self->ias_result) irias_delete_value(self->ias_result); if (err) { kfree(ias_opt); goto out; } /* Copy reply to the user */ if (copy_to_user(optval, ias_opt, sizeof(struct irda_ias_set))) { kfree(ias_opt); err = -EFAULT; goto out; } /* Note : don't need to put optlen, we checked it */ kfree(ias_opt); break; case IRLMP_WAITDEVICE: /* This function is just another way of seeing life ;-) * IRLMP_ENUMDEVICES assumes that you have a static network, * and that you just want to pick one of the devices present. * On the other hand, in here we assume that no device is * present and that at some point in the future a device will * come into range. When this device arrive, we just wake * up the caller, so that he has time to connect to it before * the device goes away... * Note : once the node has been discovered for more than a * few second, it won't trigger this function, unless it * goes away and come back changes its hint bits (so we * might call it IRLMP_WAITNEWDEVICE). */ /* Check that the user is passing us an int */ if (len != sizeof(int)) { err = -EINVAL; goto out; } /* Get timeout in ms (max time we block the caller) */ if (get_user(val, (int __user *)optval)) { err = -EFAULT; goto out; } /* Tell IrLMP we want to be notified */ irlmp_update_client(self->ckey, self->mask.word, irda_selective_discovery_indication, NULL, (void *) self); /* Do some discovery (and also return cached results) */ irlmp_discovery_request(self->nslots); /* Wait until a node is discovered */ if (!self->cachedaddr) { IRDA_DEBUG(1, "%s(), nothing discovered yet, going to sleep...\n", __func__); /* Set watchdog timer to expire in <val> ms. */ self->errno = 0; setup_timer(&self->watchdog, irda_discovery_timeout, (unsigned long)self); mod_timer(&self->watchdog, jiffies + msecs_to_jiffies(val)); /* Wait for IR-LMP to call us back */ __wait_event_interruptible(self->query_wait, (self->cachedaddr != 0 || self->errno == -ETIME), err); /* If watchdog is still activated, kill it! */ del_timer(&(self->watchdog)); IRDA_DEBUG(1, "%s(), ...waking up !\n", __func__); if (err != 0) goto out; } else IRDA_DEBUG(1, "%s(), found immediately !\n", __func__); /* Tell IrLMP that we have been notified */ irlmp_update_client(self->ckey, self->mask.word, NULL, NULL, NULL); /* Check if the we got some results */ if (!self->cachedaddr) { err = -EAGAIN; /* Didn't find any devices */ goto out; } daddr = self->cachedaddr; /* Cleanup */ self->cachedaddr = 0; /* We return the daddr of the device that trigger the * wakeup. As irlmp pass us only the new devices, we * are sure that it's not an old device. * If the user want more details, he should query * the whole discovery log and pick one device... */ if (put_user(daddr, (int __user *)optval)) { err = -EFAULT; goto out; } break; default: err = -ENOPROTOOPT; } out: release_sock(sk); return err; } static const struct net_proto_family irda_family_ops = { .family = PF_IRDA, .create = irda_create, .owner = THIS_MODULE, }; static const struct proto_ops irda_stream_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = irda_connect, .socketpair = sock_no_socketpair, .accept = irda_accept, .getname = irda_getname, .poll = irda_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = irda_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg, .recvmsg = irda_recvmsg_stream, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const struct proto_ops irda_seqpacket_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = irda_connect, .socketpair = sock_no_socketpair, .accept = irda_accept, .getname = irda_getname, .poll = datagram_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = irda_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg, .recvmsg = irda_recvmsg_dgram, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const struct proto_ops irda_dgram_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = irda_connect, .socketpair = sock_no_socketpair, .accept = irda_accept, .getname = irda_getname, .poll = datagram_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = irda_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg_dgram, .recvmsg = irda_recvmsg_dgram, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; #ifdef CONFIG_IRDA_ULTRA static const struct proto_ops irda_ultra_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = irda_getname, .poll = datagram_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = sock_no_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg_ultra, .recvmsg = irda_recvmsg_dgram, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; #endif /* CONFIG_IRDA_ULTRA */ /* * Function irsock_init (pro) * * Initialize IrDA protocol * */ int __init irsock_init(void) { int rc = proto_register(&irda_proto, 0); if (rc == 0) rc = sock_register(&irda_family_ops); return rc; } /* * Function irsock_cleanup (void) * * Remove IrDA protocol * */ void irsock_cleanup(void) { sock_unregister(PF_IRDA); proto_unregister(&irda_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5687_0
crossvul-cpp_data_bad_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"); 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/bad_2853_0
crossvul-cpp_data_good_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; msg->msg_namelen = 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/good_5688_0
crossvul-cpp_data_bad_693_0
/* * Copyright (c) 2011-2014 Yubico AB * Copyright (c) 2011 Tollef Fog Heen <tfheen@err.no> * All rights reserved. * * Author : Fredrik Thulin <fredrik@yubico.com> * Author : Tollef Fog Heen <tfheen@err.no> * * 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. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <glob.h> #include <unistd.h> #include "util.h" #if HAVE_CR /* for yubikey_hex_decode and yubikey_hex_p */ #include <yubikey.h> #include <ykpbkdf2.h> #include <ykstatus.h> #include <ykdef.h> #endif /* HAVE_CR */ int get_user_cfgfile_path(const char *common_path, const char *filename, const struct passwd *user, char **fn) { /* Getting file from user home directory, e.g. ~/.yubico/challenge, or * from a system wide directory. * * Format is hex(challenge):hex(response):slot num */ char *userfile; size_t len; if (common_path != NULL) { len = strlen(common_path) + 1 + strlen(filename) + 1; if ((userfile = malloc(len)) == NULL) { return 0; } snprintf(userfile, len, "%s/%s", common_path, filename); *fn = userfile; return 1; } /* No common path provided. Construct path to user's ~/.yubico/filename */ len = strlen(user->pw_dir) + 9 + strlen(filename) + 1; if ((userfile = malloc(len)) == NULL) { return 0; } snprintf(userfile, len, "%s/.yubico/%s", user->pw_dir, filename); *fn = userfile; return 1; } /* * This function will look for users name with valid user token id. * * Returns one of AUTH_FOUND, AUTH_NOT_FOUND, AUTH_NO_TOKENS, AUTH_ERROR. * * File format is as follows: * <user-name>:<token_id>:<token_id> * <user-name>:<token_id> * */ int check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, "%s is not a regular file", authfile); close(fd); return retval; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if(verbose) D (debug_file, "fdopen: %s", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, "Skipping comment line: %s", buf); continue; } 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 = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, ":", &saveptr); if(verbose) D (debug_file, "Authorization token: %s", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, "Match user/token as %s/%s", username, otp_id); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; } #if HAVE_CR /* Fill buf with len bytes of random data */ int generate_random(void *buf, int len) { FILE *u; int res; u = fopen("/dev/urandom", "r"); if (!u) { return -1; } res = fread(buf, 1, (size_t) len, u); fclose(u); return (res != len); } int check_firmware_version(YK_KEY *yk, bool verbose, bool quiet, FILE *debug_file) { YK_STATUS *st = ykds_alloc(); if (!yk_get_status(yk, st)) { free(st); return 0; } if (verbose) { D(debug_file, "YubiKey Firmware version: %d.%d.%d\n", ykds_version_major(st), ykds_version_minor(st), ykds_version_build(st)); } if (ykds_version_major(st) < 2 || (ykds_version_major(st) == 2 && ykds_version_minor(st) < 2)) { if (! quiet) fprintf(stderr, "Challenge-response not supported before YubiKey 2.2.\n"); free(st); return 0; } free(st); return 1; } int init_yubikey(YK_KEY **yk) { if (!yk_init()) return 0; if (!(*yk = yk_open_first_key())) return 0; return 1; } int challenge_response(YK_KEY *yk, int slot, char *challenge, unsigned int len, bool hmac, bool may_block, bool verbose, char *response, unsigned int res_size, unsigned int *res_len) { int yk_cmd; if(hmac == true) { *res_len = 20; } else { *res_len = 16; } if (res_size < *res_len) { return 0; } memset(response, 0, res_size); if (verbose) { fprintf(stderr, "Sending %u bytes %s challenge to slot %i\n", len, (hmac == true)?"HMAC":"Yubico", slot); //_yk_hexdump(challenge, len); } switch(slot) { case 1: yk_cmd = (hmac == true) ? SLOT_CHAL_HMAC1 : SLOT_CHAL_OTP1; break; case 2: yk_cmd = (hmac == true) ? SLOT_CHAL_HMAC2 : SLOT_CHAL_OTP2; break; default: return 0; } if(! yk_challenge_response(yk, yk_cmd, may_block, len, (unsigned char*)challenge, res_size, (unsigned char*)response)) { return 0; } return 1; } int check_user_challenge_file(const char *chalresp_path, const struct passwd *user, FILE *debug_file) { /* * This function will look for users challenge files. * * Returns one of AUTH_FOUND, AUTH_NOT_FOUND, AUTH_ERROR */ size_t len; int r; int ret = AUTH_NOT_FOUND; char *userfile = NULL; char *userfile_pattern = NULL; glob_t userfile_glob; const char *filename = NULL; if (! chalresp_path) { filename = "challenge"; } else { filename = user->pw_name; } /* check for userfile challenge files */ r = get_user_cfgfile_path(chalresp_path, filename, user, &userfile); if (!r) { D (debug_file, "Failed to get user cfgfile path"); ret = AUTH_ERROR; goto out; } if (!access(userfile, F_OK)) { ret = AUTH_FOUND; goto out; } /* check for userfile-* challenge files */ len = strlen(userfile) + 2 + 1; if ((userfile_pattern = malloc(len)) == NULL) { D (debug_file, "Failed to allocate memory for userfile pattern: %s", strerror(errno)); ret = AUTH_ERROR; goto out; } snprintf(userfile_pattern, len, "%s-*", userfile); r = glob(userfile_pattern, 0, NULL, &userfile_glob); globfree(&userfile_glob); switch (r) { case GLOB_NOMATCH: /* No matches found, so continue */ break; case 0: ret = AUTH_FOUND; goto out; default: D (debug_file, "Error while checking for %s challenge files: %s", userfile_pattern, strerror(errno)); ret = AUTH_ERROR; goto out; } out: free(userfile_pattern); free(userfile); return ret; } int get_user_challenge_file(YK_KEY *yk, const char *chalresp_path, const struct passwd *user, char **fn, FILE *debug_file) { /* Getting file from user home directory, i.e. ~/.yubico/challenge, or * from a system wide directory. */ /* The challenge to use is located in a file in the user's home directory, * which therefor can't be encrypted. If an encrypted home directory is used, * the option chalresp_path can be used to point to a system-wide directory. */ const char *filename = NULL; /* not including directory */ char *ptr = NULL; unsigned int serial = 0; int ret; if (! yk_get_serial(yk, 0, 0, &serial)) { D (debug_file, "Failed to read serial number (serial-api-visible disabled?)."); if (! chalresp_path) filename = "challenge"; else filename = user->pw_name; } else { /* We have serial number */ /* 0xffffffff == 4294967295 == 10 digits */ size_t len = strlen(chalresp_path == NULL ? "challenge" : user->pw_name) + 1 + 10 + 1; if ((ptr = malloc(len)) != NULL) { int res = snprintf(ptr, len, "%s-%u", chalresp_path == NULL ? "challenge" : user->pw_name, serial); filename = ptr; if (res < 0 || (unsigned long)res > len) { /* Not enough space, strangely enough. */ free(ptr); filename = NULL; } } } if (filename == NULL) return 0; ret = get_user_cfgfile_path (chalresp_path, filename, user, fn); if(ptr) { free(ptr); } return ret; } int load_chalresp_state(FILE *f, CR_STATE *state, bool verbose, FILE *debug_file) { /* * Load the current challenge and expected response information from a file handle. * * Format is hex(challenge):hex(response):slot num */ char challenge_hex[CR_CHALLENGE_SIZE * 2 + 1], response_hex[CR_RESPONSE_SIZE * 2 + 1]; char salt_hex[CR_SALT_SIZE * 2 + 1]; unsigned int iterations; int slot; int r; if (! f) goto out; /* XXX not ideal with hard coded lengths in this scan string. * 126 corresponds to twice the size of CR_CHALLENGE_SIZE, * 40 is twice the size of CR_RESPONSE_SIZE * (twice because we hex encode the challenge and response) */ r = fscanf(f, "v2:%126[0-9a-z]:%40[0-9a-z]:%64[0-9a-z]:%d:%d", challenge_hex, response_hex, salt_hex, &iterations, &slot); if(r == 5) { if (! yubikey_hex_p(salt_hex)) { D(debug_file, "Invalid salt hex input : %s", salt_hex); goto out; } if(verbose) { D(debug_file, "Challenge: %s, hashed response: %s, salt: %s, iterations: %d, slot: %d", challenge_hex, response_hex, salt_hex, iterations, slot); } yubikey_hex_decode(state->salt, salt_hex, sizeof(state->salt)); state->salt_len = strlen(salt_hex) / 2; } else { rewind(f); r = fscanf(f, "v1:%126[0-9a-z]:%40[0-9a-z]:%d", challenge_hex, response_hex, &slot); if (r != 3) { D(debug_file, "Could not parse contents of chalresp_state file (%i)", r); goto out; } if (verbose) { D(debug_file, "Challenge: %s, expected response: %s, slot: %d", challenge_hex, response_hex, slot); } iterations = CR_DEFAULT_ITERATIONS; } state->iterations = iterations; if (! yubikey_hex_p(challenge_hex)) { D(debug_file, "Invalid challenge hex input : %s", challenge_hex); goto out; } if (! yubikey_hex_p(response_hex)) { D(debug_file, "Invalid expected response hex input : %s", response_hex); goto out; } if (slot != 1 && slot != 2) { D(debug_file, "Invalid slot input : %i", slot); goto out; } yubikey_hex_decode(state->challenge, challenge_hex, sizeof(state->challenge)); state->challenge_len = strlen(challenge_hex) / 2; yubikey_hex_decode(state->response, response_hex, sizeof(state->response)); state->response_len = strlen(response_hex) / 2; state->slot = slot; return 1; out: return 0; } int write_chalresp_state(FILE *f, CR_STATE *state) { char challenge_hex[CR_CHALLENGE_SIZE * 2 + 1], response_hex[CR_RESPONSE_SIZE * 2 + 1]; char salt_hex[CR_SALT_SIZE * 2 + 1], hashed_hex[CR_RESPONSE_SIZE * 2 + 1]; unsigned char salt[CR_SALT_SIZE], hash[CR_RESPONSE_SIZE]; YK_PRF_METHOD prf_method = {20, yk_hmac_sha1}; unsigned int iterations = CR_DEFAULT_ITERATIONS; int fd; memset(challenge_hex, 0, sizeof(challenge_hex)); memset(response_hex, 0, sizeof(response_hex)); memset(salt_hex, 0, sizeof(salt_hex)); memset(hashed_hex, 0, sizeof(hashed_hex)); yubikey_hex_encode(challenge_hex, (char *)state->challenge, state->challenge_len); yubikey_hex_encode(response_hex, (char *)state->response, state->response_len); if(state->iterations > 0) { iterations = state->iterations; } generate_random(salt, CR_SALT_SIZE); yk_pbkdf2(response_hex, salt, CR_SALT_SIZE, iterations, hash, CR_RESPONSE_SIZE, &prf_method); yubikey_hex_encode(hashed_hex, (char *)hash, CR_RESPONSE_SIZE); yubikey_hex_encode(salt_hex, (char *)salt, CR_SALT_SIZE); rewind(f); fd = fileno(f); if (fd == -1) goto out; if (ftruncate(fd, 0)) goto out; fprintf(f, "v2:%s:%s:%s:%u:%d\n", challenge_hex, hashed_hex, salt_hex, iterations, state->slot); if (fflush(f) < 0) goto out; if (fsync(fd) < 0) goto out; return 1; out: return 0; } #endif /* HAVE_CR */ size_t filter_result_len(const char *filter, const char *user, char *output) { const char *part = NULL; size_t result = 0; do { size_t len; part = strstr(filter, "%u"); if(part) len = part - filter; else len = strlen(filter); if (output) { strncpy(output, filter, len); output += len; } result += len; filter += len + 2; if(part) { if(output) { strncpy(output, user, strlen(user)); output += strlen(user); } result += strlen(user); } } while(part); if(output) *output = '\0'; return(result + 1); } char *filter_printf(const char *filter, const char *user) { char *result = malloc(filter_result_len(filter, user, NULL)); filter_result_len(filter, user, result); return result; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_693_0
crossvul-cpp_data_good_5693_0
/* * Copyright (C) 2011 Intel Corporation. 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; 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. */ #define pr_fmt(fmt) "llcp: %s: " fmt, __func__ #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/nfc.h> #include "../nfc.h" #include "llcp.h" static int sock_wait_state(struct sock *sk, int state, unsigned long timeo) { DECLARE_WAITQUEUE(wait, current); int err = 0; pr_debug("sk %p", sk); add_wait_queue(sk_sleep(sk), &wait); set_current_state(TASK_INTERRUPTIBLE); while (sk->sk_state != state) { if (!timeo) { err = -EINPROGRESS; 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_INTERRUPTIBLE); err = sock_error(sk); if (err) break; } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); return err; } static struct proto llcp_sock_proto = { .name = "NFC_LLCP", .owner = THIS_MODULE, .obj_size = sizeof(struct nfc_llcp_sock), }; static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_local *local; struct nfc_dev *dev; struct sockaddr_nfc_llcp llcp_addr; int len, ret = 0; if (!addr || addr->sa_family != AF_NFC) return -EINVAL; pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family); memset(&llcp_addr, 0, sizeof(llcp_addr)); len = min_t(unsigned int, sizeof(llcp_addr), alen); memcpy(&llcp_addr, addr, len); /* This is going to be a listening socket, dsap must be 0 */ if (llcp_addr.dsap != 0) return -EINVAL; lock_sock(sk); if (sk->sk_state != LLCP_CLOSED) { ret = -EBADFD; goto error; } dev = nfc_get_device(llcp_addr.dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->nfc_protocol = llcp_addr.nfc_protocol; llcp_sock->service_name_len = min_t(unsigned int, llcp_addr.service_name_len, NFC_LLCP_MAX_SERVICE_NAME); llcp_sock->service_name = kmemdup(llcp_addr.service_name, llcp_sock->service_name_len, GFP_KERNEL); llcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock); if (llcp_sock->ssap == LLCP_SAP_MAX) { ret = -EADDRINUSE; goto put_dev; } llcp_sock->reserved_ssap = llcp_sock->ssap; nfc_llcp_sock_link(&local->sockets, sk); pr_debug("Socket bound to SAP %d\n", llcp_sock->ssap); sk->sk_state = LLCP_BOUND; put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; } static int llcp_raw_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_local *local; struct nfc_dev *dev; struct sockaddr_nfc_llcp llcp_addr; int len, ret = 0; if (!addr || addr->sa_family != AF_NFC) return -EINVAL; pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family); memset(&llcp_addr, 0, sizeof(llcp_addr)); len = min_t(unsigned int, sizeof(llcp_addr), alen); memcpy(&llcp_addr, addr, len); lock_sock(sk); if (sk->sk_state != LLCP_CLOSED) { ret = -EBADFD; goto error; } dev = nfc_get_device(llcp_addr.dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->nfc_protocol = llcp_addr.nfc_protocol; nfc_llcp_sock_link(&local->raw_sockets, sk); sk->sk_state = LLCP_BOUND; put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; } static int llcp_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int ret = 0; pr_debug("sk %p backlog %d\n", sk, backlog); lock_sock(sk); if ((sock->type != SOCK_SEQPACKET && sock->type != SOCK_STREAM) || sk->sk_state != LLCP_BOUND) { ret = -EBADFD; goto error; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; pr_debug("Socket listening\n"); sk->sk_state = LLCP_LISTEN; error: release_sock(sk); return ret; } void nfc_llcp_accept_unlink(struct sock *sk) { struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); pr_debug("state %d\n", sk->sk_state); list_del_init(&llcp_sock->accept_queue); sk_acceptq_removed(llcp_sock->parent); llcp_sock->parent = NULL; sock_put(sk); } void nfc_llcp_accept_enqueue(struct sock *parent, struct sock *sk) { struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_sock *llcp_sock_parent = nfc_llcp_sock(parent); /* Lock will be free from unlink */ sock_hold(sk); list_add_tail(&llcp_sock->accept_queue, &llcp_sock_parent->accept_queue); llcp_sock->parent = parent; sk_acceptq_added(parent); } struct sock *nfc_llcp_accept_dequeue(struct sock *parent, struct socket *newsock) { struct nfc_llcp_sock *lsk, *n, *llcp_parent; struct sock *sk; llcp_parent = nfc_llcp_sock(parent); list_for_each_entry_safe(lsk, n, &llcp_parent->accept_queue, accept_queue) { sk = &lsk->sk; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED) { release_sock(sk); nfc_llcp_accept_unlink(sk); continue; } if (sk->sk_state == LLCP_CONNECTED || !newsock) { list_del_init(&lsk->accept_queue); sock_put(sk); if (newsock) sock_graft(sk, newsock); release_sock(sk); pr_debug("Returning sk state %d\n", sk->sk_state); sk_acceptq_removed(parent); return sk; } release_sock(sk); } return NULL; } static int llcp_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *new_sk; long timeo; int ret = 0; pr_debug("parent %p\n", sk); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != LLCP_LISTEN) { ret = -EBADFD; goto error; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); /* Wait for an incoming connection. */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (!(new_sk = nfc_llcp_accept_dequeue(sk, newsock))) { set_current_state(TASK_INTERRUPTIBLE); if (!timeo) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = 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 (ret) goto error; newsock->state = SS_CONNECTED; pr_debug("new socket %p\n", new_sk); error: release_sock(sk); return ret; } static int llcp_sock_getname(struct socket *sock, struct sockaddr *uaddr, int *len, int peer) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); DECLARE_SOCKADDR(struct sockaddr_nfc_llcp *, llcp_addr, uaddr); if (llcp_sock == NULL || llcp_sock->dev == NULL) return -EBADFD; pr_debug("%p %d %d %d\n", sk, llcp_sock->target_idx, llcp_sock->dsap, llcp_sock->ssap); uaddr->sa_family = AF_NFC; *len = sizeof(struct sockaddr_nfc_llcp); llcp_addr->dev_idx = llcp_sock->dev->idx; llcp_addr->target_idx = llcp_sock->target_idx; llcp_addr->dsap = llcp_sock->dsap; llcp_addr->ssap = llcp_sock->ssap; llcp_addr->service_name_len = llcp_sock->service_name_len; memcpy(llcp_addr->service_name, llcp_sock->service_name, llcp_addr->service_name_len); return 0; } static inline unsigned int llcp_accept_poll(struct sock *parent) { struct nfc_llcp_sock *llcp_sock, *n, *parent_sock; struct sock *sk; parent_sock = nfc_llcp_sock(parent); list_for_each_entry_safe(llcp_sock, n, &parent_sock->accept_queue, accept_queue) { sk = &llcp_sock->sk; if (sk->sk_state == LLCP_CONNECTED) return POLLIN | POLLRDNORM; } return 0; } static unsigned int llcp_sock_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask = 0; pr_debug("%p\n", sk); sock_poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == LLCP_LISTEN) return llcp_accept_poll(sk); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; if (sk->sk_state == LLCP_CLOSED) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); pr_debug("mask 0x%x\n", mask); return mask; } static int llcp_sock_release(struct socket *sock) { struct sock *sk = sock->sk; struct nfc_llcp_local *local; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); int err = 0; if (!sk) return 0; pr_debug("%p\n", sk); local = llcp_sock->local; if (local == NULL) { err = -ENODEV; goto out; } lock_sock(sk); /* Send a DISC */ if (sk->sk_state == LLCP_CONNECTED) nfc_llcp_disconnect(llcp_sock); if (sk->sk_state == LLCP_LISTEN) { struct nfc_llcp_sock *lsk, *n; struct sock *accept_sk; list_for_each_entry_safe(lsk, n, &llcp_sock->accept_queue, accept_queue) { accept_sk = &lsk->sk; lock_sock(accept_sk); nfc_llcp_disconnect(lsk); nfc_llcp_accept_unlink(accept_sk); release_sock(accept_sk); } } if (llcp_sock->reserved_ssap < LLCP_SAP_MAX) nfc_llcp_put_ssap(llcp_sock->local, llcp_sock->ssap); release_sock(sk); if (sock->type == SOCK_RAW) nfc_llcp_sock_unlink(&local->raw_sockets, sk); else nfc_llcp_sock_unlink(&local->sockets, sk); out: sock_orphan(sk); sock_put(sk); return err; } static int llcp_sock_connect(struct socket *sock, struct sockaddr *_addr, int len, int flags) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct sockaddr_nfc_llcp *addr = (struct sockaddr_nfc_llcp *)_addr; struct nfc_dev *dev; struct nfc_llcp_local *local; int ret = 0; pr_debug("sock %p sk %p flags 0x%x\n", sock, sk, flags); if (!addr || len < sizeof(struct sockaddr_nfc) || addr->sa_family != AF_NFC) return -EINVAL; if (addr->service_name_len == 0 && addr->dsap == 0) return -EINVAL; pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n", addr->dev_idx, addr->target_idx, addr->nfc_protocol); lock_sock(sk); if (sk->sk_state == LLCP_CONNECTED) { ret = -EISCONN; goto error; } dev = nfc_get_device(addr->dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } device_lock(&dev->dev); if (dev->dep_link_up == false) { ret = -ENOLINK; device_unlock(&dev->dev); goto put_dev; } device_unlock(&dev->dev); if (local->rf_mode == NFC_RF_INITIATOR && addr->target_idx != local->target_idx) { ret = -ENOLINK; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->miu = llcp_sock->local->remote_miu; llcp_sock->ssap = nfc_llcp_get_local_ssap(local); if (llcp_sock->ssap == LLCP_SAP_MAX) { ret = -ENOMEM; goto put_dev; } llcp_sock->reserved_ssap = llcp_sock->ssap; if (addr->service_name_len == 0) llcp_sock->dsap = addr->dsap; else llcp_sock->dsap = LLCP_SAP_SDP; llcp_sock->nfc_protocol = addr->nfc_protocol; llcp_sock->service_name_len = min_t(unsigned int, addr->service_name_len, NFC_LLCP_MAX_SERVICE_NAME); llcp_sock->service_name = kmemdup(addr->service_name, llcp_sock->service_name_len, GFP_KERNEL); nfc_llcp_sock_link(&local->connecting_sockets, sk); ret = nfc_llcp_send_connect(llcp_sock); if (ret) goto sock_unlink; ret = sock_wait_state(sk, LLCP_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); if (ret) goto sock_unlink; release_sock(sk); return 0; sock_unlink: nfc_llcp_put_ssap(local, llcp_sock->ssap); nfc_llcp_sock_unlink(&local->connecting_sockets, sk); put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; } static int llcp_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); int ret; pr_debug("sock %p sk %p", sock, sk); ret = sock_error(sk); if (ret) return ret; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_type == SOCK_DGRAM) { struct sockaddr_nfc_llcp *addr = (struct sockaddr_nfc_llcp *)msg->msg_name; if (msg->msg_namelen < sizeof(*addr)) { release_sock(sk); return -EINVAL; } release_sock(sk); return nfc_llcp_send_ui_frame(llcp_sock, addr->dsap, addr->ssap, msg, len); } if (sk->sk_state != LLCP_CONNECTED) { release_sock(sk); return -ENOTCONN; } release_sock(sk); return nfc_llcp_send_i_frame(llcp_sock, msg, len); } static int llcp_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; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); 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_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* 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 || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ 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 const struct proto_ops llcp_sock_ops = { .family = PF_NFC, .owner = THIS_MODULE, .bind = llcp_sock_bind, .connect = llcp_sock_connect, .release = llcp_sock_release, .socketpair = sock_no_socketpair, .accept = llcp_sock_accept, .getname = llcp_sock_getname, .poll = llcp_sock_poll, .ioctl = sock_no_ioctl, .listen = llcp_sock_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = llcp_sock_sendmsg, .recvmsg = llcp_sock_recvmsg, .mmap = sock_no_mmap, }; static const struct proto_ops llcp_rawsock_ops = { .family = PF_NFC, .owner = THIS_MODULE, .bind = llcp_raw_sock_bind, .connect = sock_no_connect, .release = llcp_sock_release, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = llcp_sock_getname, .poll = llcp_sock_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = sock_no_sendmsg, .recvmsg = llcp_sock_recvmsg, .mmap = sock_no_mmap, }; static void llcp_sock_destruct(struct sock *sk) { struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); pr_debug("%p\n", sk); if (sk->sk_state == LLCP_CONNECTED) nfc_put_device(llcp_sock->dev); skb_queue_purge(&sk->sk_receive_queue); nfc_llcp_sock_free(llcp_sock); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Freeing alive NFC LLCP socket %p\n", sk); return; } } struct sock *nfc_llcp_sock_alloc(struct socket *sock, int type, gfp_t gfp) { struct sock *sk; struct nfc_llcp_sock *llcp_sock; sk = sk_alloc(&init_net, PF_NFC, gfp, &llcp_sock_proto); if (!sk) return NULL; llcp_sock = nfc_llcp_sock(sk); sock_init_data(sock, sk); sk->sk_state = LLCP_CLOSED; sk->sk_protocol = NFC_SOCKPROTO_LLCP; sk->sk_type = type; sk->sk_destruct = llcp_sock_destruct; llcp_sock->ssap = 0; llcp_sock->dsap = LLCP_SAP_SDP; llcp_sock->rw = LLCP_DEFAULT_RW; llcp_sock->miu = LLCP_DEFAULT_MIU; llcp_sock->send_n = llcp_sock->send_ack_n = 0; llcp_sock->recv_n = llcp_sock->recv_ack_n = 0; llcp_sock->remote_ready = 1; llcp_sock->reserved_ssap = LLCP_SAP_MAX; skb_queue_head_init(&llcp_sock->tx_queue); skb_queue_head_init(&llcp_sock->tx_pending_queue); INIT_LIST_HEAD(&llcp_sock->accept_queue); if (sock != NULL) sock->state = SS_UNCONNECTED; return sk; } void nfc_llcp_sock_free(struct nfc_llcp_sock *sock) { kfree(sock->service_name); skb_queue_purge(&sock->tx_queue); skb_queue_purge(&sock->tx_pending_queue); list_del_init(&sock->accept_queue); sock->parent = NULL; nfc_llcp_local_put(sock->local); } static int llcp_sock_create(struct net *net, struct socket *sock, const struct nfc_protocol *nfc_proto) { struct sock *sk; pr_debug("%p\n", sock); if (sock->type != SOCK_STREAM && sock->type != SOCK_DGRAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW) sock->ops = &llcp_rawsock_ops; else sock->ops = &llcp_sock_ops; sk = nfc_llcp_sock_alloc(sock, sock->type, GFP_ATOMIC); if (sk == NULL) return -ENOMEM; return 0; } static const struct nfc_protocol llcp_nfc_proto = { .id = NFC_SOCKPROTO_LLCP, .proto = &llcp_sock_proto, .owner = THIS_MODULE, .create = llcp_sock_create }; int __init nfc_llcp_sock_init(void) { return nfc_proto_register(&llcp_nfc_proto); } void nfc_llcp_sock_exit(void) { nfc_proto_unregister(&llcp_nfc_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_5693_0
crossvul-cpp_data_good_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; msg->msg_namelen = 0; 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/good_5678_0
crossvul-cpp_data_bad_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; 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/bad_5689_0
crossvul-cpp_data_bad_5759_0
#include <linux/fs.h> #include "headers.h" /*************************************************************** * Function - bcm_char_open() * * Description - This is the "open" entry point for the character * driver. * * Parameters - inode: Pointer to the Inode structure of char device * filp : File pointer of the char device * * Returns - Zero(Success) ****************************************************************/ static int bcm_char_open(struct inode *inode, struct file *filp) { struct bcm_mini_adapter *Adapter = NULL; struct bcm_tarang_data *pTarang = NULL; Adapter = GET_BCM_ADAPTER(gblpnetdev); pTarang = kzalloc(sizeof(struct bcm_tarang_data), GFP_KERNEL); if (!pTarang) return -ENOMEM; pTarang->Adapter = Adapter; pTarang->RxCntrlMsgBitMask = 0xFFFFFFFF & ~(1 << 0xB); down(&Adapter->RxAppControlQueuelock); pTarang->next = Adapter->pTarangs; Adapter->pTarangs = pTarang; up(&Adapter->RxAppControlQueuelock); /* Store the Adapter structure */ filp->private_data = pTarang; /* Start Queuing the control response Packets */ atomic_inc(&Adapter->ApplicationRunning); nonseekable_open(inode, filp); return 0; } static int bcm_char_release(struct inode *inode, struct file *filp) { struct bcm_tarang_data *pTarang, *tmp, *ptmp; struct bcm_mini_adapter *Adapter = NULL; struct sk_buff *pkt, *npkt; pTarang = (struct bcm_tarang_data *)filp->private_data; if (pTarang == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "ptarang is null\n"); return 0; } Adapter = pTarang->Adapter; down(&Adapter->RxAppControlQueuelock); tmp = Adapter->pTarangs; for (ptmp = NULL; tmp; ptmp = tmp, tmp = tmp->next) { if (tmp == pTarang) break; } if (tmp) { if (!ptmp) Adapter->pTarangs = tmp->next; else ptmp->next = tmp->next; } else { up(&Adapter->RxAppControlQueuelock); return 0; } pkt = pTarang->RxAppControlHead; while (pkt) { npkt = pkt->next; kfree_skb(pkt); pkt = npkt; } up(&Adapter->RxAppControlQueuelock); /* Stop Queuing the control response Packets */ atomic_dec(&Adapter->ApplicationRunning); kfree(pTarang); /* remove this filp from the asynchronously notified filp's */ filp->private_data = NULL; return 0; } static ssize_t bcm_char_read(struct file *filp, char __user *buf, size_t size, loff_t *f_pos) { struct bcm_tarang_data *pTarang = filp->private_data; struct bcm_mini_adapter *Adapter = pTarang->Adapter; struct sk_buff *Packet = NULL; ssize_t PktLen = 0; int wait_ret_val = 0; unsigned long ret = 0; wait_ret_val = wait_event_interruptible(Adapter->process_read_wait_queue, (pTarang->RxAppControlHead || Adapter->device_removed)); if ((wait_ret_val == -ERESTARTSYS)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Exiting as i've been asked to exit!!!\n"); return wait_ret_val; } if (Adapter->device_removed) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device Removed... Killing the Apps...\n"); return -ENODEV; } if (FALSE == Adapter->fw_download_done) return -EACCES; down(&Adapter->RxAppControlQueuelock); if (pTarang->RxAppControlHead) { Packet = pTarang->RxAppControlHead; DEQUEUEPACKET(pTarang->RxAppControlHead, pTarang->RxAppControlTail); pTarang->AppCtrlQueueLen--; } up(&Adapter->RxAppControlQueuelock); if (Packet) { PktLen = Packet->len; ret = copy_to_user(buf, Packet->data, min_t(size_t, PktLen, size)); if (ret) { dev_kfree_skb(Packet); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Returning from copy to user failure\n"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Read %zd Bytes From Adapter packet = %p by process %d!\n", PktLen, Packet, current->pid); dev_kfree_skb(Packet); } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "<\n"); return PktLen; } static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg) { struct bcm_tarang_data *pTarang = filp->private_data; void __user *argp = (void __user *)arg; struct bcm_mini_adapter *Adapter = pTarang->Adapter; INT Status = STATUS_FAILURE; int timeout = 0; struct bcm_ioctl_buffer IoBuffer; int bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX", cmd, arg); if (_IOC_TYPE(cmd) != BCM_IOCTL) return -EFAULT; if (_IOC_DIR(cmd) & _IOC_READ) Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd)); else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE)) Status = STATUS_SUCCESS; if (Status) return -EFAULT; if (Adapter->device_removed) return -EFAULT; if (FALSE == Adapter->fw_download_done) { switch (cmd) { case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: case IOCTL_BCM_GPIO_SET_REQUEST: case IOCTL_BCM_GPIO_STATUS_REQUEST: return -EACCES; default: break; } } Status = vendorextnIoctl(Adapter, cmd, arg); if (Status != CONTINUE_COMMON_PATH) return Status; switch (cmd) { /* Rdms for Swin Idle... */ case IOCTL_BCM_REGISTER_READ_PRIVATE: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff; UINT Bufflen; u16 temp_value; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } Bufflen = IoBuffer.OutputLength; temp_value = 4 - (Bufflen % 4); Bufflen += temp_value % 4; temp_buff = kmalloc(Bufflen, GFP_KERNEL); if (!temp_buff) return -ENOMEM; bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, Bufflen); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE_PRIVATE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; /* Get WrmBuffer structure */ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n"); return -EFAULT; } Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n"); Status = -EFAULT; } break; } case IOCTL_BCM_REGISTER_READ: case IOCTL_BCM_EEPROM_REGISTER_READ: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff = NULL; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Rdms\n"); return -EACCES; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sRdmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Done On invalid Address : %x Access Denied.\n", (int)sRdmBuffer.Register); kfree(temp_buff); return -EINVAL; } uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK; bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE: case IOCTL_BCM_EEPROM_REGISTER_WRITE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Wrms\n"); return -EACCES; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; /* Get WrmBuffer structure */ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sWrmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)sWrmBuffer.Register); return -EINVAL; } uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n"); return -EFAULT; } Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sWrmBuffer.Length); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n"); Status = -EFAULT; } break; } case IOCTL_BCM_GPIO_SET_REQUEST: { UCHAR ucResetValue[4]; UINT value = 0; UINT uiBit = 0; UINT uiOperation = 0; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode"); return -EACCES; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; uiOperation = gpio_info.uiGpioValue; value = (1<<uiBit); if (IsReqGpioIsLedInNVM(Adapter, value) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to LED !!!", value); Status = -EINVAL; break; } /* Set - setting 1 */ if (uiOperation) { /* Set the gpio output register */ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to set the %dth GPIO\n", uiBit); break; } } else { /* Set the gpio output register */ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to clear the %dth GPIO\n", uiBit); break; } } bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO_MODE_REGISTER read failed"); break; } else { Status = STATUS_SUCCESS; } /* Set the gpio mode register to output */ *(UINT *)ucResetValue |= (1<<uiBit); Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO to output Mode\n"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to put GPIO in Output Mode\n"); break; } } break; case BCM_LED_THREAD_STATE_CHANGE_REQ: { struct bcm_user_thread_req threadReq = {0}; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "User made LED thread InActive"); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode"); Status = -EACCES; break; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(threadReq)) return -EINVAL; if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; /* if LED thread is running(Actively or Inactively) set it state to make inactive */ if (Adapter->LEDInfo.led_thread_running) { if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Activating thread req"); Adapter->DriverState = LED_THREAD_ACTIVE; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DeActivating Thread req....."); Adapter->DriverState = LED_THREAD_INACTIVE; } /* signal thread. */ wake_up(&Adapter->LEDInfo.notify_led_event); } } break; case IOCTL_BCM_GPIO_STATUS_REQUEST: { ULONG uiBit = 0; UCHAR ucRead[4]; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EACCES; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; /* Set the gpio output register */ bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucRead, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Failed\n"); return Status; } else { Status = STATUS_SUCCESS; } } break; case IOCTL_BCM_GPIO_MULTI_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX]; struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info; memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info)); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_info)) return -EINVAL; if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!", pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } /* Set the gpio output register */ if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) & (pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) { /* Set 1's in GPIO OUTPUT REGISTER */ *(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & pgpio_multi_info[WIMAX_IDX].uiGPIOValue; if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_SET_REG Failed."); return Status; } /* Clear to 0's in GPIO OUTPUT REGISTER */ *(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & (~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue))); if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_CLR_REG Failed."); return Status; } } if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) { bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM to GPIO_PIN_STATE_REGISTER Failed."); return Status; } else { Status = STATUS_SUCCESS; } pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue & pgpio_multi_info[WIMAX_IDX].uiGPIOMask); } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed while copying Content to IOBufer for user space err:%d", Status); return -EFAULT; } } break; case IOCTL_BCM_GPIO_MODE_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX]; struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_mode)) return -EINVAL; if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Read of GPIO_MODE_REGISTER failed"); return Status; } else { Status = STATUS_SUCCESS; } /* Validating the request */ if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!", pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) { /* write all OUT's (1's) */ *(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); /* write all IN's (0's) */ *(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); /* Currently implemented return the modes of all GPIO's * else needs to bit AND with mask */ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM to GPIO_MODE_REGISTER Done"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to GPIO_MODE_REGISTER Failed"); Status = -EFAULT; break; } } else { /* if uiGPIOMask is 0 then return mode register configuration */ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed while copying Content to IOBufer for user space err:%d", Status); return -EFAULT; } } break; case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: { PVOID pvBuffer = NULL; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(struct bcm_link_request)) return -EINVAL; if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); down(&Adapter->LowPowerModeSync); Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue, !Adapter->bPreparingForLowPowerMode, (1 * HZ)); if (Status == -ERESTARTSYS) goto cntrlEnd; if (Adapter->bPreparingForLowPowerMode) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Preparing Idle Mode is still True - Hence Rejecting control message\n"); Status = STATUS_FAILURE; goto cntrlEnd; } Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer); cntrlEnd: up(&Adapter->LowPowerModeSync); kfree(pvBuffer); break; } case IOCTL_BCM_BUFFER_DOWNLOAD_START: { if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n"); return -EACCES; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Starting the firmware download PID =0x%x!!!!\n", current->pid); if (down_trylock(&Adapter->fw_download_sema)) return -EBUSY; Adapter->bBinDownloaded = FALSE; Adapter->fw_download_process_pid = current->pid; Adapter->bCfgDownloaded = FALSE; Adapter->fw_download_done = FALSE; netif_carrier_off(Adapter->dev); netif_stop_queue(Adapter->dev); Status = reset_card_proc(Adapter); if (Status) { pr_err(PFX "%s: reset_card_proc Failed!\n", Adapter->dev->name); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } mdelay(10); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD: { struct bcm_firmware_info *psFwInfo = NULL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Starting the firmware download PID =0x%x!!!!\n", current->pid); if (!down_trylock(&Adapter->fw_download_sema)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Invalid way to download buffer. Use Start and then call this!!!\n"); up(&Adapter->fw_download_sema); Status = -EINVAL; return Status; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { up(&Adapter->fw_download_sema); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Length for FW DLD is : %lx\n", IoBuffer.InputLength); if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) { up(&Adapter->fw_download_sema); return -EINVAL; } psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL); if (!psFwInfo) { up(&Adapter->fw_download_sema); return -ENOMEM; } if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) { up(&Adapter->fw_download_sema); kfree(psFwInfo); return -EFAULT; } if (!psFwInfo->pvMappedFirmwareAddress || (psFwInfo->u32FirmwareLength == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Something else is wrong %lu\n", psFwInfo->u32FirmwareLength); up(&Adapter->fw_download_sema); kfree(psFwInfo); Status = -EINVAL; return Status; } Status = bcm_ioctl_fw_download(Adapter, psFwInfo); if (Status != STATUS_SUCCESS) { if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Configuration File Upload Failed\n"); else BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Firmware File Upload Failed\n"); /* up(&Adapter->fw_download_sema); */ if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = DRIVER_INIT; Adapter->LEDInfo.bLedInitDone = FALSE; wake_up(&Adapter->LEDInfo.notify_led_event); } } if (Status != STATUS_SUCCESS) up(&Adapter->fw_download_sema); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "IOCTL: Firmware File Uploaded\n"); kfree(psFwInfo); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: { if (!down_trylock(&Adapter->fw_download_sema)) { up(&Adapter->fw_download_sema); return -EINVAL; } if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "FW download blocked as EEPROM Read/Write is in progress\n"); up(&Adapter->fw_download_sema); return -EACCES; } Adapter->bBinDownloaded = TRUE; Adapter->bCfgDownloaded = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->downloadDDR = 0; /* setting the Mips to Run */ Status = run_card_proc(Adapter); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Firm Download Failed\n"); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Firm Download Over...\n"); } mdelay(10); /* Wait for MailBox Interrupt */ if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter)) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Unable to send interrupt...\n"); timeout = 5*HZ; Adapter->waiting_to_fw_download_done = FALSE; wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue, Adapter->waiting_to_fw_download_done, timeout); Adapter->fw_download_process_pid = INVALID_PID; Adapter->fw_download_done = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->PrevNumRecvDescs = 0; atomic_set(&Adapter->cntrlpktCnt, 0); Adapter->LinkUpStatus = 0; Adapter->LinkStatus = 0; if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = FW_DOWNLOAD_DONE; wake_up(&Adapter->LEDInfo.notify_led_event); } if (!timeout) Status = -ENODEV; up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BE_BUCKET_SIZE: Status = 0; if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_RTPS_BUCKET_SIZE: Status = 0; if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_CHIP_RESET: { INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock); if (NVMAccess) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, " IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n"); return -EACCES; } down(&Adapter->RxAppControlQueuelock); Status = reset_card_proc(Adapter); flushAllAppQ(); up(&Adapter->RxAppControlQueuelock); up(&Adapter->NVMRdmWrmLock); ResetCounters(Adapter); break; } case IOCTL_QOS_THRESHOLD: { USHORT uiLoopIndex; Status = 0; for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) { if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold, (unsigned long __user *)arg)) { Status = -EFAULT; break; } } break; } case IOCTL_DUMP_PACKET_INFO: DumpPackInfo(Adapter); DumpPhsRules(&Adapter->stBCMPhsContext); Status = STATUS_SUCCESS; break; case IOCTL_GET_PACK_INFO: if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES)) return -EFAULT; Status = STATUS_SUCCESS; break; case IOCTL_BCM_SWITCH_TRANSFER_MODE: { UINT uiData = 0; if (copy_from_user(&uiData, argp, sizeof(UINT))) return -EFAULT; if (uiData) { /* Allow All Packets */ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\n"); Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE; } else { /* Allow IP only Packets */ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\n"); Adapter->TransferMode = IP_PACKET_ONLY_MODE; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_DRIVER_VERSION: { ulong len; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1); if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len)) return -EFAULT; Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_CURRENT_STATUS: { struct bcm_link_state link_state; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user failed..\n"); return -EFAULT; } if (IoBuffer.OutputLength != sizeof(link_state)) { Status = -EINVAL; break; } memset(&link_state, 0, sizeof(link_state)); link_state.bIdleMode = Adapter->IdleMode; link_state.bShutdownMode = Adapter->bShutStatus; link_state.ucLinkStatus = Adapter->LinkStatus; if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy_to_user Failed..\n"); return -EFAULT; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_SET_MAC_TRACING: { UINT tracing_flag; /* copy ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if (tracing_flag) Adapter->pTarangs->MacTracingEnabled = TRUE; else Adapter->pTarangs->MacTracingEnabled = FALSE; break; } case IOCTL_BCM_GET_DSX_INDICATION: { ULONG ulSFId = 0; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Mismatch req: %lx needed is =0x%zx!!!", IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt)); return -EINVAL; } if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Get DSX Data SF ID is =%lx\n", ulSFId); get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_GET_HOST_MIBS: { PVOID temp_buff; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Length Check failed %lu %zd\n", IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs)); return -EINVAL; } /* FIXME: HOST_STATS are too big for kmalloc (122048)! */ temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; Status = ProcessGetHostMibs(Adapter, temp_buff); GetDroppedAppCntrlPktMibs(temp_buff, pTarang); if (Status != STATUS_FAILURE) if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) { kfree(temp_buff); return -EFAULT; } kfree(temp_buff); break; } case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE: if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) { Adapter->usIdleModePattern = ABORT_IDLE_MODE; Adapter->bWakeUpDevice = TRUE; wake_up(&Adapter->process_rx_cntrlpkt); } Status = STATUS_SUCCESS; break; case IOCTL_BCM_BULK_WRM: { struct bcm_bulk_wrm_buffer *pBulkBuffer; UINT uiTempVar = 0; PCHAR pvBuffer = NULL; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle/Shutdown Mode, Blocking Wrms\n"); Status = -EACCES; break; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(ULONG) * 2) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer; if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 || ((ULONG)pBulkBuffer->Register & 0x3)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)pBulkBuffer->Register); kfree(pvBuffer); Status = -EINVAL; break; } uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { kfree(pvBuffer); BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n"); Status = -EFAULT; break; } if (pBulkBuffer->SwapEndian == FALSE) Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); else Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); if (Status != STATUS_SUCCESS) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Failed\n"); kfree(pvBuffer); break; } case IOCTL_BCM_GET_NVM_SIZE: if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT))) return -EFAULT; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_CAL_INIT: { UINT uiSectorSize = 0 ; if (Adapter->eNVMType == NVM_FLASH) { if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if (IsFlash2x(Adapter)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is in Idle/Shutdown Mode\n"); return -EACCES; } Adapter->uiSectorSize = uiSectorSize; BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize); } } Status = STATUS_SUCCESS; } else { Status = STATUS_FAILURE; } } break; case IOCTL_BCM_SET_DEBUG: #ifdef DEBUG { struct bcm_user_debug_state sUserDebugState; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "In SET_DEBUG ioctl\n"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state))) return -EFAULT; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x ", sUserDebugState.OnOff, sUserDebugState.Type); /* sUserDebugState.Subtype <<= 1; */ sUserDebugState.Subtype = 1 << sUserDebugState.Subtype; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "actual Subtype=0x%x\n", sUserDebugState.Subtype); /* Update new 'DebugState' in the Adapter */ Adapter->stDebugState.type |= sUserDebugState.Type; /* Subtype: A bitmap of 32 bits for Subtype per Type. * Valid indexes in 'subtype' array: 1,2,4,8 * corresponding to valid Type values. Hence we can use the 'Type' field * as the index value, ignoring the array entries 0,3,5,6,7 ! */ if (sUserDebugState.OnOff) Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype; else Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype; BCM_SHOW_DEBUG_BITMAP(Adapter); } #endif break; case IOCTL_BCM_NVM_READ: case IOCTL_BCM_NVM_WRITE: { struct bcm_nvm_readwrite stNVMReadWrite; PUCHAR pReadData = NULL; ULONG ulDSDMagicNumInUsrBuff = 0; struct timeval tv0, tv1; memset(&tv0, 0, sizeof(struct timeval)); memset(&tv1, 0, sizeof(struct timeval)); if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\n"); return -EFAULT; } if (IsFlash2x(Adapter)) { if ((Adapter->eActiveDSD != DSD0) && (Adapter->eActiveDSD != DSD1) && (Adapter->eActiveDSD != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "No DSD is active..hence NVM Command is blocked"); return STATUS_FAILURE; } } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&stNVMReadWrite, (IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; /* * Deny the access if the offset crosses the cal area limit. */ if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize) return STATUS_FAILURE; if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) { /* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Can't allow access beyond NVM Size: 0x%x 0x%x\n", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */ return STATUS_FAILURE; } pReadData = memdup_user(stNVMReadWrite.pBuffer, stNVMReadWrite.uiNumBytes); if (IS_ERR(pReadData)) return PTR_ERR(pReadData); do_gettimeofday(&tv0); if (IOCTL_BCM_NVM_READ == cmd) { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) { kfree(pReadData); return -EFAULT; } } else { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Adapter->bHeaderChangeAllowed = TRUE; if (IsFlash2x(Adapter)) { /* * New Requirement:- * DSD section updation will be allowed in two case:- * 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull * 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is * corrupted then user space program first modify the DSD header with valid DSD sig so * that this as well as further write may be worthwhile. * * This restriction has been put assuming that if DSD sig is corrupted, DSD * data won't be considered valid. */ Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD); if (Status != STATUS_SUCCESS) { if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) || (stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input.."); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE)); if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input.."); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } } } Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify); if (IsFlash2x(Adapter)) BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD); Adapter->bHeaderChangeAllowed = FALSE; up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } } do_gettimeofday(&tv1); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " timetaken by Write/read :%ld msec\n", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000); kfree(pReadData); return STATUS_SUCCESS; } case IOCTL_BCM_FLASH2X_SECTION_READ: { struct bcm_flash2x_readwrite sFlash2xRead = {0}; PUCHAR pReadBuff = NULL ; UINT NOB = 0; UINT BuffSize = 0; UINT ReadBytes = 0; UINT ReadOffset = 0; void __user *OutPutBuff; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map"); return -EINVAL; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_READ Called"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; /* Reading FLASH 2.x READ structure */ if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xRead.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%x", sFlash2xRead.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xRead.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xRead.bVerify); /* This was internal to driver for raw read. now it has ben exposed to user space app. */ if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE) return STATUS_FAILURE; NOB = sFlash2xRead.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB; ReadOffset = sFlash2xRead.offset ; OutPutBuff = IoBuffer.OutputBuffer; pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure"); return -ENOMEM; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EACCES; } while (NOB) { if (NOB > Adapter->uiSectorSize) ReadBytes = Adapter->uiSectorSize; else ReadBytes = NOB; /* Reading the data from Flash 2.x */ Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Flash 2x read err with Status :%d", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Copy to use failed with status :%d", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes ; } } up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); } break; case IOCTL_BCM_FLASH2X_SECTION_WRITE: { struct bcm_flash2x_readwrite sFlash2xWrite = {0}; PUCHAR pWriteBuff; void __user *InputAddr; UINT NOB = 0; UINT BuffSize = 0; UINT WriteOffset = 0; UINT WriteBytes = 0; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map"); return -EINVAL; } /* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_WRITE Called"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; /* Reading FLASH 2.x READ structure */ if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xWrite.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%d", sFlash2xWrite.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xWrite.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xWrite.bVerify); if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Only VSA write is allowed"); return -EINVAL; } if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE) return STATUS_FAILURE; InputAddr = sFlash2xWrite.pDataBuff; WriteOffset = sFlash2xWrite.offset; NOB = sFlash2xWrite.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB ; pWriteBuff = kmalloc(BuffSize, GFP_KERNEL); if (pWriteBuff == NULL) return -ENOMEM; /* extracting the remainder of the given offset. */ WriteBytes = Adapter->uiSectorSize; if (WriteOffset % Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize); if (NOB < WriteBytes) WriteBytes = NOB; down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EACCES; } BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section); do { Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to user failed with status :%d", Status); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EFAULT; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes); /* Writing the data from Flash 2.x */ Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status); break; } NOB = NOB - WriteBytes; if (NOB) { WriteOffset = WriteOffset + WriteBytes; InputAddr = InputAddr + WriteBytes; if (NOB > Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize; else WriteBytes = NOB; } } while (NOB > 0); BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); } break; case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: { struct bcm_flash2x_bitmap *psFlash2xBitMap; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap)) return -EINVAL; psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL); if (psFlash2xBitMap == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory is not available"); return -ENOMEM; } /* Reading the Flash Sectio Bit map */ down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); kfree(psFlash2xBitMap); return -EACCES; } BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap); up(&Adapter->NVMRdmWrmLock); if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) { kfree(psFlash2xBitMap); return -EFAULT; } kfree(psFlash2xBitMap); } break; case IOCTL_BCM_SET_ACTIVE_SECTION: { enum bcm_flash2x_section_val eFlash2xSectionVal = 0; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SET_ACTIVE_SECTION Called"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed"); return -EFAULT; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal); if (Status) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed to make it's priority Highest. Status %d", Status); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: { /* Right Now we are taking care of only DSD */ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called"); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_COPY_SECTION: { struct bcm_flash2x_copy_section sCopySectStrut = {0}; Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_COPY_SECTION Called"); Adapter->bAllDSDWriteAllow = FALSE; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed Status :%d", Status); return -EFAULT; } Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of Copy_Section_Struct failed with Status :%d", Status); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source SEction :%x", sCopySectStrut.SrcSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Destination SEction :%x", sCopySectStrut.DstSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "offset :%x", sCopySectStrut.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "NOB :%x", sCopySectStrut.numOfBytes); if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Source Section<%x> does not exixt in Flash ", sCopySectStrut.SrcSection); return -EINVAL; } if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Destinatio Section<%x> does not exixt in Flash ", sCopySectStrut.DstSection); return -EINVAL; } if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source and Destination section should be different"); return -EINVAL; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) { if (IsNonCDLessDevice(Adapter)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is Non-CDLess hence won't have ISO !!"); Status = -EINVAL; } else if (sCopySectStrut.numOfBytes == 0) { Status = BcmCopyISO(Adapter, sCopySectStrut); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Partial Copy of ISO section is not Allowed.."); Status = STATUS_FAILURE; } up(&Adapter->NVMRdmWrmLock); return Status; } Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection, sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_GET_FLASH_CS_INFO: { Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " IOCTL_BCM_GET_FLASH_CS_INFO Called"); Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed"); return -EFAULT; } if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Connected device does not have flash"); Status = -EINVAL; break; } if (IsFlash2x(Adapter) == TRUE) { if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info))) return -EFAULT; } else { if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info))) return -EFAULT; } } break; case IOCTL_BCM_SELECT_DSD: { UINT SectOfset = 0; enum bcm_flash2x_section_val eFlash2xSectionVal; eFlash2xSectionVal = NO_SECTION_VAL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SELECT_DSD Called"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Read Section :%d", eFlash2xSectionVal); if ((eFlash2xSectionVal != DSD0) && (eFlash2xSectionVal != DSD1) && (eFlash2xSectionVal != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Passed section<%x> is not DSD section", eFlash2xSectionVal); return STATUS_FAILURE; } SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal); if (SectOfset == INVALID_OFFSET) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Provided Section val <%d> does not exixt in Flash 2.x", eFlash2xSectionVal); return -EINVAL; } Adapter->bAllDSDWriteAllow = TRUE; Adapter->ulFlashCalStart = SectOfset; Adapter->eActiveDSD = eFlash2xSectionVal; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_NVM_RAW_READ: { struct bcm_nvm_readwrite stNVMRead; INT NOB ; INT BuffSize ; INT ReadOffset = 0; UINT ReadBytes = 0 ; PUCHAR pReadBuff; void __user *OutPutBuff; if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "NVM TYPE is not Flash"); return -EINVAL; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user 1 failed\n"); return -EFAULT; } if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; NOB = stNVMRead.uiNumBytes; /* In Raw-Read max Buff size : 64MB */ if (NOB > DEFAULT_BUFF_SIZE) BuffSize = DEFAULT_BUFF_SIZE; else BuffSize = NOB; ReadOffset = stNVMRead.uiOffset; OutPutBuff = stNVMRead.pBuffer; pReadBuff = kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure"); Status = -ENOMEM; break; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n"); kfree(pReadBuff); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Adapter->bFlashRawRead = TRUE; while (NOB) { if (NOB > DEFAULT_BUFF_SIZE) ReadBytes = DEFAULT_BUFF_SIZE; else ReadBytes = NOB; /* Reading the data from Flash 2.x */ Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to use failed with status :%d", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes; } } Adapter->bFlashRawRead = FALSE; up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); break; } case IOCTL_BCM_CNTRLMSG_MASK: { ULONG RxCntrlMsgBitMask = 0; /* Copy Ioctl Buffer structure */ Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of Ioctl buffer is failed from user space"); return -EFAULT; } if (IoBuffer.InputLength != sizeof(unsigned long)) { Status = -EINVAL; break; } Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of control bit mask failed from user space"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\n Got user defined cntrl msg bit mask :%lx", RxCntrlMsgBitMask); pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask; } break; case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: { struct bcm_driver_info DevInfo; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\n"); DevInfo.MaxRDMBufferSize = BUFFER_4K; DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START; DevInfo.u32RxAlignmentCorrection = 0; DevInfo.u32NVMType = Adapter->eNVMType; DevInfo.u32InterfaceType = BCM_USB; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(DevInfo)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo))) return -EFAULT; } break; case IOCTL_BCM_TIME_SINCE_NET_ENTRY: { struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0}; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_TIME_SINCE_NET_ENTRY called"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed)) return -EINVAL; stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry; if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed))) return -EFAULT; } break; case IOCTL_CLOSE_NOTIFICATION: BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_CLOSE_NOTIFICATION"); break; default: pr_info(DRV_NAME ": unknown ioctl cmd=%#x\n", cmd); Status = STATUS_FAILURE; break; } return Status; } static const struct file_operations bcm_fops = { .owner = THIS_MODULE, .open = bcm_char_open, .release = bcm_char_release, .read = bcm_char_read, .unlocked_ioctl = bcm_char_ioctl, .llseek = no_llseek, }; int register_control_device_interface(struct bcm_mini_adapter *Adapter) { if (Adapter->major > 0) return Adapter->major; Adapter->major = register_chrdev(0, DEV_NAME, &bcm_fops); if (Adapter->major < 0) { pr_err(DRV_NAME ": could not created character device\n"); return Adapter->major; } Adapter->pstCreatedClassDevice = device_create(bcm_class, NULL, MKDEV(Adapter->major, 0), Adapter, DEV_NAME); if (IS_ERR(Adapter->pstCreatedClassDevice)) { pr_err(DRV_NAME ": class device create failed\n"); unregister_chrdev(Adapter->major, DEV_NAME); return PTR_ERR(Adapter->pstCreatedClassDevice); } return 0; } void unregister_control_device_interface(struct bcm_mini_adapter *Adapter) { if (Adapter->major > 0) { device_destroy(bcm_class, MKDEV(Adapter->major, 0)); unregister_chrdev(Adapter->major, DEV_NAME); } }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5759_0
crossvul-cpp_data_good_3832_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; haddr->hci_channel= 0; 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; memset(&uf, 0, sizeof(uf)); 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/good_3832_0
crossvul-cpp_data_good_953_0
/* * Copyright (c) Dan Harkins, 2012 * * Copyright holder grants permission for redistribution and use in source * and binary forms, with or without modification, provided that the * following conditions are met: * 1. Redistribution of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer * in all source files. * 2. Redistribution in binary form must retain the above copyright * notice, this list of conditions, and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * "DISCLAIMER OF LIABILITY * * THIS SOFTWARE IS PROVIDED BY DAN HARKINS ``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 INDUSTRIAL LOUNGE 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." * * This license and distribution terms cannot be changed. In other words, * this code cannot simply be copied and put under a different distribution * license (including the GNU public license). */ RCSID("$Id$") USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */ #include "eap_pwd.h" #include <freeradius-devel/radiusd.h> #include <freeradius-devel/modules.h> /* The random function H(x) = HMAC-SHA256(0^32, x) */ static void H_Init(HMAC_CTX *ctx) { uint8_t allzero[SHA256_DIGEST_LENGTH]; memset(allzero, 0, SHA256_DIGEST_LENGTH); HMAC_Init_ex(ctx, allzero, SHA256_DIGEST_LENGTH, EVP_sha256(), NULL); } static void H_Update(HMAC_CTX *ctx, uint8_t const *data, int len) { HMAC_Update(ctx, data, len); } static void H_Final(HMAC_CTX *ctx, uint8_t *digest) { unsigned int mdlen = SHA256_DIGEST_LENGTH; HMAC_Final(ctx, digest, &mdlen); } /* a counter-based KDF based on NIST SP800-108 */ static int eap_pwd_kdf(uint8_t *key, int keylen, char const *label, int labellen, uint8_t *result, int resultbitlen) { HMAC_CTX *hctx = NULL; uint8_t digest[SHA256_DIGEST_LENGTH]; uint16_t i, ctr, L; int resultbytelen, len = 0; unsigned int mdlen = SHA256_DIGEST_LENGTH; uint8_t mask = 0xff; hctx = HMAC_CTX_new(); if (hctx == NULL) { DEBUG("failed allocating HMAC context"); return -1; } resultbytelen = (resultbitlen + 7)/8; ctr = 0; L = htons(resultbitlen); while (len < resultbytelen) { ctr++; i = htons(ctr); HMAC_Init_ex(hctx, key, keylen, EVP_sha256(), NULL); if (ctr > 1) { HMAC_Update(hctx, digest, mdlen); } HMAC_Update(hctx, (uint8_t *) &i, sizeof(uint16_t)); HMAC_Update(hctx, (uint8_t const *)label, labellen); HMAC_Update(hctx, (uint8_t *) &L, sizeof(uint16_t)); HMAC_Final(hctx, digest, &mdlen); if ((len + (int) mdlen) > resultbytelen) { memcpy(result + len, digest, resultbytelen - len); } else { memcpy(result + len, digest, mdlen); } len += mdlen; } HMAC_CTX_free(hctx); /* since we're expanding to a bit length, mask off the excess */ if (resultbitlen % 8) { mask <<= (8 - (resultbitlen % 8)); result[resultbytelen - 1] &= mask; } return 0; } int compute_password_element (pwd_session_t *session, uint16_t grp_num, char const *password, int password_len, char const *id_server, int id_server_len, char const *id_peer, int id_peer_len, uint32_t *token) { BIGNUM *x_candidate = NULL, *rnd = NULL, *cofactor = NULL; HMAC_CTX *ctx = NULL; uint8_t pwe_digest[SHA256_DIGEST_LENGTH], *prfbuf = NULL, ctr; int nid, is_odd, primebitlen, primebytelen, ret = 0; ctx = HMAC_CTX_new(); if (ctx == NULL) { DEBUG("failed allocating HMAC context"); goto fail; } switch (grp_num) { /* from IANA registry for IKE D-H groups */ case 19: nid = NID_X9_62_prime256v1; break; case 20: nid = NID_secp384r1; break; case 21: nid = NID_secp521r1; break; case 25: nid = NID_X9_62_prime192v1; break; case 26: nid = NID_secp224r1; break; default: DEBUG("unknown group %d", grp_num); goto fail; } session->pwe = NULL; session->order = NULL; session->prime = NULL; if ((session->group = EC_GROUP_new_by_curve_name(nid)) == NULL) { DEBUG("unable to create EC_GROUP"); goto fail; } if (((rnd = BN_new()) == NULL) || ((cofactor = BN_new()) == NULL) || ((session->pwe = EC_POINT_new(session->group)) == NULL) || ((session->order = BN_new()) == NULL) || ((session->prime = BN_new()) == NULL) || ((x_candidate = BN_new()) == NULL)) { DEBUG("unable to create bignums"); goto fail; } if (!EC_GROUP_get_curve_GFp(session->group, session->prime, NULL, NULL, NULL)) { DEBUG("unable to get prime for GFp curve"); goto fail; } if (!EC_GROUP_get_order(session->group, session->order, NULL)) { DEBUG("unable to get order for curve"); goto fail; } if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) { DEBUG("unable to get cofactor for curve"); goto fail; } primebitlen = BN_num_bits(session->prime); primebytelen = BN_num_bytes(session->prime); if ((prfbuf = talloc_zero_array(session, uint8_t, primebytelen)) == NULL) { DEBUG("unable to alloc space for prf buffer"); goto fail; } ctr = 0; while (1) { if (ctr > 100) { DEBUG("unable to find random point on curve for group %d, something's fishy", grp_num); goto fail; } ctr++; /* * compute counter-mode password value and stretch to prime * pwd-seed = H(token | peer-id | server-id | password | * counter) */ H_Init(ctx); H_Update(ctx, (uint8_t *)token, sizeof(*token)); H_Update(ctx, (uint8_t const *)id_peer, id_peer_len); H_Update(ctx, (uint8_t const *)id_server, id_server_len); H_Update(ctx, (uint8_t const *)password, password_len); H_Update(ctx, (uint8_t *)&ctr, sizeof(ctr)); H_Final(ctx, pwe_digest); BN_bin2bn(pwe_digest, SHA256_DIGEST_LENGTH, rnd); if (eap_pwd_kdf(pwe_digest, SHA256_DIGEST_LENGTH, "EAP-pwd Hunting And Pecking", strlen("EAP-pwd Hunting And Pecking"), prfbuf, primebitlen) != 0) { DEBUG("key derivation function failed"); goto fail; } BN_bin2bn(prfbuf, primebytelen, x_candidate); /* * eap_pwd_kdf() returns a string of bits 0..primebitlen but * BN_bin2bn will treat that string of bits as a big endian * number. If the primebitlen is not an even multiple of 8 * then excessive bits-- those _after_ primebitlen-- so now * we have to shift right the amount we masked off. */ if (primebitlen % 8) BN_rshift(x_candidate, x_candidate, (8 - (primebitlen % 8))); if (BN_ucmp(x_candidate, session->prime) >= 0) continue; /* * need to unambiguously identify the solution, if there is * one... */ is_odd = BN_is_odd(rnd) ? 1 : 0; /* * solve the quadratic equation, if it's not solvable then we * don't have a point */ if (!EC_POINT_set_compressed_coordinates_GFp(session->group, session->pwe, x_candidate, is_odd, NULL)) { continue; } /* * If there's a solution to the equation then the point must be * on the curve so why check again explicitly? OpenSSL code * says this is required by X9.62. We're not X9.62 but it can't * hurt just to be sure. */ if (!EC_POINT_is_on_curve(session->group, session->pwe, NULL)) { DEBUG("EAP-pwd: point is not on curve"); continue; } if (BN_cmp(cofactor, BN_value_one())) { /* make sure the point is not in a small sub-group */ if (!EC_POINT_mul(session->group, session->pwe, NULL, session->pwe, cofactor, NULL)) { DEBUG("EAP-pwd: cannot multiply generator by order"); continue; } if (EC_POINT_is_at_infinity(session->group, session->pwe)) { DEBUG("EAP-pwd: point is at infinity"); continue; } } /* if we got here then we have a new generator. */ break; } session->group_num = grp_num; if (0) { fail: /* DON'T free session, it's in handler->opaque */ ret = -1; } /* cleanliness and order.... */ BN_clear_free(cofactor); BN_clear_free(x_candidate); BN_clear_free(rnd); talloc_free(prfbuf); HMAC_CTX_free(ctx); return ret; } int compute_scalar_element (pwd_session_t *session, BN_CTX *bnctx) { BIGNUM *mask = NULL; int ret = -1; if (((session->private_value = BN_new()) == NULL) || ((session->my_element = EC_POINT_new(session->group)) == NULL) || ((session->my_scalar = BN_new()) == NULL) || ((mask = BN_new()) == NULL)) { DEBUG2("server scalar allocation failed"); goto fail; } if (BN_rand_range(session->private_value, session->order) != 1) { DEBUG2("Unable to get randomness for private_value"); goto fail; } if (BN_rand_range(mask, session->order) != 1) { DEBUG2("Unable to get randomness for mask"); goto fail; } BN_add(session->my_scalar, session->private_value, mask); BN_mod(session->my_scalar, session->my_scalar, session->order, bnctx); if (!EC_POINT_mul(session->group, session->my_element, NULL, session->pwe, mask, bnctx)) { DEBUG2("server element allocation failed"); goto fail; } if (!EC_POINT_invert(session->group, session->my_element, bnctx)) { DEBUG2("server element inversion failed"); goto fail; } ret = 0; fail: BN_clear_free(mask); return ret; } int process_peer_commit (pwd_session_t *session, uint8_t *in, size_t in_len, BN_CTX *bnctx) { uint8_t *ptr; size_t data_len; BIGNUM *x = NULL, *y = NULL, *cofactor = NULL; EC_POINT *K = NULL, *point = NULL; int res = 1; if (((session->peer_scalar = BN_new()) == NULL) || ((session->k = BN_new()) == NULL) || ((cofactor = BN_new()) == NULL) || ((x = BN_new()) == NULL) || ((y = BN_new()) == NULL) || ((point = EC_POINT_new(session->group)) == NULL) || ((K = EC_POINT_new(session->group)) == NULL) || ((session->peer_element = EC_POINT_new(session->group)) == NULL)) { DEBUG2("pwd: failed to allocate room to process peer's commit"); goto finish; } if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) { DEBUG2("pwd: unable to get group co-factor"); goto finish; } /* element, x then y, followed by scalar */ ptr = (uint8_t *)in; data_len = BN_num_bytes(session->prime); /* * Did the peer send enough data? */ if (in_len < (2 * data_len + BN_num_bytes(session->order))) { DEBUG("pwd: Invalid commit packet"); goto finish; } BN_bin2bn(ptr, data_len, x); ptr += data_len; BN_bin2bn(ptr, data_len, y); ptr += data_len; data_len = BN_num_bytes(session->order); BN_bin2bn(ptr, data_len, session->peer_scalar); /* validate received scalar */ if (BN_is_zero(session->peer_scalar) || BN_is_one(session->peer_scalar) || BN_cmp(session->peer_scalar, session->order) >= 0) { ERROR("Peer's scalar is not within the allowed range"); goto finish; } if (!EC_POINT_set_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of peer's element"); goto finish; } /* validate received element */ if (!EC_POINT_is_on_curve(session->group, session->peer_element, bnctx) || EC_POINT_is_at_infinity(session->group, session->peer_element)) { ERROR("Peer's element is not a point on the elliptic curve"); goto finish; } /* check to ensure peer's element is not in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(session->group, point, NULL, session->peer_element, cofactor, NULL)) { DEBUG2("pwd: unable to multiply element by co-factor"); goto finish; } if (EC_POINT_is_at_infinity(session->group, point)) { DEBUG2("pwd: peer's element is in small sub-group"); goto finish; } } /* detect reflection attacks */ if (BN_cmp(session->peer_scalar, session->my_scalar) == 0 || EC_POINT_cmp(session->group, session->peer_element, session->my_element, bnctx) == 0) { ERROR("Reflection attack detected"); goto finish; } /* compute the shared key, k */ if ((!EC_POINT_mul(session->group, K, NULL, session->pwe, session->peer_scalar, bnctx)) || (!EC_POINT_add(session->group, K, K, session->peer_element, bnctx)) || (!EC_POINT_mul(session->group, K, NULL, K, session->private_value, bnctx))) { DEBUG2("pwd: unable to compute shared key, k"); goto finish; } /* ensure that the shared key isn't in a small sub-group */ if (BN_cmp(cofactor, BN_value_one())) { if (!EC_POINT_mul(session->group, K, NULL, K, cofactor, NULL)) { DEBUG2("pwd: unable to multiply k by co-factor"); goto finish; } } /* * This check is strictly speaking just for the case above where * co-factor > 1 but it was suggested that even though this is probably * never going to happen it is a simple and safe check "just to be * sure" so let's be safe. */ if (EC_POINT_is_at_infinity(session->group, K)) { DEBUG2("pwd: k is point-at-infinity!"); goto finish; } if (!EC_POINT_get_affine_coordinates_GFp(session->group, K, session->k, NULL, bnctx)) { DEBUG2("pwd: unable to get shared secret from K"); goto finish; } res = 0; finish: EC_POINT_clear_free(K); EC_POINT_clear_free(point); BN_clear_free(cofactor); BN_clear_free(x); BN_clear_free(y); return res; } int compute_server_confirm (pwd_session_t *session, uint8_t *out, BN_CTX *bnctx) { BIGNUM *x = NULL, *y = NULL; HMAC_CTX *ctx = NULL; uint8_t *cruft = NULL; int offset, req = -1; ctx = HMAC_CTX_new(); if (ctx == NULL) { DEBUG2("pwd: unable to allocate HMAC context!"); goto finish; } /* * Each component of the cruft will be at most as big as the prime */ if (((cruft = talloc_zero_array(session, uint8_t, BN_num_bytes(session->prime))) == NULL) || ((x = BN_new()) == NULL) || ((y = BN_new()) == NULL)) { DEBUG2("pwd: unable to allocate space to compute confirm!"); goto finish; } /* * commit is H(k | server_element | server_scalar | peer_element | * peer_scalar | ciphersuite) */ H_Init(ctx); /* * Zero the memory each time because this is mod prime math and some * value may start with a few zeros and the previous one did not. * * First is k */ offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k); BN_bn2bin(session->k, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); /* * next is server element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->my_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of server element"); goto finish; } memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); /* * and server scalar */ memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar); BN_bn2bin(session->my_scalar, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->order)); /* * next is peer element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of peer's element"); goto finish; } memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); /* * and peer scalar */ memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar); BN_bn2bin(session->peer_scalar, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->order)); /* * finally, ciphersuite */ H_Update(ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite)); H_Final(ctx, out); req = 0; finish: talloc_free(cruft); BN_free(x); BN_free(y); HMAC_CTX_free(ctx); return req; } int compute_peer_confirm (pwd_session_t *session, uint8_t *out, BN_CTX *bnctx) { BIGNUM *x = NULL, *y = NULL; HMAC_CTX *ctx = NULL; uint8_t *cruft = NULL; int offset, req = -1; ctx = HMAC_CTX_new(); if (ctx == NULL) { DEBUG2("pwd: unable to allocate HMAC context!"); goto finish; } /* * Each component of the cruft will be at most as big as the prime */ if (((cruft = talloc_zero_array(session, uint8_t, BN_num_bytes(session->prime))) == NULL) || ((x = BN_new()) == NULL) || ((y = BN_new()) == NULL)) { DEBUG2("pwd: unable to allocate space to compute confirm!"); goto finish; } /* * commit is H(k | server_element | server_scalar | peer_element | * peer_scalar | ciphersuite) */ H_Init(ctx); /* * Zero the memory each time because this is mod prime math and some * value may start with a few zeros and the previous one did not. * * First is k */ offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k); BN_bn2bin(session->k, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); /* * then peer element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of peer's element"); goto finish; } memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); /* * and peer scalar */ memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar); BN_bn2bin(session->peer_scalar, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->order)); /* * then server element: x, y */ if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->my_element, x, y, bnctx)) { DEBUG2("pwd: unable to get coordinates of server element"); goto finish; } memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(x); BN_bn2bin(x, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(y); BN_bn2bin(y, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); /* * and server scalar */ memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar); BN_bn2bin(session->my_scalar, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->order)); /* * finally, ciphersuite */ H_Update(ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite)); H_Final(ctx, out); req = 0; finish: talloc_free(cruft); BN_free(x); BN_free(y); HMAC_CTX_free(ctx); return req; } int compute_keys (pwd_session_t *session, uint8_t *peer_confirm, uint8_t *msk, uint8_t *emsk) { HMAC_CTX *ctx = NULL; uint8_t mk[SHA256_DIGEST_LENGTH], *cruft = NULL; uint8_t session_id[SHA256_DIGEST_LENGTH + 1]; uint8_t msk_emsk[128]; /* 64 each */ int offset, ret = -1; ctx = HMAC_CTX_new(); if (ctx == NULL) { DEBUG2("pwd: unable to allocate HMAC context!"); goto finish; } if ((cruft = talloc_array(session, uint8_t, BN_num_bytes(session->prime))) == NULL) { DEBUG2("pwd: unable to allocate space to compute keys"); goto finish; } /* * first compute the session-id = TypeCode | H(ciphersuite | scal_p | * scal_s) */ session_id[0] = PW_EAP_PWD; H_Init(ctx); H_Update(ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite)); offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar); memset(cruft, 0, BN_num_bytes(session->prime)); BN_bn2bin(session->peer_scalar, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->order)); offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar); memset(cruft, 0, BN_num_bytes(session->prime)); BN_bn2bin(session->my_scalar, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->order)); H_Final(ctx, (uint8_t *)&session_id[1]); /* then compute MK = H(k | commit-peer | commit-server) */ H_Init(ctx); memset(cruft, 0, BN_num_bytes(session->prime)); offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k); BN_bn2bin(session->k, cruft + offset); H_Update(ctx, cruft, BN_num_bytes(session->prime)); H_Update(ctx, peer_confirm, SHA256_DIGEST_LENGTH); H_Update(ctx, session->my_confirm, SHA256_DIGEST_LENGTH); H_Final(ctx, mk); /* stretch the mk with the session-id to get MSK | EMSK */ if (eap_pwd_kdf(mk, SHA256_DIGEST_LENGTH, (char const *)session_id, SHA256_DIGEST_LENGTH + 1, msk_emsk, /* it's bits, ((64 + 64) * 8) */ 1024) != 0) { DEBUG("key derivation function failed"); goto finish; } memcpy(msk, msk_emsk, 64); memcpy(emsk, msk_emsk + 64, 64); ret = 0; finish: talloc_free(cruft); HMAC_CTX_free(ctx); return ret; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_953_0
crossvul-cpp_data_bad_5693_0
/* * Copyright (C) 2011 Intel Corporation. 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; 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. */ #define pr_fmt(fmt) "llcp: %s: " fmt, __func__ #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/nfc.h> #include "../nfc.h" #include "llcp.h" static int sock_wait_state(struct sock *sk, int state, unsigned long timeo) { DECLARE_WAITQUEUE(wait, current); int err = 0; pr_debug("sk %p", sk); add_wait_queue(sk_sleep(sk), &wait); set_current_state(TASK_INTERRUPTIBLE); while (sk->sk_state != state) { if (!timeo) { err = -EINPROGRESS; 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_INTERRUPTIBLE); err = sock_error(sk); if (err) break; } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); return err; } static struct proto llcp_sock_proto = { .name = "NFC_LLCP", .owner = THIS_MODULE, .obj_size = sizeof(struct nfc_llcp_sock), }; static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_local *local; struct nfc_dev *dev; struct sockaddr_nfc_llcp llcp_addr; int len, ret = 0; if (!addr || addr->sa_family != AF_NFC) return -EINVAL; pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family); memset(&llcp_addr, 0, sizeof(llcp_addr)); len = min_t(unsigned int, sizeof(llcp_addr), alen); memcpy(&llcp_addr, addr, len); /* This is going to be a listening socket, dsap must be 0 */ if (llcp_addr.dsap != 0) return -EINVAL; lock_sock(sk); if (sk->sk_state != LLCP_CLOSED) { ret = -EBADFD; goto error; } dev = nfc_get_device(llcp_addr.dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->nfc_protocol = llcp_addr.nfc_protocol; llcp_sock->service_name_len = min_t(unsigned int, llcp_addr.service_name_len, NFC_LLCP_MAX_SERVICE_NAME); llcp_sock->service_name = kmemdup(llcp_addr.service_name, llcp_sock->service_name_len, GFP_KERNEL); llcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock); if (llcp_sock->ssap == LLCP_SAP_MAX) { ret = -EADDRINUSE; goto put_dev; } llcp_sock->reserved_ssap = llcp_sock->ssap; nfc_llcp_sock_link(&local->sockets, sk); pr_debug("Socket bound to SAP %d\n", llcp_sock->ssap); sk->sk_state = LLCP_BOUND; put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; } static int llcp_raw_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_local *local; struct nfc_dev *dev; struct sockaddr_nfc_llcp llcp_addr; int len, ret = 0; if (!addr || addr->sa_family != AF_NFC) return -EINVAL; pr_debug("sk %p addr %p family %d\n", sk, addr, addr->sa_family); memset(&llcp_addr, 0, sizeof(llcp_addr)); len = min_t(unsigned int, sizeof(llcp_addr), alen); memcpy(&llcp_addr, addr, len); lock_sock(sk); if (sk->sk_state != LLCP_CLOSED) { ret = -EBADFD; goto error; } dev = nfc_get_device(llcp_addr.dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->nfc_protocol = llcp_addr.nfc_protocol; nfc_llcp_sock_link(&local->raw_sockets, sk); sk->sk_state = LLCP_BOUND; put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; } static int llcp_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int ret = 0; pr_debug("sk %p backlog %d\n", sk, backlog); lock_sock(sk); if ((sock->type != SOCK_SEQPACKET && sock->type != SOCK_STREAM) || sk->sk_state != LLCP_BOUND) { ret = -EBADFD; goto error; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; pr_debug("Socket listening\n"); sk->sk_state = LLCP_LISTEN; error: release_sock(sk); return ret; } void nfc_llcp_accept_unlink(struct sock *sk) { struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); pr_debug("state %d\n", sk->sk_state); list_del_init(&llcp_sock->accept_queue); sk_acceptq_removed(llcp_sock->parent); llcp_sock->parent = NULL; sock_put(sk); } void nfc_llcp_accept_enqueue(struct sock *parent, struct sock *sk) { struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_sock *llcp_sock_parent = nfc_llcp_sock(parent); /* Lock will be free from unlink */ sock_hold(sk); list_add_tail(&llcp_sock->accept_queue, &llcp_sock_parent->accept_queue); llcp_sock->parent = parent; sk_acceptq_added(parent); } struct sock *nfc_llcp_accept_dequeue(struct sock *parent, struct socket *newsock) { struct nfc_llcp_sock *lsk, *n, *llcp_parent; struct sock *sk; llcp_parent = nfc_llcp_sock(parent); list_for_each_entry_safe(lsk, n, &llcp_parent->accept_queue, accept_queue) { sk = &lsk->sk; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED) { release_sock(sk); nfc_llcp_accept_unlink(sk); continue; } if (sk->sk_state == LLCP_CONNECTED || !newsock) { list_del_init(&lsk->accept_queue); sock_put(sk); if (newsock) sock_graft(sk, newsock); release_sock(sk); pr_debug("Returning sk state %d\n", sk->sk_state); sk_acceptq_removed(parent); return sk; } release_sock(sk); } return NULL; } static int llcp_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *new_sk; long timeo; int ret = 0; pr_debug("parent %p\n", sk); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != LLCP_LISTEN) { ret = -EBADFD; goto error; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); /* Wait for an incoming connection. */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (!(new_sk = nfc_llcp_accept_dequeue(sk, newsock))) { set_current_state(TASK_INTERRUPTIBLE); if (!timeo) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = 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 (ret) goto error; newsock->state = SS_CONNECTED; pr_debug("new socket %p\n", new_sk); error: release_sock(sk); return ret; } static int llcp_sock_getname(struct socket *sock, struct sockaddr *uaddr, int *len, int peer) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); DECLARE_SOCKADDR(struct sockaddr_nfc_llcp *, llcp_addr, uaddr); if (llcp_sock == NULL || llcp_sock->dev == NULL) return -EBADFD; pr_debug("%p %d %d %d\n", sk, llcp_sock->target_idx, llcp_sock->dsap, llcp_sock->ssap); uaddr->sa_family = AF_NFC; *len = sizeof(struct sockaddr_nfc_llcp); llcp_addr->dev_idx = llcp_sock->dev->idx; llcp_addr->target_idx = llcp_sock->target_idx; llcp_addr->dsap = llcp_sock->dsap; llcp_addr->ssap = llcp_sock->ssap; llcp_addr->service_name_len = llcp_sock->service_name_len; memcpy(llcp_addr->service_name, llcp_sock->service_name, llcp_addr->service_name_len); return 0; } static inline unsigned int llcp_accept_poll(struct sock *parent) { struct nfc_llcp_sock *llcp_sock, *n, *parent_sock; struct sock *sk; parent_sock = nfc_llcp_sock(parent); list_for_each_entry_safe(llcp_sock, n, &parent_sock->accept_queue, accept_queue) { sk = &llcp_sock->sk; if (sk->sk_state == LLCP_CONNECTED) return POLLIN | POLLRDNORM; } return 0; } static unsigned int llcp_sock_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask = 0; pr_debug("%p\n", sk); sock_poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == LLCP_LISTEN) return llcp_accept_poll(sk); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; if (sk->sk_state == LLCP_CLOSED) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); pr_debug("mask 0x%x\n", mask); return mask; } static int llcp_sock_release(struct socket *sock) { struct sock *sk = sock->sk; struct nfc_llcp_local *local; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); int err = 0; if (!sk) return 0; pr_debug("%p\n", sk); local = llcp_sock->local; if (local == NULL) { err = -ENODEV; goto out; } lock_sock(sk); /* Send a DISC */ if (sk->sk_state == LLCP_CONNECTED) nfc_llcp_disconnect(llcp_sock); if (sk->sk_state == LLCP_LISTEN) { struct nfc_llcp_sock *lsk, *n; struct sock *accept_sk; list_for_each_entry_safe(lsk, n, &llcp_sock->accept_queue, accept_queue) { accept_sk = &lsk->sk; lock_sock(accept_sk); nfc_llcp_disconnect(lsk); nfc_llcp_accept_unlink(accept_sk); release_sock(accept_sk); } } if (llcp_sock->reserved_ssap < LLCP_SAP_MAX) nfc_llcp_put_ssap(llcp_sock->local, llcp_sock->ssap); release_sock(sk); if (sock->type == SOCK_RAW) nfc_llcp_sock_unlink(&local->raw_sockets, sk); else nfc_llcp_sock_unlink(&local->sockets, sk); out: sock_orphan(sk); sock_put(sk); return err; } static int llcp_sock_connect(struct socket *sock, struct sockaddr *_addr, int len, int flags) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct sockaddr_nfc_llcp *addr = (struct sockaddr_nfc_llcp *)_addr; struct nfc_dev *dev; struct nfc_llcp_local *local; int ret = 0; pr_debug("sock %p sk %p flags 0x%x\n", sock, sk, flags); if (!addr || len < sizeof(struct sockaddr_nfc) || addr->sa_family != AF_NFC) return -EINVAL; if (addr->service_name_len == 0 && addr->dsap == 0) return -EINVAL; pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n", addr->dev_idx, addr->target_idx, addr->nfc_protocol); lock_sock(sk); if (sk->sk_state == LLCP_CONNECTED) { ret = -EISCONN; goto error; } dev = nfc_get_device(addr->dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } device_lock(&dev->dev); if (dev->dep_link_up == false) { ret = -ENOLINK; device_unlock(&dev->dev); goto put_dev; } device_unlock(&dev->dev); if (local->rf_mode == NFC_RF_INITIATOR && addr->target_idx != local->target_idx) { ret = -ENOLINK; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->miu = llcp_sock->local->remote_miu; llcp_sock->ssap = nfc_llcp_get_local_ssap(local); if (llcp_sock->ssap == LLCP_SAP_MAX) { ret = -ENOMEM; goto put_dev; } llcp_sock->reserved_ssap = llcp_sock->ssap; if (addr->service_name_len == 0) llcp_sock->dsap = addr->dsap; else llcp_sock->dsap = LLCP_SAP_SDP; llcp_sock->nfc_protocol = addr->nfc_protocol; llcp_sock->service_name_len = min_t(unsigned int, addr->service_name_len, NFC_LLCP_MAX_SERVICE_NAME); llcp_sock->service_name = kmemdup(addr->service_name, llcp_sock->service_name_len, GFP_KERNEL); nfc_llcp_sock_link(&local->connecting_sockets, sk); ret = nfc_llcp_send_connect(llcp_sock); if (ret) goto sock_unlink; ret = sock_wait_state(sk, LLCP_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); if (ret) goto sock_unlink; release_sock(sk); return 0; sock_unlink: nfc_llcp_put_ssap(local, llcp_sock->ssap); nfc_llcp_sock_unlink(&local->connecting_sockets, sk); put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; } static int llcp_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); int ret; pr_debug("sock %p sk %p", sock, sk); ret = sock_error(sk); if (ret) return ret; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_type == SOCK_DGRAM) { struct sockaddr_nfc_llcp *addr = (struct sockaddr_nfc_llcp *)msg->msg_name; if (msg->msg_namelen < sizeof(*addr)) { release_sock(sk); return -EINVAL; } release_sock(sk); return nfc_llcp_send_ui_frame(llcp_sock, addr->dsap, addr->ssap, msg, len); } if (sk->sk_state != LLCP_CONNECTED) { release_sock(sk); return -ENOTCONN; } release_sock(sk); return nfc_llcp_send_i_frame(llcp_sock, msg, len); } static int llcp_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; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); 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_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* 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 || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ 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 const struct proto_ops llcp_sock_ops = { .family = PF_NFC, .owner = THIS_MODULE, .bind = llcp_sock_bind, .connect = llcp_sock_connect, .release = llcp_sock_release, .socketpair = sock_no_socketpair, .accept = llcp_sock_accept, .getname = llcp_sock_getname, .poll = llcp_sock_poll, .ioctl = sock_no_ioctl, .listen = llcp_sock_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = llcp_sock_sendmsg, .recvmsg = llcp_sock_recvmsg, .mmap = sock_no_mmap, }; static const struct proto_ops llcp_rawsock_ops = { .family = PF_NFC, .owner = THIS_MODULE, .bind = llcp_raw_sock_bind, .connect = sock_no_connect, .release = llcp_sock_release, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = llcp_sock_getname, .poll = llcp_sock_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = sock_no_sendmsg, .recvmsg = llcp_sock_recvmsg, .mmap = sock_no_mmap, }; static void llcp_sock_destruct(struct sock *sk) { struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); pr_debug("%p\n", sk); if (sk->sk_state == LLCP_CONNECTED) nfc_put_device(llcp_sock->dev); skb_queue_purge(&sk->sk_receive_queue); nfc_llcp_sock_free(llcp_sock); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Freeing alive NFC LLCP socket %p\n", sk); return; } } struct sock *nfc_llcp_sock_alloc(struct socket *sock, int type, gfp_t gfp) { struct sock *sk; struct nfc_llcp_sock *llcp_sock; sk = sk_alloc(&init_net, PF_NFC, gfp, &llcp_sock_proto); if (!sk) return NULL; llcp_sock = nfc_llcp_sock(sk); sock_init_data(sock, sk); sk->sk_state = LLCP_CLOSED; sk->sk_protocol = NFC_SOCKPROTO_LLCP; sk->sk_type = type; sk->sk_destruct = llcp_sock_destruct; llcp_sock->ssap = 0; llcp_sock->dsap = LLCP_SAP_SDP; llcp_sock->rw = LLCP_DEFAULT_RW; llcp_sock->miu = LLCP_DEFAULT_MIU; llcp_sock->send_n = llcp_sock->send_ack_n = 0; llcp_sock->recv_n = llcp_sock->recv_ack_n = 0; llcp_sock->remote_ready = 1; llcp_sock->reserved_ssap = LLCP_SAP_MAX; skb_queue_head_init(&llcp_sock->tx_queue); skb_queue_head_init(&llcp_sock->tx_pending_queue); INIT_LIST_HEAD(&llcp_sock->accept_queue); if (sock != NULL) sock->state = SS_UNCONNECTED; return sk; } void nfc_llcp_sock_free(struct nfc_llcp_sock *sock) { kfree(sock->service_name); skb_queue_purge(&sock->tx_queue); skb_queue_purge(&sock->tx_pending_queue); list_del_init(&sock->accept_queue); sock->parent = NULL; nfc_llcp_local_put(sock->local); } static int llcp_sock_create(struct net *net, struct socket *sock, const struct nfc_protocol *nfc_proto) { struct sock *sk; pr_debug("%p\n", sock); if (sock->type != SOCK_STREAM && sock->type != SOCK_DGRAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW) sock->ops = &llcp_rawsock_ops; else sock->ops = &llcp_sock_ops; sk = nfc_llcp_sock_alloc(sock, sock->type, GFP_ATOMIC); if (sk == NULL) return -ENOMEM; return 0; } static const struct nfc_protocol llcp_nfc_proto = { .id = NFC_SOCKPROTO_LLCP, .proto = &llcp_sock_proto, .owner = THIS_MODULE, .create = llcp_sock_create }; int __init nfc_llcp_sock_init(void) { return nfc_proto_register(&llcp_nfc_proto); } void nfc_llcp_sock_exit(void) { nfc_proto_unregister(&llcp_nfc_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5693_0
crossvul-cpp_data_good_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; memset(&uf, 0, sizeof(uf)); 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/good_3834_0
crossvul-cpp_data_bad_5692_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) { memset(sax, 0, sizeof(sax)); 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_5692_0
crossvul-cpp_data_good_3838_0
/* net/atm/pvc.c - ATM PVC sockets */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #include <linux/net.h> /* struct socket, struct proto_ops */ #include <linux/atm.h> /* ATM stuff */ #include <linux/atmdev.h> /* ATM devices */ #include <linux/errno.h> /* error codes */ #include <linux/kernel.h> /* printk */ #include <linux/init.h> #include <linux/skbuff.h> #include <linux/bitops.h> #include <linux/export.h> #include <net/sock.h> /* for sock_no_* */ #include "resources.h" /* devs and vccs */ #include "common.h" /* common for PVCs and SVCs */ static int pvc_shutdown(struct socket *sock, int how) { return 0; } static int pvc_bind(struct socket *sock, struct sockaddr *sockaddr, int sockaddr_len) { struct sock *sk = sock->sk; struct sockaddr_atmpvc *addr; struct atm_vcc *vcc; int error; if (sockaddr_len != sizeof(struct sockaddr_atmpvc)) return -EINVAL; addr = (struct sockaddr_atmpvc *)sockaddr; if (addr->sap_family != AF_ATMPVC) return -EAFNOSUPPORT; lock_sock(sk); vcc = ATM_SD(sock); if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) { error = -EBADFD; goto out; } if (test_bit(ATM_VF_PARTIAL, &vcc->flags)) { if (vcc->vpi != ATM_VPI_UNSPEC) addr->sap_addr.vpi = vcc->vpi; if (vcc->vci != ATM_VCI_UNSPEC) addr->sap_addr.vci = vcc->vci; } error = vcc_connect(sock, addr->sap_addr.itf, addr->sap_addr.vpi, addr->sap_addr.vci); out: release_sock(sk); return error; } static int pvc_connect(struct socket *sock, struct sockaddr *sockaddr, int sockaddr_len, int flags) { return pvc_bind(sock, sockaddr, sockaddr_len); } static int pvc_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int error; lock_sock(sk); error = vcc_setsockopt(sock, level, optname, optval, optlen); release_sock(sk); return error; } static int pvc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int error; lock_sock(sk); error = vcc_getsockopt(sock, level, optname, optval, optlen); release_sock(sk); return error; } static int pvc_getname(struct socket *sock, struct sockaddr *sockaddr, int *sockaddr_len, int peer) { struct sockaddr_atmpvc *addr; struct atm_vcc *vcc = ATM_SD(sock); if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; *sockaddr_len = sizeof(struct sockaddr_atmpvc); addr = (struct sockaddr_atmpvc *)sockaddr; memset(addr, 0, sizeof(*addr)); addr->sap_family = AF_ATMPVC; addr->sap_addr.itf = vcc->dev->number; addr->sap_addr.vpi = vcc->vpi; addr->sap_addr.vci = vcc->vci; return 0; } static const struct proto_ops pvc_proto_ops = { .family = PF_ATMPVC, .owner = THIS_MODULE, .release = vcc_release, .bind = pvc_bind, .connect = pvc_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = pvc_getname, .poll = vcc_poll, .ioctl = vcc_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = vcc_compat_ioctl, #endif .listen = sock_no_listen, .shutdown = pvc_shutdown, .setsockopt = pvc_setsockopt, .getsockopt = pvc_getsockopt, .sendmsg = vcc_sendmsg, .recvmsg = vcc_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static int pvc_create(struct net *net, struct socket *sock, int protocol, int kern) { if (net != &init_net) return -EAFNOSUPPORT; sock->ops = &pvc_proto_ops; return vcc_create(net, sock, protocol, PF_ATMPVC); } static const struct net_proto_family pvc_family_ops = { .family = PF_ATMPVC, .create = pvc_create, .owner = THIS_MODULE, }; /* * Initialize the ATM PVC protocol family */ int __init atmpvc_init(void) { return sock_register(&pvc_family_ops); } void atmpvc_exit(void) { sock_unregister(PF_ATMPVC); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3838_0
crossvul-cpp_data_good_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; msg->msg_namelen = 0; 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/good_5685_0
crossvul-cpp_data_good_3830_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 (!capable(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/good_3830_0
crossvul-cpp_data_good_5682_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 (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk) * Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) * Copyright (C) Darryl Miles G7LED (dlm@g7led.demon.co.uk) * Copyright (C) Steven Whitehouse GW7RRM (stevew@acm.org) * Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de) * Copyright (C) Hans-Joachim Hetscher DD8NE (dd8ne@bnv-bamberg.de) * Copyright (C) Hans Alblas PE1AYX (hans@esrac.ele.tue.nl) * Copyright (C) Frederic Rible F1OAT (frible@teaser.fr) */ #include <linux/capability.h> #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.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/slab.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/skbuff.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 <linux/proc_fs.h> #include <linux/stat.h> #include <linux/netfilter.h> #include <linux/sysctl.h> #include <linux/init.h> #include <linux/spinlock.h> #include <net/net_namespace.h> #include <net/tcp_states.h> #include <net/ip.h> #include <net/arp.h> HLIST_HEAD(ax25_list); DEFINE_SPINLOCK(ax25_list_lock); static const struct proto_ops ax25_proto_ops; static void ax25_free_sock(struct sock *sk) { ax25_cb_put(ax25_sk(sk)); } /* * Socket removal during an interrupt is now safe. */ static void ax25_cb_del(ax25_cb *ax25) { if (!hlist_unhashed(&ax25->ax25_node)) { spin_lock_bh(&ax25_list_lock); hlist_del_init(&ax25->ax25_node); spin_unlock_bh(&ax25_list_lock); ax25_cb_put(ax25); } } /* * Kill all bound sockets on a dropped device. */ static void ax25_kill_by_device(struct net_device *dev) { ax25_dev *ax25_dev; ax25_cb *s; if ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL) return; spin_lock_bh(&ax25_list_lock); again: ax25_for_each(s, &ax25_list) { if (s->ax25_dev == ax25_dev) { s->ax25_dev = NULL; spin_unlock_bh(&ax25_list_lock); ax25_disconnect(s, ENETUNREACH); spin_lock_bh(&ax25_list_lock); /* The entry could have been deleted from the * list meanwhile and thus the next pointer is * no longer valid. Play it safe and restart * the scan. Forward progress is ensured * because we set s->ax25_dev to NULL and we * are never passed a NULL 'dev' argument. */ goto again; } } spin_unlock_bh(&ax25_list_lock); } /* * Handle device status changes. */ static int ax25_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; /* Reject non AX.25 devices */ if (dev->type != ARPHRD_AX25) return NOTIFY_DONE; switch (event) { case NETDEV_UP: ax25_dev_device_up(dev); break; case NETDEV_DOWN: ax25_kill_by_device(dev); ax25_rt_device_down(dev); ax25_dev_device_down(dev); break; default: break; } return NOTIFY_DONE; } /* * Add a socket to the bound sockets list. */ void ax25_cb_add(ax25_cb *ax25) { spin_lock_bh(&ax25_list_lock); ax25_cb_hold(ax25); hlist_add_head(&ax25->ax25_node, &ax25_list); spin_unlock_bh(&ax25_list_lock); } /* * Find a socket that wants to accept the SABM we have just * received. */ struct sock *ax25_find_listener(ax25_address *addr, int digi, struct net_device *dev, int type) { ax25_cb *s; spin_lock(&ax25_list_lock); ax25_for_each(s, &ax25_list) { if ((s->iamdigi && !digi) || (!s->iamdigi && digi)) continue; if (s->sk && !ax25cmp(&s->source_addr, addr) && s->sk->sk_type == type && s->sk->sk_state == TCP_LISTEN) { /* If device is null we match any device */ if (s->ax25_dev == NULL || s->ax25_dev->dev == dev) { sock_hold(s->sk); spin_unlock(&ax25_list_lock); return s->sk; } } } spin_unlock(&ax25_list_lock); return NULL; } /* * Find an AX.25 socket given both ends. */ struct sock *ax25_get_socket(ax25_address *my_addr, ax25_address *dest_addr, int type) { struct sock *sk = NULL; ax25_cb *s; spin_lock(&ax25_list_lock); ax25_for_each(s, &ax25_list) { if (s->sk && !ax25cmp(&s->source_addr, my_addr) && !ax25cmp(&s->dest_addr, dest_addr) && s->sk->sk_type == type) { sk = s->sk; sock_hold(sk); break; } } spin_unlock(&ax25_list_lock); return sk; } /* * Find an AX.25 control block given both ends. It will only pick up * floating AX.25 control blocks or non Raw socket bound control blocks. */ ax25_cb *ax25_find_cb(ax25_address *src_addr, ax25_address *dest_addr, ax25_digi *digi, struct net_device *dev) { ax25_cb *s; spin_lock_bh(&ax25_list_lock); ax25_for_each(s, &ax25_list) { if (s->sk && s->sk->sk_type != SOCK_SEQPACKET) continue; if (s->ax25_dev == NULL) continue; if (ax25cmp(&s->source_addr, src_addr) == 0 && ax25cmp(&s->dest_addr, dest_addr) == 0 && s->ax25_dev->dev == dev) { if (digi != NULL && digi->ndigi != 0) { if (s->digipeat == NULL) continue; if (ax25digicmp(s->digipeat, digi) != 0) continue; } else { if (s->digipeat != NULL && s->digipeat->ndigi != 0) continue; } ax25_cb_hold(s); spin_unlock_bh(&ax25_list_lock); return s; } } spin_unlock_bh(&ax25_list_lock); return NULL; } EXPORT_SYMBOL(ax25_find_cb); void ax25_send_to_raw(ax25_address *addr, struct sk_buff *skb, int proto) { ax25_cb *s; struct sk_buff *copy; spin_lock(&ax25_list_lock); ax25_for_each(s, &ax25_list) { if (s->sk != NULL && ax25cmp(&s->source_addr, addr) == 0 && s->sk->sk_type == SOCK_RAW && s->sk->sk_protocol == proto && s->ax25_dev->dev == skb->dev && atomic_read(&s->sk->sk_rmem_alloc) <= s->sk->sk_rcvbuf) { if ((copy = skb_clone(skb, GFP_ATOMIC)) == NULL) continue; if (sock_queue_rcv_skb(s->sk, copy) != 0) kfree_skb(copy); } } spin_unlock(&ax25_list_lock); } /* * Deferred destroy. */ void ax25_destroy_socket(ax25_cb *); /* * Handler for deferred kills. */ static void ax25_destroy_timer(unsigned long data) { ax25_cb *ax25=(ax25_cb *)data; struct sock *sk; sk=ax25->sk; bh_lock_sock(sk); sock_hold(sk); ax25_destroy_socket(ax25); 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 ax25_destroy_socket(ax25_cb *ax25) { struct sk_buff *skb; ax25_cb_del(ax25); ax25_stop_heartbeat(ax25); ax25_stop_t1timer(ax25); ax25_stop_t2timer(ax25); ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); ax25_clear_queues(ax25); /* Flush the queues */ if (ax25->sk != NULL) { while ((skb = skb_dequeue(&ax25->sk->sk_receive_queue)) != NULL) { if (skb->sk != ax25->sk) { /* A pending connection */ ax25_cb *sax25 = ax25_sk(skb->sk); /* Queue the unaccepted socket for death */ sock_orphan(skb->sk); /* 9A4GL: hack to release unaccepted sockets */ skb->sk->sk_state = TCP_LISTEN; ax25_start_heartbeat(sax25); sax25->state = AX25_STATE_0; } kfree_skb(skb); } skb_queue_purge(&ax25->sk->sk_write_queue); } if (ax25->sk != NULL) { if (sk_has_allocations(ax25->sk)) { /* Defer: outstanding buffers */ setup_timer(&ax25->dtimer, ax25_destroy_timer, (unsigned long)ax25); ax25->dtimer.expires = jiffies + 2 * HZ; add_timer(&ax25->dtimer); } else { struct sock *sk=ax25->sk; ax25->sk=NULL; sock_put(sk); } } else { ax25_cb_put(ax25); } } /* * dl1bke 960311: set parameters for existing AX.25 connections, * includes a KILL command to abort any connection. * VERY useful for debugging ;-) */ static int ax25_ctl_ioctl(const unsigned int cmd, void __user *arg) { struct ax25_ctl_struct ax25_ctl; ax25_digi digi; ax25_dev *ax25_dev; ax25_cb *ax25; unsigned int k; int ret = 0; if (copy_from_user(&ax25_ctl, arg, sizeof(ax25_ctl))) return -EFAULT; if ((ax25_dev = ax25_addr_ax25dev(&ax25_ctl.port_addr)) == NULL) return -ENODEV; if (ax25_ctl.digi_count > AX25_MAX_DIGIS) return -EINVAL; if (ax25_ctl.arg > ULONG_MAX / HZ && ax25_ctl.cmd != AX25_KILL) return -EINVAL; digi.ndigi = ax25_ctl.digi_count; for (k = 0; k < digi.ndigi; k++) digi.calls[k] = ax25_ctl.digi_addr[k]; if ((ax25 = ax25_find_cb(&ax25_ctl.source_addr, &ax25_ctl.dest_addr, &digi, ax25_dev->dev)) == NULL) return -ENOTCONN; switch (ax25_ctl.cmd) { case AX25_KILL: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); #ifdef CONFIG_AX25_DAMA_SLAVE if (ax25_dev->dama.slave && ax25->ax25_dev->values[AX25_VALUES_PROTOCOL] == AX25_PROTO_DAMA_SLAVE) ax25_dama_off(ax25); #endif ax25_disconnect(ax25, ENETRESET); break; case AX25_WINDOW: if (ax25->modulus == AX25_MODULUS) { if (ax25_ctl.arg < 1 || ax25_ctl.arg > 7) goto einval_put; } else { if (ax25_ctl.arg < 1 || ax25_ctl.arg > 63) goto einval_put; } ax25->window = ax25_ctl.arg; break; case AX25_T1: if (ax25_ctl.arg < 1 || ax25_ctl.arg > ULONG_MAX / HZ) goto einval_put; ax25->rtt = (ax25_ctl.arg * HZ) / 2; ax25->t1 = ax25_ctl.arg * HZ; break; case AX25_T2: if (ax25_ctl.arg < 1 || ax25_ctl.arg > ULONG_MAX / HZ) goto einval_put; ax25->t2 = ax25_ctl.arg * HZ; break; case AX25_N2: if (ax25_ctl.arg < 1 || ax25_ctl.arg > 31) goto einval_put; ax25->n2count = 0; ax25->n2 = ax25_ctl.arg; break; case AX25_T3: if (ax25_ctl.arg > ULONG_MAX / HZ) goto einval_put; ax25->t3 = ax25_ctl.arg * HZ; break; case AX25_IDLE: if (ax25_ctl.arg > ULONG_MAX / (60 * HZ)) goto einval_put; ax25->idle = ax25_ctl.arg * 60 * HZ; break; case AX25_PACLEN: if (ax25_ctl.arg < 16 || ax25_ctl.arg > 65535) goto einval_put; ax25->paclen = ax25_ctl.arg; break; default: goto einval_put; } out_put: ax25_cb_put(ax25); return ret; einval_put: ret = -EINVAL; goto out_put; } static void ax25_fillin_cb_from_dev(ax25_cb *ax25, ax25_dev *ax25_dev) { ax25->rtt = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T1]) / 2; ax25->t1 = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T1]); ax25->t2 = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T2]); ax25->t3 = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T3]); ax25->n2 = ax25_dev->values[AX25_VALUES_N2]; ax25->paclen = ax25_dev->values[AX25_VALUES_PACLEN]; ax25->idle = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_IDLE]); ax25->backoff = ax25_dev->values[AX25_VALUES_BACKOFF]; if (ax25_dev->values[AX25_VALUES_AXDEFMODE]) { ax25->modulus = AX25_EMODULUS; ax25->window = ax25_dev->values[AX25_VALUES_EWINDOW]; } else { ax25->modulus = AX25_MODULUS; ax25->window = ax25_dev->values[AX25_VALUES_WINDOW]; } } /* * Fill in a created AX.25 created control block with the default * values for a particular device. */ void ax25_fillin_cb(ax25_cb *ax25, ax25_dev *ax25_dev) { ax25->ax25_dev = ax25_dev; if (ax25->ax25_dev != NULL) { ax25_fillin_cb_from_dev(ax25, ax25_dev); return; } /* * No device, use kernel / AX.25 spec default values */ ax25->rtt = msecs_to_jiffies(AX25_DEF_T1) / 2; ax25->t1 = msecs_to_jiffies(AX25_DEF_T1); ax25->t2 = msecs_to_jiffies(AX25_DEF_T2); ax25->t3 = msecs_to_jiffies(AX25_DEF_T3); ax25->n2 = AX25_DEF_N2; ax25->paclen = AX25_DEF_PACLEN; ax25->idle = msecs_to_jiffies(AX25_DEF_IDLE); ax25->backoff = AX25_DEF_BACKOFF; if (AX25_DEF_AXDEFMODE) { ax25->modulus = AX25_EMODULUS; ax25->window = AX25_DEF_EWINDOW; } else { ax25->modulus = AX25_MODULUS; ax25->window = AX25_DEF_WINDOW; } } /* * Create an empty AX.25 control block. */ ax25_cb *ax25_create_cb(void) { ax25_cb *ax25; if ((ax25 = kzalloc(sizeof(*ax25), GFP_ATOMIC)) == NULL) return NULL; atomic_set(&ax25->refcount, 1); skb_queue_head_init(&ax25->write_queue); skb_queue_head_init(&ax25->frag_queue); skb_queue_head_init(&ax25->ack_queue); skb_queue_head_init(&ax25->reseq_queue); ax25_setup_timers(ax25); ax25_fillin_cb(ax25, NULL); ax25->state = AX25_STATE_0; return ax25; } /* * Handling for system calls applied via the various interfaces to an * AX25 socket object */ static int ax25_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; ax25_cb *ax25; struct net_device *dev; char devname[IFNAMSIZ]; unsigned long opt; int res = 0; if (level != SOL_AX25) return -ENOPROTOOPT; if (optlen < sizeof(unsigned int)) return -EINVAL; if (get_user(opt, (unsigned int __user *)optval)) return -EFAULT; lock_sock(sk); ax25 = ax25_sk(sk); switch (optname) { case AX25_WINDOW: if (ax25->modulus == AX25_MODULUS) { if (opt < 1 || opt > 7) { res = -EINVAL; break; } } else { if (opt < 1 || opt > 63) { res = -EINVAL; break; } } ax25->window = opt; break; case AX25_T1: if (opt < 1 || opt > ULONG_MAX / HZ) { res = -EINVAL; break; } ax25->rtt = (opt * HZ) >> 1; ax25->t1 = opt * HZ; break; case AX25_T2: if (opt < 1 || opt > ULONG_MAX / HZ) { res = -EINVAL; break; } ax25->t2 = opt * HZ; break; case AX25_N2: if (opt < 1 || opt > 31) { res = -EINVAL; break; } ax25->n2 = opt; break; case AX25_T3: if (opt < 1 || opt > ULONG_MAX / HZ) { res = -EINVAL; break; } ax25->t3 = opt * HZ; break; case AX25_IDLE: if (opt > ULONG_MAX / (60 * HZ)) { res = -EINVAL; break; } ax25->idle = opt * 60 * HZ; break; case AX25_BACKOFF: if (opt > 2) { res = -EINVAL; break; } ax25->backoff = opt; break; case AX25_EXTSEQ: ax25->modulus = opt ? AX25_EMODULUS : AX25_MODULUS; break; case AX25_PIDINCL: ax25->pidincl = opt ? 1 : 0; break; case AX25_IAMDIGI: ax25->iamdigi = opt ? 1 : 0; break; case AX25_PACLEN: if (opt < 16 || opt > 65535) { res = -EINVAL; break; } ax25->paclen = opt; break; case SO_BINDTODEVICE: if (optlen > IFNAMSIZ) optlen = IFNAMSIZ; if (copy_from_user(devname, optval, optlen)) { res = -EFAULT; break; } if (sk->sk_type == SOCK_SEQPACKET && (sock->state != SS_UNCONNECTED || sk->sk_state == TCP_LISTEN)) { res = -EADDRNOTAVAIL; break; } dev = dev_get_by_name(&init_net, devname); if (!dev) { res = -ENODEV; break; } ax25->ax25_dev = ax25_dev_ax25dev(dev); ax25_fillin_cb(ax25, ax25->ax25_dev); dev_put(dev); break; default: res = -ENOPROTOOPT; } release_sock(sk); return res; } static int ax25_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; ax25_cb *ax25; struct ax25_dev *ax25_dev; char devname[IFNAMSIZ]; void *valptr; int val = 0; int maxlen, length; if (level != SOL_AX25) return -ENOPROTOOPT; if (get_user(maxlen, optlen)) return -EFAULT; if (maxlen < 1) return -EFAULT; valptr = (void *) &val; length = min_t(unsigned int, maxlen, sizeof(int)); lock_sock(sk); ax25 = ax25_sk(sk); switch (optname) { case AX25_WINDOW: val = ax25->window; break; case AX25_T1: val = ax25->t1 / HZ; break; case AX25_T2: val = ax25->t2 / HZ; break; case AX25_N2: val = ax25->n2; break; case AX25_T3: val = ax25->t3 / HZ; break; case AX25_IDLE: val = ax25->idle / (60 * HZ); break; case AX25_BACKOFF: val = ax25->backoff; break; case AX25_EXTSEQ: val = (ax25->modulus == AX25_EMODULUS); break; case AX25_PIDINCL: val = ax25->pidincl; break; case AX25_IAMDIGI: val = ax25->iamdigi; break; case AX25_PACLEN: val = ax25->paclen; break; case SO_BINDTODEVICE: ax25_dev = ax25->ax25_dev; if (ax25_dev != NULL && ax25_dev->dev != NULL) { strlcpy(devname, ax25_dev->dev->name, sizeof(devname)); length = strlen(devname) + 1; } else { *devname = '\0'; length = 1; } valptr = (void *) devname; break; default: release_sock(sk); return -ENOPROTOOPT; } release_sock(sk); if (put_user(length, optlen)) return -EFAULT; return copy_to_user(optval, valptr, length) ? -EFAULT : 0; } static int ax25_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int res = 0; lock_sock(sk); if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_LISTEN) { sk->sk_max_ack_backlog = backlog; sk->sk_state = TCP_LISTEN; goto out; } res = -EOPNOTSUPP; out: release_sock(sk); return res; } /* * XXX: when creating ax25_sock we should update the .obj_size setting * below. */ static struct proto ax25_proto = { .name = "AX25", .owner = THIS_MODULE, .obj_size = sizeof(struct sock), }; static int ax25_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; ax25_cb *ax25; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; switch (sock->type) { case SOCK_DGRAM: if (protocol == 0 || protocol == PF_AX25) protocol = AX25_P_TEXT; break; case SOCK_SEQPACKET: switch (protocol) { case 0: case PF_AX25: /* For CLX */ protocol = AX25_P_TEXT; break; case AX25_P_SEGMENT: #ifdef CONFIG_INET case AX25_P_ARP: case AX25_P_IP: #endif #ifdef CONFIG_NETROM case AX25_P_NETROM: #endif #ifdef CONFIG_ROSE case AX25_P_ROSE: #endif return -ESOCKTNOSUPPORT; #ifdef CONFIG_NETROM_MODULE case AX25_P_NETROM: if (ax25_protocol_is_registered(AX25_P_NETROM)) return -ESOCKTNOSUPPORT; break; #endif #ifdef CONFIG_ROSE_MODULE case AX25_P_ROSE: if (ax25_protocol_is_registered(AX25_P_ROSE)) return -ESOCKTNOSUPPORT; #endif default: break; } break; case SOCK_RAW: break; default: return -ESOCKTNOSUPPORT; } sk = sk_alloc(net, PF_AX25, GFP_ATOMIC, &ax25_proto); if (sk == NULL) return -ENOMEM; ax25 = sk->sk_protinfo = ax25_create_cb(); if (!ax25) { sk_free(sk); return -ENOMEM; } sock_init_data(sock, sk); sk->sk_destruct = ax25_free_sock; sock->ops = &ax25_proto_ops; sk->sk_protocol = protocol; ax25->sk = sk; return 0; } struct sock *ax25_make_new(struct sock *osk, struct ax25_dev *ax25_dev) { struct sock *sk; ax25_cb *ax25, *oax25; sk = sk_alloc(sock_net(osk), PF_AX25, GFP_ATOMIC, osk->sk_prot); if (sk == NULL) return NULL; if ((ax25 = ax25_create_cb()) == NULL) { sk_free(sk); return NULL; } switch (osk->sk_type) { case SOCK_DGRAM: break; case SOCK_SEQPACKET: break; default: sk_free(sk); ax25_cb_put(ax25); return NULL; } 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); oax25 = ax25_sk(osk); ax25->modulus = oax25->modulus; ax25->backoff = oax25->backoff; ax25->pidincl = oax25->pidincl; ax25->iamdigi = oax25->iamdigi; ax25->rtt = oax25->rtt; ax25->t1 = oax25->t1; ax25->t2 = oax25->t2; ax25->t3 = oax25->t3; ax25->n2 = oax25->n2; ax25->idle = oax25->idle; ax25->paclen = oax25->paclen; ax25->window = oax25->window; ax25->ax25_dev = ax25_dev; ax25->source_addr = oax25->source_addr; if (oax25->digipeat != NULL) { ax25->digipeat = kmemdup(oax25->digipeat, sizeof(ax25_digi), GFP_ATOMIC); if (ax25->digipeat == NULL) { sk_free(sk); ax25_cb_put(ax25); return NULL; } } sk->sk_protinfo = ax25; sk->sk_destruct = ax25_free_sock; ax25->sk = sk; return sk; } static int ax25_release(struct socket *sock) { struct sock *sk = sock->sk; ax25_cb *ax25; if (sk == NULL) return 0; sock_hold(sk); sock_orphan(sk); lock_sock(sk); ax25 = ax25_sk(sk); if (sk->sk_type == SOCK_SEQPACKET) { switch (ax25->state) { case AX25_STATE_0: release_sock(sk); ax25_disconnect(ax25, 0); lock_sock(sk); ax25_destroy_socket(ax25); break; case AX25_STATE_1: case AX25_STATE_2: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); release_sock(sk); ax25_disconnect(ax25, 0); lock_sock(sk); ax25_destroy_socket(ax25); break; case AX25_STATE_3: case AX25_STATE_4: ax25_clear_queues(ax25); ax25->n2count = 0; switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) { case AX25_PROTO_STD_SIMPLEX: case AX25_PROTO_STD_DUPLEX: ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND); ax25_stop_t2timer(ax25); ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); break; #ifdef CONFIG_AX25_DAMA_SLAVE case AX25_PROTO_DAMA_SLAVE: ax25_stop_t3timer(ax25); ax25_stop_idletimer(ax25); break; #endif } ax25_calculate_t1(ax25); ax25_start_t1timer(ax25); ax25->state = AX25_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; } } else { sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); ax25_destroy_socket(ax25); } sock->sk = NULL; release_sock(sk); sock_put(sk); return 0; } /* * We support a funny extension here so you can (as root) give any callsign * digipeated via a local address as source. This hack is obsolete now * that we've implemented support for SO_BINDTODEVICE. It is however small * and trivially backward compatible. */ static int ax25_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct full_sockaddr_ax25 *addr = (struct full_sockaddr_ax25 *)uaddr; ax25_dev *ax25_dev = NULL; ax25_uid_assoc *user; ax25_address call; ax25_cb *ax25; int err = 0; if (addr_len != sizeof(struct sockaddr_ax25) && addr_len != sizeof(struct full_sockaddr_ax25)) /* support for old structure may go away some time * ax25_bind(): uses old (6 digipeater) socket structure. */ if ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) || (addr_len > sizeof(struct full_sockaddr_ax25))) return -EINVAL; if (addr->fsa_ax25.sax25_family != AF_AX25) return -EINVAL; user = ax25_findbyuid(current_euid()); if (user) { call = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_ADMIN)) return -EACCES; call = addr->fsa_ax25.sax25_call; } lock_sock(sk); ax25 = ax25_sk(sk); if (!sock_flag(sk, SOCK_ZAPPED)) { err = -EINVAL; goto out; } ax25->source_addr = call; /* * User already set interface with SO_BINDTODEVICE */ if (ax25->ax25_dev != NULL) goto done; if (addr_len > sizeof(struct sockaddr_ax25) && addr->fsa_ax25.sax25_ndigis == 1) { if (ax25cmp(&addr->fsa_digipeater[0], &null_ax25_address) != 0 && (ax25_dev = ax25_addr_ax25dev(&addr->fsa_digipeater[0])) == NULL) { err = -EADDRNOTAVAIL; goto out; } } else { if ((ax25_dev = ax25_addr_ax25dev(&addr->fsa_ax25.sax25_call)) == NULL) { err = -EADDRNOTAVAIL; goto out; } } if (ax25_dev != NULL) ax25_fillin_cb(ax25, ax25_dev); done: ax25_cb_add(ax25); sock_reset_flag(sk, SOCK_ZAPPED); out: release_sock(sk); return err; } /* * FIXME: nonblock behaviour looks like it may have a bug. */ static int __must_check ax25_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; ax25_cb *ax25 = ax25_sk(sk), *ax25t; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)uaddr; ax25_digi *digi = NULL; int ct = 0, err = 0; /* * some sanity checks. code further down depends on this */ if (addr_len == sizeof(struct sockaddr_ax25)) /* support for this will go away in early 2.5.x * ax25_connect(): uses obsolete socket structure */ ; else if (addr_len != sizeof(struct full_sockaddr_ax25)) /* support for old structure may go away some time * ax25_connect(): uses old (6 digipeater) socket structure. */ if ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) || (addr_len > sizeof(struct full_sockaddr_ax25))) return -EINVAL; if (fsa->fsa_ax25.sax25_family != AF_AX25) return -EINVAL; lock_sock(sk); /* deal with restarts */ if (sock->state == SS_CONNECTING) { switch (sk->sk_state) { case TCP_SYN_SENT: /* still trying */ err = -EINPROGRESS; goto out_release; case TCP_ESTABLISHED: /* connection established */ sock->state = SS_CONNECTED; goto out_release; case TCP_CLOSE: /* connection refused */ sock->state = SS_UNCONNECTED; err = -ECONNREFUSED; goto out_release; } } if (sk->sk_state == TCP_ESTABLISHED && sk->sk_type == SOCK_SEQPACKET) { err = -EISCONN; /* No reconnect on a seqpacket socket */ goto out_release; } sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; kfree(ax25->digipeat); ax25->digipeat = NULL; /* * Handle digi-peaters to be used. */ if (addr_len > sizeof(struct sockaddr_ax25) && fsa->fsa_ax25.sax25_ndigis != 0) { /* Valid number of digipeaters ? */ if (fsa->fsa_ax25.sax25_ndigis < 1 || fsa->fsa_ax25.sax25_ndigis > AX25_MAX_DIGIS) { err = -EINVAL; goto out_release; } if ((digi = kmalloc(sizeof(ax25_digi), GFP_KERNEL)) == NULL) { err = -ENOBUFS; goto out_release; } digi->ndigi = fsa->fsa_ax25.sax25_ndigis; digi->lastrepeat = -1; while (ct < fsa->fsa_ax25.sax25_ndigis) { if ((fsa->fsa_digipeater[ct].ax25_call[6] & AX25_HBIT) && ax25->iamdigi) { digi->repeated[ct] = 1; digi->lastrepeat = ct; } else { digi->repeated[ct] = 0; } digi->calls[ct] = fsa->fsa_digipeater[ct]; ct++; } } /* * Must bind first - autobinding in this may or may not work. If * the socket is already bound, check to see if the device has * been filled in, error if it hasn't. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* check if we can remove this feature. It is broken. */ printk(KERN_WARNING "ax25_connect(): %s uses autobind, please contact jreuter@yaina.de\n", current->comm); if ((err = ax25_rt_autobind(ax25, &fsa->fsa_ax25.sax25_call)) < 0) { kfree(digi); goto out_release; } ax25_fillin_cb(ax25, ax25->ax25_dev); ax25_cb_add(ax25); } else { if (ax25->ax25_dev == NULL) { kfree(digi); err = -EHOSTUNREACH; goto out_release; } } if (sk->sk_type == SOCK_SEQPACKET && (ax25t=ax25_find_cb(&ax25->source_addr, &fsa->fsa_ax25.sax25_call, digi, ax25->ax25_dev->dev))) { kfree(digi); err = -EADDRINUSE; /* Already such a connection */ ax25_cb_put(ax25t); goto out_release; } ax25->dest_addr = fsa->fsa_ax25.sax25_call; ax25->digipeat = digi; /* First the easy one */ if (sk->sk_type != SOCK_SEQPACKET) { sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; goto out_release; } /* Move to connecting socket, ax.25 lapb WAIT_UA.. */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) { case AX25_PROTO_STD_SIMPLEX: case AX25_PROTO_STD_DUPLEX: ax25_std_establish_data_link(ax25); break; #ifdef CONFIG_AX25_DAMA_SLAVE case AX25_PROTO_DAMA_SLAVE: ax25->modulus = AX25_MODULUS; ax25->window = ax25->ax25_dev->values[AX25_VALUES_WINDOW]; if (ax25->ax25_dev->dama.slave) ax25_ds_establish_data_link(ax25); else ax25_std_establish_data_link(ax25); break; #endif } ax25->state = AX25_STATE_1; ax25_start_heartbeat(ax25); /* Now the loop */ if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) { err = -EINPROGRESS; goto out_release; } 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) { /* Not in ABM, not in WAIT_UA -> failed */ sock->state = SS_UNCONNECTED; err = sock_error(sk); /* Always set at this point */ goto out_release; } sock->state = SS_CONNECTED; err = 0; out_release: release_sock(sk); return err; } static int ax25_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 (sock->state != SS_UNCONNECTED) return -EINVAL; if ((sk = sock->sk) == NULL) return -EINVAL; lock_sock(sk); if (sk->sk_type != SOCK_SEQPACKET) { err = -EOPNOTSUPP; goto out; } if (sk->sk_state != TCP_LISTEN) { err = -EINVAL; goto out; } /* * The read 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; newsk = skb->sk; sock_graft(newsk, newsock); /* Now attach up the new socket */ kfree_skb(skb); sk->sk_ack_backlog--; newsock->state = SS_CONNECTED; out: release_sock(sk); return err; } static int ax25_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)uaddr; struct sock *sk = sock->sk; unsigned char ndigi, i; ax25_cb *ax25; int err = 0; memset(fsa, 0, sizeof(*fsa)); lock_sock(sk); ax25 = ax25_sk(sk); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } fsa->fsa_ax25.sax25_family = AF_AX25; fsa->fsa_ax25.sax25_call = ax25->dest_addr; if (ax25->digipeat != NULL) { ndigi = ax25->digipeat->ndigi; fsa->fsa_ax25.sax25_ndigis = ndigi; for (i = 0; i < ndigi; i++) fsa->fsa_digipeater[i] = ax25->digipeat->calls[i]; } } else { fsa->fsa_ax25.sax25_family = AF_AX25; fsa->fsa_ax25.sax25_call = ax25->source_addr; fsa->fsa_ax25.sax25_ndigis = 1; if (ax25->ax25_dev != NULL) { memcpy(&fsa->fsa_digipeater[0], ax25->ax25_dev->dev->dev_addr, AX25_ADDR_LEN); } else { fsa->fsa_digipeater[0] = null_ax25_address; } } *uaddr_len = sizeof (struct full_sockaddr_ax25); out: release_sock(sk); return err; } static int ax25_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sockaddr_ax25 *usax = (struct sockaddr_ax25 *)msg->msg_name; struct sock *sk = sock->sk; struct sockaddr_ax25 sax; struct sk_buff *skb; ax25_digi dtmp, *dp; ax25_cb *ax25; size_t size; int lv, err, addr_len = msg->msg_namelen; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); ax25 = ax25_sk(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 (ax25->ax25_dev == NULL) { err = -ENETUNREACH; goto out; } if (len > ax25->ax25_dev->dev->mtu) { err = -EMSGSIZE; goto out; } if (usax != NULL) { if (usax->sax25_family != AF_AX25) { err = -EINVAL; goto out; } if (addr_len == sizeof(struct sockaddr_ax25)) /* ax25_sendmsg(): uses obsolete socket structure */ ; else if (addr_len != sizeof(struct full_sockaddr_ax25)) /* support for old structure may go away some time * ax25_sendmsg(): uses old (6 digipeater) * socket structure. */ if ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) || (addr_len > sizeof(struct full_sockaddr_ax25))) { err = -EINVAL; goto out; } if (addr_len > sizeof(struct sockaddr_ax25) && usax->sax25_ndigis != 0) { int ct = 0; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)usax; /* Valid number of digipeaters ? */ if (usax->sax25_ndigis < 1 || usax->sax25_ndigis > AX25_MAX_DIGIS) { err = -EINVAL; goto out; } dtmp.ndigi = usax->sax25_ndigis; while (ct < usax->sax25_ndigis) { dtmp.repeated[ct] = 0; dtmp.calls[ct] = fsa->fsa_digipeater[ct]; ct++; } dtmp.lastrepeat = 0; } sax = *usax; if (sk->sk_type == SOCK_SEQPACKET && ax25cmp(&ax25->dest_addr, &sax.sax25_call)) { err = -EISCONN; goto out; } if (usax->sax25_ndigis == 0) dp = NULL; else dp = &dtmp; } else { /* * FIXME: 1003.1g - if the socket is like this because * it has become closed (not started closed) and is VC * we ought to SIGPIPE, EPIPE */ if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } sax.sax25_family = AF_AX25; sax.sax25_call = ax25->dest_addr; dp = ax25->digipeat; } /* Build a packet */ /* Assume the worst case */ size = len + ax25->ax25_dev->dev->hard_header_len; skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT, &err); if (skb == NULL) goto out; skb_reserve(skb, size - len); /* User data follows immediately after the AX.25 data */ if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { err = -EFAULT; kfree_skb(skb); goto out; } skb_reset_network_header(skb); /* Add the PID if one is not supplied by the user in the skb */ if (!ax25->pidincl) *skb_push(skb, 1) = sk->sk_protocol; if (sk->sk_type == SOCK_SEQPACKET) { /* Connected mode sockets go via the LAPB machine */ if (sk->sk_state != TCP_ESTABLISHED) { kfree_skb(skb); err = -ENOTCONN; goto out; } /* Shove it onto the queue and kick */ ax25_output(ax25, ax25->paclen, skb); err = len; goto out; } skb_push(skb, 1 + ax25_addr_size(dp)); /* Building AX.25 Header */ /* Build an AX.25 header */ lv = ax25_addr_build(skb->data, &ax25->source_addr, &sax.sax25_call, dp, AX25_COMMAND, AX25_MODULUS); skb_set_transport_header(skb, lv); *skb_transport_header(skb) = AX25_UI; /* Datagram frames go straight out of the door as UI */ ax25_queue_xmit(skb, ax25->ax25_dev->dev); err = len; out: release_sock(sk); return err; } static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int err = 0; lock_sock(sk); /* * This works for seqpacket too. The receiver has ordered the * queue for us! We do one quick check first though */ if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Now we can treat all alike */ skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; if (!ax25_sk(sk)->pidincl) skb_pull(skb, 1); /* Remove PID */ skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (msg->msg_namelen != 0) { struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; ax25_digi digi; ax25_address src; const unsigned char *mac = skb_mac_header(skb); memset(sax, 0, sizeof(struct full_sockaddr_ax25)); ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL, &digi, NULL, NULL); sax->sax25_family = AF_AX25; /* We set this correctly, even though we may not let the application know the digi calls further down (because it did NOT ask to know them). This could get political... **/ sax->sax25_ndigis = digi.ndigi; sax->sax25_call = src; if (sax->sax25_ndigis != 0) { int ct; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax; for (ct = 0; ct < digi.ndigi; ct++) fsa->fsa_digipeater[ct] = digi.calls[ct]; } msg->msg_namelen = sizeof(struct full_sockaddr_ax25); } skb_free_datagram(sk, skb); err = copied; out: release_sock(sk); return err; } static int ax25_shutdown(struct socket *sk, int how) { /* FIXME - generate DM and RNR states */ return -EOPNOTSUPP; } static int ax25_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; void __user *argp = (void __user *)arg; int res = 0; lock_sock(sk); switch (cmd) { case TIOCOUTQ: { long amount; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; res = put_user(amount, (int __user *)argp); break; } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; /* 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; res = put_user(amount, (int __user *) argp); break; } case SIOCGSTAMP: res = sock_get_timestamp(sk, argp); break; case SIOCGSTAMPNS: res = sock_get_timestampns(sk, argp); break; case SIOCAX25ADDUID: /* Add a uid to the uid/call map table */ case SIOCAX25DELUID: /* Delete a uid from the uid/call map table */ case SIOCAX25GETUID: { struct sockaddr_ax25 sax25; if (copy_from_user(&sax25, argp, sizeof(sax25))) { res = -EFAULT; break; } res = ax25_uid_ioctl(cmd, &sax25); break; } case SIOCAX25NOUID: { /* Set the default policy (default/bar) */ long amount; if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } if (get_user(amount, (long __user *)argp)) { res = -EFAULT; break; } if (amount > AX25_NOUID_BLOCK) { res = -EINVAL; break; } ax25_uid_policy = amount; res = 0; break; } case SIOCADDRT: case SIOCDELRT: case SIOCAX25OPTRT: if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } res = ax25_rt_ioctl(cmd, argp); break; case SIOCAX25CTLCON: if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } res = ax25_ctl_ioctl(cmd, argp); break; case SIOCAX25GETINFO: case SIOCAX25GETINFOOLD: { ax25_cb *ax25 = ax25_sk(sk); struct ax25_info_struct ax25_info; ax25_info.t1 = ax25->t1 / HZ; ax25_info.t2 = ax25->t2 / HZ; ax25_info.t3 = ax25->t3 / HZ; ax25_info.idle = ax25->idle / (60 * HZ); ax25_info.n2 = ax25->n2; ax25_info.t1timer = ax25_display_timer(&ax25->t1timer) / HZ; ax25_info.t2timer = ax25_display_timer(&ax25->t2timer) / HZ; ax25_info.t3timer = ax25_display_timer(&ax25->t3timer) / HZ; ax25_info.idletimer = ax25_display_timer(&ax25->idletimer) / (60 * HZ); ax25_info.n2count = ax25->n2count; ax25_info.state = ax25->state; ax25_info.rcv_q = sk_rmem_alloc_get(sk); ax25_info.snd_q = sk_wmem_alloc_get(sk); ax25_info.vs = ax25->vs; ax25_info.vr = ax25->vr; ax25_info.va = ax25->va; ax25_info.vs_max = ax25->vs; /* reserved */ ax25_info.paclen = ax25->paclen; ax25_info.window = ax25->window; /* old structure? */ if (cmd == SIOCAX25GETINFOOLD) { static int warned = 0; if (!warned) { printk(KERN_INFO "%s uses old SIOCAX25GETINFO\n", current->comm); warned=1; } if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct_deprecated))) { res = -EFAULT; break; } } else { if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct))) { res = -EINVAL; break; } } res = 0; break; } case SIOCAX25ADDFWD: case SIOCAX25DELFWD: { struct ax25_fwd_struct ax25_fwd; if (!capable(CAP_NET_ADMIN)) { res = -EPERM; break; } if (copy_from_user(&ax25_fwd, argp, sizeof(ax25_fwd))) { res = -EFAULT; break; } res = ax25_fwd_ioctl(cmd, &ax25_fwd); break; } case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFMETRIC: case SIOCSIFMETRIC: res = -EINVAL; break; default: res = -ENOIOCTLCMD; break; } release_sock(sk); return res; } #ifdef CONFIG_PROC_FS static void *ax25_info_start(struct seq_file *seq, loff_t *pos) __acquires(ax25_list_lock) { spin_lock_bh(&ax25_list_lock); return seq_hlist_start(&ax25_list, *pos); } static void *ax25_info_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_hlist_next(v, &ax25_list, pos); } static void ax25_info_stop(struct seq_file *seq, void *v) __releases(ax25_list_lock) { spin_unlock_bh(&ax25_list_lock); } static int ax25_info_show(struct seq_file *seq, void *v) { ax25_cb *ax25 = hlist_entry(v, struct ax25_cb, ax25_node); char buf[11]; int k; /* * New format: * magic dev src_addr dest_addr,digi1,digi2,.. st vs vr va t1 t1 t2 t2 t3 t3 idle idle n2 n2 rtt window paclen Snd-Q Rcv-Q inode */ seq_printf(seq, "%8.8lx %s %s%s ", (long) ax25, ax25->ax25_dev == NULL? "???" : ax25->ax25_dev->dev->name, ax2asc(buf, &ax25->source_addr), ax25->iamdigi? "*":""); seq_printf(seq, "%s", ax2asc(buf, &ax25->dest_addr)); for (k=0; (ax25->digipeat != NULL) && (k < ax25->digipeat->ndigi); k++) { seq_printf(seq, ",%s%s", ax2asc(buf, &ax25->digipeat->calls[k]), ax25->digipeat->repeated[k]? "*":""); } seq_printf(seq, " %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %lu %d %d %lu %d %d", ax25->state, ax25->vs, ax25->vr, ax25->va, ax25_display_timer(&ax25->t1timer) / HZ, ax25->t1 / HZ, ax25_display_timer(&ax25->t2timer) / HZ, ax25->t2 / HZ, ax25_display_timer(&ax25->t3timer) / HZ, ax25->t3 / HZ, ax25_display_timer(&ax25->idletimer) / (60 * HZ), ax25->idle / (60 * HZ), ax25->n2count, ax25->n2, ax25->rtt / HZ, ax25->window, ax25->paclen); if (ax25->sk != NULL) { seq_printf(seq, " %d %d %lu\n", sk_wmem_alloc_get(ax25->sk), sk_rmem_alloc_get(ax25->sk), sock_i_ino(ax25->sk)); } else { seq_puts(seq, " * * *\n"); } return 0; } static const struct seq_operations ax25_info_seqops = { .start = ax25_info_start, .next = ax25_info_next, .stop = ax25_info_stop, .show = ax25_info_show, }; static int ax25_info_open(struct inode *inode, struct file *file) { return seq_open(file, &ax25_info_seqops); } static const struct file_operations ax25_info_fops = { .owner = THIS_MODULE, .open = ax25_info_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif static const struct net_proto_family ax25_family_ops = { .family = PF_AX25, .create = ax25_create, .owner = THIS_MODULE, }; static const struct proto_ops ax25_proto_ops = { .family = PF_AX25, .owner = THIS_MODULE, .release = ax25_release, .bind = ax25_bind, .connect = ax25_connect, .socketpair = sock_no_socketpair, .accept = ax25_accept, .getname = ax25_getname, .poll = datagram_poll, .ioctl = ax25_ioctl, .listen = ax25_listen, .shutdown = ax25_shutdown, .setsockopt = ax25_setsockopt, .getsockopt = ax25_getsockopt, .sendmsg = ax25_sendmsg, .recvmsg = ax25_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; /* * Called by socket.c on kernel start up */ static struct packet_type ax25_packet_type __read_mostly = { .type = cpu_to_be16(ETH_P_AX25), .func = ax25_kiss_rcv, }; static struct notifier_block ax25_dev_notifier = { .notifier_call =ax25_device_event, }; static int __init ax25_init(void) { int rc = proto_register(&ax25_proto, 0); if (rc != 0) goto out; sock_register(&ax25_family_ops); dev_add_pack(&ax25_packet_type); register_netdevice_notifier(&ax25_dev_notifier); proc_create("ax25_route", S_IRUGO, init_net.proc_net, &ax25_route_fops); proc_create("ax25", S_IRUGO, init_net.proc_net, &ax25_info_fops); proc_create("ax25_calls", S_IRUGO, init_net.proc_net, &ax25_uid_fops); out: return rc; } module_init(ax25_init); MODULE_AUTHOR("Jonathan Naylor G4KLX <g4klx@g4klx.demon.co.uk>"); MODULE_DESCRIPTION("The amateur radio AX.25 link layer protocol"); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_AX25); static void __exit ax25_exit(void) { remove_proc_entry("ax25_route", init_net.proc_net); remove_proc_entry("ax25", init_net.proc_net); remove_proc_entry("ax25_calls", init_net.proc_net); unregister_netdevice_notifier(&ax25_dev_notifier); dev_remove_pack(&ax25_packet_type); sock_unregister(PF_AX25); proto_unregister(&ax25_proto); ax25_rt_free(); ax25_uid_free(); ax25_dev_free(); } module_exit(ax25_exit);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5682_0
crossvul-cpp_data_bad_867_1
/* * Copyright (C) 2014-2018 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, 0); 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; } 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); else if (fd >= 0) 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/bad_867_1
crossvul-cpp_data_good_3444_0
/* * Copyright (C) 2004 IBM Corporation * * Authors: * Leendert van Doorn <leendert@watson.ibm.com> * Dave Safford <safford@watson.ibm.com> * Reiner Sailer <sailer@watson.ibm.com> * Kylene Hall <kjhall@us.ibm.com> * * Maintained by: <tpmdd-devel@lists.sourceforge.net> * * Device driver for TCG/TCPA TPM (trusted platform module). * Specifications at www.trustedcomputinggroup.org * * 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 of the * License. * * Note, the TPM chip is not interrupt driven (only polling) * and can have very long timeouts (minutes!). Hence the unusual * calls to msleep. * */ #include <linux/poll.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/spinlock.h> #include "tpm.h" enum tpm_const { TPM_MINOR = 224, /* officially assigned */ TPM_BUFSIZE = 4096, TPM_NUM_DEVICES = 256, }; enum tpm_duration { TPM_SHORT = 0, TPM_MEDIUM = 1, TPM_LONG = 2, TPM_UNDEFINED, }; #define TPM_MAX_ORDINAL 243 #define TPM_MAX_PROTECTED_ORDINAL 12 #define TPM_PROTECTED_ORDINAL_MASK 0xFF /* * Bug workaround - some TPM's don't flush the most * recently changed pcr on suspend, so force the flush * with an extend to the selected _unused_ non-volatile pcr. */ static int tpm_suspend_pcr; module_param_named(suspend_pcr, tpm_suspend_pcr, uint, 0644); MODULE_PARM_DESC(suspend_pcr, "PCR to use for dummy writes to faciltate flush on suspend."); static LIST_HEAD(tpm_chip_list); static DEFINE_SPINLOCK(driver_lock); static DECLARE_BITMAP(dev_mask, TPM_NUM_DEVICES); /* * Array with one entry per ordinal defining the maximum amount * of time the chip could take to return the result. The ordinal * designation of short, medium or long is defined in a table in * TCG Specification TPM Main Part 2 TPM Structures Section 17. The * values of the SHORT, MEDIUM, and LONG durations are retrieved * from the chip during initialization with a call to tpm_get_timeouts. */ static const u8 tpm_protected_ordinal_duration[TPM_MAX_PROTECTED_ORDINAL] = { TPM_UNDEFINED, /* 0 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 5 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 10 */ TPM_SHORT, }; static const u8 tpm_ordinal_duration[TPM_MAX_ORDINAL] = { TPM_UNDEFINED, /* 0 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 5 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 10 */ TPM_SHORT, TPM_MEDIUM, TPM_LONG, TPM_LONG, TPM_MEDIUM, /* 15 */ TPM_SHORT, TPM_SHORT, TPM_MEDIUM, TPM_LONG, TPM_SHORT, /* 20 */ TPM_SHORT, TPM_MEDIUM, TPM_MEDIUM, TPM_MEDIUM, TPM_SHORT, /* 25 */ TPM_SHORT, TPM_MEDIUM, TPM_SHORT, TPM_SHORT, TPM_MEDIUM, /* 30 */ TPM_LONG, TPM_MEDIUM, TPM_SHORT, TPM_SHORT, TPM_SHORT, /* 35 */ TPM_MEDIUM, TPM_MEDIUM, TPM_UNDEFINED, TPM_UNDEFINED, TPM_MEDIUM, /* 40 */ TPM_LONG, TPM_MEDIUM, TPM_SHORT, TPM_SHORT, TPM_SHORT, /* 45 */ TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_LONG, TPM_MEDIUM, /* 50 */ TPM_MEDIUM, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 55 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_MEDIUM, /* 60 */ TPM_MEDIUM, TPM_MEDIUM, TPM_SHORT, TPM_SHORT, TPM_MEDIUM, /* 65 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 70 */ TPM_SHORT, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 75 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_LONG, /* 80 */ TPM_UNDEFINED, TPM_MEDIUM, TPM_LONG, TPM_SHORT, TPM_UNDEFINED, /* 85 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 90 */ TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_UNDEFINED, /* 95 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_MEDIUM, /* 100 */ TPM_SHORT, TPM_SHORT, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 105 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 110 */ TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_SHORT, /* 115 */ TPM_SHORT, TPM_SHORT, TPM_UNDEFINED, TPM_UNDEFINED, TPM_LONG, /* 120 */ TPM_LONG, TPM_MEDIUM, TPM_UNDEFINED, TPM_SHORT, TPM_SHORT, /* 125 */ TPM_SHORT, TPM_LONG, TPM_SHORT, TPM_SHORT, TPM_SHORT, /* 130 */ TPM_MEDIUM, TPM_UNDEFINED, TPM_SHORT, TPM_MEDIUM, TPM_UNDEFINED, /* 135 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 140 */ TPM_SHORT, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 145 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 150 */ TPM_MEDIUM, TPM_MEDIUM, TPM_SHORT, TPM_SHORT, TPM_UNDEFINED, /* 155 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 160 */ TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_UNDEFINED, TPM_UNDEFINED, /* 165 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_LONG, /* 170 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 175 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_MEDIUM, /* 180 */ TPM_SHORT, TPM_MEDIUM, TPM_MEDIUM, TPM_MEDIUM, TPM_MEDIUM, /* 185 */ TPM_SHORT, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 190 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 195 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 200 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, TPM_SHORT, /* 205 */ TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_MEDIUM, /* 210 */ TPM_UNDEFINED, TPM_MEDIUM, TPM_MEDIUM, TPM_MEDIUM, TPM_UNDEFINED, /* 215 */ TPM_MEDIUM, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, TPM_SHORT, /* 220 */ TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_SHORT, TPM_UNDEFINED, /* 225 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 230 */ TPM_LONG, TPM_MEDIUM, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, /* 235 */ TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_UNDEFINED, TPM_SHORT, /* 240 */ TPM_UNDEFINED, TPM_MEDIUM, }; static void user_reader_timeout(unsigned long ptr) { struct tpm_chip *chip = (struct tpm_chip *) ptr; schedule_work(&chip->work); } static void timeout_work(struct work_struct *work) { struct tpm_chip *chip = container_of(work, struct tpm_chip, work); mutex_lock(&chip->buffer_mutex); atomic_set(&chip->data_pending, 0); memset(chip->data_buffer, 0, TPM_BUFSIZE); mutex_unlock(&chip->buffer_mutex); } /* * Returns max number of jiffies to wait */ unsigned long tpm_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal) { int duration_idx = TPM_UNDEFINED; int duration = 0; if (ordinal < TPM_MAX_ORDINAL) duration_idx = tpm_ordinal_duration[ordinal]; else if ((ordinal & TPM_PROTECTED_ORDINAL_MASK) < TPM_MAX_PROTECTED_ORDINAL) duration_idx = tpm_protected_ordinal_duration[ordinal & TPM_PROTECTED_ORDINAL_MASK]; if (duration_idx != TPM_UNDEFINED) duration = chip->vendor.duration[duration_idx]; if (duration <= 0) return 2 * 60 * HZ; else return duration; } EXPORT_SYMBOL_GPL(tpm_calc_ordinal_duration); /* * Internal kernel interface to transmit TPM commands */ static ssize_t tpm_transmit(struct tpm_chip *chip, const char *buf, size_t bufsiz) { ssize_t rc; u32 count, ordinal; unsigned long stop; count = be32_to_cpu(*((__be32 *) (buf + 2))); ordinal = be32_to_cpu(*((__be32 *) (buf + 6))); if (count == 0) return -ENODATA; if (count > bufsiz) { dev_err(chip->dev, "invalid count value %x %zx \n", count, bufsiz); return -E2BIG; } mutex_lock(&chip->tpm_mutex); if ((rc = chip->vendor.send(chip, (u8 *) buf, count)) < 0) { dev_err(chip->dev, "tpm_transmit: tpm_send: error %zd\n", rc); goto out; } if (chip->vendor.irq) goto out_recv; stop = jiffies + tpm_calc_ordinal_duration(chip, ordinal); do { u8 status = chip->vendor.status(chip); if ((status & chip->vendor.req_complete_mask) == chip->vendor.req_complete_val) goto out_recv; if ((status == chip->vendor.req_canceled)) { dev_err(chip->dev, "Operation Canceled\n"); rc = -ECANCELED; goto out; } msleep(TPM_TIMEOUT); /* CHECK */ rmb(); } while (time_before(jiffies, stop)); chip->vendor.cancel(chip); dev_err(chip->dev, "Operation Timed out\n"); rc = -ETIME; goto out; out_recv: rc = chip->vendor.recv(chip, (u8 *) buf, bufsiz); if (rc < 0) dev_err(chip->dev, "tpm_transmit: tpm_recv: error %zd\n", rc); out: mutex_unlock(&chip->tpm_mutex); return rc; } #define TPM_DIGEST_SIZE 20 #define TPM_ERROR_SIZE 10 #define TPM_RET_CODE_IDX 6 enum tpm_capabilities { TPM_CAP_FLAG = cpu_to_be32(4), TPM_CAP_PROP = cpu_to_be32(5), CAP_VERSION_1_1 = cpu_to_be32(0x06), CAP_VERSION_1_2 = cpu_to_be32(0x1A) }; enum tpm_sub_capabilities { TPM_CAP_PROP_PCR = cpu_to_be32(0x101), TPM_CAP_PROP_MANUFACTURER = cpu_to_be32(0x103), TPM_CAP_FLAG_PERM = cpu_to_be32(0x108), TPM_CAP_FLAG_VOL = cpu_to_be32(0x109), TPM_CAP_PROP_OWNER = cpu_to_be32(0x111), TPM_CAP_PROP_TIS_TIMEOUT = cpu_to_be32(0x115), TPM_CAP_PROP_TIS_DURATION = cpu_to_be32(0x120), }; static ssize_t transmit_cmd(struct tpm_chip *chip, struct tpm_cmd_t *cmd, int len, const char *desc) { int err; len = tpm_transmit(chip,(u8 *) cmd, len); if (len < 0) return len; if (len == TPM_ERROR_SIZE) { err = be32_to_cpu(cmd->header.out.return_code); dev_dbg(chip->dev, "A TPM error (%d) occurred %s\n", err, desc); return err; } return 0; } #define TPM_INTERNAL_RESULT_SIZE 200 #define TPM_TAG_RQU_COMMAND cpu_to_be16(193) #define TPM_ORD_GET_CAP cpu_to_be32(101) static const struct tpm_input_header tpm_getcap_header = { .tag = TPM_TAG_RQU_COMMAND, .length = cpu_to_be32(22), .ordinal = TPM_ORD_GET_CAP }; ssize_t tpm_getcap(struct device *dev, __be32 subcap_id, cap_t *cap, const char *desc) { struct tpm_cmd_t tpm_cmd; int rc; struct tpm_chip *chip = dev_get_drvdata(dev); tpm_cmd.header.in = tpm_getcap_header; if (subcap_id == CAP_VERSION_1_1 || subcap_id == CAP_VERSION_1_2) { tpm_cmd.params.getcap_in.cap = subcap_id; /*subcap field not necessary */ tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(0); tpm_cmd.header.in.length -= cpu_to_be32(sizeof(__be32)); } else { if (subcap_id == TPM_CAP_FLAG_PERM || subcap_id == TPM_CAP_FLAG_VOL) tpm_cmd.params.getcap_in.cap = TPM_CAP_FLAG; else tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP; tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4); tpm_cmd.params.getcap_in.subcap = subcap_id; } rc = transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE, desc); if (!rc) *cap = tpm_cmd.params.getcap_out.cap; return rc; } void tpm_gen_interrupt(struct tpm_chip *chip) { struct tpm_cmd_t tpm_cmd; ssize_t rc; tpm_cmd.header.in = tpm_getcap_header; tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP; tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4); tpm_cmd.params.getcap_in.subcap = TPM_CAP_PROP_TIS_TIMEOUT; rc = transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE, "attempting to determine the timeouts"); } EXPORT_SYMBOL_GPL(tpm_gen_interrupt); void tpm_get_timeouts(struct tpm_chip *chip) { struct tpm_cmd_t tpm_cmd; struct timeout_t *timeout_cap; struct duration_t *duration_cap; ssize_t rc; u32 timeout; tpm_cmd.header.in = tpm_getcap_header; tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP; tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4); tpm_cmd.params.getcap_in.subcap = TPM_CAP_PROP_TIS_TIMEOUT; rc = transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE, "attempting to determine the timeouts"); if (rc) goto duration; if (be32_to_cpu(tpm_cmd.header.out.length) != 4 * sizeof(u32)) goto duration; timeout_cap = &tpm_cmd.params.getcap_out.cap.timeout; /* Don't overwrite default if value is 0 */ timeout = be32_to_cpu(timeout_cap->a); if (timeout) chip->vendor.timeout_a = usecs_to_jiffies(timeout); timeout = be32_to_cpu(timeout_cap->b); if (timeout) chip->vendor.timeout_b = usecs_to_jiffies(timeout); timeout = be32_to_cpu(timeout_cap->c); if (timeout) chip->vendor.timeout_c = usecs_to_jiffies(timeout); timeout = be32_to_cpu(timeout_cap->d); if (timeout) chip->vendor.timeout_d = usecs_to_jiffies(timeout); duration: tpm_cmd.header.in = tpm_getcap_header; tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP; tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4); tpm_cmd.params.getcap_in.subcap = TPM_CAP_PROP_TIS_DURATION; rc = transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE, "attempting to determine the durations"); if (rc) return; if (be32_to_cpu(tpm_cmd.header.out.return_code) != 3 * sizeof(u32)) return; duration_cap = &tpm_cmd.params.getcap_out.cap.duration; chip->vendor.duration[TPM_SHORT] = usecs_to_jiffies(be32_to_cpu(duration_cap->tpm_short)); /* The Broadcom BCM0102 chipset in a Dell Latitude D820 gets the above * value wrong and apparently reports msecs rather than usecs. So we * fix up the resulting too-small TPM_SHORT value to make things work. */ if (chip->vendor.duration[TPM_SHORT] < (HZ/100)) chip->vendor.duration[TPM_SHORT] = HZ; chip->vendor.duration[TPM_MEDIUM] = usecs_to_jiffies(be32_to_cpu(duration_cap->tpm_medium)); chip->vendor.duration[TPM_LONG] = usecs_to_jiffies(be32_to_cpu(duration_cap->tpm_long)); } EXPORT_SYMBOL_GPL(tpm_get_timeouts); void tpm_continue_selftest(struct tpm_chip *chip) { u8 data[] = { 0, 193, /* TPM_TAG_RQU_COMMAND */ 0, 0, 0, 10, /* length */ 0, 0, 0, 83, /* TPM_ORD_GetCapability */ }; tpm_transmit(chip, data, sizeof(data)); } EXPORT_SYMBOL_GPL(tpm_continue_selftest); ssize_t tpm_show_enabled(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; rc = tpm_getcap(dev, TPM_CAP_FLAG_PERM, &cap, "attempting to determine the permanent enabled state"); if (rc) return 0; rc = sprintf(buf, "%d\n", !cap.perm_flags.disable); return rc; } EXPORT_SYMBOL_GPL(tpm_show_enabled); ssize_t tpm_show_active(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; rc = tpm_getcap(dev, TPM_CAP_FLAG_PERM, &cap, "attempting to determine the permanent active state"); if (rc) return 0; rc = sprintf(buf, "%d\n", !cap.perm_flags.deactivated); return rc; } EXPORT_SYMBOL_GPL(tpm_show_active); ssize_t tpm_show_owned(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; rc = tpm_getcap(dev, TPM_CAP_PROP_OWNER, &cap, "attempting to determine the owner state"); if (rc) return 0; rc = sprintf(buf, "%d\n", cap.owned); return rc; } EXPORT_SYMBOL_GPL(tpm_show_owned); ssize_t tpm_show_temp_deactivated(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; rc = tpm_getcap(dev, TPM_CAP_FLAG_VOL, &cap, "attempting to determine the temporary state"); if (rc) return 0; rc = sprintf(buf, "%d\n", cap.stclear_flags.deactivated); return rc; } EXPORT_SYMBOL_GPL(tpm_show_temp_deactivated); /* * tpm_chip_find_get - return tpm_chip for given chip number */ static struct tpm_chip *tpm_chip_find_get(int chip_num) { struct tpm_chip *pos, *chip = NULL; rcu_read_lock(); list_for_each_entry_rcu(pos, &tpm_chip_list, list) { if (chip_num != TPM_ANY_NUM && chip_num != pos->dev_num) continue; if (try_module_get(pos->dev->driver->owner)) { chip = pos; break; } } rcu_read_unlock(); return chip; } #define TPM_ORDINAL_PCRREAD cpu_to_be32(21) #define READ_PCR_RESULT_SIZE 30 static struct tpm_input_header pcrread_header = { .tag = TPM_TAG_RQU_COMMAND, .length = cpu_to_be32(14), .ordinal = TPM_ORDINAL_PCRREAD }; int __tpm_pcr_read(struct tpm_chip *chip, int pcr_idx, u8 *res_buf) { int rc; struct tpm_cmd_t cmd; cmd.header.in = pcrread_header; cmd.params.pcrread_in.pcr_idx = cpu_to_be32(pcr_idx); rc = transmit_cmd(chip, &cmd, READ_PCR_RESULT_SIZE, "attempting to read a pcr value"); if (rc == 0) memcpy(res_buf, cmd.params.pcrread_out.pcr_result, TPM_DIGEST_SIZE); return rc; } /** * tpm_pcr_read - read a pcr value * @chip_num: tpm idx # or ANY * @pcr_idx: pcr idx to retrieve * @res_buf: TPM_PCR value * size of res_buf is 20 bytes (or NULL if you don't care) * * The TPM driver should be built-in, but for whatever reason it * isn't, protect against the chip disappearing, by incrementing * the module usage count. */ int tpm_pcr_read(u32 chip_num, int pcr_idx, u8 *res_buf) { struct tpm_chip *chip; int rc; chip = tpm_chip_find_get(chip_num); if (chip == NULL) return -ENODEV; rc = __tpm_pcr_read(chip, pcr_idx, res_buf); tpm_chip_put(chip); return rc; } EXPORT_SYMBOL_GPL(tpm_pcr_read); /** * tpm_pcr_extend - extend pcr value with hash * @chip_num: tpm idx # or AN& * @pcr_idx: pcr idx to extend * @hash: hash value used to extend pcr value * * The TPM driver should be built-in, but for whatever reason it * isn't, protect against the chip disappearing, by incrementing * the module usage count. */ #define TPM_ORD_PCR_EXTEND cpu_to_be32(20) #define EXTEND_PCR_RESULT_SIZE 34 static struct tpm_input_header pcrextend_header = { .tag = TPM_TAG_RQU_COMMAND, .length = cpu_to_be32(34), .ordinal = TPM_ORD_PCR_EXTEND }; int tpm_pcr_extend(u32 chip_num, int pcr_idx, const u8 *hash) { struct tpm_cmd_t cmd; int rc; struct tpm_chip *chip; chip = tpm_chip_find_get(chip_num); if (chip == NULL) return -ENODEV; cmd.header.in = pcrextend_header; cmd.params.pcrextend_in.pcr_idx = cpu_to_be32(pcr_idx); memcpy(cmd.params.pcrextend_in.hash, hash, TPM_DIGEST_SIZE); rc = transmit_cmd(chip, &cmd, EXTEND_PCR_RESULT_SIZE, "attempting extend a PCR value"); tpm_chip_put(chip); return rc; } EXPORT_SYMBOL_GPL(tpm_pcr_extend); int tpm_send(u32 chip_num, void *cmd, size_t buflen) { struct tpm_chip *chip; int rc; chip = tpm_chip_find_get(chip_num); if (chip == NULL) return -ENODEV; rc = transmit_cmd(chip, cmd, buflen, "attempting tpm_cmd"); tpm_chip_put(chip); return rc; } EXPORT_SYMBOL_GPL(tpm_send); ssize_t tpm_show_pcrs(struct device *dev, struct device_attribute *attr, char *buf) { cap_t cap; u8 digest[TPM_DIGEST_SIZE]; ssize_t rc; int i, j, num_pcrs; char *str = buf; struct tpm_chip *chip = dev_get_drvdata(dev); rc = tpm_getcap(dev, TPM_CAP_PROP_PCR, &cap, "attempting to determine the number of PCRS"); if (rc) return 0; num_pcrs = be32_to_cpu(cap.num_pcrs); for (i = 0; i < num_pcrs; i++) { rc = __tpm_pcr_read(chip, i, digest); if (rc) break; str += sprintf(str, "PCR-%02d: ", i); for (j = 0; j < TPM_DIGEST_SIZE; j++) str += sprintf(str, "%02X ", digest[j]); str += sprintf(str, "\n"); } return str - buf; } EXPORT_SYMBOL_GPL(tpm_show_pcrs); #define READ_PUBEK_RESULT_SIZE 314 #define TPM_ORD_READPUBEK cpu_to_be32(124) struct tpm_input_header tpm_readpubek_header = { .tag = TPM_TAG_RQU_COMMAND, .length = cpu_to_be32(30), .ordinal = TPM_ORD_READPUBEK }; ssize_t tpm_show_pubek(struct device *dev, struct device_attribute *attr, char *buf) { u8 *data; struct tpm_cmd_t tpm_cmd; ssize_t err; int i, rc; char *str = buf; struct tpm_chip *chip = dev_get_drvdata(dev); tpm_cmd.header.in = tpm_readpubek_header; err = transmit_cmd(chip, &tpm_cmd, READ_PUBEK_RESULT_SIZE, "attempting to read the PUBEK"); if (err) goto out; /* ignore header 10 bytes algorithm 32 bits (1 == RSA ) encscheme 16 bits sigscheme 16 bits parameters (RSA 12->bytes: keybit, #primes, expbit) keylenbytes 32 bits 256 byte modulus ignore checksum 20 bytes */ data = tpm_cmd.params.readpubek_out_buffer; str += sprintf(str, "Algorithm: %02X %02X %02X %02X\nEncscheme: %02X %02X\n" "Sigscheme: %02X %02X\nParameters: %02X %02X %02X %02X" " %02X %02X %02X %02X %02X %02X %02X %02X\n" "Modulus length: %d\nModulus: \n", data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[22], data[23], data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31], data[32], data[33], be32_to_cpu(*((__be32 *) (data + 34)))); for (i = 0; i < 256; i++) { str += sprintf(str, "%02X ", data[i + 38]); if ((i + 1) % 16 == 0) str += sprintf(str, "\n"); } out: rc = str - buf; return rc; } EXPORT_SYMBOL_GPL(tpm_show_pubek); ssize_t tpm_show_caps(struct device *dev, struct device_attribute *attr, char *buf) { cap_t cap; ssize_t rc; char *str = buf; rc = tpm_getcap(dev, TPM_CAP_PROP_MANUFACTURER, &cap, "attempting to determine the manufacturer"); if (rc) return 0; str += sprintf(str, "Manufacturer: 0x%x\n", be32_to_cpu(cap.manufacturer_id)); rc = tpm_getcap(dev, CAP_VERSION_1_1, &cap, "attempting to determine the 1.1 version"); if (rc) return 0; str += sprintf(str, "TCG version: %d.%d\nFirmware version: %d.%d\n", cap.tpm_version.Major, cap.tpm_version.Minor, cap.tpm_version.revMajor, cap.tpm_version.revMinor); return str - buf; } EXPORT_SYMBOL_GPL(tpm_show_caps); ssize_t tpm_show_caps_1_2(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; char *str = buf; rc = tpm_getcap(dev, TPM_CAP_PROP_MANUFACTURER, &cap, "attempting to determine the manufacturer"); if (rc) return 0; str += sprintf(str, "Manufacturer: 0x%x\n", be32_to_cpu(cap.manufacturer_id)); rc = tpm_getcap(dev, CAP_VERSION_1_2, &cap, "attempting to determine the 1.2 version"); if (rc) return 0; str += sprintf(str, "TCG version: %d.%d\nFirmware version: %d.%d\n", cap.tpm_version_1_2.Major, cap.tpm_version_1_2.Minor, cap.tpm_version_1_2.revMajor, cap.tpm_version_1_2.revMinor); return str - buf; } EXPORT_SYMBOL_GPL(tpm_show_caps_1_2); ssize_t tpm_store_cancel(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct tpm_chip *chip = dev_get_drvdata(dev); if (chip == NULL) return 0; chip->vendor.cancel(chip); return count; } EXPORT_SYMBOL_GPL(tpm_store_cancel); /* * Device file system interface to the TPM * * It's assured that the chip will be opened just once, * by the check of is_open variable, which is protected * by driver_lock. */ int tpm_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct tpm_chip *chip = NULL, *pos; rcu_read_lock(); list_for_each_entry_rcu(pos, &tpm_chip_list, list) { if (pos->vendor.miscdev.minor == minor) { chip = pos; get_device(chip->dev); break; } } rcu_read_unlock(); if (!chip) return -ENODEV; if (test_and_set_bit(0, &chip->is_open)) { dev_dbg(chip->dev, "Another process owns this TPM\n"); put_device(chip->dev); return -EBUSY; } chip->data_buffer = kzalloc(TPM_BUFSIZE, GFP_KERNEL); if (chip->data_buffer == NULL) { clear_bit(0, &chip->is_open); put_device(chip->dev); return -ENOMEM; } atomic_set(&chip->data_pending, 0); file->private_data = chip; return 0; } EXPORT_SYMBOL_GPL(tpm_open); /* * Called on file close */ int tpm_release(struct inode *inode, struct file *file) { struct tpm_chip *chip = file->private_data; del_singleshot_timer_sync(&chip->user_read_timer); flush_work_sync(&chip->work); file->private_data = NULL; atomic_set(&chip->data_pending, 0); kfree(chip->data_buffer); clear_bit(0, &chip->is_open); put_device(chip->dev); return 0; } EXPORT_SYMBOL_GPL(tpm_release); ssize_t tpm_write(struct file *file, const char __user *buf, size_t size, loff_t *off) { struct tpm_chip *chip = file->private_data; size_t in_size = size, out_size; /* cannot perform a write until the read has cleared either via tpm_read or a user_read_timer timeout */ while (atomic_read(&chip->data_pending) != 0) msleep(TPM_TIMEOUT); mutex_lock(&chip->buffer_mutex); if (in_size > TPM_BUFSIZE) in_size = TPM_BUFSIZE; if (copy_from_user (chip->data_buffer, (void __user *) buf, in_size)) { mutex_unlock(&chip->buffer_mutex); return -EFAULT; } /* atomic tpm command send and result receive */ out_size = tpm_transmit(chip, chip->data_buffer, TPM_BUFSIZE); atomic_set(&chip->data_pending, out_size); mutex_unlock(&chip->buffer_mutex); /* Set a timeout by which the reader must come claim the result */ mod_timer(&chip->user_read_timer, jiffies + (60 * HZ)); return in_size; } EXPORT_SYMBOL_GPL(tpm_write); ssize_t tpm_read(struct file *file, char __user *buf, size_t size, loff_t *off) { struct tpm_chip *chip = file->private_data; ssize_t ret_size; del_singleshot_timer_sync(&chip->user_read_timer); flush_work_sync(&chip->work); ret_size = atomic_read(&chip->data_pending); atomic_set(&chip->data_pending, 0); if (ret_size > 0) { /* relay data */ if (size < ret_size) ret_size = size; mutex_lock(&chip->buffer_mutex); if (copy_to_user(buf, chip->data_buffer, ret_size)) ret_size = -EFAULT; mutex_unlock(&chip->buffer_mutex); } return ret_size; } EXPORT_SYMBOL_GPL(tpm_read); void tpm_remove_hardware(struct device *dev) { struct tpm_chip *chip = dev_get_drvdata(dev); if (chip == NULL) { dev_err(dev, "No device data found\n"); return; } spin_lock(&driver_lock); list_del_rcu(&chip->list); spin_unlock(&driver_lock); synchronize_rcu(); misc_deregister(&chip->vendor.miscdev); sysfs_remove_group(&dev->kobj, chip->vendor.attr_group); tpm_bios_log_teardown(chip->bios_dir); /* write it this way to be explicit (chip->dev == dev) */ put_device(chip->dev); } EXPORT_SYMBOL_GPL(tpm_remove_hardware); #define TPM_ORD_SAVESTATE cpu_to_be32(152) #define SAVESTATE_RESULT_SIZE 10 static struct tpm_input_header savestate_header = { .tag = TPM_TAG_RQU_COMMAND, .length = cpu_to_be32(10), .ordinal = TPM_ORD_SAVESTATE }; /* * We are about to suspend. Save the TPM state * so that it can be restored. */ int tpm_pm_suspend(struct device *dev, pm_message_t pm_state) { struct tpm_chip *chip = dev_get_drvdata(dev); struct tpm_cmd_t cmd; int rc; u8 dummy_hash[TPM_DIGEST_SIZE] = { 0 }; if (chip == NULL) return -ENODEV; /* for buggy tpm, flush pcrs with extend to selected dummy */ if (tpm_suspend_pcr) { cmd.header.in = pcrextend_header; cmd.params.pcrextend_in.pcr_idx = cpu_to_be32(tpm_suspend_pcr); memcpy(cmd.params.pcrextend_in.hash, dummy_hash, TPM_DIGEST_SIZE); rc = transmit_cmd(chip, &cmd, EXTEND_PCR_RESULT_SIZE, "extending dummy pcr before suspend"); } /* now do the actual savestate */ cmd.header.in = savestate_header; rc = transmit_cmd(chip, &cmd, SAVESTATE_RESULT_SIZE, "sending savestate before suspend"); return rc; } EXPORT_SYMBOL_GPL(tpm_pm_suspend); /* * Resume from a power safe. The BIOS already restored * the TPM state. */ int tpm_pm_resume(struct device *dev) { struct tpm_chip *chip = dev_get_drvdata(dev); if (chip == NULL) return -ENODEV; return 0; } EXPORT_SYMBOL_GPL(tpm_pm_resume); /* In case vendor provided release function, call it too.*/ void tpm_dev_vendor_release(struct tpm_chip *chip) { if (chip->vendor.release) chip->vendor.release(chip->dev); clear_bit(chip->dev_num, dev_mask); kfree(chip->vendor.miscdev.name); } EXPORT_SYMBOL_GPL(tpm_dev_vendor_release); /* * Once all references to platform device are down to 0, * release all allocated structures. */ void tpm_dev_release(struct device *dev) { struct tpm_chip *chip = dev_get_drvdata(dev); tpm_dev_vendor_release(chip); chip->release(dev); kfree(chip); } EXPORT_SYMBOL_GPL(tpm_dev_release); /* * Called from tpm_<specific>.c probe function only for devices * the driver has determined it should claim. Prior to calling * this function the specific probe function has called pci_enable_device * upon errant exit from this function specific probe function should call * pci_disable_device */ struct tpm_chip *tpm_register_hardware(struct device *dev, const struct tpm_vendor_specific *entry) { #define DEVNAME_SIZE 7 char *devname; struct tpm_chip *chip; /* Driver specific per-device data */ chip = kzalloc(sizeof(*chip), GFP_KERNEL); devname = kmalloc(DEVNAME_SIZE, GFP_KERNEL); if (chip == NULL || devname == NULL) goto out_free; mutex_init(&chip->buffer_mutex); mutex_init(&chip->tpm_mutex); INIT_LIST_HEAD(&chip->list); INIT_WORK(&chip->work, timeout_work); setup_timer(&chip->user_read_timer, user_reader_timeout, (unsigned long)chip); memcpy(&chip->vendor, entry, sizeof(struct tpm_vendor_specific)); chip->dev_num = find_first_zero_bit(dev_mask, TPM_NUM_DEVICES); if (chip->dev_num >= TPM_NUM_DEVICES) { dev_err(dev, "No available tpm device numbers\n"); goto out_free; } else if (chip->dev_num == 0) chip->vendor.miscdev.minor = TPM_MINOR; else chip->vendor.miscdev.minor = MISC_DYNAMIC_MINOR; set_bit(chip->dev_num, dev_mask); scnprintf(devname, DEVNAME_SIZE, "%s%d", "tpm", chip->dev_num); chip->vendor.miscdev.name = devname; chip->vendor.miscdev.parent = dev; chip->dev = get_device(dev); chip->release = dev->release; dev->release = tpm_dev_release; dev_set_drvdata(dev, chip); if (misc_register(&chip->vendor.miscdev)) { dev_err(chip->dev, "unable to misc_register %s, minor %d\n", chip->vendor.miscdev.name, chip->vendor.miscdev.minor); put_device(chip->dev); return NULL; } if (sysfs_create_group(&dev->kobj, chip->vendor.attr_group)) { misc_deregister(&chip->vendor.miscdev); put_device(chip->dev); return NULL; } chip->bios_dir = tpm_bios_log_setup(devname); /* Make chip available */ spin_lock(&driver_lock); list_add_rcu(&chip->list, &tpm_chip_list); spin_unlock(&driver_lock); return chip; out_free: kfree(chip); kfree(devname); return NULL; } EXPORT_SYMBOL_GPL(tpm_register_hardware); MODULE_AUTHOR("Leendert van Doorn (leendert@watson.ibm.com)"); MODULE_DESCRIPTION("TPM Driver"); MODULE_VERSION("2.0"); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_3444_0
crossvul-cpp_data_good_758_2
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/workqueue.h> #include <linux/rtnetlink.h> #include <linux/cache.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/idr.h> #include <linux/rculist.h> #include <linux/nsproxy.h> #include <linux/fs.h> #include <linux/proc_ns.h> #include <linux/file.h> #include <linux/export.h> #include <linux/user_namespace.h> #include <linux/net_namespace.h> #include <linux/sched/task.h> #include <linux/uidgid.h> #include <net/sock.h> #include <net/netlink.h> #include <net/net_namespace.h> #include <net/netns/generic.h> /* * Our network namespace constructor/destructor lists */ static LIST_HEAD(pernet_list); static struct list_head *first_device = &pernet_list; LIST_HEAD(net_namespace_list); EXPORT_SYMBOL_GPL(net_namespace_list); /* Protects net_namespace_list. Nests iside rtnl_lock() */ DECLARE_RWSEM(net_rwsem); EXPORT_SYMBOL_GPL(net_rwsem); struct net init_net = { .count = REFCOUNT_INIT(1), .dev_base_head = LIST_HEAD_INIT(init_net.dev_base_head), }; EXPORT_SYMBOL(init_net); static bool init_net_initialized; /* * pernet_ops_rwsem: protects: pernet_list, net_generic_ids, * init_net_initialized and first_device pointer. * This is internal net namespace object. Please, don't use it * outside. */ DECLARE_RWSEM(pernet_ops_rwsem); EXPORT_SYMBOL_GPL(pernet_ops_rwsem); #define MIN_PERNET_OPS_ID \ ((sizeof(struct net_generic) + sizeof(void *) - 1) / sizeof(void *)) #define INITIAL_NET_GEN_PTRS 13 /* +1 for len +2 for rcu_head */ static unsigned int max_gen_ptrs = INITIAL_NET_GEN_PTRS; static struct net_generic *net_alloc_generic(void) { struct net_generic *ng; unsigned int generic_size = offsetof(struct net_generic, ptr[max_gen_ptrs]); ng = kzalloc(generic_size, GFP_KERNEL); if (ng) ng->s.len = max_gen_ptrs; return ng; } static int net_assign_generic(struct net *net, unsigned int id, void *data) { struct net_generic *ng, *old_ng; BUG_ON(id < MIN_PERNET_OPS_ID); old_ng = rcu_dereference_protected(net->gen, lockdep_is_held(&pernet_ops_rwsem)); if (old_ng->s.len > id) { old_ng->ptr[id] = data; return 0; } ng = net_alloc_generic(); if (ng == NULL) return -ENOMEM; /* * Some synchronisation notes: * * The net_generic explores the net->gen array inside rcu * read section. Besides once set the net->gen->ptr[x] * pointer never changes (see rules in netns/generic.h). * * That said, we simply duplicate this array and schedule * the old copy for kfree after a grace period. */ memcpy(&ng->ptr[MIN_PERNET_OPS_ID], &old_ng->ptr[MIN_PERNET_OPS_ID], (old_ng->s.len - MIN_PERNET_OPS_ID) * sizeof(void *)); ng->ptr[id] = data; rcu_assign_pointer(net->gen, ng); kfree_rcu(old_ng, s.rcu); return 0; } static int ops_init(const struct pernet_operations *ops, struct net *net) { int err = -ENOMEM; void *data = NULL; if (ops->id && ops->size) { data = kzalloc(ops->size, GFP_KERNEL); if (!data) goto out; err = net_assign_generic(net, *ops->id, data); if (err) goto cleanup; } err = 0; if (ops->init) err = ops->init(net); if (!err) return 0; cleanup: kfree(data); out: return err; } static void ops_free(const struct pernet_operations *ops, struct net *net) { if (ops->id && ops->size) { kfree(net_generic(net, *ops->id)); } } static void ops_exit_list(const struct pernet_operations *ops, struct list_head *net_exit_list) { struct net *net; if (ops->exit) { list_for_each_entry(net, net_exit_list, exit_list) ops->exit(net); } if (ops->exit_batch) ops->exit_batch(net_exit_list); } static void ops_free_list(const struct pernet_operations *ops, struct list_head *net_exit_list) { struct net *net; if (ops->size && ops->id) { list_for_each_entry(net, net_exit_list, exit_list) ops_free(ops, net); } } /* should be called with nsid_lock held */ static int alloc_netid(struct net *net, struct net *peer, int reqid) { int min = 0, max = 0; if (reqid >= 0) { min = reqid; max = reqid + 1; } return idr_alloc(&net->netns_ids, peer, min, max, GFP_ATOMIC); } /* This function is used by idr_for_each(). If net is equal to peer, the * function returns the id so that idr_for_each() stops. Because we cannot * returns the id 0 (idr_for_each() will not stop), we return the magic value * NET_ID_ZERO (-1) for it. */ #define NET_ID_ZERO -1 static int net_eq_idr(int id, void *net, void *peer) { if (net_eq(net, peer)) return id ? : NET_ID_ZERO; return 0; } /* Should be called with nsid_lock held. If a new id is assigned, the bool alloc * is set to true, thus the caller knows that the new id must be notified via * rtnl. */ static int __peernet2id_alloc(struct net *net, struct net *peer, bool *alloc) { int id = idr_for_each(&net->netns_ids, net_eq_idr, peer); bool alloc_it = *alloc; *alloc = false; /* Magic value for id 0. */ if (id == NET_ID_ZERO) return 0; if (id > 0) return id; if (alloc_it) { id = alloc_netid(net, peer, -1); *alloc = true; return id >= 0 ? id : NETNSA_NSID_NOT_ASSIGNED; } return NETNSA_NSID_NOT_ASSIGNED; } /* should be called with nsid_lock held */ static int __peernet2id(struct net *net, struct net *peer) { bool no = false; return __peernet2id_alloc(net, peer, &no); } static void rtnl_net_notifyid(struct net *net, int cmd, int id); /* This function returns the id of a peer netns. If no id is assigned, one will * be allocated and returned. */ int peernet2id_alloc(struct net *net, struct net *peer) { bool alloc = false, alive = false; int id; if (refcount_read(&net->count) == 0) return NETNSA_NSID_NOT_ASSIGNED; spin_lock_bh(&net->nsid_lock); /* * When peer is obtained from RCU lists, we may race with * its cleanup. Check whether it's alive, and this guarantees * we never hash a peer back to net->netns_ids, after it has * just been idr_remove()'d from there in cleanup_net(). */ if (maybe_get_net(peer)) alive = alloc = true; id = __peernet2id_alloc(net, peer, &alloc); spin_unlock_bh(&net->nsid_lock); if (alloc && id >= 0) rtnl_net_notifyid(net, RTM_NEWNSID, id); if (alive) put_net(peer); return id; } EXPORT_SYMBOL_GPL(peernet2id_alloc); /* This function returns, if assigned, the id of a peer netns. */ int peernet2id(struct net *net, struct net *peer) { int id; spin_lock_bh(&net->nsid_lock); id = __peernet2id(net, peer); spin_unlock_bh(&net->nsid_lock); return id; } EXPORT_SYMBOL(peernet2id); /* This function returns true is the peer netns has an id assigned into the * current netns. */ bool peernet_has_id(struct net *net, struct net *peer) { return peernet2id(net, peer) >= 0; } struct net *get_net_ns_by_id(struct net *net, int id) { struct net *peer; if (id < 0) return NULL; rcu_read_lock(); peer = idr_find(&net->netns_ids, id); if (peer) peer = maybe_get_net(peer); rcu_read_unlock(); return peer; } /* * setup_net runs the initializers for the network namespace object. */ static __net_init int setup_net(struct net *net, struct user_namespace *user_ns) { /* Must be called with pernet_ops_rwsem held */ const struct pernet_operations *ops, *saved_ops; int error = 0; LIST_HEAD(net_exit_list); refcount_set(&net->count, 1); refcount_set(&net->passive, 1); get_random_bytes(&net->hash_mix, sizeof(u32)); net->dev_base_seq = 1; net->user_ns = user_ns; idr_init(&net->netns_ids); spin_lock_init(&net->nsid_lock); mutex_init(&net->ipv4.ra_mutex); list_for_each_entry(ops, &pernet_list, list) { error = ops_init(ops, net); if (error < 0) goto out_undo; } down_write(&net_rwsem); list_add_tail_rcu(&net->list, &net_namespace_list); up_write(&net_rwsem); out: return error; out_undo: /* Walk through the list backwards calling the exit functions * for the pernet modules whose init functions did not fail. */ list_add(&net->exit_list, &net_exit_list); saved_ops = ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_exit_list(ops, &net_exit_list); ops = saved_ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_free_list(ops, &net_exit_list); rcu_barrier(); goto out; } static int __net_init net_defaults_init_net(struct net *net) { net->core.sysctl_somaxconn = SOMAXCONN; return 0; } static struct pernet_operations net_defaults_ops = { .init = net_defaults_init_net, }; static __init int net_defaults_init(void) { if (register_pernet_subsys(&net_defaults_ops)) panic("Cannot initialize net default settings"); return 0; } core_initcall(net_defaults_init); #ifdef CONFIG_NET_NS static struct ucounts *inc_net_namespaces(struct user_namespace *ns) { return inc_ucount(ns, current_euid(), UCOUNT_NET_NAMESPACES); } static void dec_net_namespaces(struct ucounts *ucounts) { dec_ucount(ucounts, UCOUNT_NET_NAMESPACES); } static struct kmem_cache *net_cachep __ro_after_init; static struct workqueue_struct *netns_wq; static struct net *net_alloc(void) { struct net *net = NULL; struct net_generic *ng; ng = net_alloc_generic(); if (!ng) goto out; net = kmem_cache_zalloc(net_cachep, GFP_KERNEL); if (!net) goto out_free; rcu_assign_pointer(net->gen, ng); out: return net; out_free: kfree(ng); goto out; } static void net_free(struct net *net) { kfree(rcu_access_pointer(net->gen)); kmem_cache_free(net_cachep, net); } void net_drop_ns(void *p) { struct net *ns = p; if (ns && refcount_dec_and_test(&ns->passive)) net_free(ns); } struct net *copy_net_ns(unsigned long flags, struct user_namespace *user_ns, struct net *old_net) { struct ucounts *ucounts; struct net *net; int rv; if (!(flags & CLONE_NEWNET)) return get_net(old_net); ucounts = inc_net_namespaces(user_ns); if (!ucounts) return ERR_PTR(-ENOSPC); net = net_alloc(); if (!net) { rv = -ENOMEM; goto dec_ucounts; } refcount_set(&net->passive, 1); net->ucounts = ucounts; get_user_ns(user_ns); rv = down_read_killable(&pernet_ops_rwsem); if (rv < 0) goto put_userns; rv = setup_net(net, user_ns); up_read(&pernet_ops_rwsem); if (rv < 0) { put_userns: put_user_ns(user_ns); net_drop_ns(net); dec_ucounts: dec_net_namespaces(ucounts); return ERR_PTR(rv); } return net; } /** * net_ns_get_ownership - get sysfs ownership data for @net * @net: network namespace in question (can be NULL) * @uid: kernel user ID for sysfs objects * @gid: kernel group ID for sysfs objects * * Returns the uid/gid pair of root in the user namespace associated with the * given network namespace. */ void net_ns_get_ownership(const struct net *net, kuid_t *uid, kgid_t *gid) { if (net) { kuid_t ns_root_uid = make_kuid(net->user_ns, 0); kgid_t ns_root_gid = make_kgid(net->user_ns, 0); if (uid_valid(ns_root_uid)) *uid = ns_root_uid; if (gid_valid(ns_root_gid)) *gid = ns_root_gid; } else { *uid = GLOBAL_ROOT_UID; *gid = GLOBAL_ROOT_GID; } } EXPORT_SYMBOL_GPL(net_ns_get_ownership); static void unhash_nsid(struct net *net, struct net *last) { struct net *tmp; /* This function is only called from cleanup_net() work, * and this work is the only process, that may delete * a net from net_namespace_list. So, when the below * is executing, the list may only grow. Thus, we do not * use for_each_net_rcu() or net_rwsem. */ for_each_net(tmp) { int id; spin_lock_bh(&tmp->nsid_lock); id = __peernet2id(tmp, net); if (id >= 0) idr_remove(&tmp->netns_ids, id); spin_unlock_bh(&tmp->nsid_lock); if (id >= 0) rtnl_net_notifyid(tmp, RTM_DELNSID, id); if (tmp == last) break; } spin_lock_bh(&net->nsid_lock); idr_destroy(&net->netns_ids); spin_unlock_bh(&net->nsid_lock); } static LLIST_HEAD(cleanup_list); static void cleanup_net(struct work_struct *work) { const struct pernet_operations *ops; struct net *net, *tmp, *last; struct llist_node *net_kill_list; LIST_HEAD(net_exit_list); /* Atomically snapshot the list of namespaces to cleanup */ net_kill_list = llist_del_all(&cleanup_list); down_read(&pernet_ops_rwsem); /* Don't let anyone else find us. */ down_write(&net_rwsem); llist_for_each_entry(net, net_kill_list, cleanup_list) list_del_rcu(&net->list); /* Cache last net. After we unlock rtnl, no one new net * added to net_namespace_list can assign nsid pointer * to a net from net_kill_list (see peernet2id_alloc()). * So, we skip them in unhash_nsid(). * * Note, that unhash_nsid() does not delete nsid links * between net_kill_list's nets, as they've already * deleted from net_namespace_list. But, this would be * useless anyway, as netns_ids are destroyed there. */ last = list_last_entry(&net_namespace_list, struct net, list); up_write(&net_rwsem); llist_for_each_entry(net, net_kill_list, cleanup_list) { unhash_nsid(net, last); list_add_tail(&net->exit_list, &net_exit_list); } /* * Another CPU might be rcu-iterating the list, wait for it. * This needs to be before calling the exit() notifiers, so * the rcu_barrier() below isn't sufficient alone. */ synchronize_rcu(); /* Run all of the network namespace exit methods */ list_for_each_entry_reverse(ops, &pernet_list, list) ops_exit_list(ops, &net_exit_list); /* Free the net generic variables */ list_for_each_entry_reverse(ops, &pernet_list, list) ops_free_list(ops, &net_exit_list); up_read(&pernet_ops_rwsem); /* Ensure there are no outstanding rcu callbacks using this * network namespace. */ rcu_barrier(); /* Finally it is safe to free my network namespace structure */ list_for_each_entry_safe(net, tmp, &net_exit_list, exit_list) { list_del_init(&net->exit_list); dec_net_namespaces(net->ucounts); put_user_ns(net->user_ns); net_drop_ns(net); } } /** * net_ns_barrier - wait until concurrent net_cleanup_work is done * * cleanup_net runs from work queue and will first remove namespaces * from the global list, then run net exit functions. * * Call this in module exit path to make sure that all netns * ->exit ops have been invoked before the function is removed. */ void net_ns_barrier(void) { down_write(&pernet_ops_rwsem); up_write(&pernet_ops_rwsem); } EXPORT_SYMBOL(net_ns_barrier); static DECLARE_WORK(net_cleanup_work, cleanup_net); void __put_net(struct net *net) { /* Cleanup the network namespace in process context */ if (llist_add(&net->cleanup_list, &cleanup_list)) queue_work(netns_wq, &net_cleanup_work); } EXPORT_SYMBOL_GPL(__put_net); struct net *get_net_ns_by_fd(int fd) { struct file *file; struct ns_common *ns; struct net *net; file = proc_ns_fget(fd); if (IS_ERR(file)) return ERR_CAST(file); ns = get_proc_ns(file_inode(file)); if (ns->ops == &netns_operations) net = get_net(container_of(ns, struct net, ns)); else net = ERR_PTR(-EINVAL); fput(file); return net; } #else struct net *get_net_ns_by_fd(int fd) { return ERR_PTR(-EINVAL); } #endif EXPORT_SYMBOL_GPL(get_net_ns_by_fd); struct net *get_net_ns_by_pid(pid_t pid) { struct task_struct *tsk; struct net *net; /* Lookup the network namespace */ net = ERR_PTR(-ESRCH); rcu_read_lock(); tsk = find_task_by_vpid(pid); if (tsk) { struct nsproxy *nsproxy; task_lock(tsk); nsproxy = tsk->nsproxy; if (nsproxy) net = get_net(nsproxy->net_ns); task_unlock(tsk); } rcu_read_unlock(); return net; } EXPORT_SYMBOL_GPL(get_net_ns_by_pid); static __net_init int net_ns_net_init(struct net *net) { #ifdef CONFIG_NET_NS net->ns.ops = &netns_operations; #endif return ns_alloc_inum(&net->ns); } static __net_exit void net_ns_net_exit(struct net *net) { ns_free_inum(&net->ns); } static struct pernet_operations __net_initdata net_ns_ops = { .init = net_ns_net_init, .exit = net_ns_net_exit, }; static const struct nla_policy rtnl_net_policy[NETNSA_MAX + 1] = { [NETNSA_NONE] = { .type = NLA_UNSPEC }, [NETNSA_NSID] = { .type = NLA_S32 }, [NETNSA_PID] = { .type = NLA_U32 }, [NETNSA_FD] = { .type = NLA_U32 }, [NETNSA_TARGET_NSID] = { .type = NLA_S32 }, }; static int rtnl_net_newid(struct sk_buff *skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(skb->sk); struct nlattr *tb[NETNSA_MAX + 1]; struct nlattr *nla; struct net *peer; int nsid, err; err = nlmsg_parse(nlh, sizeof(struct rtgenmsg), tb, NETNSA_MAX, rtnl_net_policy, extack); if (err < 0) return err; if (!tb[NETNSA_NSID]) { NL_SET_ERR_MSG(extack, "nsid is missing"); return -EINVAL; } nsid = nla_get_s32(tb[NETNSA_NSID]); if (tb[NETNSA_PID]) { peer = get_net_ns_by_pid(nla_get_u32(tb[NETNSA_PID])); nla = tb[NETNSA_PID]; } else if (tb[NETNSA_FD]) { peer = get_net_ns_by_fd(nla_get_u32(tb[NETNSA_FD])); nla = tb[NETNSA_FD]; } else { NL_SET_ERR_MSG(extack, "Peer netns reference is missing"); return -EINVAL; } if (IS_ERR(peer)) { NL_SET_BAD_ATTR(extack, nla); NL_SET_ERR_MSG(extack, "Peer netns reference is invalid"); return PTR_ERR(peer); } spin_lock_bh(&net->nsid_lock); if (__peernet2id(net, peer) >= 0) { spin_unlock_bh(&net->nsid_lock); err = -EEXIST; NL_SET_BAD_ATTR(extack, nla); NL_SET_ERR_MSG(extack, "Peer netns already has a nsid assigned"); goto out; } err = alloc_netid(net, peer, nsid); spin_unlock_bh(&net->nsid_lock); if (err >= 0) { rtnl_net_notifyid(net, RTM_NEWNSID, err); err = 0; } else if (err == -ENOSPC && nsid >= 0) { err = -EEXIST; NL_SET_BAD_ATTR(extack, tb[NETNSA_NSID]); NL_SET_ERR_MSG(extack, "The specified nsid is already used"); } out: put_net(peer); return err; } static int rtnl_net_get_size(void) { return NLMSG_ALIGN(sizeof(struct rtgenmsg)) + nla_total_size(sizeof(s32)) /* NETNSA_NSID */ + nla_total_size(sizeof(s32)) /* NETNSA_CURRENT_NSID */ ; } struct net_fill_args { u32 portid; u32 seq; int flags; int cmd; int nsid; bool add_ref; int ref_nsid; }; static int rtnl_net_fill(struct sk_buff *skb, struct net_fill_args *args) { struct nlmsghdr *nlh; struct rtgenmsg *rth; nlh = nlmsg_put(skb, args->portid, args->seq, args->cmd, sizeof(*rth), args->flags); if (!nlh) return -EMSGSIZE; rth = nlmsg_data(nlh); rth->rtgen_family = AF_UNSPEC; if (nla_put_s32(skb, NETNSA_NSID, args->nsid)) goto nla_put_failure; if (args->add_ref && nla_put_s32(skb, NETNSA_CURRENT_NSID, args->ref_nsid)) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int rtnl_net_valid_getid_req(struct sk_buff *skb, const struct nlmsghdr *nlh, struct nlattr **tb, struct netlink_ext_ack *extack) { int i, err; if (!netlink_strict_get_check(skb)) return nlmsg_parse(nlh, sizeof(struct rtgenmsg), tb, NETNSA_MAX, rtnl_net_policy, extack); err = nlmsg_parse_strict(nlh, sizeof(struct rtgenmsg), tb, NETNSA_MAX, rtnl_net_policy, extack); if (err) return err; for (i = 0; i <= NETNSA_MAX; i++) { if (!tb[i]) continue; switch (i) { case NETNSA_PID: case NETNSA_FD: case NETNSA_NSID: case NETNSA_TARGET_NSID: break; default: NL_SET_ERR_MSG(extack, "Unsupported attribute in peer netns getid request"); return -EINVAL; } } return 0; } static int rtnl_net_getid(struct sk_buff *skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(skb->sk); struct nlattr *tb[NETNSA_MAX + 1]; struct net_fill_args fillargs = { .portid = NETLINK_CB(skb).portid, .seq = nlh->nlmsg_seq, .cmd = RTM_NEWNSID, }; struct net *peer, *target = net; struct nlattr *nla; struct sk_buff *msg; int err; err = rtnl_net_valid_getid_req(skb, nlh, tb, extack); if (err < 0) return err; if (tb[NETNSA_PID]) { peer = get_net_ns_by_pid(nla_get_u32(tb[NETNSA_PID])); nla = tb[NETNSA_PID]; } else if (tb[NETNSA_FD]) { peer = get_net_ns_by_fd(nla_get_u32(tb[NETNSA_FD])); nla = tb[NETNSA_FD]; } else if (tb[NETNSA_NSID]) { peer = get_net_ns_by_id(net, nla_get_u32(tb[NETNSA_NSID])); if (!peer) peer = ERR_PTR(-ENOENT); nla = tb[NETNSA_NSID]; } else { NL_SET_ERR_MSG(extack, "Peer netns reference is missing"); return -EINVAL; } if (IS_ERR(peer)) { NL_SET_BAD_ATTR(extack, nla); NL_SET_ERR_MSG(extack, "Peer netns reference is invalid"); return PTR_ERR(peer); } if (tb[NETNSA_TARGET_NSID]) { int id = nla_get_s32(tb[NETNSA_TARGET_NSID]); target = rtnl_get_net_ns_capable(NETLINK_CB(skb).sk, id); if (IS_ERR(target)) { NL_SET_BAD_ATTR(extack, tb[NETNSA_TARGET_NSID]); NL_SET_ERR_MSG(extack, "Target netns reference is invalid"); err = PTR_ERR(target); goto out; } fillargs.add_ref = true; fillargs.ref_nsid = peernet2id(net, peer); } msg = nlmsg_new(rtnl_net_get_size(), GFP_KERNEL); if (!msg) { err = -ENOMEM; goto out; } fillargs.nsid = peernet2id(target, peer); err = rtnl_net_fill(msg, &fillargs); if (err < 0) goto err_out; err = rtnl_unicast(msg, net, NETLINK_CB(skb).portid); goto out; err_out: nlmsg_free(msg); out: if (fillargs.add_ref) put_net(target); put_net(peer); return err; } struct rtnl_net_dump_cb { struct net *tgt_net; struct net *ref_net; struct sk_buff *skb; struct net_fill_args fillargs; int idx; int s_idx; }; static int rtnl_net_dumpid_one(int id, void *peer, void *data) { struct rtnl_net_dump_cb *net_cb = (struct rtnl_net_dump_cb *)data; int ret; if (net_cb->idx < net_cb->s_idx) goto cont; net_cb->fillargs.nsid = id; if (net_cb->fillargs.add_ref) net_cb->fillargs.ref_nsid = __peernet2id(net_cb->ref_net, peer); ret = rtnl_net_fill(net_cb->skb, &net_cb->fillargs); if (ret < 0) return ret; cont: net_cb->idx++; return 0; } static int rtnl_valid_dump_net_req(const struct nlmsghdr *nlh, struct sock *sk, struct rtnl_net_dump_cb *net_cb, struct netlink_callback *cb) { struct netlink_ext_ack *extack = cb->extack; struct nlattr *tb[NETNSA_MAX + 1]; int err, i; err = nlmsg_parse_strict(nlh, sizeof(struct rtgenmsg), tb, NETNSA_MAX, rtnl_net_policy, extack); if (err < 0) return err; for (i = 0; i <= NETNSA_MAX; i++) { if (!tb[i]) continue; if (i == NETNSA_TARGET_NSID) { struct net *net; net = rtnl_get_net_ns_capable(sk, nla_get_s32(tb[i])); if (IS_ERR(net)) { NL_SET_BAD_ATTR(extack, tb[i]); NL_SET_ERR_MSG(extack, "Invalid target network namespace id"); return PTR_ERR(net); } net_cb->fillargs.add_ref = true; net_cb->ref_net = net_cb->tgt_net; net_cb->tgt_net = net; } else { NL_SET_BAD_ATTR(extack, tb[i]); NL_SET_ERR_MSG(extack, "Unsupported attribute in dump request"); return -EINVAL; } } return 0; } static int rtnl_net_dumpid(struct sk_buff *skb, struct netlink_callback *cb) { struct rtnl_net_dump_cb net_cb = { .tgt_net = sock_net(skb->sk), .skb = skb, .fillargs = { .portid = NETLINK_CB(cb->skb).portid, .seq = cb->nlh->nlmsg_seq, .flags = NLM_F_MULTI, .cmd = RTM_NEWNSID, }, .idx = 0, .s_idx = cb->args[0], }; int err = 0; if (cb->strict_check) { err = rtnl_valid_dump_net_req(cb->nlh, skb->sk, &net_cb, cb); if (err < 0) goto end; } spin_lock_bh(&net_cb.tgt_net->nsid_lock); if (net_cb.fillargs.add_ref && !net_eq(net_cb.ref_net, net_cb.tgt_net) && !spin_trylock_bh(&net_cb.ref_net->nsid_lock)) { spin_unlock_bh(&net_cb.tgt_net->nsid_lock); err = -EAGAIN; goto end; } idr_for_each(&net_cb.tgt_net->netns_ids, rtnl_net_dumpid_one, &net_cb); if (net_cb.fillargs.add_ref && !net_eq(net_cb.ref_net, net_cb.tgt_net)) spin_unlock_bh(&net_cb.ref_net->nsid_lock); spin_unlock_bh(&net_cb.tgt_net->nsid_lock); cb->args[0] = net_cb.idx; end: if (net_cb.fillargs.add_ref) put_net(net_cb.tgt_net); return err < 0 ? err : skb->len; } static void rtnl_net_notifyid(struct net *net, int cmd, int id) { struct net_fill_args fillargs = { .cmd = cmd, .nsid = id, }; struct sk_buff *msg; int err = -ENOMEM; msg = nlmsg_new(rtnl_net_get_size(), GFP_KERNEL); if (!msg) goto out; err = rtnl_net_fill(msg, &fillargs); if (err < 0) goto err_out; rtnl_notify(msg, net, 0, RTNLGRP_NSID, NULL, 0); return; err_out: nlmsg_free(msg); out: rtnl_set_sk_err(net, RTNLGRP_NSID, err); } static int __init net_ns_init(void) { struct net_generic *ng; #ifdef CONFIG_NET_NS net_cachep = kmem_cache_create("net_namespace", sizeof(struct net), SMP_CACHE_BYTES, SLAB_PANIC|SLAB_ACCOUNT, NULL); /* Create workqueue for cleanup */ netns_wq = create_singlethread_workqueue("netns"); if (!netns_wq) panic("Could not create netns workq"); #endif ng = net_alloc_generic(); if (!ng) panic("Could not allocate generic netns"); rcu_assign_pointer(init_net.gen, ng); down_write(&pernet_ops_rwsem); if (setup_net(&init_net, &init_user_ns)) panic("Could not setup the initial network namespace"); init_net_initialized = true; up_write(&pernet_ops_rwsem); if (register_pernet_subsys(&net_ns_ops)) panic("Could not register network namespace subsystems"); rtnl_register(PF_UNSPEC, RTM_NEWNSID, rtnl_net_newid, NULL, RTNL_FLAG_DOIT_UNLOCKED); rtnl_register(PF_UNSPEC, RTM_GETNSID, rtnl_net_getid, rtnl_net_dumpid, RTNL_FLAG_DOIT_UNLOCKED); return 0; } pure_initcall(net_ns_init); #ifdef CONFIG_NET_NS static int __register_pernet_operations(struct list_head *list, struct pernet_operations *ops) { struct net *net; int error; LIST_HEAD(net_exit_list); list_add_tail(&ops->list, list); if (ops->init || (ops->id && ops->size)) { /* We held write locked pernet_ops_rwsem, and parallel * setup_net() and cleanup_net() are not possible. */ for_each_net(net) { error = ops_init(ops, net); if (error) goto out_undo; list_add_tail(&net->exit_list, &net_exit_list); } } return 0; out_undo: /* If I have an error cleanup all namespaces I initialized */ list_del(&ops->list); ops_exit_list(ops, &net_exit_list); ops_free_list(ops, &net_exit_list); return error; } static void __unregister_pernet_operations(struct pernet_operations *ops) { struct net *net; LIST_HEAD(net_exit_list); list_del(&ops->list); /* See comment in __register_pernet_operations() */ for_each_net(net) list_add_tail(&net->exit_list, &net_exit_list); ops_exit_list(ops, &net_exit_list); ops_free_list(ops, &net_exit_list); } #else static int __register_pernet_operations(struct list_head *list, struct pernet_operations *ops) { if (!init_net_initialized) { list_add_tail(&ops->list, list); return 0; } return ops_init(ops, &init_net); } static void __unregister_pernet_operations(struct pernet_operations *ops) { if (!init_net_initialized) { list_del(&ops->list); } else { LIST_HEAD(net_exit_list); list_add(&init_net.exit_list, &net_exit_list); ops_exit_list(ops, &net_exit_list); ops_free_list(ops, &net_exit_list); } } #endif /* CONFIG_NET_NS */ static DEFINE_IDA(net_generic_ids); static int register_pernet_operations(struct list_head *list, struct pernet_operations *ops) { int error; if (ops->id) { error = ida_alloc_min(&net_generic_ids, MIN_PERNET_OPS_ID, GFP_KERNEL); if (error < 0) return error; *ops->id = error; max_gen_ptrs = max(max_gen_ptrs, *ops->id + 1); } error = __register_pernet_operations(list, ops); if (error) { rcu_barrier(); if (ops->id) ida_free(&net_generic_ids, *ops->id); } return error; } static void unregister_pernet_operations(struct pernet_operations *ops) { __unregister_pernet_operations(ops); rcu_barrier(); if (ops->id) ida_free(&net_generic_ids, *ops->id); } /** * register_pernet_subsys - register a network namespace subsystem * @ops: pernet operations structure for the subsystem * * Register a subsystem which has init and exit functions * that are called when network namespaces are created and * destroyed respectively. * * When registered all network namespace init functions are * called for every existing network namespace. Allowing kernel * modules to have a race free view of the set of network namespaces. * * When a new network namespace is created all of the init * methods are called in the order in which they were registered. * * When a network namespace is destroyed all of the exit methods * are called in the reverse of the order with which they were * registered. */ int register_pernet_subsys(struct pernet_operations *ops) { int error; down_write(&pernet_ops_rwsem); error = register_pernet_operations(first_device, ops); up_write(&pernet_ops_rwsem); return error; } EXPORT_SYMBOL_GPL(register_pernet_subsys); /** * unregister_pernet_subsys - unregister a network namespace subsystem * @ops: pernet operations structure to manipulate * * Remove the pernet operations structure from the list to be * used when network namespaces are created or destroyed. In * addition run the exit method for all existing network * namespaces. */ void unregister_pernet_subsys(struct pernet_operations *ops) { down_write(&pernet_ops_rwsem); unregister_pernet_operations(ops); up_write(&pernet_ops_rwsem); } EXPORT_SYMBOL_GPL(unregister_pernet_subsys); /** * register_pernet_device - register a network namespace device * @ops: pernet operations structure for the subsystem * * Register a device which has init and exit functions * that are called when network namespaces are created and * destroyed respectively. * * When registered all network namespace init functions are * called for every existing network namespace. Allowing kernel * modules to have a race free view of the set of network namespaces. * * When a new network namespace is created all of the init * methods are called in the order in which they were registered. * * When a network namespace is destroyed all of the exit methods * are called in the reverse of the order with which they were * registered. */ int register_pernet_device(struct pernet_operations *ops) { int error; down_write(&pernet_ops_rwsem); error = register_pernet_operations(&pernet_list, ops); if (!error && (first_device == &pernet_list)) first_device = &ops->list; up_write(&pernet_ops_rwsem); return error; } EXPORT_SYMBOL_GPL(register_pernet_device); /** * unregister_pernet_device - unregister a network namespace netdevice * @ops: pernet operations structure to manipulate * * Remove the pernet operations structure from the list to be * used when network namespaces are created or destroyed. In * addition run the exit method for all existing network * namespaces. */ void unregister_pernet_device(struct pernet_operations *ops) { down_write(&pernet_ops_rwsem); if (&ops->list == first_device) first_device = first_device->next; unregister_pernet_operations(ops); up_write(&pernet_ops_rwsem); } EXPORT_SYMBOL_GPL(unregister_pernet_device); #ifdef CONFIG_NET_NS static struct ns_common *netns_get(struct task_struct *task) { struct net *net = NULL; struct nsproxy *nsproxy; task_lock(task); nsproxy = task->nsproxy; if (nsproxy) net = get_net(nsproxy->net_ns); task_unlock(task); return net ? &net->ns : NULL; } static inline struct net *to_net_ns(struct ns_common *ns) { return container_of(ns, struct net, ns); } static void netns_put(struct ns_common *ns) { put_net(to_net_ns(ns)); } static int netns_install(struct nsproxy *nsproxy, struct ns_common *ns) { struct net *net = to_net_ns(ns); if (!ns_capable(net->user_ns, CAP_SYS_ADMIN) || !ns_capable(current_user_ns(), CAP_SYS_ADMIN)) return -EPERM; put_net(nsproxy->net_ns); nsproxy->net_ns = get_net(net); return 0; } static struct user_namespace *netns_owner(struct ns_common *ns) { return to_net_ns(ns)->user_ns; } const struct proc_ns_operations netns_operations = { .name = "net", .type = CLONE_NEWNET, .get = netns_get, .put = netns_put, .install = netns_install, .owner = netns_owner, }; #endif
./CrossVul/dataset_final_sorted/CWE-200/c/good_758_2
crossvul-cpp_data_bad_1508_2
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 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 <sys/utsname.h> #include "libabrt.h" #include <selinux/selinux.h> #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 static int g_user_core_flags; static int g_need_nonrelative; /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static DIR *proc_cwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static DIR *open_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); DIR *cwd = opendir(buf); if (cwd == NULL) perror_msg("Can't open process's CWD for CompatCore"); return cwd; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_proc_fs_id(char type) { const char *scanf_format = "%*cid:\t%d\t%d\t%d\t%d\n"; char id_type[] = "_id"; id_type[0] = type; int real, e_id, saved; int fs_id = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, id_type, 3) == 0) { int n = sscanf(line, scanf_format, &real, &e_id, &saved, &fs_id); if (n != 4) { perror_msg_and_die("Can't parse %cid: line", type); } return fs_id; } line = strchr(line, '\n'); if (!line) break; line++; } perror_msg_and_die("Failed to get file system %cID of the crashed process", type); } static int get_fsuid(void) { return get_proc_fs_id(/*UID*/'U'); } static int get_fsgid(void) { return get_proc_fs_id(/*GID*/'G'); } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } /* Computes a security context of new file created by the given process with * pid in the given directory represented by file descriptor. * * On errors returns negative number. Returns 0 if the function succeeds and * computes the context and returns positive number and assigns NULL to newcon * if the security context is not needed (SELinux disabled). */ static int compute_selinux_con_for_new_file(pid_t pid, int dir_fd, security_context_t *newcon) { security_context_t srccon; security_context_t dstcon; const int r = is_selinux_enabled(); if (r == 0) { *newcon = NULL; return 1; } else if (r == -1) { perror_msg("Couldn't get state of SELinux"); return -1; } else if (r != 1) error_msg_and_die("Unexpected SELinux return value: %d", r); if (getpidcon_raw(pid, &srccon) < 0) { perror_msg("getpidcon_raw(%d)", pid); return -1; } if (fgetfilecon_raw(dir_fd, &dstcon) < 0) { perror_msg("getfilecon_raw(%s)", user_pwd); return -1; } if (security_compute_create_raw(srccon, dstcon, string_to_security_class("file"), newcon) < 0) { perror_msg("security_compute_create_raw(%s, %s, 'file')", srccon, dstcon); return -1; } return 0; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { proc_cwd = open_cwd(pid); if (proc_cwd == NULL) return -1; errno = 0; /* http://article.gmane.org/gmane.comp.security.selinux/21842 */ security_context_t newcon; if (compute_selinux_con_for_new_file(pid, dirfd(proc_cwd), &newcon) < 0) { log_notice("Not going to create a user core due to SELinux errors"); return -1; } xsetegid(get_fsgid()); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } if (g_need_nonrelative && core_basename[0] != '/') { error_msg("Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern"); return -1; } /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ /* Set SELinux context like kernel when creating core dump file */ if (newcon != NULL && setfscreatecon_raw(newcon) < 0) { perror_msg("setfscreatecon_raw(%s)", newcon); return -1; } struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = openat(dirfd(proc_cwd), core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */ if (newcon != NULL && setfscreatecon_raw(NULL) < 0) { error_msg("setfscreatecon_raw(NULL)"); goto user_core_fail; } xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 || sb.st_uid != fsuid ) { if (user_core_fd < 0) perror_msg("Can't open '%s' at '%s'", core_basename, user_pwd); else perror_msg("'%s' at '%s' is not a regular file with link count 1 owned by UID(%d)", core_basename, user_pwd, fsuid); goto user_core_fail; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' at '%s' to size 0", core_basename, user_pwd); goto user_core_fail; } return user_core_fd; user_core_fail: if (user_core_fd >= 0) { close(user_core_fd); unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); } return -1; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "wx"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) fsuid = tmp_fsuid; else { g_user_core_flags = O_EXCL; g_need_nonrelative = 1; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ if (snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash) >= sizeof(path)) error_msg_and_die("Error saving '%s': truncated long file path", path); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); if (proc_cwd != NULL) closedir(proc_cwd); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt * * dd_create_skeleton() creates a new directory and leaves ownership to * the current user, hence, we have to call dd_reset_ownership() after the * directory is populated. */ dd = dd_create_skeleton(path, fsuid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* And finally set the right uid and gid */ dd_reset_ownership(dd); /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); if (proc_cwd != NULL) closedir(proc_cwd); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s' at '%s'", core_basename, user_pwd); unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); if (proc_cwd != NULL) closedir(proc_cwd); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { unlinkat(dirfd(proc_cwd), core_basename, /*unlink file*/0); if (proc_cwd != NULL) closedir(proc_cwd); return 1; } log("Saved core dump of pid %lu to %s at %s (%llu bytes)", (long)pid, core_basename, user_pwd, (long long)core_size); } if (proc_cwd != NULL) closedir(proc_cwd); return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1508_2
crossvul-cpp_data_good_3876_0
// SPDX-License-Identifier: GPL-2.0-only /* * linux/fs/binfmt_elf.c * * These are the functions used to load ELF format executables as used * on SVr4 machines. Information on the format may be found in the book * "UNIX SYSTEM V RELEASE 4 Programmers Guide: Ansi C and Programming Support * Tools". * * Copyright 1993, 1994: Eric Youngdale (ericy@cais.com). */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/errno.h> #include <linux/signal.h> #include <linux/binfmts.h> #include <linux/string.h> #include <linux/file.h> #include <linux/slab.h> #include <linux/personality.h> #include <linux/elfcore.h> #include <linux/init.h> #include <linux/highuid.h> #include <linux/compiler.h> #include <linux/highmem.h> #include <linux/hugetlb.h> #include <linux/pagemap.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/random.h> #include <linux/elf.h> #include <linux/elf-randomize.h> #include <linux/utsname.h> #include <linux/coredump.h> #include <linux/sched.h> #include <linux/sched/coredump.h> #include <linux/sched/task_stack.h> #include <linux/sched/cputime.h> #include <linux/cred.h> #include <linux/dax.h> #include <linux/uaccess.h> #include <asm/param.h> #include <asm/page.h> #ifndef user_long_t #define user_long_t long #endif #ifndef user_siginfo_t #define user_siginfo_t siginfo_t #endif /* That's for binfmt_elf_fdpic to deal with */ #ifndef elf_check_fdpic #define elf_check_fdpic(ex) false #endif static int load_elf_binary(struct linux_binprm *bprm); #ifdef CONFIG_USELIB static int load_elf_library(struct file *); #else #define load_elf_library NULL #endif /* * If we don't support core dumping, then supply a NULL so we * don't even try. */ #ifdef CONFIG_ELF_CORE static int elf_core_dump(struct coredump_params *cprm); #else #define elf_core_dump NULL #endif #if ELF_EXEC_PAGESIZE > PAGE_SIZE #define ELF_MIN_ALIGN ELF_EXEC_PAGESIZE #else #define ELF_MIN_ALIGN PAGE_SIZE #endif #ifndef ELF_CORE_EFLAGS #define ELF_CORE_EFLAGS 0 #endif #define ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(ELF_MIN_ALIGN-1)) #define ELF_PAGEOFFSET(_v) ((_v) & (ELF_MIN_ALIGN-1)) #define ELF_PAGEALIGN(_v) (((_v) + ELF_MIN_ALIGN - 1) & ~(ELF_MIN_ALIGN - 1)) static struct linux_binfmt elf_format = { .module = THIS_MODULE, .load_binary = load_elf_binary, .load_shlib = load_elf_library, .core_dump = elf_core_dump, .min_coredump = ELF_EXEC_PAGESIZE, }; #define BAD_ADDR(x) (unlikely((unsigned long)(x) >= TASK_SIZE)) static int set_brk(unsigned long start, unsigned long end, int prot) { start = ELF_PAGEALIGN(start); end = ELF_PAGEALIGN(end); if (end > start) { /* * Map the last of the bss segment. * If the header is requesting these pages to be * executable, honour that (ppc32 needs this). */ int error = vm_brk_flags(start, end - start, prot & PROT_EXEC ? VM_EXEC : 0); if (error) return error; } current->mm->start_brk = current->mm->brk = end; return 0; } /* We need to explicitly zero any fractional pages after the data section (i.e. bss). This would contain the junk from the file that should not be in memory */ static int padzero(unsigned long elf_bss) { unsigned long nbyte; nbyte = ELF_PAGEOFFSET(elf_bss); if (nbyte) { nbyte = ELF_MIN_ALIGN - nbyte; if (clear_user((void __user *) elf_bss, nbyte)) return -EFAULT; } return 0; } /* Let's use some macros to make this stack manipulation a little clearer */ #ifdef CONFIG_STACK_GROWSUP #define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) + (items)) #define STACK_ROUND(sp, items) \ ((15 + (unsigned long) ((sp) + (items))) &~ 15UL) #define STACK_ALLOC(sp, len) ({ \ elf_addr_t __user *old_sp = (elf_addr_t __user *)sp; sp += len; \ old_sp; }) #else #define STACK_ADD(sp, items) ((elf_addr_t __user *)(sp) - (items)) #define STACK_ROUND(sp, items) \ (((unsigned long) (sp - items)) &~ 15UL) #define STACK_ALLOC(sp, len) ({ sp -= len ; sp; }) #endif #ifndef ELF_BASE_PLATFORM /* * AT_BASE_PLATFORM indicates the "real" hardware/microarchitecture. * If the arch defines ELF_BASE_PLATFORM (in asm/elf.h), the value * will be copied to the user stack in the same manner as AT_PLATFORM. */ #define ELF_BASE_PLATFORM NULL #endif static int create_elf_tables(struct linux_binprm *bprm, const struct elfhdr *exec, unsigned long load_addr, unsigned long interp_load_addr, unsigned long e_entry) { struct mm_struct *mm = current->mm; unsigned long p = bprm->p; int argc = bprm->argc; int envc = bprm->envc; elf_addr_t __user *sp; elf_addr_t __user *u_platform; elf_addr_t __user *u_base_platform; elf_addr_t __user *u_rand_bytes; const char *k_platform = ELF_PLATFORM; const char *k_base_platform = ELF_BASE_PLATFORM; unsigned char k_rand_bytes[16]; int items; elf_addr_t *elf_info; int ei_index; const struct cred *cred = current_cred(); struct vm_area_struct *vma; /* * In some cases (e.g. Hyper-Threading), we want to avoid L1 * evictions by the processes running on the same package. One * thing we can do is to shuffle the initial stack for them. */ p = arch_align_stack(p); /* * If this architecture has a platform capability string, copy it * to userspace. In some cases (Sparc), this info is impossible * for userspace to get any other way, in others (i386) it is * merely difficult. */ u_platform = NULL; if (k_platform) { size_t len = strlen(k_platform) + 1; u_platform = (elf_addr_t __user *)STACK_ALLOC(p, len); if (__copy_to_user(u_platform, k_platform, len)) return -EFAULT; } /* * If this architecture has a "base" platform capability * string, copy it to userspace. */ u_base_platform = NULL; if (k_base_platform) { size_t len = strlen(k_base_platform) + 1; u_base_platform = (elf_addr_t __user *)STACK_ALLOC(p, len); if (__copy_to_user(u_base_platform, k_base_platform, len)) return -EFAULT; } /* * Generate 16 random bytes for userspace PRNG seeding. */ get_random_bytes(k_rand_bytes, sizeof(k_rand_bytes)); u_rand_bytes = (elf_addr_t __user *) STACK_ALLOC(p, sizeof(k_rand_bytes)); if (__copy_to_user(u_rand_bytes, k_rand_bytes, sizeof(k_rand_bytes))) return -EFAULT; /* Create the ELF interpreter info */ elf_info = (elf_addr_t *)mm->saved_auxv; /* update AT_VECTOR_SIZE_BASE if the number of NEW_AUX_ENT() changes */ #define NEW_AUX_ENT(id, val) \ do { \ *elf_info++ = id; \ *elf_info++ = val; \ } while (0) #ifdef ARCH_DLINFO /* * ARCH_DLINFO must come first so PPC can do its special alignment of * AUXV. * update AT_VECTOR_SIZE_ARCH if the number of NEW_AUX_ENT() in * ARCH_DLINFO changes */ ARCH_DLINFO; #endif NEW_AUX_ENT(AT_HWCAP, ELF_HWCAP); NEW_AUX_ENT(AT_PAGESZ, ELF_EXEC_PAGESIZE); NEW_AUX_ENT(AT_CLKTCK, CLOCKS_PER_SEC); NEW_AUX_ENT(AT_PHDR, load_addr + exec->e_phoff); NEW_AUX_ENT(AT_PHENT, sizeof(struct elf_phdr)); NEW_AUX_ENT(AT_PHNUM, exec->e_phnum); NEW_AUX_ENT(AT_BASE, interp_load_addr); NEW_AUX_ENT(AT_FLAGS, 0); NEW_AUX_ENT(AT_ENTRY, e_entry); NEW_AUX_ENT(AT_UID, from_kuid_munged(cred->user_ns, cred->uid)); NEW_AUX_ENT(AT_EUID, from_kuid_munged(cred->user_ns, cred->euid)); NEW_AUX_ENT(AT_GID, from_kgid_munged(cred->user_ns, cred->gid)); NEW_AUX_ENT(AT_EGID, from_kgid_munged(cred->user_ns, cred->egid)); NEW_AUX_ENT(AT_SECURE, bprm->secureexec); NEW_AUX_ENT(AT_RANDOM, (elf_addr_t)(unsigned long)u_rand_bytes); #ifdef ELF_HWCAP2 NEW_AUX_ENT(AT_HWCAP2, ELF_HWCAP2); #endif NEW_AUX_ENT(AT_EXECFN, bprm->exec); if (k_platform) { NEW_AUX_ENT(AT_PLATFORM, (elf_addr_t)(unsigned long)u_platform); } if (k_base_platform) { NEW_AUX_ENT(AT_BASE_PLATFORM, (elf_addr_t)(unsigned long)u_base_platform); } if (bprm->interp_flags & BINPRM_FLAGS_EXECFD) { NEW_AUX_ENT(AT_EXECFD, bprm->interp_data); } #undef NEW_AUX_ENT /* AT_NULL is zero; clear the rest too */ memset(elf_info, 0, (char *)mm->saved_auxv + sizeof(mm->saved_auxv) - (char *)elf_info); /* And advance past the AT_NULL entry. */ elf_info += 2; ei_index = elf_info - (elf_addr_t *)mm->saved_auxv; sp = STACK_ADD(p, ei_index); items = (argc + 1) + (envc + 1) + 1; bprm->p = STACK_ROUND(sp, items); /* Point sp at the lowest address on the stack */ #ifdef CONFIG_STACK_GROWSUP sp = (elf_addr_t __user *)bprm->p - items - ei_index; bprm->exec = (unsigned long)sp; /* XXX: PARISC HACK */ #else sp = (elf_addr_t __user *)bprm->p; #endif /* * Grow the stack manually; some architectures have a limit on how * far ahead a user-space access may be in order to grow the stack. */ vma = find_extend_vma(mm, bprm->p); if (!vma) return -EFAULT; /* Now, let's put argc (and argv, envp if appropriate) on the stack */ if (__put_user(argc, sp++)) return -EFAULT; /* Populate list of argv pointers back to argv strings. */ p = mm->arg_end = mm->arg_start; while (argc-- > 0) { size_t len; if (__put_user((elf_addr_t)p, sp++)) return -EFAULT; len = strnlen_user((void __user *)p, MAX_ARG_STRLEN); if (!len || len > MAX_ARG_STRLEN) return -EINVAL; p += len; } if (__put_user(0, sp++)) return -EFAULT; mm->arg_end = p; /* Populate list of envp pointers back to envp strings. */ mm->env_end = mm->env_start = p; while (envc-- > 0) { size_t len; if (__put_user((elf_addr_t)p, sp++)) return -EFAULT; len = strnlen_user((void __user *)p, MAX_ARG_STRLEN); if (!len || len > MAX_ARG_STRLEN) return -EINVAL; p += len; } if (__put_user(0, sp++)) return -EFAULT; mm->env_end = p; /* Put the elf_info on the stack in the right place. */ if (copy_to_user(sp, mm->saved_auxv, ei_index * sizeof(elf_addr_t))) return -EFAULT; return 0; } static unsigned long elf_map(struct file *filep, unsigned long addr, const struct elf_phdr *eppnt, int prot, int type, unsigned long total_size) { unsigned long map_addr; unsigned long size = eppnt->p_filesz + ELF_PAGEOFFSET(eppnt->p_vaddr); unsigned long off = eppnt->p_offset - ELF_PAGEOFFSET(eppnt->p_vaddr); addr = ELF_PAGESTART(addr); size = ELF_PAGEALIGN(size); /* mmap() will return -EINVAL if given a zero size, but a * segment with zero filesize is perfectly valid */ if (!size) return addr; /* * total_size is the size of the ELF (interpreter) image. * The _first_ mmap needs to know the full size, otherwise * randomization might put this image into an overlapping * position with the ELF binary image. (since size < total_size) * So we first map the 'big' image - and unmap the remainder at * the end. (which unmap is needed for ELF images with holes.) */ if (total_size) { total_size = ELF_PAGEALIGN(total_size); map_addr = vm_mmap(filep, addr, total_size, prot, type, off); if (!BAD_ADDR(map_addr)) vm_munmap(map_addr+size, total_size-size); } else map_addr = vm_mmap(filep, addr, size, prot, type, off); if ((type & MAP_FIXED_NOREPLACE) && PTR_ERR((void *)map_addr) == -EEXIST) pr_info("%d (%s): Uhuuh, elf segment at %px requested but the memory is mapped already\n", task_pid_nr(current), current->comm, (void *)addr); return(map_addr); } static unsigned long total_mapping_size(const struct elf_phdr *cmds, int nr) { int i, first_idx = -1, last_idx = -1; for (i = 0; i < nr; i++) { if (cmds[i].p_type == PT_LOAD) { last_idx = i; if (first_idx == -1) first_idx = i; } } if (first_idx == -1) return 0; return cmds[last_idx].p_vaddr + cmds[last_idx].p_memsz - ELF_PAGESTART(cmds[first_idx].p_vaddr); } static int elf_read(struct file *file, void *buf, size_t len, loff_t pos) { ssize_t rv; rv = kernel_read(file, buf, len, &pos); if (unlikely(rv != len)) { return (rv < 0) ? rv : -EIO; } return 0; } /** * load_elf_phdrs() - load ELF program headers * @elf_ex: ELF header of the binary whose program headers should be loaded * @elf_file: the opened ELF binary file * * Loads ELF program headers from the binary file elf_file, which has the ELF * header pointed to by elf_ex, into a newly allocated array. The caller is * responsible for freeing the allocated data. Returns an ERR_PTR upon failure. */ static struct elf_phdr *load_elf_phdrs(const struct elfhdr *elf_ex, struct file *elf_file) { struct elf_phdr *elf_phdata = NULL; int retval, err = -1; unsigned int size; /* * If the size of this structure has changed, then punt, since * we will be doing the wrong thing. */ if (elf_ex->e_phentsize != sizeof(struct elf_phdr)) goto out; /* Sanity check the number of program headers... */ /* ...and their total size. */ size = sizeof(struct elf_phdr) * elf_ex->e_phnum; if (size == 0 || size > 65536 || size > ELF_MIN_ALIGN) goto out; elf_phdata = kmalloc(size, GFP_KERNEL); if (!elf_phdata) goto out; /* Read in the program headers */ retval = elf_read(elf_file, elf_phdata, size, elf_ex->e_phoff); if (retval < 0) { err = retval; goto out; } /* Success! */ err = 0; out: if (err) { kfree(elf_phdata); elf_phdata = NULL; } return elf_phdata; } #ifndef CONFIG_ARCH_BINFMT_ELF_STATE /** * struct arch_elf_state - arch-specific ELF loading state * * This structure is used to preserve architecture specific data during * the loading of an ELF file, throughout the checking of architecture * specific ELF headers & through to the point where the ELF load is * known to be proceeding (ie. SET_PERSONALITY). * * This implementation is a dummy for architectures which require no * specific state. */ struct arch_elf_state { }; #define INIT_ARCH_ELF_STATE {} /** * arch_elf_pt_proc() - check a PT_LOPROC..PT_HIPROC ELF program header * @ehdr: The main ELF header * @phdr: The program header to check * @elf: The open ELF file * @is_interp: True if the phdr is from the interpreter of the ELF being * loaded, else false. * @state: Architecture-specific state preserved throughout the process * of loading the ELF. * * Inspects the program header phdr to validate its correctness and/or * suitability for the system. Called once per ELF program header in the * range PT_LOPROC to PT_HIPROC, for both the ELF being loaded and its * interpreter. * * Return: Zero to proceed with the ELF load, non-zero to fail the ELF load * with that return code. */ static inline int arch_elf_pt_proc(struct elfhdr *ehdr, struct elf_phdr *phdr, struct file *elf, bool is_interp, struct arch_elf_state *state) { /* Dummy implementation, always proceed */ return 0; } /** * arch_check_elf() - check an ELF executable * @ehdr: The main ELF header * @has_interp: True if the ELF has an interpreter, else false. * @interp_ehdr: The interpreter's ELF header * @state: Architecture-specific state preserved throughout the process * of loading the ELF. * * Provides a final opportunity for architecture code to reject the loading * of the ELF & cause an exec syscall to return an error. This is called after * all program headers to be checked by arch_elf_pt_proc have been. * * Return: Zero to proceed with the ELF load, non-zero to fail the ELF load * with that return code. */ static inline int arch_check_elf(struct elfhdr *ehdr, bool has_interp, struct elfhdr *interp_ehdr, struct arch_elf_state *state) { /* Dummy implementation, always proceed */ return 0; } #endif /* !CONFIG_ARCH_BINFMT_ELF_STATE */ static inline int make_prot(u32 p_flags) { int prot = 0; if (p_flags & PF_R) prot |= PROT_READ; if (p_flags & PF_W) prot |= PROT_WRITE; if (p_flags & PF_X) prot |= PROT_EXEC; return prot; } /* This is much more generalized than the library routine read function, so we keep this separate. Technically the library read function is only provided so that we can read a.out libraries that have an ELF header */ static unsigned long load_elf_interp(struct elfhdr *interp_elf_ex, struct file *interpreter, unsigned long no_base, struct elf_phdr *interp_elf_phdata) { struct elf_phdr *eppnt; unsigned long load_addr = 0; int load_addr_set = 0; unsigned long last_bss = 0, elf_bss = 0; int bss_prot = 0; unsigned long error = ~0UL; unsigned long total_size; int i; /* First of all, some simple consistency checks */ if (interp_elf_ex->e_type != ET_EXEC && interp_elf_ex->e_type != ET_DYN) goto out; if (!elf_check_arch(interp_elf_ex) || elf_check_fdpic(interp_elf_ex)) goto out; if (!interpreter->f_op->mmap) goto out; total_size = total_mapping_size(interp_elf_phdata, interp_elf_ex->e_phnum); if (!total_size) { error = -EINVAL; goto out; } eppnt = interp_elf_phdata; for (i = 0; i < interp_elf_ex->e_phnum; i++, eppnt++) { if (eppnt->p_type == PT_LOAD) { int elf_type = MAP_PRIVATE | MAP_DENYWRITE; int elf_prot = make_prot(eppnt->p_flags); unsigned long vaddr = 0; unsigned long k, map_addr; vaddr = eppnt->p_vaddr; if (interp_elf_ex->e_type == ET_EXEC || load_addr_set) elf_type |= MAP_FIXED_NOREPLACE; else if (no_base && interp_elf_ex->e_type == ET_DYN) load_addr = -vaddr; map_addr = elf_map(interpreter, load_addr + vaddr, eppnt, elf_prot, elf_type, total_size); total_size = 0; error = map_addr; if (BAD_ADDR(map_addr)) goto out; if (!load_addr_set && interp_elf_ex->e_type == ET_DYN) { load_addr = map_addr - ELF_PAGESTART(vaddr); load_addr_set = 1; } /* * Check to see if the section's size will overflow the * allowed task size. Note that p_filesz must always be * <= p_memsize so it's only necessary to check p_memsz. */ k = load_addr + eppnt->p_vaddr; if (BAD_ADDR(k) || eppnt->p_filesz > eppnt->p_memsz || eppnt->p_memsz > TASK_SIZE || TASK_SIZE - eppnt->p_memsz < k) { error = -ENOMEM; goto out; } /* * Find the end of the file mapping for this phdr, and * keep track of the largest address we see for this. */ k = load_addr + eppnt->p_vaddr + eppnt->p_filesz; if (k > elf_bss) elf_bss = k; /* * Do the same thing for the memory mapping - between * elf_bss and last_bss is the bss section. */ k = load_addr + eppnt->p_vaddr + eppnt->p_memsz; if (k > last_bss) { last_bss = k; bss_prot = elf_prot; } } } /* * Now fill out the bss section: first pad the last page from * the file up to the page boundary, and zero it from elf_bss * up to the end of the page. */ if (padzero(elf_bss)) { error = -EFAULT; goto out; } /* * Next, align both the file and mem bss up to the page size, * since this is where elf_bss was just zeroed up to, and where * last_bss will end after the vm_brk_flags() below. */ elf_bss = ELF_PAGEALIGN(elf_bss); last_bss = ELF_PAGEALIGN(last_bss); /* Finally, if there is still more bss to allocate, do it. */ if (last_bss > elf_bss) { error = vm_brk_flags(elf_bss, last_bss - elf_bss, bss_prot & PROT_EXEC ? VM_EXEC : 0); if (error) goto out; } error = load_addr; out: return error; } /* * These are the functions used to load ELF style executables and shared * libraries. There is no binary dependent code anywhere else. */ static int load_elf_binary(struct linux_binprm *bprm) { struct file *interpreter = NULL; /* to shut gcc up */ unsigned long load_addr = 0, load_bias = 0; int load_addr_set = 0; unsigned long error; struct elf_phdr *elf_ppnt, *elf_phdata, *interp_elf_phdata = NULL; unsigned long elf_bss, elf_brk; int bss_prot = 0; int retval, i; unsigned long elf_entry; unsigned long e_entry; unsigned long interp_load_addr = 0; unsigned long start_code, end_code, start_data, end_data; unsigned long reloc_func_desc __maybe_unused = 0; int executable_stack = EXSTACK_DEFAULT; struct elfhdr *elf_ex = (struct elfhdr *)bprm->buf; struct elfhdr *interp_elf_ex = NULL; struct arch_elf_state arch_state = INIT_ARCH_ELF_STATE; struct mm_struct *mm; struct pt_regs *regs; retval = -ENOEXEC; /* First of all, some simple consistency checks */ if (memcmp(elf_ex->e_ident, ELFMAG, SELFMAG) != 0) goto out; if (elf_ex->e_type != ET_EXEC && elf_ex->e_type != ET_DYN) goto out; if (!elf_check_arch(elf_ex)) goto out; if (elf_check_fdpic(elf_ex)) goto out; if (!bprm->file->f_op->mmap) goto out; elf_phdata = load_elf_phdrs(elf_ex, bprm->file); if (!elf_phdata) goto out; elf_ppnt = elf_phdata; for (i = 0; i < elf_ex->e_phnum; i++, elf_ppnt++) { char *elf_interpreter; if (elf_ppnt->p_type != PT_INTERP) continue; /* * This is the program interpreter used for shared libraries - * for now assume that this is an a.out format binary. */ retval = -ENOEXEC; if (elf_ppnt->p_filesz > PATH_MAX || elf_ppnt->p_filesz < 2) goto out_free_ph; retval = -ENOMEM; elf_interpreter = kmalloc(elf_ppnt->p_filesz, GFP_KERNEL); if (!elf_interpreter) goto out_free_ph; retval = elf_read(bprm->file, elf_interpreter, elf_ppnt->p_filesz, elf_ppnt->p_offset); if (retval < 0) goto out_free_interp; /* make sure path is NULL terminated */ retval = -ENOEXEC; if (elf_interpreter[elf_ppnt->p_filesz - 1] != '\0') goto out_free_interp; interpreter = open_exec(elf_interpreter); kfree(elf_interpreter); retval = PTR_ERR(interpreter); if (IS_ERR(interpreter)) goto out_free_ph; /* * If the binary is not readable then enforce mm->dumpable = 0 * regardless of the interpreter's permissions. */ would_dump(bprm, interpreter); interp_elf_ex = kmalloc(sizeof(*interp_elf_ex), GFP_KERNEL); if (!interp_elf_ex) { retval = -ENOMEM; goto out_free_ph; } /* Get the exec headers */ retval = elf_read(interpreter, interp_elf_ex, sizeof(*interp_elf_ex), 0); if (retval < 0) goto out_free_dentry; break; out_free_interp: kfree(elf_interpreter); goto out_free_ph; } elf_ppnt = elf_phdata; for (i = 0; i < elf_ex->e_phnum; i++, elf_ppnt++) switch (elf_ppnt->p_type) { case PT_GNU_STACK: if (elf_ppnt->p_flags & PF_X) executable_stack = EXSTACK_ENABLE_X; else executable_stack = EXSTACK_DISABLE_X; break; case PT_LOPROC ... PT_HIPROC: retval = arch_elf_pt_proc(elf_ex, elf_ppnt, bprm->file, false, &arch_state); if (retval) goto out_free_dentry; break; } /* Some simple consistency checks for the interpreter */ if (interpreter) { retval = -ELIBBAD; /* Not an ELF interpreter */ if (memcmp(interp_elf_ex->e_ident, ELFMAG, SELFMAG) != 0) goto out_free_dentry; /* Verify the interpreter has a valid arch */ if (!elf_check_arch(interp_elf_ex) || elf_check_fdpic(interp_elf_ex)) goto out_free_dentry; /* Load the interpreter program headers */ interp_elf_phdata = load_elf_phdrs(interp_elf_ex, interpreter); if (!interp_elf_phdata) goto out_free_dentry; /* Pass PT_LOPROC..PT_HIPROC headers to arch code */ elf_ppnt = interp_elf_phdata; for (i = 0; i < interp_elf_ex->e_phnum; i++, elf_ppnt++) switch (elf_ppnt->p_type) { case PT_LOPROC ... PT_HIPROC: retval = arch_elf_pt_proc(interp_elf_ex, elf_ppnt, interpreter, true, &arch_state); if (retval) goto out_free_dentry; break; } } /* * Allow arch code to reject the ELF at this point, whilst it's * still possible to return an error to the code that invoked * the exec syscall. */ retval = arch_check_elf(elf_ex, !!interpreter, interp_elf_ex, &arch_state); if (retval) goto out_free_dentry; /* Flush all traces of the currently running executable */ retval = flush_old_exec(bprm); if (retval) goto out_free_dentry; /* Do this immediately, since STACK_TOP as used in setup_arg_pages may depend on the personality. */ SET_PERSONALITY2(*elf_ex, &arch_state); if (elf_read_implies_exec(*elf_ex, executable_stack)) current->personality |= READ_IMPLIES_EXEC; if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) current->flags |= PF_RANDOMIZE; setup_new_exec(bprm); install_exec_creds(bprm); /* Do this so that we can load the interpreter, if need be. We will change some of these later */ retval = setup_arg_pages(bprm, randomize_stack_top(STACK_TOP), executable_stack); if (retval < 0) goto out_free_dentry; elf_bss = 0; elf_brk = 0; start_code = ~0UL; end_code = 0; start_data = 0; end_data = 0; /* Now we do a little grungy work by mmapping the ELF image into the correct location in memory. */ for(i = 0, elf_ppnt = elf_phdata; i < elf_ex->e_phnum; i++, elf_ppnt++) { int elf_prot, elf_flags; unsigned long k, vaddr; unsigned long total_size = 0; if (elf_ppnt->p_type != PT_LOAD) continue; if (unlikely (elf_brk > elf_bss)) { unsigned long nbyte; /* There was a PT_LOAD segment with p_memsz > p_filesz before this one. Map anonymous pages, if needed, and clear the area. */ retval = set_brk(elf_bss + load_bias, elf_brk + load_bias, bss_prot); if (retval) goto out_free_dentry; nbyte = ELF_PAGEOFFSET(elf_bss); if (nbyte) { nbyte = ELF_MIN_ALIGN - nbyte; if (nbyte > elf_brk - elf_bss) nbyte = elf_brk - elf_bss; if (clear_user((void __user *)elf_bss + load_bias, nbyte)) { /* * This bss-zeroing can fail if the ELF * file specifies odd protections. So * we don't check the return value */ } } } elf_prot = make_prot(elf_ppnt->p_flags); elf_flags = MAP_PRIVATE | MAP_DENYWRITE | MAP_EXECUTABLE; vaddr = elf_ppnt->p_vaddr; /* * If we are loading ET_EXEC or we have already performed * the ET_DYN load_addr calculations, proceed normally. */ if (elf_ex->e_type == ET_EXEC || load_addr_set) { elf_flags |= MAP_FIXED; } else if (elf_ex->e_type == ET_DYN) { /* * This logic is run once for the first LOAD Program * Header for ET_DYN binaries to calculate the * randomization (load_bias) for all the LOAD * Program Headers, and to calculate the entire * size of the ELF mapping (total_size). (Note that * load_addr_set is set to true later once the * initial mapping is performed.) * * There are effectively two types of ET_DYN * binaries: programs (i.e. PIE: ET_DYN with INTERP) * and loaders (ET_DYN without INTERP, since they * _are_ the ELF interpreter). The loaders must * be loaded away from programs since the program * may otherwise collide with the loader (especially * for ET_EXEC which does not have a randomized * position). For example to handle invocations of * "./ld.so someprog" to test out a new version of * the loader, the subsequent program that the * loader loads must avoid the loader itself, so * they cannot share the same load range. Sufficient * room for the brk must be allocated with the * loader as well, since brk must be available with * the loader. * * Therefore, programs are loaded offset from * ELF_ET_DYN_BASE and loaders are loaded into the * independently randomized mmap region (0 load_bias * without MAP_FIXED). */ if (interpreter) { load_bias = ELF_ET_DYN_BASE; if (current->flags & PF_RANDOMIZE) load_bias += arch_mmap_rnd(); elf_flags |= MAP_FIXED; } else load_bias = 0; /* * Since load_bias is used for all subsequent loading * calculations, we must lower it by the first vaddr * so that the remaining calculations based on the * ELF vaddrs will be correctly offset. The result * is then page aligned. */ load_bias = ELF_PAGESTART(load_bias - vaddr); total_size = total_mapping_size(elf_phdata, elf_ex->e_phnum); if (!total_size) { retval = -EINVAL; goto out_free_dentry; } } error = elf_map(bprm->file, load_bias + vaddr, elf_ppnt, elf_prot, elf_flags, total_size); if (BAD_ADDR(error)) { retval = IS_ERR((void *)error) ? PTR_ERR((void*)error) : -EINVAL; goto out_free_dentry; } if (!load_addr_set) { load_addr_set = 1; load_addr = (elf_ppnt->p_vaddr - elf_ppnt->p_offset); if (elf_ex->e_type == ET_DYN) { load_bias += error - ELF_PAGESTART(load_bias + vaddr); load_addr += load_bias; reloc_func_desc = load_bias; } } k = elf_ppnt->p_vaddr; if ((elf_ppnt->p_flags & PF_X) && k < start_code) start_code = k; if (start_data < k) start_data = k; /* * Check to see if the section's size will overflow the * allowed task size. Note that p_filesz must always be * <= p_memsz so it is only necessary to check p_memsz. */ if (BAD_ADDR(k) || elf_ppnt->p_filesz > elf_ppnt->p_memsz || elf_ppnt->p_memsz > TASK_SIZE || TASK_SIZE - elf_ppnt->p_memsz < k) { /* set_brk can never work. Avoid overflows. */ retval = -EINVAL; goto out_free_dentry; } k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz; if (k > elf_bss) elf_bss = k; if ((elf_ppnt->p_flags & PF_X) && end_code < k) end_code = k; if (end_data < k) end_data = k; k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz; if (k > elf_brk) { bss_prot = elf_prot; elf_brk = k; } } e_entry = elf_ex->e_entry + load_bias; elf_bss += load_bias; elf_brk += load_bias; start_code += load_bias; end_code += load_bias; start_data += load_bias; end_data += load_bias; /* Calling set_brk effectively mmaps the pages that we need * for the bss and break sections. We must do this before * mapping in the interpreter, to make sure it doesn't wind * up getting placed where the bss needs to go. */ retval = set_brk(elf_bss, elf_brk, bss_prot); if (retval) goto out_free_dentry; if (likely(elf_bss != elf_brk) && unlikely(padzero(elf_bss))) { retval = -EFAULT; /* Nobody gets to see this, but.. */ goto out_free_dentry; } if (interpreter) { elf_entry = load_elf_interp(interp_elf_ex, interpreter, load_bias, interp_elf_phdata); if (!IS_ERR((void *)elf_entry)) { /* * load_elf_interp() returns relocation * adjustment */ interp_load_addr = elf_entry; elf_entry += interp_elf_ex->e_entry; } if (BAD_ADDR(elf_entry)) { retval = IS_ERR((void *)elf_entry) ? (int)elf_entry : -EINVAL; goto out_free_dentry; } reloc_func_desc = interp_load_addr; allow_write_access(interpreter); fput(interpreter); kfree(interp_elf_ex); kfree(interp_elf_phdata); } else { elf_entry = e_entry; if (BAD_ADDR(elf_entry)) { retval = -EINVAL; goto out_free_dentry; } } kfree(elf_phdata); set_binfmt(&elf_format); #ifdef ARCH_HAS_SETUP_ADDITIONAL_PAGES retval = arch_setup_additional_pages(bprm, !!interpreter); if (retval < 0) goto out; #endif /* ARCH_HAS_SETUP_ADDITIONAL_PAGES */ retval = create_elf_tables(bprm, elf_ex, load_addr, interp_load_addr, e_entry); if (retval < 0) goto out; mm = current->mm; mm->end_code = end_code; mm->start_code = start_code; mm->start_data = start_data; mm->end_data = end_data; mm->start_stack = bprm->p; if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) { /* * For architectures with ELF randomization, when executing * a loader directly (i.e. no interpreter listed in ELF * headers), move the brk area out of the mmap region * (since it grows up, and may collide early with the stack * growing down), and into the unused ELF_ET_DYN_BASE region. */ if (IS_ENABLED(CONFIG_ARCH_HAS_ELF_RANDOMIZE) && elf_ex->e_type == ET_DYN && !interpreter) { mm->brk = mm->start_brk = ELF_ET_DYN_BASE; } mm->brk = mm->start_brk = arch_randomize_brk(mm); #ifdef compat_brk_randomized current->brk_randomized = 1; #endif } if (current->personality & MMAP_PAGE_ZERO) { /* Why this, you ask??? Well SVr4 maps page 0 as read-only, and some applications "depend" upon this behavior. Since we do not have the power to recompile these, we emulate the SVr4 behavior. Sigh. */ error = vm_mmap(NULL, 0, PAGE_SIZE, PROT_READ | PROT_EXEC, MAP_FIXED | MAP_PRIVATE, 0); } regs = current_pt_regs(); #ifdef ELF_PLAT_INIT /* * The ABI may specify that certain registers be set up in special * ways (on i386 %edx is the address of a DT_FINI function, for * example. In addition, it may also specify (eg, PowerPC64 ELF) * that the e_entry field is the address of the function descriptor * for the startup routine, rather than the address of the startup * routine itself. This macro performs whatever initialization to * the regs structure is required as well as any relocations to the * function descriptor entries when executing dynamically links apps. */ ELF_PLAT_INIT(regs, reloc_func_desc); #endif finalize_exec(bprm); start_thread(regs, elf_entry, bprm->p); retval = 0; out: return retval; /* error cleanup */ out_free_dentry: kfree(interp_elf_ex); kfree(interp_elf_phdata); allow_write_access(interpreter); if (interpreter) fput(interpreter); out_free_ph: kfree(elf_phdata); goto out; } #ifdef CONFIG_USELIB /* This is really simpleminded and specialized - we are loading an a.out library that is given an ELF header. */ static int load_elf_library(struct file *file) { struct elf_phdr *elf_phdata; struct elf_phdr *eppnt; unsigned long elf_bss, bss, len; int retval, error, i, j; struct elfhdr elf_ex; error = -ENOEXEC; retval = elf_read(file, &elf_ex, sizeof(elf_ex), 0); if (retval < 0) goto out; if (memcmp(elf_ex.e_ident, ELFMAG, SELFMAG) != 0) goto out; /* First of all, some simple consistency checks */ if (elf_ex.e_type != ET_EXEC || elf_ex.e_phnum > 2 || !elf_check_arch(&elf_ex) || !file->f_op->mmap) goto out; if (elf_check_fdpic(&elf_ex)) goto out; /* Now read in all of the header information */ j = sizeof(struct elf_phdr) * elf_ex.e_phnum; /* j < ELF_MIN_ALIGN because elf_ex.e_phnum <= 2 */ error = -ENOMEM; elf_phdata = kmalloc(j, GFP_KERNEL); if (!elf_phdata) goto out; eppnt = elf_phdata; error = -ENOEXEC; retval = elf_read(file, eppnt, j, elf_ex.e_phoff); if (retval < 0) goto out_free_ph; for (j = 0, i = 0; i<elf_ex.e_phnum; i++) if ((eppnt + i)->p_type == PT_LOAD) j++; if (j != 1) goto out_free_ph; while (eppnt->p_type != PT_LOAD) eppnt++; /* Now use mmap to map the library into memory. */ error = vm_mmap(file, ELF_PAGESTART(eppnt->p_vaddr), (eppnt->p_filesz + ELF_PAGEOFFSET(eppnt->p_vaddr)), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED_NOREPLACE | MAP_PRIVATE | MAP_DENYWRITE, (eppnt->p_offset - ELF_PAGEOFFSET(eppnt->p_vaddr))); if (error != ELF_PAGESTART(eppnt->p_vaddr)) goto out_free_ph; elf_bss = eppnt->p_vaddr + eppnt->p_filesz; if (padzero(elf_bss)) { error = -EFAULT; goto out_free_ph; } len = ELF_PAGEALIGN(eppnt->p_filesz + eppnt->p_vaddr); bss = ELF_PAGEALIGN(eppnt->p_memsz + eppnt->p_vaddr); if (bss > len) { error = vm_brk(len, bss - len); if (error) goto out_free_ph; } error = 0; out_free_ph: kfree(elf_phdata); out: return error; } #endif /* #ifdef CONFIG_USELIB */ #ifdef CONFIG_ELF_CORE /* * ELF core dumper * * Modelled on fs/exec.c:aout_core_dump() * Jeremy Fitzhardinge <jeremy@sw.oz.au> */ /* * The purpose of always_dump_vma() is to make sure that special kernel mappings * that are useful for post-mortem analysis are included in every core dump. * In that way we ensure that the core dump is fully interpretable later * without matching up the same kernel and hardware config to see what PC values * meant. These special mappings include - vDSO, vsyscall, and other * architecture specific mappings */ static bool always_dump_vma(struct vm_area_struct *vma) { /* Any vsyscall mappings? */ if (vma == get_gate_vma(vma->vm_mm)) return true; /* * Assume that all vmas with a .name op should always be dumped. * If this changes, a new vm_ops field can easily be added. */ if (vma->vm_ops && vma->vm_ops->name && vma->vm_ops->name(vma)) return true; /* * arch_vma_name() returns non-NULL for special architecture mappings, * such as vDSO sections. */ if (arch_vma_name(vma)) return true; return false; } /* * Decide what to dump of a segment, part, all or none. */ static unsigned long vma_dump_size(struct vm_area_struct *vma, unsigned long mm_flags) { #define FILTER(type) (mm_flags & (1UL << MMF_DUMP_##type)) /* always dump the vdso and vsyscall sections */ if (always_dump_vma(vma)) goto whole; if (vma->vm_flags & VM_DONTDUMP) return 0; /* support for DAX */ if (vma_is_dax(vma)) { if ((vma->vm_flags & VM_SHARED) && FILTER(DAX_SHARED)) goto whole; if (!(vma->vm_flags & VM_SHARED) && FILTER(DAX_PRIVATE)) goto whole; return 0; } /* Hugetlb memory check */ if (is_vm_hugetlb_page(vma)) { if ((vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_SHARED)) goto whole; if (!(vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_PRIVATE)) goto whole; return 0; } /* Do not dump I/O mapped devices or special mappings */ if (vma->vm_flags & VM_IO) return 0; /* By default, dump shared memory if mapped from an anonymous file. */ if (vma->vm_flags & VM_SHARED) { if (file_inode(vma->vm_file)->i_nlink == 0 ? FILTER(ANON_SHARED) : FILTER(MAPPED_SHARED)) goto whole; return 0; } /* Dump segments that have been written to. */ if (vma->anon_vma && FILTER(ANON_PRIVATE)) goto whole; if (vma->vm_file == NULL) return 0; if (FILTER(MAPPED_PRIVATE)) goto whole; /* * If this looks like the beginning of a DSO or executable mapping, * check for an ELF header. If we find one, dump the first page to * aid in determining what was mapped here. */ if (FILTER(ELF_HEADERS) && vma->vm_pgoff == 0 && (vma->vm_flags & VM_READ)) { u32 __user *header = (u32 __user *) vma->vm_start; u32 word; mm_segment_t fs = get_fs(); /* * Doing it this way gets the constant folded by GCC. */ union { u32 cmp; char elfmag[SELFMAG]; } magic; BUILD_BUG_ON(SELFMAG != sizeof word); magic.elfmag[EI_MAG0] = ELFMAG0; magic.elfmag[EI_MAG1] = ELFMAG1; magic.elfmag[EI_MAG2] = ELFMAG2; magic.elfmag[EI_MAG3] = ELFMAG3; /* * Switch to the user "segment" for get_user(), * then put back what elf_core_dump() had in place. */ set_fs(USER_DS); if (unlikely(get_user(word, header))) word = 0; set_fs(fs); if (word == magic.cmp) return PAGE_SIZE; } #undef FILTER return 0; whole: return vma->vm_end - vma->vm_start; } /* An ELF note in memory */ struct memelfnote { const char *name; int type; unsigned int datasz; void *data; }; static int notesize(struct memelfnote *en) { int sz; sz = sizeof(struct elf_note); sz += roundup(strlen(en->name) + 1, 4); sz += roundup(en->datasz, 4); return sz; } static int writenote(struct memelfnote *men, struct coredump_params *cprm) { struct elf_note en; en.n_namesz = strlen(men->name) + 1; en.n_descsz = men->datasz; en.n_type = men->type; return dump_emit(cprm, &en, sizeof(en)) && dump_emit(cprm, men->name, en.n_namesz) && dump_align(cprm, 4) && dump_emit(cprm, men->data, men->datasz) && dump_align(cprm, 4); } static void fill_elf_header(struct elfhdr *elf, int segs, u16 machine, u32 flags) { memset(elf, 0, sizeof(*elf)); memcpy(elf->e_ident, ELFMAG, SELFMAG); elf->e_ident[EI_CLASS] = ELF_CLASS; elf->e_ident[EI_DATA] = ELF_DATA; elf->e_ident[EI_VERSION] = EV_CURRENT; elf->e_ident[EI_OSABI] = ELF_OSABI; elf->e_type = ET_CORE; elf->e_machine = machine; elf->e_version = EV_CURRENT; elf->e_phoff = sizeof(struct elfhdr); elf->e_flags = flags; elf->e_ehsize = sizeof(struct elfhdr); elf->e_phentsize = sizeof(struct elf_phdr); elf->e_phnum = segs; } static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, loff_t offset) { phdr->p_type = PT_NOTE; phdr->p_offset = offset; phdr->p_vaddr = 0; phdr->p_paddr = 0; phdr->p_filesz = sz; phdr->p_memsz = 0; phdr->p_flags = 0; phdr->p_align = 0; } static void fill_note(struct memelfnote *note, const char *name, int type, unsigned int sz, void *data) { note->name = name; note->type = type; note->datasz = sz; note->data = data; } /* * fill up all the fields in prstatus from the given task struct, except * registers which need to be filled up separately. */ static void fill_prstatus(struct elf_prstatus *prstatus, struct task_struct *p, long signr) { prstatus->pr_info.si_signo = prstatus->pr_cursig = signr; prstatus->pr_sigpend = p->pending.signal.sig[0]; prstatus->pr_sighold = p->blocked.sig[0]; rcu_read_lock(); prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent)); rcu_read_unlock(); prstatus->pr_pid = task_pid_vnr(p); prstatus->pr_pgrp = task_pgrp_vnr(p); prstatus->pr_sid = task_session_vnr(p); if (thread_group_leader(p)) { struct task_cputime cputime; /* * This is the record for the group leader. It shows the * group-wide total, not its individual thread total. */ thread_group_cputime(p, &cputime); prstatus->pr_utime = ns_to_kernel_old_timeval(cputime.utime); prstatus->pr_stime = ns_to_kernel_old_timeval(cputime.stime); } else { u64 utime, stime; task_cputime(p, &utime, &stime); prstatus->pr_utime = ns_to_kernel_old_timeval(utime); prstatus->pr_stime = ns_to_kernel_old_timeval(stime); } prstatus->pr_cutime = ns_to_kernel_old_timeval(p->signal->cutime); prstatus->pr_cstime = ns_to_kernel_old_timeval(p->signal->cstime); } static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p, struct mm_struct *mm) { const struct cred *cred; unsigned int i, len; /* first copy the parameters from user space */ memset(psinfo, 0, sizeof(struct elf_prpsinfo)); len = mm->arg_end - mm->arg_start; if (len >= ELF_PRARGSZ) len = ELF_PRARGSZ-1; if (copy_from_user(&psinfo->pr_psargs, (const char __user *)mm->arg_start, len)) return -EFAULT; for(i = 0; i < len; i++) if (psinfo->pr_psargs[i] == 0) psinfo->pr_psargs[i] = ' '; psinfo->pr_psargs[len] = 0; rcu_read_lock(); psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent)); rcu_read_unlock(); psinfo->pr_pid = task_pid_vnr(p); psinfo->pr_pgrp = task_pgrp_vnr(p); psinfo->pr_sid = task_session_vnr(p); i = p->state ? ffz(~p->state) + 1 : 0; psinfo->pr_state = i; psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i]; psinfo->pr_zomb = psinfo->pr_sname == 'Z'; psinfo->pr_nice = task_nice(p); psinfo->pr_flag = p->flags; rcu_read_lock(); cred = __task_cred(p); SET_UID(psinfo->pr_uid, from_kuid_munged(cred->user_ns, cred->uid)); SET_GID(psinfo->pr_gid, from_kgid_munged(cred->user_ns, cred->gid)); rcu_read_unlock(); strncpy(psinfo->pr_fname, p->comm, sizeof(psinfo->pr_fname)); return 0; } static void fill_auxv_note(struct memelfnote *note, struct mm_struct *mm) { elf_addr_t *auxv = (elf_addr_t *) mm->saved_auxv; int i = 0; do i += 2; while (auxv[i - 2] != AT_NULL); fill_note(note, "CORE", NT_AUXV, i * sizeof(elf_addr_t), auxv); } static void fill_siginfo_note(struct memelfnote *note, user_siginfo_t *csigdata, const kernel_siginfo_t *siginfo) { mm_segment_t old_fs = get_fs(); set_fs(KERNEL_DS); copy_siginfo_to_user((user_siginfo_t __user *) csigdata, siginfo); set_fs(old_fs); fill_note(note, "CORE", NT_SIGINFO, sizeof(*csigdata), csigdata); } #define MAX_FILE_NOTE_SIZE (4*1024*1024) /* * Format of NT_FILE note: * * long count -- how many files are mapped * long page_size -- units for file_ofs * array of [COUNT] elements of * long start * long end * long file_ofs * followed by COUNT filenames in ASCII: "FILE1" NUL "FILE2" NUL... */ static int fill_files_note(struct memelfnote *note) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; unsigned count, size, names_ofs, remaining, n; user_long_t *data; user_long_t *start_end_ofs; char *name_base, *name_curpos; /* *Estimated* file count and total data size needed */ count = mm->map_count; if (count > UINT_MAX / 64) return -EINVAL; size = count * 64; names_ofs = (2 + 3 * count) * sizeof(data[0]); alloc: if (size >= MAX_FILE_NOTE_SIZE) /* paranoia check */ return -EINVAL; size = round_up(size, PAGE_SIZE); /* * "size" can be 0 here legitimately. * Let it ENOMEM and omit NT_FILE section which will be empty anyway. */ data = kvmalloc(size, GFP_KERNEL); if (ZERO_OR_NULL_PTR(data)) return -ENOMEM; start_end_ofs = data + 2; name_base = name_curpos = ((char *)data) + names_ofs; remaining = size - names_ofs; count = 0; for (vma = mm->mmap; vma != NULL; vma = vma->vm_next) { struct file *file; const char *filename; file = vma->vm_file; if (!file) continue; filename = file_path(file, name_curpos, remaining); if (IS_ERR(filename)) { if (PTR_ERR(filename) == -ENAMETOOLONG) { kvfree(data); size = size * 5 / 4; goto alloc; } continue; } /* file_path() fills at the end, move name down */ /* n = strlen(filename) + 1: */ n = (name_curpos + remaining) - filename; remaining = filename - name_curpos; memmove(name_curpos, filename, n); name_curpos += n; *start_end_ofs++ = vma->vm_start; *start_end_ofs++ = vma->vm_end; *start_end_ofs++ = vma->vm_pgoff; count++; } /* Now we know exact count of files, can store it */ data[0] = count; data[1] = PAGE_SIZE; /* * Count usually is less than mm->map_count, * we need to move filenames down. */ n = mm->map_count - count; if (n != 0) { unsigned shift_bytes = n * 3 * sizeof(data[0]); memmove(name_base - shift_bytes, name_base, name_curpos - name_base); name_curpos -= shift_bytes; } size = name_curpos - (char *)data; fill_note(note, "CORE", NT_FILE, size, data); return 0; } #ifdef CORE_DUMP_USE_REGSET #include <linux/regset.h> struct elf_thread_core_info { struct elf_thread_core_info *next; struct task_struct *task; struct elf_prstatus prstatus; struct memelfnote notes[0]; }; struct elf_note_info { struct elf_thread_core_info *thread; struct memelfnote psinfo; struct memelfnote signote; struct memelfnote auxv; struct memelfnote files; user_siginfo_t csigdata; size_t size; int thread_notes; }; /* * When a regset has a writeback hook, we call it on each thread before * dumping user memory. On register window machines, this makes sure the * user memory backing the register data is up to date before we read it. */ static void do_thread_regset_writeback(struct task_struct *task, const struct user_regset *regset) { if (regset->writeback) regset->writeback(task, regset, 1); } #ifndef PRSTATUS_SIZE #define PRSTATUS_SIZE(S, R) sizeof(S) #endif #ifndef SET_PR_FPVALID #define SET_PR_FPVALID(S, V, R) ((S)->pr_fpvalid = (V)) #endif static int fill_thread_core_info(struct elf_thread_core_info *t, const struct user_regset_view *view, long signr, size_t *total) { unsigned int i; unsigned int regset0_size = regset_size(t->task, &view->regsets[0]); /* * NT_PRSTATUS is the one special case, because the regset data * goes into the pr_reg field inside the note contents, rather * than being the whole note contents. We fill the reset in here. * We assume that regset 0 is NT_PRSTATUS. */ fill_prstatus(&t->prstatus, t->task, signr); (void) view->regsets[0].get(t->task, &view->regsets[0], 0, regset0_size, &t->prstatus.pr_reg, NULL); fill_note(&t->notes[0], "CORE", NT_PRSTATUS, PRSTATUS_SIZE(t->prstatus, regset0_size), &t->prstatus); *total += notesize(&t->notes[0]); do_thread_regset_writeback(t->task, &view->regsets[0]); /* * Each other regset might generate a note too. For each regset * that has no core_note_type or is inactive, we leave t->notes[i] * all zero and we'll know to skip writing it later. */ for (i = 1; i < view->n; ++i) { const struct user_regset *regset = &view->regsets[i]; do_thread_regset_writeback(t->task, regset); if (regset->core_note_type && regset->get && (!regset->active || regset->active(t->task, regset) > 0)) { int ret; size_t size = regset_size(t->task, regset); void *data = kzalloc(size, GFP_KERNEL); if (unlikely(!data)) return 0; ret = regset->get(t->task, regset, 0, size, data, NULL); if (unlikely(ret)) kfree(data); else { if (regset->core_note_type != NT_PRFPREG) fill_note(&t->notes[i], "LINUX", regset->core_note_type, size, data); else { SET_PR_FPVALID(&t->prstatus, 1, regset0_size); fill_note(&t->notes[i], "CORE", NT_PRFPREG, size, data); } *total += notesize(&t->notes[i]); } } } return 1; } static int fill_note_info(struct elfhdr *elf, int phdrs, struct elf_note_info *info, const kernel_siginfo_t *siginfo, struct pt_regs *regs) { struct task_struct *dump_task = current; const struct user_regset_view *view = task_user_regset_view(dump_task); struct elf_thread_core_info *t; struct elf_prpsinfo *psinfo; struct core_thread *ct; unsigned int i; info->size = 0; info->thread = NULL; psinfo = kmalloc(sizeof(*psinfo), GFP_KERNEL); if (psinfo == NULL) { info->psinfo.data = NULL; /* So we don't free this wrongly */ return 0; } fill_note(&info->psinfo, "CORE", NT_PRPSINFO, sizeof(*psinfo), psinfo); /* * Figure out how many notes we're going to need for each thread. */ info->thread_notes = 0; for (i = 0; i < view->n; ++i) if (view->regsets[i].core_note_type != 0) ++info->thread_notes; /* * Sanity check. We rely on regset 0 being in NT_PRSTATUS, * since it is our one special case. */ if (unlikely(info->thread_notes == 0) || unlikely(view->regsets[0].core_note_type != NT_PRSTATUS)) { WARN_ON(1); return 0; } /* * Initialize the ELF file header. */ fill_elf_header(elf, phdrs, view->e_machine, view->e_flags); /* * Allocate a structure for each thread. */ for (ct = &dump_task->mm->core_state->dumper; ct; ct = ct->next) { t = kzalloc(offsetof(struct elf_thread_core_info, notes[info->thread_notes]), GFP_KERNEL); if (unlikely(!t)) return 0; t->task = ct->task; if (ct->task == dump_task || !info->thread) { t->next = info->thread; info->thread = t; } else { /* * Make sure to keep the original task at * the head of the list. */ t->next = info->thread->next; info->thread->next = t; } } /* * Now fill in each thread's information. */ for (t = info->thread; t != NULL; t = t->next) if (!fill_thread_core_info(t, view, siginfo->si_signo, &info->size)) return 0; /* * Fill in the two process-wide notes. */ fill_psinfo(psinfo, dump_task->group_leader, dump_task->mm); info->size += notesize(&info->psinfo); fill_siginfo_note(&info->signote, &info->csigdata, siginfo); info->size += notesize(&info->signote); fill_auxv_note(&info->auxv, current->mm); info->size += notesize(&info->auxv); if (fill_files_note(&info->files) == 0) info->size += notesize(&info->files); return 1; } static size_t get_note_info_size(struct elf_note_info *info) { return info->size; } /* * Write all the notes for each thread. When writing the first thread, the * process-wide notes are interleaved after the first thread-specific note. */ static int write_note_info(struct elf_note_info *info, struct coredump_params *cprm) { bool first = true; struct elf_thread_core_info *t = info->thread; do { int i; if (!writenote(&t->notes[0], cprm)) return 0; if (first && !writenote(&info->psinfo, cprm)) return 0; if (first && !writenote(&info->signote, cprm)) return 0; if (first && !writenote(&info->auxv, cprm)) return 0; if (first && info->files.data && !writenote(&info->files, cprm)) return 0; for (i = 1; i < info->thread_notes; ++i) if (t->notes[i].data && !writenote(&t->notes[i], cprm)) return 0; first = false; t = t->next; } while (t); return 1; } static void free_note_info(struct elf_note_info *info) { struct elf_thread_core_info *threads = info->thread; while (threads) { unsigned int i; struct elf_thread_core_info *t = threads; threads = t->next; WARN_ON(t->notes[0].data && t->notes[0].data != &t->prstatus); for (i = 1; i < info->thread_notes; ++i) kfree(t->notes[i].data); kfree(t); } kfree(info->psinfo.data); kvfree(info->files.data); } #else /* Here is the structure in which status of each thread is captured. */ struct elf_thread_status { struct list_head list; struct elf_prstatus prstatus; /* NT_PRSTATUS */ elf_fpregset_t fpu; /* NT_PRFPREG */ struct task_struct *thread; #ifdef ELF_CORE_COPY_XFPREGS elf_fpxregset_t xfpu; /* ELF_CORE_XFPREG_TYPE */ #endif struct memelfnote notes[3]; int num_notes; }; /* * In order to add the specific thread information for the elf file format, * we need to keep a linked list of every threads pr_status and then create * a single section for them in the final core file. */ static int elf_dump_thread_status(long signr, struct elf_thread_status *t) { int sz = 0; struct task_struct *p = t->thread; t->num_notes = 0; fill_prstatus(&t->prstatus, p, signr); elf_core_copy_task_regs(p, &t->prstatus.pr_reg); fill_note(&t->notes[0], "CORE", NT_PRSTATUS, sizeof(t->prstatus), &(t->prstatus)); t->num_notes++; sz += notesize(&t->notes[0]); if ((t->prstatus.pr_fpvalid = elf_core_copy_task_fpregs(p, NULL, &t->fpu))) { fill_note(&t->notes[1], "CORE", NT_PRFPREG, sizeof(t->fpu), &(t->fpu)); t->num_notes++; sz += notesize(&t->notes[1]); } #ifdef ELF_CORE_COPY_XFPREGS if (elf_core_copy_task_xfpregs(p, &t->xfpu)) { fill_note(&t->notes[2], "LINUX", ELF_CORE_XFPREG_TYPE, sizeof(t->xfpu), &t->xfpu); t->num_notes++; sz += notesize(&t->notes[2]); } #endif return sz; } struct elf_note_info { struct memelfnote *notes; struct memelfnote *notes_files; struct elf_prstatus *prstatus; /* NT_PRSTATUS */ struct elf_prpsinfo *psinfo; /* NT_PRPSINFO */ struct list_head thread_list; elf_fpregset_t *fpu; #ifdef ELF_CORE_COPY_XFPREGS elf_fpxregset_t *xfpu; #endif user_siginfo_t csigdata; int thread_status_size; int numnote; }; static int elf_note_info_init(struct elf_note_info *info) { memset(info, 0, sizeof(*info)); INIT_LIST_HEAD(&info->thread_list); /* Allocate space for ELF notes */ info->notes = kmalloc_array(8, sizeof(struct memelfnote), GFP_KERNEL); if (!info->notes) return 0; info->psinfo = kmalloc(sizeof(*info->psinfo), GFP_KERNEL); if (!info->psinfo) return 0; info->prstatus = kmalloc(sizeof(*info->prstatus), GFP_KERNEL); if (!info->prstatus) return 0; info->fpu = kmalloc(sizeof(*info->fpu), GFP_KERNEL); if (!info->fpu) return 0; #ifdef ELF_CORE_COPY_XFPREGS info->xfpu = kmalloc(sizeof(*info->xfpu), GFP_KERNEL); if (!info->xfpu) return 0; #endif return 1; } static int fill_note_info(struct elfhdr *elf, int phdrs, struct elf_note_info *info, const kernel_siginfo_t *siginfo, struct pt_regs *regs) { struct core_thread *ct; struct elf_thread_status *ets; if (!elf_note_info_init(info)) return 0; for (ct = current->mm->core_state->dumper.next; ct; ct = ct->next) { ets = kzalloc(sizeof(*ets), GFP_KERNEL); if (!ets) return 0; ets->thread = ct->task; list_add(&ets->list, &info->thread_list); } list_for_each_entry(ets, &info->thread_list, list) { int sz; sz = elf_dump_thread_status(siginfo->si_signo, ets); info->thread_status_size += sz; } /* now collect the dump for the current */ memset(info->prstatus, 0, sizeof(*info->prstatus)); fill_prstatus(info->prstatus, current, siginfo->si_signo); elf_core_copy_regs(&info->prstatus->pr_reg, regs); /* Set up header */ fill_elf_header(elf, phdrs, ELF_ARCH, ELF_CORE_EFLAGS); /* * Set up the notes in similar form to SVR4 core dumps made * with info from their /proc. */ fill_note(info->notes + 0, "CORE", NT_PRSTATUS, sizeof(*info->prstatus), info->prstatus); fill_psinfo(info->psinfo, current->group_leader, current->mm); fill_note(info->notes + 1, "CORE", NT_PRPSINFO, sizeof(*info->psinfo), info->psinfo); fill_siginfo_note(info->notes + 2, &info->csigdata, siginfo); fill_auxv_note(info->notes + 3, current->mm); info->numnote = 4; if (fill_files_note(info->notes + info->numnote) == 0) { info->notes_files = info->notes + info->numnote; info->numnote++; } /* Try to dump the FPU. */ info->prstatus->pr_fpvalid = elf_core_copy_task_fpregs(current, regs, info->fpu); if (info->prstatus->pr_fpvalid) fill_note(info->notes + info->numnote++, "CORE", NT_PRFPREG, sizeof(*info->fpu), info->fpu); #ifdef ELF_CORE_COPY_XFPREGS if (elf_core_copy_task_xfpregs(current, info->xfpu)) fill_note(info->notes + info->numnote++, "LINUX", ELF_CORE_XFPREG_TYPE, sizeof(*info->xfpu), info->xfpu); #endif return 1; } static size_t get_note_info_size(struct elf_note_info *info) { int sz = 0; int i; for (i = 0; i < info->numnote; i++) sz += notesize(info->notes + i); sz += info->thread_status_size; return sz; } static int write_note_info(struct elf_note_info *info, struct coredump_params *cprm) { struct elf_thread_status *ets; int i; for (i = 0; i < info->numnote; i++) if (!writenote(info->notes + i, cprm)) return 0; /* write out the thread status notes section */ list_for_each_entry(ets, &info->thread_list, list) { for (i = 0; i < ets->num_notes; i++) if (!writenote(&ets->notes[i], cprm)) return 0; } return 1; } static void free_note_info(struct elf_note_info *info) { while (!list_empty(&info->thread_list)) { struct list_head *tmp = info->thread_list.next; list_del(tmp); kfree(list_entry(tmp, struct elf_thread_status, list)); } /* Free data possibly allocated by fill_files_note(): */ if (info->notes_files) kvfree(info->notes_files->data); kfree(info->prstatus); kfree(info->psinfo); kfree(info->notes); kfree(info->fpu); #ifdef ELF_CORE_COPY_XFPREGS kfree(info->xfpu); #endif } #endif static struct vm_area_struct *first_vma(struct task_struct *tsk, struct vm_area_struct *gate_vma) { struct vm_area_struct *ret = tsk->mm->mmap; if (ret) return ret; return gate_vma; } /* * Helper function for iterating across a vma list. It ensures that the caller * will visit `gate_vma' prior to terminating the search. */ static struct vm_area_struct *next_vma(struct vm_area_struct *this_vma, struct vm_area_struct *gate_vma) { struct vm_area_struct *ret; ret = this_vma->vm_next; if (ret) return ret; if (this_vma == gate_vma) return NULL; return gate_vma; } static void fill_extnum_info(struct elfhdr *elf, struct elf_shdr *shdr4extnum, elf_addr_t e_shoff, int segs) { elf->e_shoff = e_shoff; elf->e_shentsize = sizeof(*shdr4extnum); elf->e_shnum = 1; elf->e_shstrndx = SHN_UNDEF; memset(shdr4extnum, 0, sizeof(*shdr4extnum)); shdr4extnum->sh_type = SHT_NULL; shdr4extnum->sh_size = elf->e_shnum; shdr4extnum->sh_link = elf->e_shstrndx; shdr4extnum->sh_info = segs; } /* * Actual dumper * * This is a two-pass process; first we find the offsets of the bits, * and then they are actually written out. If we run out of core limit * we just truncate. */ static int elf_core_dump(struct coredump_params *cprm) { int has_dumped = 0; mm_segment_t fs; int segs, i; size_t vma_data_size = 0; struct vm_area_struct *vma, *gate_vma; struct elfhdr elf; loff_t offset = 0, dataoff; struct elf_note_info info = { }; struct elf_phdr *phdr4note = NULL; struct elf_shdr *shdr4extnum = NULL; Elf_Half e_phnum; elf_addr_t e_shoff; elf_addr_t *vma_filesz = NULL; /* * We no longer stop all VM operations. * * This is because those proceses that could possibly change map_count * or the mmap / vma pages are now blocked in do_exit on current * finishing this core dump. * * Only ptrace can touch these memory addresses, but it doesn't change * the map_count or the pages allocated. So no possibility of crashing * exists while dumping the mm->vm_next areas to the core file. */ /* * The number of segs are recored into ELF header as 16bit value. * Please check DEFAULT_MAX_MAP_COUNT definition when you modify here. */ segs = current->mm->map_count; segs += elf_core_extra_phdrs(); gate_vma = get_gate_vma(current->mm); if (gate_vma != NULL) segs++; /* for notes section */ segs++; /* If segs > PN_XNUM(0xffff), then e_phnum overflows. To avoid * this, kernel supports extended numbering. Have a look at * include/linux/elf.h for further information. */ e_phnum = segs > PN_XNUM ? PN_XNUM : segs; /* * Collect all the non-memory information about the process for the * notes. This also sets up the file header. */ if (!fill_note_info(&elf, e_phnum, &info, cprm->siginfo, cprm->regs)) goto cleanup; has_dumped = 1; fs = get_fs(); set_fs(KERNEL_DS); offset += sizeof(elf); /* Elf header */ offset += segs * sizeof(struct elf_phdr); /* Program headers */ /* Write notes phdr entry */ { size_t sz = get_note_info_size(&info); sz += elf_coredump_extra_notes_size(); phdr4note = kmalloc(sizeof(*phdr4note), GFP_KERNEL); if (!phdr4note) goto end_coredump; fill_elf_note_phdr(phdr4note, sz, offset); offset += sz; } dataoff = offset = roundup(offset, ELF_EXEC_PAGESIZE); /* * Zero vma process will get ZERO_SIZE_PTR here. * Let coredump continue for register state at least. */ vma_filesz = kvmalloc(array_size(sizeof(*vma_filesz), (segs - 1)), GFP_KERNEL); if (!vma_filesz) goto end_coredump; for (i = 0, vma = first_vma(current, gate_vma); vma != NULL; vma = next_vma(vma, gate_vma)) { unsigned long dump_size; dump_size = vma_dump_size(vma, cprm->mm_flags); vma_filesz[i++] = dump_size; vma_data_size += dump_size; } offset += vma_data_size; offset += elf_core_extra_data_size(); e_shoff = offset; if (e_phnum == PN_XNUM) { shdr4extnum = kmalloc(sizeof(*shdr4extnum), GFP_KERNEL); if (!shdr4extnum) goto end_coredump; fill_extnum_info(&elf, shdr4extnum, e_shoff, segs); } offset = dataoff; if (!dump_emit(cprm, &elf, sizeof(elf))) goto end_coredump; if (!dump_emit(cprm, phdr4note, sizeof(*phdr4note))) goto end_coredump; /* Write program headers for segments dump */ for (i = 0, vma = first_vma(current, gate_vma); vma != NULL; vma = next_vma(vma, gate_vma)) { struct elf_phdr phdr; phdr.p_type = PT_LOAD; phdr.p_offset = offset; phdr.p_vaddr = vma->vm_start; phdr.p_paddr = 0; phdr.p_filesz = vma_filesz[i++]; phdr.p_memsz = vma->vm_end - vma->vm_start; offset += phdr.p_filesz; phdr.p_flags = vma->vm_flags & VM_READ ? PF_R : 0; if (vma->vm_flags & VM_WRITE) phdr.p_flags |= PF_W; if (vma->vm_flags & VM_EXEC) phdr.p_flags |= PF_X; phdr.p_align = ELF_EXEC_PAGESIZE; if (!dump_emit(cprm, &phdr, sizeof(phdr))) goto end_coredump; } if (!elf_core_write_extra_phdrs(cprm, offset)) goto end_coredump; /* write out the notes section */ if (!write_note_info(&info, cprm)) goto end_coredump; if (elf_coredump_extra_notes_write(cprm)) goto end_coredump; /* Align to page */ if (!dump_skip(cprm, dataoff - cprm->pos)) goto end_coredump; for (i = 0, vma = first_vma(current, gate_vma); vma != NULL; vma = next_vma(vma, gate_vma)) { unsigned long addr; unsigned long end; end = vma->vm_start + vma_filesz[i++]; for (addr = vma->vm_start; addr < end; addr += PAGE_SIZE) { struct page *page; int stop; page = get_dump_page(addr); if (page) { void *kaddr = kmap(page); stop = !dump_emit(cprm, kaddr, PAGE_SIZE); kunmap(page); put_page(page); } else stop = !dump_skip(cprm, PAGE_SIZE); if (stop) goto end_coredump; } } dump_truncate(cprm); if (!elf_core_write_extra_data(cprm)) goto end_coredump; if (e_phnum == PN_XNUM) { if (!dump_emit(cprm, shdr4extnum, sizeof(*shdr4extnum))) goto end_coredump; } end_coredump: set_fs(fs); cleanup: free_note_info(&info); kfree(shdr4extnum); kvfree(vma_filesz); kfree(phdr4note); return has_dumped; } #endif /* CONFIG_ELF_CORE */ static int __init init_elf_binfmt(void) { register_binfmt(&elf_format); return 0; } static void __exit exit_elf_binfmt(void) { /* Remove the COFF and ELF loaders. */ unregister_binfmt(&elf_format); } core_initcall(init_elf_binfmt); module_exit(exit_elf_binfmt); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_3876_0
crossvul-cpp_data_bad_151_0
/* * linux/kernel/compat.c * * Kernel compatibililty routines for e.g. 32 bit syscall support * on 64 bit kernels. * * Copyright (C) 2002-2003 Stephen Rothwell, IBM Corporation * * 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. */ #include <linux/linkage.h> #include <linux/compat.h> #include <linux/errno.h> #include <linux/time.h> #include <linux/signal.h> #include <linux/sched.h> /* for MAX_SCHEDULE_TIMEOUT */ #include <linux/syscalls.h> #include <linux/unistd.h> #include <linux/security.h> #include <linux/timex.h> #include <linux/export.h> #include <linux/migrate.h> #include <linux/posix-timers.h> #include <linux/times.h> #include <linux/ptrace.h> #include <linux/gfp.h> #include <linux/uaccess.h> int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp) { struct compat_timex tx32; if (copy_from_user(&tx32, utp, sizeof(struct compat_timex))) return -EFAULT; txc->modes = tx32.modes; txc->offset = tx32.offset; txc->freq = tx32.freq; txc->maxerror = tx32.maxerror; txc->esterror = tx32.esterror; txc->status = tx32.status; txc->constant = tx32.constant; txc->precision = tx32.precision; txc->tolerance = tx32.tolerance; txc->time.tv_sec = tx32.time.tv_sec; txc->time.tv_usec = tx32.time.tv_usec; txc->tick = tx32.tick; txc->ppsfreq = tx32.ppsfreq; txc->jitter = tx32.jitter; txc->shift = tx32.shift; txc->stabil = tx32.stabil; txc->jitcnt = tx32.jitcnt; txc->calcnt = tx32.calcnt; txc->errcnt = tx32.errcnt; txc->stbcnt = tx32.stbcnt; return 0; } int compat_put_timex(struct compat_timex __user *utp, const struct timex *txc) { struct compat_timex tx32; memset(&tx32, 0, sizeof(struct compat_timex)); tx32.modes = txc->modes; tx32.offset = txc->offset; tx32.freq = txc->freq; tx32.maxerror = txc->maxerror; tx32.esterror = txc->esterror; tx32.status = txc->status; tx32.constant = txc->constant; tx32.precision = txc->precision; tx32.tolerance = txc->tolerance; tx32.time.tv_sec = txc->time.tv_sec; tx32.time.tv_usec = txc->time.tv_usec; tx32.tick = txc->tick; tx32.ppsfreq = txc->ppsfreq; tx32.jitter = txc->jitter; tx32.shift = txc->shift; tx32.stabil = txc->stabil; tx32.jitcnt = txc->jitcnt; tx32.calcnt = txc->calcnt; tx32.errcnt = txc->errcnt; tx32.stbcnt = txc->stbcnt; tx32.tai = txc->tai; if (copy_to_user(utp, &tx32, sizeof(struct compat_timex))) return -EFAULT; return 0; } static int __compat_get_timeval(struct timeval *tv, const struct compat_timeval __user *ctv) { return (!access_ok(VERIFY_READ, ctv, sizeof(*ctv)) || __get_user(tv->tv_sec, &ctv->tv_sec) || __get_user(tv->tv_usec, &ctv->tv_usec)) ? -EFAULT : 0; } static int __compat_put_timeval(const struct timeval *tv, struct compat_timeval __user *ctv) { return (!access_ok(VERIFY_WRITE, ctv, sizeof(*ctv)) || __put_user(tv->tv_sec, &ctv->tv_sec) || __put_user(tv->tv_usec, &ctv->tv_usec)) ? -EFAULT : 0; } static int __compat_get_timespec(struct timespec *ts, const struct compat_timespec __user *cts) { return (!access_ok(VERIFY_READ, cts, sizeof(*cts)) || __get_user(ts->tv_sec, &cts->tv_sec) || __get_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0; } static int __compat_put_timespec(const struct timespec *ts, struct compat_timespec __user *cts) { return (!access_ok(VERIFY_WRITE, cts, sizeof(*cts)) || __put_user(ts->tv_sec, &cts->tv_sec) || __put_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0; } static int __compat_get_timespec64(struct timespec64 *ts64, const struct compat_timespec __user *cts) { struct compat_timespec ts; int ret; ret = copy_from_user(&ts, cts, sizeof(ts)); if (ret) return -EFAULT; ts64->tv_sec = ts.tv_sec; ts64->tv_nsec = ts.tv_nsec; return 0; } static int __compat_put_timespec64(const struct timespec64 *ts64, struct compat_timespec __user *cts) { struct compat_timespec ts = { .tv_sec = ts64->tv_sec, .tv_nsec = ts64->tv_nsec }; return copy_to_user(cts, &ts, sizeof(ts)) ? -EFAULT : 0; } int compat_get_timespec64(struct timespec64 *ts, const void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_from_user(ts, uts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_get_timespec64(ts, uts); } EXPORT_SYMBOL_GPL(compat_get_timespec64); int compat_put_timespec64(const struct timespec64 *ts, void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_to_user(uts, ts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_put_timespec64(ts, uts); } EXPORT_SYMBOL_GPL(compat_put_timespec64); int compat_get_timeval(struct timeval *tv, const void __user *utv) { if (COMPAT_USE_64BIT_TIME) return copy_from_user(tv, utv, sizeof(*tv)) ? -EFAULT : 0; else return __compat_get_timeval(tv, utv); } EXPORT_SYMBOL_GPL(compat_get_timeval); int compat_put_timeval(const struct timeval *tv, void __user *utv) { if (COMPAT_USE_64BIT_TIME) return copy_to_user(utv, tv, sizeof(*tv)) ? -EFAULT : 0; else return __compat_put_timeval(tv, utv); } EXPORT_SYMBOL_GPL(compat_put_timeval); int compat_get_timespec(struct timespec *ts, const void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_from_user(ts, uts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_get_timespec(ts, uts); } EXPORT_SYMBOL_GPL(compat_get_timespec); int compat_put_timespec(const struct timespec *ts, void __user *uts) { if (COMPAT_USE_64BIT_TIME) return copy_to_user(uts, ts, sizeof(*ts)) ? -EFAULT : 0; else return __compat_put_timespec(ts, uts); } EXPORT_SYMBOL_GPL(compat_put_timespec); int get_compat_itimerval(struct itimerval *o, const struct compat_itimerval __user *i) { struct compat_itimerval v32; if (copy_from_user(&v32, i, sizeof(struct compat_itimerval))) return -EFAULT; o->it_interval.tv_sec = v32.it_interval.tv_sec; o->it_interval.tv_usec = v32.it_interval.tv_usec; o->it_value.tv_sec = v32.it_value.tv_sec; o->it_value.tv_usec = v32.it_value.tv_usec; return 0; } int put_compat_itimerval(struct compat_itimerval __user *o, const struct itimerval *i) { struct compat_itimerval v32; v32.it_interval.tv_sec = i->it_interval.tv_sec; v32.it_interval.tv_usec = i->it_interval.tv_usec; v32.it_value.tv_sec = i->it_value.tv_sec; v32.it_value.tv_usec = i->it_value.tv_usec; return copy_to_user(o, &v32, sizeof(struct compat_itimerval)) ? -EFAULT : 0; } #ifdef __ARCH_WANT_SYS_SIGPROCMASK /* * sys_sigprocmask SIG_SETMASK sets the first (compat) word of the * blocked set of signals to the supplied signal set */ static inline void compat_sig_setmask(sigset_t *blocked, compat_sigset_word set) { memcpy(blocked->sig, &set, sizeof(set)); } COMPAT_SYSCALL_DEFINE3(sigprocmask, int, how, compat_old_sigset_t __user *, nset, compat_old_sigset_t __user *, oset) { old_sigset_t old_set, new_set; sigset_t new_blocked; old_set = current->blocked.sig[0]; if (nset) { if (get_user(new_set, nset)) return -EFAULT; new_set &= ~(sigmask(SIGKILL) | sigmask(SIGSTOP)); new_blocked = current->blocked; switch (how) { case SIG_BLOCK: sigaddsetmask(&new_blocked, new_set); break; case SIG_UNBLOCK: sigdelsetmask(&new_blocked, new_set); break; case SIG_SETMASK: compat_sig_setmask(&new_blocked, new_set); break; default: return -EINVAL; } set_current_blocked(&new_blocked); } if (oset) { if (put_user(old_set, oset)) return -EFAULT; } return 0; } #endif int put_compat_rusage(const struct rusage *r, struct compat_rusage __user *ru) { struct compat_rusage r32; memset(&r32, 0, sizeof(r32)); r32.ru_utime.tv_sec = r->ru_utime.tv_sec; r32.ru_utime.tv_usec = r->ru_utime.tv_usec; r32.ru_stime.tv_sec = r->ru_stime.tv_sec; r32.ru_stime.tv_usec = r->ru_stime.tv_usec; r32.ru_maxrss = r->ru_maxrss; r32.ru_ixrss = r->ru_ixrss; r32.ru_idrss = r->ru_idrss; r32.ru_isrss = r->ru_isrss; r32.ru_minflt = r->ru_minflt; r32.ru_majflt = r->ru_majflt; r32.ru_nswap = r->ru_nswap; r32.ru_inblock = r->ru_inblock; r32.ru_oublock = r->ru_oublock; r32.ru_msgsnd = r->ru_msgsnd; r32.ru_msgrcv = r->ru_msgrcv; r32.ru_nsignals = r->ru_nsignals; r32.ru_nvcsw = r->ru_nvcsw; r32.ru_nivcsw = r->ru_nivcsw; if (copy_to_user(ru, &r32, sizeof(r32))) return -EFAULT; return 0; } static int compat_get_user_cpu_mask(compat_ulong_t __user *user_mask_ptr, unsigned len, struct cpumask *new_mask) { unsigned long *k; if (len < cpumask_size()) memset(new_mask, 0, cpumask_size()); else if (len > cpumask_size()) len = cpumask_size(); k = cpumask_bits(new_mask); return compat_get_bitmap(k, user_mask_ptr, len * 8); } COMPAT_SYSCALL_DEFINE3(sched_setaffinity, compat_pid_t, pid, unsigned int, len, compat_ulong_t __user *, user_mask_ptr) { cpumask_var_t new_mask; int retval; if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) return -ENOMEM; retval = compat_get_user_cpu_mask(user_mask_ptr, len, new_mask); if (retval) goto out; retval = sched_setaffinity(pid, new_mask); out: free_cpumask_var(new_mask); return retval; } COMPAT_SYSCALL_DEFINE3(sched_getaffinity, compat_pid_t, pid, unsigned int, len, compat_ulong_t __user *, user_mask_ptr) { int ret; cpumask_var_t mask; if ((len * BITS_PER_BYTE) < nr_cpu_ids) return -EINVAL; if (len & (sizeof(compat_ulong_t)-1)) return -EINVAL; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; ret = sched_getaffinity(pid, mask); if (ret == 0) { unsigned int retlen = min(len, cpumask_size()); if (compat_put_bitmap(user_mask_ptr, cpumask_bits(mask), retlen * 8)) ret = -EFAULT; else ret = retlen; } free_cpumask_var(mask); return ret; } int get_compat_itimerspec64(struct itimerspec64 *its, const struct compat_itimerspec __user *uits) { if (__compat_get_timespec64(&its->it_interval, &uits->it_interval) || __compat_get_timespec64(&its->it_value, &uits->it_value)) return -EFAULT; return 0; } EXPORT_SYMBOL_GPL(get_compat_itimerspec64); int put_compat_itimerspec64(const struct itimerspec64 *its, struct compat_itimerspec __user *uits) { if (__compat_put_timespec64(&its->it_interval, &uits->it_interval) || __compat_put_timespec64(&its->it_value, &uits->it_value)) return -EFAULT; return 0; } EXPORT_SYMBOL_GPL(put_compat_itimerspec64); /* * We currently only need the following fields from the sigevent * structure: sigev_value, sigev_signo, sig_notify and (sometimes * sigev_notify_thread_id). The others are handled in user mode. * We also assume that copying sigev_value.sival_int is sufficient * to keep all the bits of sigev_value.sival_ptr intact. */ int get_compat_sigevent(struct sigevent *event, const struct compat_sigevent __user *u_event) { memset(event, 0, sizeof(*event)); return (!access_ok(VERIFY_READ, u_event, sizeof(*u_event)) || __get_user(event->sigev_value.sival_int, &u_event->sigev_value.sival_int) || __get_user(event->sigev_signo, &u_event->sigev_signo) || __get_user(event->sigev_notify, &u_event->sigev_notify) || __get_user(event->sigev_notify_thread_id, &u_event->sigev_notify_thread_id)) ? -EFAULT : 0; } long compat_get_bitmap(unsigned long *mask, const compat_ulong_t __user *umask, unsigned long bitmap_size) { unsigned long nr_compat_longs; /* align bitmap up to nearest compat_long_t boundary */ bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG); nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size); if (!access_ok(VERIFY_READ, umask, bitmap_size / 8)) return -EFAULT; user_access_begin(); while (nr_compat_longs > 1) { compat_ulong_t l1, l2; unsafe_get_user(l1, umask++, Efault); unsafe_get_user(l2, umask++, Efault); *mask++ = ((unsigned long)l2 << BITS_PER_COMPAT_LONG) | l1; nr_compat_longs -= 2; } if (nr_compat_longs) unsafe_get_user(*mask, umask++, Efault); user_access_end(); return 0; Efault: user_access_end(); return -EFAULT; } long compat_put_bitmap(compat_ulong_t __user *umask, unsigned long *mask, unsigned long bitmap_size) { unsigned long nr_compat_longs; /* align bitmap up to nearest compat_long_t boundary */ bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG); nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size); if (!access_ok(VERIFY_WRITE, umask, bitmap_size / 8)) return -EFAULT; user_access_begin(); while (nr_compat_longs > 1) { unsigned long m = *mask++; unsafe_put_user((compat_ulong_t)m, umask++, Efault); unsafe_put_user(m >> BITS_PER_COMPAT_LONG, umask++, Efault); nr_compat_longs -= 2; } if (nr_compat_longs) unsafe_put_user((compat_ulong_t)*mask, umask++, Efault); user_access_end(); return 0; Efault: user_access_end(); return -EFAULT; } int get_compat_sigset(sigset_t *set, const compat_sigset_t __user *compat) { #ifdef __BIG_ENDIAN compat_sigset_t v; if (copy_from_user(&v, compat, sizeof(compat_sigset_t))) return -EFAULT; switch (_NSIG_WORDS) { case 4: set->sig[3] = v.sig[6] | (((long)v.sig[7]) << 32 ); case 3: set->sig[2] = v.sig[4] | (((long)v.sig[5]) << 32 ); case 2: set->sig[1] = v.sig[2] | (((long)v.sig[3]) << 32 ); case 1: set->sig[0] = v.sig[0] | (((long)v.sig[1]) << 32 ); } #else if (copy_from_user(set, compat, sizeof(compat_sigset_t))) return -EFAULT; #endif return 0; } EXPORT_SYMBOL_GPL(get_compat_sigset); /* * Allocate user-space memory for the duration of a single system call, * in order to marshall parameters inside a compat thunk. */ void __user *compat_alloc_user_space(unsigned long len) { void __user *ptr; /* If len would occupy more than half of the entire compat space... */ if (unlikely(len > (((compat_uptr_t)~0) >> 1))) return NULL; ptr = arch_compat_alloc_user_space(len); if (unlikely(!access_ok(VERIFY_WRITE, ptr, len))) return NULL; return ptr; } EXPORT_SYMBOL_GPL(compat_alloc_user_space);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_151_0
crossvul-cpp_data_bad_3118_0
#include <linux/export.h> #include <linux/bvec.h> #include <linux/uio.h> #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/splice.h> #include <net/checksum.h> #define PIPE_PARANOIA /* for now */ #define iterate_iovec(i, n, __v, __p, skip, STEP) { \ size_t left; \ size_t wanted = n; \ __p = i->iov; \ __v.iov_len = min(n, __p->iov_len - skip); \ if (likely(__v.iov_len)) { \ __v.iov_base = __p->iov_base + skip; \ left = (STEP); \ __v.iov_len -= left; \ skip += __v.iov_len; \ n -= __v.iov_len; \ } else { \ left = 0; \ } \ while (unlikely(!left && n)) { \ __p++; \ __v.iov_len = min(n, __p->iov_len); \ if (unlikely(!__v.iov_len)) \ continue; \ __v.iov_base = __p->iov_base; \ left = (STEP); \ __v.iov_len -= left; \ skip = __v.iov_len; \ n -= __v.iov_len; \ } \ n = wanted - n; \ } #define iterate_kvec(i, n, __v, __p, skip, STEP) { \ size_t wanted = n; \ __p = i->kvec; \ __v.iov_len = min(n, __p->iov_len - skip); \ if (likely(__v.iov_len)) { \ __v.iov_base = __p->iov_base + skip; \ (void)(STEP); \ skip += __v.iov_len; \ n -= __v.iov_len; \ } \ while (unlikely(n)) { \ __p++; \ __v.iov_len = min(n, __p->iov_len); \ if (unlikely(!__v.iov_len)) \ continue; \ __v.iov_base = __p->iov_base; \ (void)(STEP); \ skip = __v.iov_len; \ n -= __v.iov_len; \ } \ n = wanted; \ } #define iterate_bvec(i, n, __v, __bi, skip, STEP) { \ struct bvec_iter __start; \ __start.bi_size = n; \ __start.bi_bvec_done = skip; \ __start.bi_idx = 0; \ for_each_bvec(__v, i->bvec, __bi, __start) { \ if (!__v.bv_len) \ continue; \ (void)(STEP); \ } \ } #define iterate_all_kinds(i, n, v, I, B, K) { \ if (likely(n)) { \ size_t skip = i->iov_offset; \ if (unlikely(i->type & ITER_BVEC)) { \ struct bio_vec v; \ struct bvec_iter __bi; \ iterate_bvec(i, n, v, __bi, skip, (B)) \ } else if (unlikely(i->type & ITER_KVEC)) { \ const struct kvec *kvec; \ struct kvec v; \ iterate_kvec(i, n, v, kvec, skip, (K)) \ } else { \ const struct iovec *iov; \ struct iovec v; \ iterate_iovec(i, n, v, iov, skip, (I)) \ } \ } \ } #define iterate_and_advance(i, n, v, I, B, K) { \ if (unlikely(i->count < n)) \ n = i->count; \ if (i->count) { \ size_t skip = i->iov_offset; \ if (unlikely(i->type & ITER_BVEC)) { \ const struct bio_vec *bvec = i->bvec; \ struct bio_vec v; \ struct bvec_iter __bi; \ iterate_bvec(i, n, v, __bi, skip, (B)) \ i->bvec = __bvec_iter_bvec(i->bvec, __bi); \ i->nr_segs -= i->bvec - bvec; \ skip = __bi.bi_bvec_done; \ } else if (unlikely(i->type & ITER_KVEC)) { \ const struct kvec *kvec; \ struct kvec v; \ iterate_kvec(i, n, v, kvec, skip, (K)) \ if (skip == kvec->iov_len) { \ kvec++; \ skip = 0; \ } \ i->nr_segs -= kvec - i->kvec; \ i->kvec = kvec; \ } else { \ const struct iovec *iov; \ struct iovec v; \ iterate_iovec(i, n, v, iov, skip, (I)) \ if (skip == iov->iov_len) { \ iov++; \ skip = 0; \ } \ i->nr_segs -= iov - i->iov; \ i->iov = iov; \ } \ i->count -= n; \ i->iov_offset = skip; \ } \ } static size_t copy_page_to_iter_iovec(struct page *page, size_t offset, size_t bytes, struct iov_iter *i) { size_t skip, copy, left, wanted; const struct iovec *iov; char __user *buf; void *kaddr, *from; if (unlikely(bytes > i->count)) bytes = i->count; if (unlikely(!bytes)) return 0; wanted = bytes; iov = i->iov; skip = i->iov_offset; buf = iov->iov_base + skip; copy = min(bytes, iov->iov_len - skip); if (IS_ENABLED(CONFIG_HIGHMEM) && !fault_in_pages_writeable(buf, copy)) { kaddr = kmap_atomic(page); from = kaddr + offset; /* first chunk, usually the only one */ left = __copy_to_user_inatomic(buf, from, copy); copy -= left; skip += copy; from += copy; bytes -= copy; while (unlikely(!left && bytes)) { iov++; buf = iov->iov_base; copy = min(bytes, iov->iov_len); left = __copy_to_user_inatomic(buf, from, copy); copy -= left; skip = copy; from += copy; bytes -= copy; } if (likely(!bytes)) { kunmap_atomic(kaddr); goto done; } offset = from - kaddr; buf += copy; kunmap_atomic(kaddr); copy = min(bytes, iov->iov_len - skip); } /* Too bad - revert to non-atomic kmap */ kaddr = kmap(page); from = kaddr + offset; left = __copy_to_user(buf, from, copy); copy -= left; skip += copy; from += copy; bytes -= copy; while (unlikely(!left && bytes)) { iov++; buf = iov->iov_base; copy = min(bytes, iov->iov_len); left = __copy_to_user(buf, from, copy); copy -= left; skip = copy; from += copy; bytes -= copy; } kunmap(page); done: if (skip == iov->iov_len) { iov++; skip = 0; } i->count -= wanted - bytes; i->nr_segs -= iov - i->iov; i->iov = iov; i->iov_offset = skip; return wanted - bytes; } static size_t copy_page_from_iter_iovec(struct page *page, size_t offset, size_t bytes, struct iov_iter *i) { size_t skip, copy, left, wanted; const struct iovec *iov; char __user *buf; void *kaddr, *to; if (unlikely(bytes > i->count)) bytes = i->count; if (unlikely(!bytes)) return 0; wanted = bytes; iov = i->iov; skip = i->iov_offset; buf = iov->iov_base + skip; copy = min(bytes, iov->iov_len - skip); if (IS_ENABLED(CONFIG_HIGHMEM) && !fault_in_pages_readable(buf, copy)) { kaddr = kmap_atomic(page); to = kaddr + offset; /* first chunk, usually the only one */ left = __copy_from_user_inatomic(to, buf, copy); copy -= left; skip += copy; to += copy; bytes -= copy; while (unlikely(!left && bytes)) { iov++; buf = iov->iov_base; copy = min(bytes, iov->iov_len); left = __copy_from_user_inatomic(to, buf, copy); copy -= left; skip = copy; to += copy; bytes -= copy; } if (likely(!bytes)) { kunmap_atomic(kaddr); goto done; } offset = to - kaddr; buf += copy; kunmap_atomic(kaddr); copy = min(bytes, iov->iov_len - skip); } /* Too bad - revert to non-atomic kmap */ kaddr = kmap(page); to = kaddr + offset; left = __copy_from_user(to, buf, copy); copy -= left; skip += copy; to += copy; bytes -= copy; while (unlikely(!left && bytes)) { iov++; buf = iov->iov_base; copy = min(bytes, iov->iov_len); left = __copy_from_user(to, buf, copy); copy -= left; skip = copy; to += copy; bytes -= copy; } kunmap(page); done: if (skip == iov->iov_len) { iov++; skip = 0; } i->count -= wanted - bytes; i->nr_segs -= iov - i->iov; i->iov = iov; i->iov_offset = skip; return wanted - bytes; } #ifdef PIPE_PARANOIA static bool sanity(const struct iov_iter *i) { struct pipe_inode_info *pipe = i->pipe; int idx = i->idx; int next = pipe->curbuf + pipe->nrbufs; if (i->iov_offset) { struct pipe_buffer *p; if (unlikely(!pipe->nrbufs)) goto Bad; // pipe must be non-empty if (unlikely(idx != ((next - 1) & (pipe->buffers - 1)))) goto Bad; // must be at the last buffer... p = &pipe->bufs[idx]; if (unlikely(p->offset + p->len != i->iov_offset)) goto Bad; // ... at the end of segment } else { if (idx != (next & (pipe->buffers - 1))) goto Bad; // must be right after the last buffer } return true; Bad: printk(KERN_ERR "idx = %d, offset = %zd\n", i->idx, i->iov_offset); printk(KERN_ERR "curbuf = %d, nrbufs = %d, buffers = %d\n", pipe->curbuf, pipe->nrbufs, pipe->buffers); for (idx = 0; idx < pipe->buffers; idx++) printk(KERN_ERR "[%p %p %d %d]\n", pipe->bufs[idx].ops, pipe->bufs[idx].page, pipe->bufs[idx].offset, pipe->bufs[idx].len); WARN_ON(1); return false; } #else #define sanity(i) true #endif static inline int next_idx(int idx, struct pipe_inode_info *pipe) { return (idx + 1) & (pipe->buffers - 1); } static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes, struct iov_iter *i) { struct pipe_inode_info *pipe = i->pipe; struct pipe_buffer *buf; size_t off; int idx; if (unlikely(bytes > i->count)) bytes = i->count; if (unlikely(!bytes)) return 0; if (!sanity(i)) return 0; off = i->iov_offset; idx = i->idx; buf = &pipe->bufs[idx]; if (off) { if (offset == off && buf->page == page) { /* merge with the last one */ buf->len += bytes; i->iov_offset += bytes; goto out; } idx = next_idx(idx, pipe); buf = &pipe->bufs[idx]; } if (idx == pipe->curbuf && pipe->nrbufs) return 0; pipe->nrbufs++; buf->ops = &page_cache_pipe_buf_ops; get_page(buf->page = page); buf->offset = offset; buf->len = bytes; i->iov_offset = offset + bytes; i->idx = idx; out: i->count -= bytes; return bytes; } /* * Fault in one or more iovecs of the given iov_iter, to a maximum length of * bytes. For each iovec, fault in each page that constitutes the iovec. * * Return 0 on success, or non-zero if the memory could not be accessed (i.e. * because it is an invalid address). */ int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes) { size_t skip = i->iov_offset; const struct iovec *iov; int err; struct iovec v; if (!(i->type & (ITER_BVEC|ITER_KVEC))) { iterate_iovec(i, bytes, v, iov, skip, ({ err = fault_in_pages_readable(v.iov_base, v.iov_len); if (unlikely(err)) return err; 0;})) } return 0; } EXPORT_SYMBOL(iov_iter_fault_in_readable); void iov_iter_init(struct iov_iter *i, int direction, const struct iovec *iov, unsigned long nr_segs, size_t count) { /* It will get better. Eventually... */ if (segment_eq(get_fs(), KERNEL_DS)) { direction |= ITER_KVEC; i->type = direction; i->kvec = (struct kvec *)iov; } else { i->type = direction; i->iov = iov; } i->nr_segs = nr_segs; i->iov_offset = 0; i->count = count; } EXPORT_SYMBOL(iov_iter_init); static void memcpy_from_page(char *to, struct page *page, size_t offset, size_t len) { char *from = kmap_atomic(page); memcpy(to, from + offset, len); kunmap_atomic(from); } static void memcpy_to_page(struct page *page, size_t offset, const char *from, size_t len) { char *to = kmap_atomic(page); memcpy(to + offset, from, len); kunmap_atomic(to); } static void memzero_page(struct page *page, size_t offset, size_t len) { char *addr = kmap_atomic(page); memset(addr + offset, 0, len); kunmap_atomic(addr); } static inline bool allocated(struct pipe_buffer *buf) { return buf->ops == &default_pipe_buf_ops; } static inline void data_start(const struct iov_iter *i, int *idxp, size_t *offp) { size_t off = i->iov_offset; int idx = i->idx; if (off && (!allocated(&i->pipe->bufs[idx]) || off == PAGE_SIZE)) { idx = next_idx(idx, i->pipe); off = 0; } *idxp = idx; *offp = off; } static size_t push_pipe(struct iov_iter *i, size_t size, int *idxp, size_t *offp) { struct pipe_inode_info *pipe = i->pipe; size_t off; int idx; ssize_t left; if (unlikely(size > i->count)) size = i->count; if (unlikely(!size)) return 0; left = size; data_start(i, &idx, &off); *idxp = idx; *offp = off; if (off) { left -= PAGE_SIZE - off; if (left <= 0) { pipe->bufs[idx].len += size; return size; } pipe->bufs[idx].len = PAGE_SIZE; idx = next_idx(idx, pipe); } while (idx != pipe->curbuf || !pipe->nrbufs) { struct page *page = alloc_page(GFP_USER); if (!page) break; pipe->nrbufs++; pipe->bufs[idx].ops = &default_pipe_buf_ops; pipe->bufs[idx].page = page; pipe->bufs[idx].offset = 0; if (left <= PAGE_SIZE) { pipe->bufs[idx].len = left; return size; } pipe->bufs[idx].len = PAGE_SIZE; left -= PAGE_SIZE; idx = next_idx(idx, pipe); } return size - left; } static size_t copy_pipe_to_iter(const void *addr, size_t bytes, struct iov_iter *i) { struct pipe_inode_info *pipe = i->pipe; size_t n, off; int idx; if (!sanity(i)) return 0; bytes = n = push_pipe(i, bytes, &idx, &off); if (unlikely(!n)) return 0; for ( ; n; idx = next_idx(idx, pipe), off = 0) { size_t chunk = min_t(size_t, n, PAGE_SIZE - off); memcpy_to_page(pipe->bufs[idx].page, off, addr, chunk); i->idx = idx; i->iov_offset = off + chunk; n -= chunk; addr += chunk; } i->count -= bytes; return bytes; } size_t copy_to_iter(const void *addr, size_t bytes, struct iov_iter *i) { const char *from = addr; if (unlikely(i->type & ITER_PIPE)) return copy_pipe_to_iter(addr, bytes, i); iterate_and_advance(i, bytes, v, __copy_to_user(v.iov_base, (from += v.iov_len) - v.iov_len, v.iov_len), memcpy_to_page(v.bv_page, v.bv_offset, (from += v.bv_len) - v.bv_len, v.bv_len), memcpy(v.iov_base, (from += v.iov_len) - v.iov_len, v.iov_len) ) return bytes; } EXPORT_SYMBOL(copy_to_iter); size_t copy_from_iter(void *addr, size_t bytes, struct iov_iter *i) { char *to = addr; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return 0; } iterate_and_advance(i, bytes, v, __copy_from_user((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len), memcpy_from_page((to += v.bv_len) - v.bv_len, v.bv_page, v.bv_offset, v.bv_len), memcpy((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len) ) return bytes; } EXPORT_SYMBOL(copy_from_iter); bool copy_from_iter_full(void *addr, size_t bytes, struct iov_iter *i) { char *to = addr; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return false; } if (unlikely(i->count < bytes)) return false; iterate_all_kinds(i, bytes, v, ({ if (__copy_from_user((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len)) return false; 0;}), memcpy_from_page((to += v.bv_len) - v.bv_len, v.bv_page, v.bv_offset, v.bv_len), memcpy((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len) ) iov_iter_advance(i, bytes); return true; } EXPORT_SYMBOL(copy_from_iter_full); size_t copy_from_iter_nocache(void *addr, size_t bytes, struct iov_iter *i) { char *to = addr; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return 0; } iterate_and_advance(i, bytes, v, __copy_from_user_nocache((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len), memcpy_from_page((to += v.bv_len) - v.bv_len, v.bv_page, v.bv_offset, v.bv_len), memcpy((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len) ) return bytes; } EXPORT_SYMBOL(copy_from_iter_nocache); bool copy_from_iter_full_nocache(void *addr, size_t bytes, struct iov_iter *i) { char *to = addr; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return false; } if (unlikely(i->count < bytes)) return false; iterate_all_kinds(i, bytes, v, ({ if (__copy_from_user_nocache((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len)) return false; 0;}), memcpy_from_page((to += v.bv_len) - v.bv_len, v.bv_page, v.bv_offset, v.bv_len), memcpy((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len) ) iov_iter_advance(i, bytes); return true; } EXPORT_SYMBOL(copy_from_iter_full_nocache); size_t copy_page_to_iter(struct page *page, size_t offset, size_t bytes, struct iov_iter *i) { if (i->type & (ITER_BVEC|ITER_KVEC)) { void *kaddr = kmap_atomic(page); size_t wanted = copy_to_iter(kaddr + offset, bytes, i); kunmap_atomic(kaddr); return wanted; } else if (likely(!(i->type & ITER_PIPE))) return copy_page_to_iter_iovec(page, offset, bytes, i); else return copy_page_to_iter_pipe(page, offset, bytes, i); } EXPORT_SYMBOL(copy_page_to_iter); size_t copy_page_from_iter(struct page *page, size_t offset, size_t bytes, struct iov_iter *i) { if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return 0; } if (i->type & (ITER_BVEC|ITER_KVEC)) { void *kaddr = kmap_atomic(page); size_t wanted = copy_from_iter(kaddr + offset, bytes, i); kunmap_atomic(kaddr); return wanted; } else return copy_page_from_iter_iovec(page, offset, bytes, i); } EXPORT_SYMBOL(copy_page_from_iter); static size_t pipe_zero(size_t bytes, struct iov_iter *i) { struct pipe_inode_info *pipe = i->pipe; size_t n, off; int idx; if (!sanity(i)) return 0; bytes = n = push_pipe(i, bytes, &idx, &off); if (unlikely(!n)) return 0; for ( ; n; idx = next_idx(idx, pipe), off = 0) { size_t chunk = min_t(size_t, n, PAGE_SIZE - off); memzero_page(pipe->bufs[idx].page, off, chunk); i->idx = idx; i->iov_offset = off + chunk; n -= chunk; } i->count -= bytes; return bytes; } size_t iov_iter_zero(size_t bytes, struct iov_iter *i) { if (unlikely(i->type & ITER_PIPE)) return pipe_zero(bytes, i); iterate_and_advance(i, bytes, v, __clear_user(v.iov_base, v.iov_len), memzero_page(v.bv_page, v.bv_offset, v.bv_len), memset(v.iov_base, 0, v.iov_len) ) return bytes; } EXPORT_SYMBOL(iov_iter_zero); size_t iov_iter_copy_from_user_atomic(struct page *page, struct iov_iter *i, unsigned long offset, size_t bytes) { char *kaddr = kmap_atomic(page), *p = kaddr + offset; if (unlikely(i->type & ITER_PIPE)) { kunmap_atomic(kaddr); WARN_ON(1); return 0; } iterate_all_kinds(i, bytes, v, __copy_from_user_inatomic((p += v.iov_len) - v.iov_len, v.iov_base, v.iov_len), memcpy_from_page((p += v.bv_len) - v.bv_len, v.bv_page, v.bv_offset, v.bv_len), memcpy((p += v.iov_len) - v.iov_len, v.iov_base, v.iov_len) ) kunmap_atomic(kaddr); return bytes; } EXPORT_SYMBOL(iov_iter_copy_from_user_atomic); static void pipe_advance(struct iov_iter *i, size_t size) { struct pipe_inode_info *pipe = i->pipe; struct pipe_buffer *buf; int idx = i->idx; size_t off = i->iov_offset, orig_sz; if (unlikely(i->count < size)) size = i->count; orig_sz = size; if (size) { if (off) /* make it relative to the beginning of buffer */ size += off - pipe->bufs[idx].offset; while (1) { buf = &pipe->bufs[idx]; if (size <= buf->len) break; size -= buf->len; idx = next_idx(idx, pipe); } buf->len = size; i->idx = idx; off = i->iov_offset = buf->offset + size; } if (off) idx = next_idx(idx, pipe); if (pipe->nrbufs) { int unused = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1); /* [curbuf,unused) is in use. Free [idx,unused) */ while (idx != unused) { pipe_buf_release(pipe, &pipe->bufs[idx]); idx = next_idx(idx, pipe); pipe->nrbufs--; } } i->count -= orig_sz; } void iov_iter_advance(struct iov_iter *i, size_t size) { if (unlikely(i->type & ITER_PIPE)) { pipe_advance(i, size); return; } iterate_and_advance(i, size, v, 0, 0, 0) } EXPORT_SYMBOL(iov_iter_advance); /* * Return the count of just the current iov_iter segment. */ size_t iov_iter_single_seg_count(const struct iov_iter *i) { if (unlikely(i->type & ITER_PIPE)) return i->count; // it is a silly place, anyway if (i->nr_segs == 1) return i->count; else if (i->type & ITER_BVEC) return min(i->count, i->bvec->bv_len - i->iov_offset); else return min(i->count, i->iov->iov_len - i->iov_offset); } EXPORT_SYMBOL(iov_iter_single_seg_count); void iov_iter_kvec(struct iov_iter *i, int direction, const struct kvec *kvec, unsigned long nr_segs, size_t count) { BUG_ON(!(direction & ITER_KVEC)); i->type = direction; i->kvec = kvec; i->nr_segs = nr_segs; i->iov_offset = 0; i->count = count; } EXPORT_SYMBOL(iov_iter_kvec); void iov_iter_bvec(struct iov_iter *i, int direction, const struct bio_vec *bvec, unsigned long nr_segs, size_t count) { BUG_ON(!(direction & ITER_BVEC)); i->type = direction; i->bvec = bvec; i->nr_segs = nr_segs; i->iov_offset = 0; i->count = count; } EXPORT_SYMBOL(iov_iter_bvec); void iov_iter_pipe(struct iov_iter *i, int direction, struct pipe_inode_info *pipe, size_t count) { BUG_ON(direction != ITER_PIPE); i->type = direction; i->pipe = pipe; i->idx = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1); i->iov_offset = 0; i->count = count; } EXPORT_SYMBOL(iov_iter_pipe); unsigned long iov_iter_alignment(const struct iov_iter *i) { unsigned long res = 0; size_t size = i->count; if (unlikely(i->type & ITER_PIPE)) { if (size && i->iov_offset && allocated(&i->pipe->bufs[i->idx])) return size | i->iov_offset; return size; } iterate_all_kinds(i, size, v, (res |= (unsigned long)v.iov_base | v.iov_len, 0), res |= v.bv_offset | v.bv_len, res |= (unsigned long)v.iov_base | v.iov_len ) return res; } EXPORT_SYMBOL(iov_iter_alignment); unsigned long iov_iter_gap_alignment(const struct iov_iter *i) { unsigned long res = 0; size_t size = i->count; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return ~0U; } iterate_all_kinds(i, size, v, (res |= (!res ? 0 : (unsigned long)v.iov_base) | (size != v.iov_len ? size : 0), 0), (res |= (!res ? 0 : (unsigned long)v.bv_offset) | (size != v.bv_len ? size : 0)), (res |= (!res ? 0 : (unsigned long)v.iov_base) | (size != v.iov_len ? size : 0)) ); return res; } EXPORT_SYMBOL(iov_iter_gap_alignment); static inline size_t __pipe_get_pages(struct iov_iter *i, size_t maxsize, struct page **pages, int idx, size_t *start) { struct pipe_inode_info *pipe = i->pipe; ssize_t n = push_pipe(i, maxsize, &idx, start); if (!n) return -EFAULT; maxsize = n; n += *start; while (n > 0) { get_page(*pages++ = pipe->bufs[idx].page); idx = next_idx(idx, pipe); n -= PAGE_SIZE; } return maxsize; } static ssize_t pipe_get_pages(struct iov_iter *i, struct page **pages, size_t maxsize, unsigned maxpages, size_t *start) { unsigned npages; size_t capacity; int idx; if (!maxsize) return 0; if (!sanity(i)) return -EFAULT; data_start(i, &idx, start); /* some of this one + all after this one */ npages = ((i->pipe->curbuf - idx - 1) & (i->pipe->buffers - 1)) + 1; capacity = min(npages,maxpages) * PAGE_SIZE - *start; return __pipe_get_pages(i, min(maxsize, capacity), pages, idx, start); } ssize_t iov_iter_get_pages(struct iov_iter *i, struct page **pages, size_t maxsize, unsigned maxpages, size_t *start) { if (maxsize > i->count) maxsize = i->count; if (unlikely(i->type & ITER_PIPE)) return pipe_get_pages(i, pages, maxsize, maxpages, start); iterate_all_kinds(i, maxsize, v, ({ unsigned long addr = (unsigned long)v.iov_base; size_t len = v.iov_len + (*start = addr & (PAGE_SIZE - 1)); int n; int res; if (len > maxpages * PAGE_SIZE) len = maxpages * PAGE_SIZE; addr &= ~(PAGE_SIZE - 1); n = DIV_ROUND_UP(len, PAGE_SIZE); res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, pages); if (unlikely(res < 0)) return res; return (res == n ? len : res * PAGE_SIZE) - *start; 0;}),({ /* can't be more than PAGE_SIZE */ *start = v.bv_offset; get_page(*pages = v.bv_page); return v.bv_len; }),({ return -EFAULT; }) ) return 0; } EXPORT_SYMBOL(iov_iter_get_pages); static struct page **get_pages_array(size_t n) { struct page **p = kmalloc(n * sizeof(struct page *), GFP_KERNEL); if (!p) p = vmalloc(n * sizeof(struct page *)); return p; } static ssize_t pipe_get_pages_alloc(struct iov_iter *i, struct page ***pages, size_t maxsize, size_t *start) { struct page **p; size_t n; int idx; int npages; if (!maxsize) return 0; if (!sanity(i)) return -EFAULT; data_start(i, &idx, start); /* some of this one + all after this one */ npages = ((i->pipe->curbuf - idx - 1) & (i->pipe->buffers - 1)) + 1; n = npages * PAGE_SIZE - *start; if (maxsize > n) maxsize = n; else npages = DIV_ROUND_UP(maxsize + *start, PAGE_SIZE); p = get_pages_array(npages); if (!p) return -ENOMEM; n = __pipe_get_pages(i, maxsize, p, idx, start); if (n > 0) *pages = p; else kvfree(p); return n; } ssize_t iov_iter_get_pages_alloc(struct iov_iter *i, struct page ***pages, size_t maxsize, size_t *start) { struct page **p; if (maxsize > i->count) maxsize = i->count; if (unlikely(i->type & ITER_PIPE)) return pipe_get_pages_alloc(i, pages, maxsize, start); iterate_all_kinds(i, maxsize, v, ({ unsigned long addr = (unsigned long)v.iov_base; size_t len = v.iov_len + (*start = addr & (PAGE_SIZE - 1)); int n; int res; addr &= ~(PAGE_SIZE - 1); n = DIV_ROUND_UP(len, PAGE_SIZE); p = get_pages_array(n); if (!p) return -ENOMEM; res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, p); if (unlikely(res < 0)) { kvfree(p); return res; } *pages = p; return (res == n ? len : res * PAGE_SIZE) - *start; 0;}),({ /* can't be more than PAGE_SIZE */ *start = v.bv_offset; *pages = p = get_pages_array(1); if (!p) return -ENOMEM; get_page(*p = v.bv_page); return v.bv_len; }),({ return -EFAULT; }) ) return 0; } EXPORT_SYMBOL(iov_iter_get_pages_alloc); size_t csum_and_copy_from_iter(void *addr, size_t bytes, __wsum *csum, struct iov_iter *i) { char *to = addr; __wsum sum, next; size_t off = 0; sum = *csum; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return 0; } iterate_and_advance(i, bytes, v, ({ int err = 0; next = csum_and_copy_from_user(v.iov_base, (to += v.iov_len) - v.iov_len, v.iov_len, 0, &err); if (!err) { sum = csum_block_add(sum, next, off); off += v.iov_len; } err ? v.iov_len : 0; }), ({ char *p = kmap_atomic(v.bv_page); next = csum_partial_copy_nocheck(p + v.bv_offset, (to += v.bv_len) - v.bv_len, v.bv_len, 0); kunmap_atomic(p); sum = csum_block_add(sum, next, off); off += v.bv_len; }),({ next = csum_partial_copy_nocheck(v.iov_base, (to += v.iov_len) - v.iov_len, v.iov_len, 0); sum = csum_block_add(sum, next, off); off += v.iov_len; }) ) *csum = sum; return bytes; } EXPORT_SYMBOL(csum_and_copy_from_iter); bool csum_and_copy_from_iter_full(void *addr, size_t bytes, __wsum *csum, struct iov_iter *i) { char *to = addr; __wsum sum, next; size_t off = 0; sum = *csum; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); return false; } if (unlikely(i->count < bytes)) return false; iterate_all_kinds(i, bytes, v, ({ int err = 0; next = csum_and_copy_from_user(v.iov_base, (to += v.iov_len) - v.iov_len, v.iov_len, 0, &err); if (err) return false; sum = csum_block_add(sum, next, off); off += v.iov_len; 0; }), ({ char *p = kmap_atomic(v.bv_page); next = csum_partial_copy_nocheck(p + v.bv_offset, (to += v.bv_len) - v.bv_len, v.bv_len, 0); kunmap_atomic(p); sum = csum_block_add(sum, next, off); off += v.bv_len; }),({ next = csum_partial_copy_nocheck(v.iov_base, (to += v.iov_len) - v.iov_len, v.iov_len, 0); sum = csum_block_add(sum, next, off); off += v.iov_len; }) ) *csum = sum; iov_iter_advance(i, bytes); return true; } EXPORT_SYMBOL(csum_and_copy_from_iter_full); size_t csum_and_copy_to_iter(const void *addr, size_t bytes, __wsum *csum, struct iov_iter *i) { const char *from = addr; __wsum sum, next; size_t off = 0; sum = *csum; if (unlikely(i->type & ITER_PIPE)) { WARN_ON(1); /* for now */ return 0; } iterate_and_advance(i, bytes, v, ({ int err = 0; next = csum_and_copy_to_user((from += v.iov_len) - v.iov_len, v.iov_base, v.iov_len, 0, &err); if (!err) { sum = csum_block_add(sum, next, off); off += v.iov_len; } err ? v.iov_len : 0; }), ({ char *p = kmap_atomic(v.bv_page); next = csum_partial_copy_nocheck((from += v.bv_len) - v.bv_len, p + v.bv_offset, v.bv_len, 0); kunmap_atomic(p); sum = csum_block_add(sum, next, off); off += v.bv_len; }),({ next = csum_partial_copy_nocheck((from += v.iov_len) - v.iov_len, v.iov_base, v.iov_len, 0); sum = csum_block_add(sum, next, off); off += v.iov_len; }) ) *csum = sum; return bytes; } EXPORT_SYMBOL(csum_and_copy_to_iter); int iov_iter_npages(const struct iov_iter *i, int maxpages) { size_t size = i->count; int npages = 0; if (!size) return 0; if (unlikely(i->type & ITER_PIPE)) { struct pipe_inode_info *pipe = i->pipe; size_t off; int idx; if (!sanity(i)) return 0; data_start(i, &idx, &off); /* some of this one + all after this one */ npages = ((pipe->curbuf - idx - 1) & (pipe->buffers - 1)) + 1; if (npages >= maxpages) return maxpages; } else iterate_all_kinds(i, size, v, ({ unsigned long p = (unsigned long)v.iov_base; npages += DIV_ROUND_UP(p + v.iov_len, PAGE_SIZE) - p / PAGE_SIZE; if (npages >= maxpages) return maxpages; 0;}),({ npages++; if (npages >= maxpages) return maxpages; }),({ unsigned long p = (unsigned long)v.iov_base; npages += DIV_ROUND_UP(p + v.iov_len, PAGE_SIZE) - p / PAGE_SIZE; if (npages >= maxpages) return maxpages; }) ) return npages; } EXPORT_SYMBOL(iov_iter_npages); const void *dup_iter(struct iov_iter *new, struct iov_iter *old, gfp_t flags) { *new = *old; if (unlikely(new->type & ITER_PIPE)) { WARN_ON(1); return NULL; } if (new->type & ITER_BVEC) return new->bvec = kmemdup(new->bvec, new->nr_segs * sizeof(struct bio_vec), flags); else /* iovec and kvec have identical layout */ return new->iov = kmemdup(new->iov, new->nr_segs * sizeof(struct iovec), flags); } EXPORT_SYMBOL(dup_iter); /** * import_iovec() - Copy an array of &struct iovec from userspace * into the kernel, check that it is valid, and initialize a new * &struct iov_iter iterator to access it. * * @type: One of %READ or %WRITE. * @uvector: Pointer to the userspace array. * @nr_segs: Number of elements in userspace array. * @fast_segs: Number of elements in @iov. * @iov: (input and output parameter) Pointer to pointer to (usually small * on-stack) kernel array. * @i: Pointer to iterator that will be initialized on success. * * If the array pointed to by *@iov is large enough to hold all @nr_segs, * then this function places %NULL in *@iov on return. Otherwise, a new * array will be allocated and the result placed in *@iov. This means that * the caller may call kfree() on *@iov regardless of whether the small * on-stack array was used or not (and regardless of whether this function * returns an error or not). * * Return: 0 on success or negative error code on error. */ int import_iovec(int type, const struct iovec __user * uvector, unsigned nr_segs, unsigned fast_segs, struct iovec **iov, struct iov_iter *i) { ssize_t n; struct iovec *p; n = rw_copy_check_uvector(type, uvector, nr_segs, fast_segs, *iov, &p); if (n < 0) { if (p != *iov) kfree(p); *iov = NULL; return n; } iov_iter_init(i, type, p, nr_segs, n); *iov = p == *iov ? NULL : p; return 0; } EXPORT_SYMBOL(import_iovec); #ifdef CONFIG_COMPAT #include <linux/compat.h> int compat_import_iovec(int type, const struct compat_iovec __user * uvector, unsigned nr_segs, unsigned fast_segs, struct iovec **iov, struct iov_iter *i) { ssize_t n; struct iovec *p; n = compat_rw_copy_check_uvector(type, uvector, nr_segs, fast_segs, *iov, &p); if (n < 0) { if (p != *iov) kfree(p); *iov = NULL; return n; } iov_iter_init(i, type, p, nr_segs, n); *iov = p == *iov ? NULL : p; return 0; } #endif int import_single_range(int rw, void __user *buf, size_t len, struct iovec *iov, struct iov_iter *i) { if (len > MAX_RW_COUNT) len = MAX_RW_COUNT; if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iov->iov_base = buf; iov->iov_len = len; iov_iter_init(i, rw, iov, 1, len); return 0; } EXPORT_SYMBOL(import_single_range);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3118_0
crossvul-cpp_data_good_3841_0
/* * namei.c * * PURPOSE * Inode name handling routines for the OSTA-UDF(tm) filesystem. * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. * * (C) 1998-2004 Ben Fennema * (C) 1999-2000 Stelias Computing Inc * * HISTORY * * 12/12/98 blf Created. Split out the lookup code from dir.c * 04/19/99 blf link, mknod, symlink support */ #include "udfdecl.h" #include "udf_i.h" #include "udf_sb.h" #include <linux/string.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/buffer_head.h> #include <linux/sched.h> #include <linux/crc-itu-t.h> #include <linux/exportfs.h> static inline int udf_match(int len1, const unsigned char *name1, int len2, const unsigned char *name2) { if (len1 != len2) return 0; return !memcmp(name1, name2, len1); } int udf_write_fi(struct inode *inode, struct fileIdentDesc *cfi, struct fileIdentDesc *sfi, struct udf_fileident_bh *fibh, uint8_t *impuse, uint8_t *fileident) { uint16_t crclen = fibh->eoffset - fibh->soffset - sizeof(struct tag); uint16_t crc; int offset; uint16_t liu = le16_to_cpu(cfi->lengthOfImpUse); uint8_t lfi = cfi->lengthFileIdent; int padlen = fibh->eoffset - fibh->soffset - liu - lfi - sizeof(struct fileIdentDesc); int adinicb = 0; if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) adinicb = 1; offset = fibh->soffset + sizeof(struct fileIdentDesc); if (impuse) { if (adinicb || (offset + liu < 0)) { memcpy((uint8_t *)sfi->impUse, impuse, liu); } else if (offset >= 0) { memcpy(fibh->ebh->b_data + offset, impuse, liu); } else { memcpy((uint8_t *)sfi->impUse, impuse, -offset); memcpy(fibh->ebh->b_data, impuse - offset, liu + offset); } } offset += liu; if (fileident) { if (adinicb || (offset + lfi < 0)) { memcpy((uint8_t *)sfi->fileIdent + liu, fileident, lfi); } else if (offset >= 0) { memcpy(fibh->ebh->b_data + offset, fileident, lfi); } else { memcpy((uint8_t *)sfi->fileIdent + liu, fileident, -offset); memcpy(fibh->ebh->b_data, fileident - offset, lfi + offset); } } offset += lfi; if (adinicb || (offset + padlen < 0)) { memset((uint8_t *)sfi->padding + liu + lfi, 0x00, padlen); } else if (offset >= 0) { memset(fibh->ebh->b_data + offset, 0x00, padlen); } else { memset((uint8_t *)sfi->padding + liu + lfi, 0x00, -offset); memset(fibh->ebh->b_data, 0x00, padlen + offset); } crc = crc_itu_t(0, (uint8_t *)cfi + sizeof(struct tag), sizeof(struct fileIdentDesc) - sizeof(struct tag)); if (fibh->sbh == fibh->ebh) { crc = crc_itu_t(crc, (uint8_t *)sfi->impUse, crclen + sizeof(struct tag) - sizeof(struct fileIdentDesc)); } else if (sizeof(struct fileIdentDesc) >= -fibh->soffset) { crc = crc_itu_t(crc, fibh->ebh->b_data + sizeof(struct fileIdentDesc) + fibh->soffset, crclen + sizeof(struct tag) - sizeof(struct fileIdentDesc)); } else { crc = crc_itu_t(crc, (uint8_t *)sfi->impUse, -fibh->soffset - sizeof(struct fileIdentDesc)); crc = crc_itu_t(crc, fibh->ebh->b_data, fibh->eoffset); } cfi->descTag.descCRC = cpu_to_le16(crc); cfi->descTag.descCRCLength = cpu_to_le16(crclen); cfi->descTag.tagChecksum = udf_tag_checksum(&cfi->descTag); if (adinicb || (sizeof(struct fileIdentDesc) <= -fibh->soffset)) { memcpy((uint8_t *)sfi, (uint8_t *)cfi, sizeof(struct fileIdentDesc)); } else { memcpy((uint8_t *)sfi, (uint8_t *)cfi, -fibh->soffset); memcpy(fibh->ebh->b_data, (uint8_t *)cfi - fibh->soffset, sizeof(struct fileIdentDesc) + fibh->soffset); } if (adinicb) { mark_inode_dirty(inode); } else { if (fibh->sbh != fibh->ebh) mark_buffer_dirty_inode(fibh->ebh, inode); mark_buffer_dirty_inode(fibh->sbh, inode); } return 0; } static struct fileIdentDesc *udf_find_entry(struct inode *dir, const struct qstr *child, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi) { struct fileIdentDesc *fi = NULL; loff_t f_pos; int block, flen; unsigned char *fname = NULL; unsigned char *nameptr; uint8_t lfi; uint16_t liu; loff_t size; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo = UDF_I(dir); int isdotdot = child->len == 2 && child->name[0] == '.' && child->name[1] == '.'; size = udf_ext0_offset(dir) + dir->i_size; f_pos = udf_ext0_offset(dir); fibh->sbh = fibh->ebh = NULL; fibh->soffset = fibh->eoffset = f_pos & (dir->i_sb->s_blocksize - 1); if (dinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) goto out_err; block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh->sbh = fibh->ebh = udf_tread(dir->i_sb, block); if (!fibh->sbh) goto out_err; } fname = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!fname) goto out_err; while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, fibh, cfi, &epos, &eloc, &elen, &offset); if (!fi) goto out_err; liu = le16_to_cpu(cfi->lengthOfImpUse); lfi = cfi->lengthFileIdent; if (fibh->sbh == fibh->ebh) { nameptr = fi->fileIdent + liu; } else { int poffset; /* Unpaded ending offset */ poffset = fibh->soffset + sizeof(struct fileIdentDesc) + liu + lfi; if (poffset >= lfi) nameptr = (uint8_t *)(fibh->ebh->b_data + poffset - lfi); else { nameptr = fname; memcpy(nameptr, fi->fileIdent + liu, lfi - poffset); memcpy(nameptr + lfi - poffset, fibh->ebh->b_data, poffset); } } if ((cfi->fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNDELETE)) continue; } if ((cfi->fileCharacteristics & FID_FILE_CHAR_HIDDEN) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNHIDE)) continue; } if ((cfi->fileCharacteristics & FID_FILE_CHAR_PARENT) && isdotdot) goto out_ok; if (!lfi) continue; flen = udf_get_filename(dir->i_sb, nameptr, fname, lfi); if (flen && udf_match(flen, fname, child->len, child->name)) goto out_ok; } out_err: fi = NULL; if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); out_ok: brelse(epos.bh); kfree(fname); return fi; } static struct dentry *udf_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct inode *inode = NULL; struct fileIdentDesc cfi; struct udf_fileident_bh fibh; if (dentry->d_name.len > UDF_NAME_LEN - 2) return ERR_PTR(-ENAMETOOLONG); #ifdef UDF_RECOVERY /* temporary shorthand for specifying files by inode number */ if (!strncmp(dentry->d_name.name, ".B=", 3)) { struct kernel_lb_addr lb = { .logicalBlockNum = 0, .partitionReferenceNum = simple_strtoul(dentry->d_name.name + 3, NULL, 0), }; inode = udf_iget(dir->i_sb, lb); if (!inode) { return ERR_PTR(-EACCES); } } else #endif /* UDF_RECOVERY */ if (udf_find_entry(dir, &dentry->d_name, &fibh, &cfi)) { struct kernel_lb_addr loc; if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); loc = lelb_to_cpu(cfi.icb.extLocation); inode = udf_iget(dir->i_sb, &loc); if (!inode) { return ERR_PTR(-EACCES); } } return d_splice_alias(inode, dentry); } static struct fileIdentDesc *udf_add_entry(struct inode *dir, struct dentry *dentry, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi, int *err) { struct super_block *sb = dir->i_sb; struct fileIdentDesc *fi = NULL; unsigned char *name = NULL; int namelen; loff_t f_pos; loff_t size = udf_ext0_offset(dir) + dir->i_size; int nfidlen; uint8_t lfi; uint16_t liu; int block; struct kernel_lb_addr eloc; uint32_t elen = 0; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo; fibh->sbh = fibh->ebh = NULL; name = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!name) { *err = -ENOMEM; goto out_err; } if (dentry) { if (!dentry->d_name.len) { *err = -EINVAL; goto out_err; } namelen = udf_put_filename(sb, dentry->d_name.name, name, dentry->d_name.len); if (!namelen) { *err = -ENAMETOOLONG; goto out_err; } } else { namelen = 0; } nfidlen = (sizeof(struct fileIdentDesc) + namelen + 3) & ~3; f_pos = udf_ext0_offset(dir); fibh->soffset = fibh->eoffset = f_pos & (dir->i_sb->s_blocksize - 1); dinfo = UDF_I(dir); if (dinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) { block = udf_get_lb_pblock(dir->i_sb, &dinfo->i_location, 0); fibh->soffset = fibh->eoffset = sb->s_blocksize; goto add; } block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh->sbh = fibh->ebh = udf_tread(dir->i_sb, block); if (!fibh->sbh) { *err = -EIO; goto out_err; } block = dinfo->i_location.logicalBlockNum; } while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, fibh, cfi, &epos, &eloc, &elen, &offset); if (!fi) { *err = -EIO; goto out_err; } liu = le16_to_cpu(cfi->lengthOfImpUse); lfi = cfi->lengthFileIdent; if ((cfi->fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (((sizeof(struct fileIdentDesc) + liu + lfi + 3) & ~3) == nfidlen) { cfi->descTag.tagSerialNum = cpu_to_le16(1); cfi->fileVersionNum = cpu_to_le16(1); cfi->fileCharacteristics = 0; cfi->lengthFileIdent = namelen; cfi->lengthOfImpUse = cpu_to_le16(0); if (!udf_write_fi(dir, cfi, fi, fibh, NULL, name)) goto out_ok; else { *err = -EIO; goto out_err; } } } } add: f_pos += nfidlen; if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB && sb->s_blocksize - fibh->eoffset < nfidlen) { brelse(epos.bh); epos.bh = NULL; fibh->soffset -= udf_ext0_offset(dir); fibh->eoffset -= udf_ext0_offset(dir); f_pos -= udf_ext0_offset(dir); if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); fibh->sbh = fibh->ebh = udf_expand_dir_adinicb(dir, &block, err); if (!fibh->sbh) goto out_err; epos.block = dinfo->i_location; epos.offset = udf_file_entry_alloc_offset(dir); /* Load extent udf_expand_dir_adinicb() has created */ udf_current_aext(dir, &epos, &eloc, &elen, 1); } /* Entry fits into current block? */ if (sb->s_blocksize - fibh->eoffset >= nfidlen) { fibh->soffset = fibh->eoffset; fibh->eoffset += nfidlen; if (fibh->sbh != fibh->ebh) { brelse(fibh->sbh); fibh->sbh = fibh->ebh; } if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { block = dinfo->i_location.logicalBlockNum; fi = (struct fileIdentDesc *) (dinfo->i_ext.i_data + fibh->soffset - udf_ext0_offset(dir) + dinfo->i_lenEAttr); } else { block = eloc.logicalBlockNum + ((elen - 1) >> dir->i_sb->s_blocksize_bits); fi = (struct fileIdentDesc *) (fibh->sbh->b_data + fibh->soffset); } } else { /* Round up last extent in the file */ elen = (elen + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1); if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); udf_write_aext(dir, &epos, &eloc, elen, 1); dinfo->i_lenExtents = (dinfo->i_lenExtents + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1); fibh->soffset = fibh->eoffset - sb->s_blocksize; fibh->eoffset += nfidlen - sb->s_blocksize; if (fibh->sbh != fibh->ebh) { brelse(fibh->sbh); fibh->sbh = fibh->ebh; } block = eloc.logicalBlockNum + ((elen - 1) >> dir->i_sb->s_blocksize_bits); fibh->ebh = udf_bread(dir, f_pos >> dir->i_sb->s_blocksize_bits, 1, err); if (!fibh->ebh) goto out_err; /* Extents could have been merged, invalidate our position */ brelse(epos.bh); epos.bh = NULL; epos.block = dinfo->i_location; epos.offset = udf_file_entry_alloc_offset(dir); if (!fibh->soffset) { /* Find the freshly allocated block */ while (udf_next_aext(dir, &epos, &eloc, &elen, 1) == (EXT_RECORDED_ALLOCATED >> 30)) ; block = eloc.logicalBlockNum + ((elen - 1) >> dir->i_sb->s_blocksize_bits); brelse(fibh->sbh); fibh->sbh = fibh->ebh; fi = (struct fileIdentDesc *)(fibh->sbh->b_data); } else { fi = (struct fileIdentDesc *) (fibh->sbh->b_data + sb->s_blocksize + fibh->soffset); } } memset(cfi, 0, sizeof(struct fileIdentDesc)); if (UDF_SB(sb)->s_udfrev >= 0x0200) udf_new_tag((char *)cfi, TAG_IDENT_FID, 3, 1, block, sizeof(struct tag)); else udf_new_tag((char *)cfi, TAG_IDENT_FID, 2, 1, block, sizeof(struct tag)); cfi->fileVersionNum = cpu_to_le16(1); cfi->lengthFileIdent = namelen; cfi->lengthOfImpUse = cpu_to_le16(0); if (!udf_write_fi(dir, cfi, fi, fibh, NULL, name)) { dir->i_size += nfidlen; if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) dinfo->i_lenAlloc += nfidlen; else { /* Find the last extent and truncate it to proper size */ while (udf_next_aext(dir, &epos, &eloc, &elen, 1) == (EXT_RECORDED_ALLOCATED >> 30)) ; elen -= dinfo->i_lenExtents - dir->i_size; if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); udf_write_aext(dir, &epos, &eloc, elen, 1); dinfo->i_lenExtents = dir->i_size; } mark_inode_dirty(dir); goto out_ok; } else { *err = -EIO; goto out_err; } out_err: fi = NULL; if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); out_ok: brelse(epos.bh); kfree(name); return fi; } static int udf_delete_entry(struct inode *inode, struct fileIdentDesc *fi, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi) { cfi->fileCharacteristics |= FID_FILE_CHAR_DELETED; if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT)) memset(&(cfi->icb), 0x00, sizeof(struct long_ad)); return udf_write_fi(inode, cfi, fi, fibh, NULL, NULL); } static int udf_create(struct inode *dir, struct dentry *dentry, umode_t mode, struct nameidata *nd) { struct udf_fileident_bh fibh; struct inode *inode; struct fileIdentDesc cfi, *fi; int err; struct udf_inode_info *iinfo; inode = udf_new_inode(dir, mode, &err); if (!inode) { return err; } iinfo = UDF_I(inode); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) inode->i_data.a_ops = &udf_adinicb_aops; else inode->i_data.a_ops = &udf_aops; inode->i_op = &udf_file_inode_operations; inode->i_fop = &udf_file_operations; mark_inode_dirty(inode); fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) { inode_dec_link_count(inode); iput(inode); return err; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(iinfo->i_unique & 0x00000000FFFFFFFFUL); udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(dir); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); d_instantiate(dentry, inode); return 0; } static int udf_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { struct inode *inode; struct udf_fileident_bh fibh; struct fileIdentDesc cfi, *fi; int err; struct udf_inode_info *iinfo; if (!old_valid_dev(rdev)) return -EINVAL; err = -EIO; inode = udf_new_inode(dir, mode, &err); if (!inode) goto out; iinfo = UDF_I(inode); init_special_inode(inode, mode, rdev); fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) { inode_dec_link_count(inode); iput(inode); return err; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(iinfo->i_unique & 0x00000000FFFFFFFFUL); udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(dir); mark_inode_dirty(inode); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); d_instantiate(dentry, inode); err = 0; out: return err; } static int udf_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { struct inode *inode; struct udf_fileident_bh fibh; struct fileIdentDesc cfi, *fi; int err; struct udf_inode_info *dinfo = UDF_I(dir); struct udf_inode_info *iinfo; err = -EIO; inode = udf_new_inode(dir, S_IFDIR | mode, &err); if (!inode) goto out; iinfo = UDF_I(inode); inode->i_op = &udf_dir_inode_operations; inode->i_fop = &udf_dir_operations; fi = udf_add_entry(inode, NULL, &fibh, &cfi, &err); if (!fi) { inode_dec_link_count(inode); iput(inode); goto out; } set_nlink(inode, 2); cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(dinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(dinfo->i_unique & 0x00000000FFFFFFFFUL); cfi.fileCharacteristics = FID_FILE_CHAR_DIRECTORY | FID_FILE_CHAR_PARENT; udf_write_fi(inode, &cfi, fi, &fibh, NULL, NULL); brelse(fibh.sbh); mark_inode_dirty(inode); fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) { clear_nlink(inode); mark_inode_dirty(inode); iput(inode); goto out; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(iinfo->i_unique & 0x00000000FFFFFFFFUL); cfi.fileCharacteristics |= FID_FILE_CHAR_DIRECTORY; udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); inc_nlink(dir); mark_inode_dirty(dir); d_instantiate(dentry, inode); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); err = 0; out: return err; } static int empty_dir(struct inode *dir) { struct fileIdentDesc *fi, cfi; struct udf_fileident_bh fibh; loff_t f_pos; loff_t size = udf_ext0_offset(dir) + dir->i_size; int block; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo = UDF_I(dir); f_pos = udf_ext0_offset(dir); fibh.soffset = fibh.eoffset = f_pos & (dir->i_sb->s_blocksize - 1); if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) fibh.sbh = fibh.ebh = NULL; else if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) == (EXT_RECORDED_ALLOCATED >> 30)) { block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh.sbh = fibh.ebh = udf_tread(dir->i_sb, block); if (!fibh.sbh) { brelse(epos.bh); return 0; } } else { brelse(epos.bh); return 0; } while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, &fibh, &cfi, &epos, &eloc, &elen, &offset); if (!fi) { if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); return 0; } if (cfi.lengthFileIdent && (cfi.fileCharacteristics & FID_FILE_CHAR_DELETED) == 0) { if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); return 0; } } if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); return 1; } static int udf_rmdir(struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode = dentry->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc *fi, cfi; struct kernel_lb_addr tloc; retval = -ENOENT; fi = udf_find_entry(dir, &dentry->d_name, &fibh, &cfi); if (!fi) goto out; retval = -EIO; tloc = lelb_to_cpu(cfi.icb.extLocation); if (udf_get_lb_pblock(dir->i_sb, &tloc, 0) != inode->i_ino) goto end_rmdir; retval = -ENOTEMPTY; if (!empty_dir(inode)) goto end_rmdir; retval = udf_delete_entry(dir, fi, &fibh, &cfi); if (retval) goto end_rmdir; if (inode->i_nlink != 2) udf_warn(inode->i_sb, "empty directory has nlink != 2 (%d)\n", inode->i_nlink); clear_nlink(inode); inode->i_size = 0; inode_dec_link_count(dir); inode->i_ctime = dir->i_ctime = dir->i_mtime = current_fs_time(dir->i_sb); mark_inode_dirty(dir); end_rmdir: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); out: return retval; } static int udf_unlink(struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode = dentry->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc *fi; struct fileIdentDesc cfi; struct kernel_lb_addr tloc; retval = -ENOENT; fi = udf_find_entry(dir, &dentry->d_name, &fibh, &cfi); if (!fi) goto out; retval = -EIO; tloc = lelb_to_cpu(cfi.icb.extLocation); if (udf_get_lb_pblock(dir->i_sb, &tloc, 0) != inode->i_ino) goto end_unlink; if (!inode->i_nlink) { udf_debug("Deleting nonexistent file (%lu), %d\n", inode->i_ino, inode->i_nlink); set_nlink(inode, 1); } retval = udf_delete_entry(dir, fi, &fibh, &cfi); if (retval) goto end_unlink; dir->i_ctime = dir->i_mtime = current_fs_time(dir->i_sb); mark_inode_dirty(dir); inode_dec_link_count(inode); inode->i_ctime = dir->i_ctime; retval = 0; end_unlink: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); out: return retval; } static int udf_symlink(struct inode *dir, struct dentry *dentry, const char *symname) { struct inode *inode; struct pathComponent *pc; const char *compstart; struct udf_fileident_bh fibh; struct extent_position epos = {}; int eoffset, elen = 0; struct fileIdentDesc *fi; struct fileIdentDesc cfi; uint8_t *ea; int err; int block; unsigned char *name = NULL; int namelen; struct udf_inode_info *iinfo; struct super_block *sb = dir->i_sb; inode = udf_new_inode(dir, S_IFLNK | S_IRWXUGO, &err); if (!inode) goto out; iinfo = UDF_I(inode); down_write(&iinfo->i_data_sem); name = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!name) { err = -ENOMEM; goto out_no_entry; } inode->i_data.a_ops = &udf_symlink_aops; inode->i_op = &udf_symlink_inode_operations; if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { struct kernel_lb_addr eloc; uint32_t bsize; block = udf_new_block(sb, inode, iinfo->i_location.partitionReferenceNum, iinfo->i_location.logicalBlockNum, &err); if (!block) goto out_no_entry; epos.block = iinfo->i_location; epos.offset = udf_file_entry_alloc_offset(inode); epos.bh = NULL; eloc.logicalBlockNum = block; eloc.partitionReferenceNum = iinfo->i_location.partitionReferenceNum; bsize = sb->s_blocksize; iinfo->i_lenExtents = bsize; udf_add_aext(inode, &epos, &eloc, bsize, 0); brelse(epos.bh); block = udf_get_pblock(sb, block, iinfo->i_location.partitionReferenceNum, 0); epos.bh = udf_tgetblk(sb, block); lock_buffer(epos.bh); memset(epos.bh->b_data, 0x00, bsize); set_buffer_uptodate(epos.bh); unlock_buffer(epos.bh); mark_buffer_dirty_inode(epos.bh, inode); ea = epos.bh->b_data + udf_ext0_offset(inode); } else ea = iinfo->i_ext.i_data + iinfo->i_lenEAttr; eoffset = sb->s_blocksize - udf_ext0_offset(inode); pc = (struct pathComponent *)ea; if (*symname == '/') { do { symname++; } while (*symname == '/'); pc->componentType = 1; pc->lengthComponentIdent = 0; pc->componentFileVersionNum = 0; elen += sizeof(struct pathComponent); } err = -ENAMETOOLONG; while (*symname) { if (elen + sizeof(struct pathComponent) > eoffset) goto out_no_entry; pc = (struct pathComponent *)(ea + elen); compstart = symname; do { symname++; } while (*symname && *symname != '/'); pc->componentType = 5; pc->lengthComponentIdent = 0; pc->componentFileVersionNum = 0; if (compstart[0] == '.') { if ((symname - compstart) == 1) pc->componentType = 4; else if ((symname - compstart) == 2 && compstart[1] == '.') pc->componentType = 3; } if (pc->componentType == 5) { namelen = udf_put_filename(sb, compstart, name, symname - compstart); if (!namelen) goto out_no_entry; if (elen + sizeof(struct pathComponent) + namelen > eoffset) goto out_no_entry; else pc->lengthComponentIdent = namelen; memcpy(pc->componentIdent, name, namelen); } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; if (*symname) { do { symname++; } while (*symname == '/'); } } brelse(epos.bh); inode->i_size = elen; if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) iinfo->i_lenAlloc = inode->i_size; else udf_truncate_tail_extent(inode); mark_inode_dirty(inode); fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) goto out_no_entry; cfi.icb.extLength = cpu_to_le32(sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location); if (UDF_SB(inode->i_sb)->s_lvid_bh) { *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(lvid_get_unique_id(sb)); } udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(dir); up_write(&iinfo->i_data_sem); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); d_instantiate(dentry, inode); err = 0; out: kfree(name); return err; out_no_entry: up_write(&iinfo->i_data_sem); inode_dec_link_count(inode); iput(inode); goto out; } static int udf_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { struct inode *inode = old_dentry->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc cfi, *fi; int err; fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) { return err; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(UDF_I(inode)->i_location); if (UDF_SB(inode->i_sb)->s_lvid_bh) { *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(lvid_get_unique_id(inode->i_sb)); } udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(dir); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); inc_nlink(inode); inode->i_ctime = current_fs_time(inode->i_sb); mark_inode_dirty(inode); ihold(inode); d_instantiate(dentry, inode); return 0; } /* Anybody can rename anything with this: the permission checks are left to the * higher-level routines. */ static int udf_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct inode *old_inode = old_dentry->d_inode; struct inode *new_inode = new_dentry->d_inode; struct udf_fileident_bh ofibh, nfibh; struct fileIdentDesc *ofi = NULL, *nfi = NULL, *dir_fi = NULL; struct fileIdentDesc ocfi, ncfi; struct buffer_head *dir_bh = NULL; int retval = -ENOENT; struct kernel_lb_addr tloc; struct udf_inode_info *old_iinfo = UDF_I(old_inode); ofi = udf_find_entry(old_dir, &old_dentry->d_name, &ofibh, &ocfi); if (ofi) { if (ofibh.sbh != ofibh.ebh) brelse(ofibh.ebh); brelse(ofibh.sbh); } tloc = lelb_to_cpu(ocfi.icb.extLocation); if (!ofi || udf_get_lb_pblock(old_dir->i_sb, &tloc, 0) != old_inode->i_ino) goto end_rename; nfi = udf_find_entry(new_dir, &new_dentry->d_name, &nfibh, &ncfi); if (nfi) { if (!new_inode) { if (nfibh.sbh != nfibh.ebh) brelse(nfibh.ebh); brelse(nfibh.sbh); nfi = NULL; } } if (S_ISDIR(old_inode->i_mode)) { int offset = udf_ext0_offset(old_inode); if (new_inode) { retval = -ENOTEMPTY; if (!empty_dir(new_inode)) goto end_rename; } retval = -EIO; if (old_iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { dir_fi = udf_get_fileident( old_iinfo->i_ext.i_data - (old_iinfo->i_efe ? sizeof(struct extendedFileEntry) : sizeof(struct fileEntry)), old_inode->i_sb->s_blocksize, &offset); } else { dir_bh = udf_bread(old_inode, 0, 0, &retval); if (!dir_bh) goto end_rename; dir_fi = udf_get_fileident(dir_bh->b_data, old_inode->i_sb->s_blocksize, &offset); } if (!dir_fi) goto end_rename; tloc = lelb_to_cpu(dir_fi->icb.extLocation); if (udf_get_lb_pblock(old_inode->i_sb, &tloc, 0) != old_dir->i_ino) goto end_rename; } if (!nfi) { nfi = udf_add_entry(new_dir, new_dentry, &nfibh, &ncfi, &retval); if (!nfi) goto end_rename; } /* * Like most other Unix systems, set the ctime for inodes on a * rename. */ old_inode->i_ctime = current_fs_time(old_inode->i_sb); mark_inode_dirty(old_inode); /* * ok, that's it */ ncfi.fileVersionNum = ocfi.fileVersionNum; ncfi.fileCharacteristics = ocfi.fileCharacteristics; memcpy(&(ncfi.icb), &(ocfi.icb), sizeof(struct long_ad)); udf_write_fi(new_dir, &ncfi, nfi, &nfibh, NULL, NULL); /* The old fid may have moved - find it again */ ofi = udf_find_entry(old_dir, &old_dentry->d_name, &ofibh, &ocfi); udf_delete_entry(old_dir, ofi, &ofibh, &ocfi); if (new_inode) { new_inode->i_ctime = current_fs_time(new_inode->i_sb); inode_dec_link_count(new_inode); } old_dir->i_ctime = old_dir->i_mtime = current_fs_time(old_dir->i_sb); mark_inode_dirty(old_dir); if (dir_fi) { dir_fi->icb.extLocation = cpu_to_lelb(UDF_I(new_dir)->i_location); udf_update_tag((char *)dir_fi, (sizeof(struct fileIdentDesc) + le16_to_cpu(dir_fi->lengthOfImpUse) + 3) & ~3); if (old_iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(old_inode); else mark_buffer_dirty_inode(dir_bh, old_inode); inode_dec_link_count(old_dir); if (new_inode) inode_dec_link_count(new_inode); else { inc_nlink(new_dir); mark_inode_dirty(new_dir); } } if (ofi) { if (ofibh.sbh != ofibh.ebh) brelse(ofibh.ebh); brelse(ofibh.sbh); } retval = 0; end_rename: brelse(dir_bh); if (nfi) { if (nfibh.sbh != nfibh.ebh) brelse(nfibh.ebh); brelse(nfibh.sbh); } return retval; } static struct dentry *udf_get_parent(struct dentry *child) { struct kernel_lb_addr tloc; struct inode *inode = NULL; struct qstr dotdot = QSTR_INIT("..", 2); struct fileIdentDesc cfi; struct udf_fileident_bh fibh; if (!udf_find_entry(child->d_inode, &dotdot, &fibh, &cfi)) goto out_unlock; if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); tloc = lelb_to_cpu(cfi.icb.extLocation); inode = udf_iget(child->d_inode->i_sb, &tloc); if (!inode) goto out_unlock; return d_obtain_alias(inode); out_unlock: return ERR_PTR(-EACCES); } static struct dentry *udf_nfs_get_inode(struct super_block *sb, u32 block, u16 partref, __u32 generation) { struct inode *inode; struct kernel_lb_addr loc; if (block == 0) return ERR_PTR(-ESTALE); loc.logicalBlockNum = block; loc.partitionReferenceNum = partref; inode = udf_iget(sb, &loc); if (inode == NULL) return ERR_PTR(-ENOMEM); if (generation && inode->i_generation != generation) { iput(inode); return ERR_PTR(-ESTALE); } return d_obtain_alias(inode); } static struct dentry *udf_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { if ((fh_len != 3 && fh_len != 5) || (fh_type != FILEID_UDF_WITH_PARENT && fh_type != FILEID_UDF_WITHOUT_PARENT)) return NULL; return udf_nfs_get_inode(sb, fid->udf.block, fid->udf.partref, fid->udf.generation); } static struct dentry *udf_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { if (fh_len != 5 || fh_type != FILEID_UDF_WITH_PARENT) return NULL; return udf_nfs_get_inode(sb, fid->udf.parent_block, fid->udf.parent_partref, fid->udf.parent_generation); } static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.parent_partref = 0; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; } const struct export_operations udf_export_ops = { .encode_fh = udf_encode_fh, .fh_to_dentry = udf_fh_to_dentry, .fh_to_parent = udf_fh_to_parent, .get_parent = udf_get_parent, }; const struct inode_operations udf_dir_inode_operations = { .lookup = udf_lookup, .create = udf_create, .link = udf_link, .unlink = udf_unlink, .symlink = udf_symlink, .mkdir = udf_mkdir, .rmdir = udf_rmdir, .mknod = udf_mknod, .rename = udf_rename, }; const struct inode_operations udf_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, };
./CrossVul/dataset_final_sorted/CWE-200/c/good_3841_0
crossvul-cpp_data_good_293_0
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2017 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Pierre A. Joye <pierre@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef PHP_WIN32 #include "php.h" #include "php_filestat.h" #include "php_globals.h" #include <WinBase.h> #include <stdlib.h> #include <string.h> #if HAVE_PWD_H #include "win32/pwd.h" #endif #if HAVE_GRP_H #include "win32/grp.h" #endif #include <errno.h> #include <ctype.h> #include "php_link.h" #include "php_string.h" /* TODO: - Create php_readlink (done), php_link and php_symlink in win32/link.c - Expose them (PHPAPI) so extensions developers can use them - define link/readlink/symlink to their php_ equivalent and use them in ext/standart/link.c - this file is then useless and we have a portable link API */ #ifndef VOLUME_NAME_NT #define VOLUME_NAME_NT 0x2 #endif #ifndef VOLUME_NAME_DOS #define VOLUME_NAME_DOS 0x0 #endif /* {{{ proto string readlink(string filename) Return the target of a symbolic link */ PHP_FUNCTION(readlink) { char *link; size_t link_len; char target[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } if (OPENBASEDIR_CHECKPATH(link)) { RETURN_FALSE; } if (php_sys_readlink(link, target, MAXPATHLEN) == -1) { php_error_docref(NULL, E_WARNING, "readlink failed to read the symbolic link (%s), error %d)", link, GetLastError()); RETURN_FALSE; } RETURN_STRING(target); } /* }}} */ /* {{{ proto int linkinfo(string filename) Returns the st_dev field of the UNIX C stat structure describing the link */ PHP_FUNCTION(linkinfo) { char *link; char *dirname; size_t link_len; zend_stat_t sb; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } dirname = estrndup(link, link_len); php_dirname(dirname, link_len); if (php_check_open_basedir(dirname)) { efree(dirname); RETURN_FALSE; } ret = VCWD_STAT(link, &sb); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); efree(dirname); RETURN_LONG(Z_L(-1)); } efree(dirname); RETURN_LONG((zend_long) sb.st_dev); } /* }}} */ /* {{{ proto int symlink(string target, string link) Create a symbolic link */ PHP_FUNCTION(symlink) { char *topath, *frompath; size_t topath_len, frompath_len; BOOLEAN ret; char source_p[MAXPATHLEN]; char dest_p[MAXPATHLEN]; char dirname[MAXPATHLEN]; size_t len; DWORD attr; HINSTANCE kernel32; typedef BOOLEAN (WINAPI *csla_func)(LPCSTR, LPCSTR, DWORD); csla_func pCreateSymbolicLinkA; kernel32 = LoadLibrary("kernel32.dll"); if (kernel32) { pCreateSymbolicLinkA = (csla_func)GetProcAddress(kernel32, "CreateSymbolicLinkA"); if (pCreateSymbolicLinkA == NULL) { php_error_docref(NULL, E_WARNING, "Can't call CreateSymbolicLinkA"); RETURN_FALSE; } } else { php_error_docref(NULL, E_WARNING, "Can't call get a handle on kernel32.dll"); RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &topath, &topath_len, &frompath, &frompath_len) == FAILURE) { return; } if (!expand_filepath(frompath, source_p)) { php_error_docref(NULL, E_WARNING, "No such file or directory"); RETURN_FALSE; } memcpy(dirname, source_p, sizeof(source_p)); len = php_dirname(dirname, strlen(dirname)); if (!expand_filepath_ex(topath, dest_p, dirname, len)) { php_error_docref(NULL, E_WARNING, "No such file or directory"); RETURN_FALSE; } if (php_stream_locate_url_wrapper(source_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) || php_stream_locate_url_wrapper(dest_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) ) { php_error_docref(NULL, E_WARNING, "Unable to symlink to a URL"); RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(dest_p)) { RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(source_p)) { RETURN_FALSE; } if ((attr = GetFileAttributes(topath)) == INVALID_FILE_ATTRIBUTES) { php_error_docref(NULL, E_WARNING, "Could not fetch file information(error %d)", GetLastError()); RETURN_FALSE; } /* For the source, an expanded path must be used (in ZTS an other thread could have changed the CWD). * For the target the exact string given by the user must be used, relative or not, existing or not. * The target is relative to the link itself, not to the CWD. */ ret = pCreateSymbolicLinkA(source_p, topath, (attr & FILE_ATTRIBUTE_DIRECTORY ? 1 : 0)); if (!ret) { php_error_docref(NULL, E_WARNING, "Cannot create symlink, error code(%d)", GetLastError()); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int link(string target, string link) Create a hard link */ PHP_FUNCTION(link) { char *topath, *frompath; size_t topath_len, frompath_len; int ret; char source_p[MAXPATHLEN]; char dest_p[MAXPATHLEN]; /*First argument to link function is the target and hence should go to frompath Second argument to link function is the link itself and hence should go to topath */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &frompath, &frompath_len, &topath, &topath_len) == FAILURE) { return; } if (!expand_filepath(frompath, source_p) || !expand_filepath(topath, dest_p)) { php_error_docref(NULL, E_WARNING, "No such file or directory"); RETURN_FALSE; } if (php_stream_locate_url_wrapper(source_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) || php_stream_locate_url_wrapper(dest_p, NULL, STREAM_LOCATE_WRAPPERS_ONLY) ) { php_error_docref(NULL, E_WARNING, "Unable to link to a URL"); RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(source_p)) { RETURN_FALSE; } if (OPENBASEDIR_CHECKPATH(dest_p)) { RETURN_FALSE; } #ifndef ZTS ret = CreateHardLinkA(topath, frompath, NULL); #else ret = CreateHardLinkA(dest_p, source_p, NULL); #endif if (ret == 0) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-200/c/good_293_0
crossvul-cpp_data_bad_4948_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * * 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/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.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 32k 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. */ /* types of values stored in eBPF registers */ enum bpf_reg_type { NOT_INIT = 0, /* nothing was written into register */ UNKNOWN_VALUE, /* reg doesn't contain a valid pointer */ PTR_TO_CTX, /* reg points to bpf_context */ CONST_PTR_TO_MAP, /* reg points to struct bpf_map */ PTR_TO_MAP_VALUE, /* reg points to map element value */ PTR_TO_MAP_VALUE_OR_NULL,/* points to map elem value or NULL */ FRAME_PTR, /* reg == frame_pointer */ PTR_TO_STACK, /* reg == frame_pointer + imm */ CONST_IMM, /* constant integer value */ }; struct reg_state { enum bpf_reg_type type; union { /* valid when type == CONST_IMM | PTR_TO_STACK */ int imm; /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE | * PTR_TO_MAP_VALUE_OR_NULL */ struct bpf_map *map_ptr; }; }; enum bpf_stack_slot_type { STACK_INVALID, /* nothing was stored in this stack slot */ STACK_SPILL, /* register spilled into stack */ STACK_MISC /* BPF program wrote some data into this slot */ }; #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */ /* state of the program: * type of all registers and stack info */ struct verifier_state { struct reg_state regs[MAX_BPF_REG]; u8 stack_slot_type[MAX_BPF_STACK]; struct reg_state spilled_regs[MAX_BPF_STACK / BPF_REG_SIZE]; }; /* linked list of verifier states used to prune search */ struct verifier_state_list { struct verifier_state state; struct verifier_state_list *next; }; /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct verifier_state st; int insn_idx; int prev_insn_idx; struct verifier_stack_elem *next; }; #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */ /* single container for all structs * one verifier_env per bpf_check() call */ struct verifier_env { struct bpf_prog *prog; /* eBPF program being verified */ struct verifier_stack_elem *head; /* stack of verifier states to be processed */ int stack_size; /* number of states to be processed */ struct verifier_state cur_state; /* current verifier state */ struct verifier_state_list **explored_states; /* search pruning optimization */ struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */ u32 used_map_cnt; /* number of used maps */ bool allow_ptr_leaks; }; /* 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", [FRAME_PTR] = "fp", [PTR_TO_STACK] = "fp", [CONST_IMM] = "imm", }; static const struct { int map_type; int func_id; } func_limit[] = { {BPF_MAP_TYPE_PROG_ARRAY, BPF_FUNC_tail_call}, {BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_FUNC_perf_event_read}, {BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_FUNC_perf_event_output}, }; static void print_verifier_state(struct verifier_env *env) { enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { t = env->cur_state.regs[i].type; if (t == NOT_INIT) continue; verbose(" R%d=%s", i, reg_type_str[t]); if (t == CONST_IMM || t == PTR_TO_STACK) verbose("%d", env->cur_state.regs[i].imm); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL) verbose("(ks=%d,vs=%d)", env->cur_state.regs[i].map_ptr->key_size, env->cur_state.regs[i].map_ptr->value_size); } for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) { if (env->cur_state.stack_slot_type[i] == STACK_SPILL) verbose(" fp%d=%s", -MAX_BPF_STACK + i, reg_type_str[env->cur_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 %d\n", insn->code, 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 verifier_env *env, int *prev_insn_idx) { struct 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 verifier_state *push_stack(struct verifier_env *env, int insn_idx, int prev_insn_idx) { struct verifier_stack_elem *elem; elem = kmalloc(sizeof(struct 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 > 1024) { 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 reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { regs[i].type = NOT_INIT; regs[i].imm = 0; regs[i].map_ptr = NULL; } /* 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 reg_state *regs, u32 regno) { BUG_ON(regno >= MAX_BPF_REG); regs[regno].type = UNKNOWN_VALUE; regs[regno].imm = 0; regs[regno].map_ptr = NULL; } 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 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_STACK: case PTR_TO_CTX: 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 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 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 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(state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int check_map_access(struct verifier_env *env, u32 regno, int off, int size) { struct bpf_map *map = env->cur_state.regs[regno].map_ptr; if (off < 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 access to 'struct bpf_context' fields */ static int check_ctx_access(struct verifier_env *env, int off, int size, enum bpf_access_type t) { if (env->prog->aux->ops->is_valid_access && env->prog->aux->ops->is_valid_access(off, size, t)) return 0; verbose("invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool is_pointer_value(struct 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; } } /* 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 verifier_env *env, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct verifier_state *state = &env->cur_state; int size, err = 0; if (state->regs[regno].type == PTR_TO_STACK) off += state->regs[regno].imm; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; if (off % size != 0) { verbose("misaligned access off %d size %d\n", off, size); return -EACCES; } if (state->regs[regno].type == PTR_TO_MAP_VALUE) { 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; } err = check_map_access(env, regno, off, size); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown_value(state->regs, value_regno); } else if (state->regs[regno].type == PTR_TO_CTX) { 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); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown_value(state->regs, value_regno); } else if (state->regs[regno].type == FRAME_PTR || state->regs[regno].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 { verbose("R%d invalid mem access '%s'\n", regno, reg_type_str[state->regs[regno].type]); return -EACCES; } return err; } static int check_xadd(struct verifier_env *env, struct bpf_insn *insn) { struct 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 verifier_env *env, int regno, int access_size) { struct verifier_state *state = &env->cur_state; struct reg_state *regs = state->regs; int off, i; if (regs[regno].type != 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; } 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_func_arg(struct verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_map **mapp) { struct reg_state *reg = env->cur_state.regs + regno; enum bpf_reg_type expected_type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; if (reg->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 (arg_type == ARG_PTR_TO_STACK || arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; } else if (arg_type == ARG_CONST_STACK_SIZE) { expected_type = CONST_IMM; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; } else { verbose("unsupported arg_type %d\n", arg_type); return -EFAULT; } if (reg->type != expected_type) { verbose("R%d type=%s expected=%s\n", regno, reg_type_str[reg->type], reg_type_str[expected_type]); return -EACCES; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ *mapp = 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 (!*mapp) { /* 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; } err = check_stack_boundary(env, regno, (*mapp)->key_size); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!*mapp) { /* kernel subsystem misconfigured verifier */ verbose("invalid map_ptr to access map->value\n"); return -EACCES; } err = check_stack_boundary(env, regno, (*mapp)->value_size); } else if (arg_type == ARG_CONST_STACK_SIZE) { /* 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_STACK_SIZE cannot be first argument\n"); return -EACCES; } err = check_stack_boundary(env, regno - 1, reg->imm); } return err; } static int check_map_func_compatibility(struct bpf_map *map, int func_id) { bool bool_map, bool_func; int i; if (!map) return 0; for (i = 0; i < ARRAY_SIZE(func_limit); i++) { bool_map = (map->map_type == func_limit[i].map_type); bool_func = (func_id == func_limit[i].func_id); /* only when map & func pair match it can continue. * don't allow any other map type to be passed into * the special func; */ if (bool_func && bool_map != bool_func) return -EINVAL; } return 0; } static int check_call(struct verifier_env *env, int func_id) { struct verifier_state *state = &env->cur_state; const struct bpf_func_proto *fn = NULL; struct reg_state *regs = state->regs; struct bpf_map *map = NULL; struct reg_state *reg; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose("invalid func %d\n", 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 %d\n", 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; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &map); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &map); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &map); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &map); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &map); 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) { regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* 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 (map == NULL) { verbose("kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = map; } else { verbose("unknown return type %d of func %d\n", fn->ret_type, func_id); return -EINVAL; } err = check_map_func_compatibility(map, func_id); if (err) return err; return 0; } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct verifier_env *env, struct bpf_insn *insn) { struct reg_state *regs = env->cur_state.regs; 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; 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; } regs[insn->dst_reg].type = UNKNOWN_VALUE; regs[insn->dst_reg].map_ptr = NULL; } } 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; } } else if (opcode > BPF_END) { verbose("invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ bool stack_relative = false; 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; } } /* pattern match 'bpf_add Rx, imm' instruction */ if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 && regs[insn->dst_reg].type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) { stack_relative = true; } 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; } /* check dest operand */ err = check_reg_arg(regs, insn->dst_reg, DST_OP); if (err) return err; if (stack_relative) { regs[insn->dst_reg].type = PTR_TO_STACK; regs[insn->dst_reg].imm = insn->imm; } } return 0; } static int check_cond_jmp_op(struct verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct reg_state *regs = env->cur_state.regs; struct verifier_state *other_branch; 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; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && regs[insn->dst_reg].type == CONST_IMM && regs[insn->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 R == 0 where R is returned value from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && regs[insn->dst_reg].type == PTR_TO_MAP_VALUE_OR_NULL) { if (opcode == BPF_JEQ) { /* next fallthrough insn can access memory via * this register */ regs[insn->dst_reg].type = PTR_TO_MAP_VALUE; /* branch targer cannot access it, since reg == 0 */ other_branch->regs[insn->dst_reg].type = CONST_IMM; other_branch->regs[insn->dst_reg].imm = 0; } else { other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE; regs[insn->dst_reg].type = CONST_IMM; regs[insn->dst_reg].imm = 0; } } else if (is_pointer_value(env, insn->dst_reg)) { verbose("R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } else if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE)) { if (opcode == BPF_JEQ) { /* detect if (R == imm) goto * and in the target state recognize that R = imm */ other_branch->regs[insn->dst_reg].type = CONST_IMM; other_branch->regs[insn->dst_reg].imm = insn->imm; } else { /* detect if (R != imm) goto * and in the fall-through state recognize that R = imm */ regs[insn->dst_reg].type = CONST_IMM; regs[insn->dst_reg].imm = insn->imm; } } if (log_level) print_verifier_state(env); 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 verifier_env *env, struct bpf_insn *insn) { struct 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) /* generic move 64-bit immediate into a register */ 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 verifier_env *env, struct bpf_insn *insn) { struct reg_state *regs = env->cur_state.regs; u8 mode = BPF_MODE(insn->code); struct 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 || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose("BPF_LD_ABS 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 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 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 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; } 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; } /* 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 verifier_state *old, struct verifier_state *cur) { int i; for (i = 0; i < MAX_BPF_REG; i++) { if (memcmp(&old->regs[i], &cur->regs[i], sizeof(old->regs[0])) != 0) { if (old->regs[i].type == NOT_INIT || (old->regs[i].type == UNKNOWN_VALUE && cur->regs[i].type != NOT_INIT)) 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 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8} * but current path has stored: * (struct 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 verifier_env *env, int insn_idx) { struct verifier_state_list *new_sl; struct 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(&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 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 do_check(struct verifier_env *env) { struct verifier_state *state = &env->cur_state; struct bpf_insn *insns = env->prog->insnsi; struct 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; 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 > 32768) { verbose("BPF program is too large. Proccessed %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); do_print_state = false; } if (log_level) { verbose("%d: ", insn_idx); print_bpf_insn(insn); } 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 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) { insn_idx++; continue; } if (insn->imm == 0) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * use reserved 'imm' field to mark this insn */ insn->imm = src_reg_type; } else if (src_reg_type != insn->imm && (src_reg_type == PTR_TO_CTX || insn->imm == 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 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; if (insn->imm == 0) { insn->imm = dst_reg_type; } else if (dst_reg_type != insn->imm && (dst_reg_type == PTR_TO_CTX || insn->imm == 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); 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; } } else { verbose("unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } 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 verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j; 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); fdput(f); return PTR_ERR(map); } /* 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; } /* remember this map */ env->used_maps[env->used_map_cnt++] = map; /* 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() */ bpf_map_inc(map, false); 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 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 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; } static void adjust_branches(struct bpf_prog *prog, int pos, int delta) { struct bpf_insn *insn = prog->insnsi; int insn_cnt = prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) != BPF_JMP || BPF_OP(insn->code) == BPF_CALL || BPF_OP(insn->code) == BPF_EXIT) continue; /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos && i + insn->off + 1 < pos) insn->off -= delta; } } /* 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 verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; u32 cnt; int i; enum bpf_access_type type; if (!env->prog->aux->ops->convert_ctx_access) return 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_W)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_W)) type = BPF_WRITE; else continue; if (insn->imm != PTR_TO_CTX) { /* clear internal mark */ insn->imm = 0; continue; } cnt = env->prog->aux->ops-> convert_ctx_access(type, insn->dst_reg, insn->src_reg, insn->off, insn_buf, env->prog); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose("bpf verifier is misconfigured\n"); return -EINVAL; } if (cnt == 1) { memcpy(insn, insn_buf, sizeof(*insn)); continue; } /* several new insns need to be inserted. Make room for them */ insn_cnt += cnt - 1; new_prog = bpf_prog_realloc(env->prog, bpf_prog_size(insn_cnt), GFP_USER); if (!new_prog) return -ENOMEM; new_prog->len = insn_cnt; memmove(new_prog->insnsi + i + cnt, new_prog->insns + i + 1, sizeof(*insn) * (insn_cnt - i - cnt)); /* copy substitute insns in place of load instruction */ memcpy(new_prog->insnsi + i, insn_buf, sizeof(*insn) * cnt); /* adjust branches in the whole program */ adjust_branches(new_prog, i, cnt - 1); /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + cnt - 1; i += cnt - 1; } return 0; } static void free_states(struct verifier_env *env) { struct 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 verifier_env *env; int ret = -EINVAL; if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS) return -E2BIG; /* 'struct verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; 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 free_env; ret = -ENOMEM; log_buf = vmalloc(log_size); if (!log_buf) goto free_env; } 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 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 (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); free_env: 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; kfree(env); mutex_unlock(&bpf_verifier_lock); return ret; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_4948_0
crossvul-cpp_data_good_3822_1
/* 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]; struct xfrm_replay_state_esn *rs; if (p->flags & XFRM_STATE_ESN) { if (!rt) return -EINVAL; rs = nla_data(rt); if (rs->bmp_len > XFRMA_REPLAY_ESN_MAX / sizeof(rs->bmp[0]) / 8) return -EINVAL; if (nla_len(rt) < xfrm_replay_state_esn_len(rs) && nla_len(rt) != sizeof(*rs)) 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; int ulen; if (!replay_esn || !rp) return 0; up = nla_data(rp); ulen = xfrm_replay_state_esn_len(up); if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen) 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; int klen, ulen; if (!rta) return 0; up = nla_data(rta); klen = xfrm_replay_state_esn_len(up); ulen = nla_len(rta) >= klen ? klen : sizeof(*up); p = kzalloc(klen, GFP_KERNEL); if (!p) return -ENOMEM; pp = kzalloc(klen, GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } memcpy(p, up, ulen); memcpy(pp, up, ulen); *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) { memset(p, 0, sizeof(*p)); 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]; memset(up, 0, sizeof(*up)); 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_3822_1
crossvul-cpp_data_good_5678_1
/* * algif_skcipher: User-space interface for skcipher algorithms * * This file provides the user-space API for symmetric key ciphers. * * 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/scatterwalk.h> #include <crypto/skcipher.h> #include <crypto/if_alg.h> #include <linux/init.h> #include <linux/list.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/net.h> #include <net/sock.h> struct skcipher_sg_list { struct list_head list; int cur; struct scatterlist sg[0]; }; struct skcipher_ctx { struct list_head tsgl; struct af_alg_sgl rsgl; void *iv; struct af_alg_completion completion; unsigned used; unsigned int len; bool more; bool merge; bool enc; struct ablkcipher_request req; }; #define MAX_SGL_ENTS ((PAGE_SIZE - sizeof(struct skcipher_sg_list)) / \ sizeof(struct scatterlist) - 1) static inline int skcipher_sndbuf(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) - ctx->used, 0); } static inline bool skcipher_writable(struct sock *sk) { return PAGE_SIZE <= skcipher_sndbuf(sk); } static int skcipher_alloc_sgl(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; struct skcipher_sg_list *sgl; struct scatterlist *sg = NULL; sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list); if (!list_empty(&ctx->tsgl)) sg = sgl->sg; if (!sg || sgl->cur >= MAX_SGL_ENTS) { sgl = sock_kmalloc(sk, sizeof(*sgl) + sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1), GFP_KERNEL); if (!sgl) return -ENOMEM; sg_init_table(sgl->sg, MAX_SGL_ENTS + 1); sgl->cur = 0; if (sg) scatterwalk_sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg); list_add_tail(&sgl->list, &ctx->tsgl); } return 0; } static void skcipher_pull_sgl(struct sock *sk, int used) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; struct skcipher_sg_list *sgl; struct scatterlist *sg; int i; while (!list_empty(&ctx->tsgl)) { sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list, list); sg = sgl->sg; for (i = 0; i < sgl->cur; i++) { int plen = min_t(int, used, sg[i].length); if (!sg_page(sg + i)) continue; sg[i].length -= plen; sg[i].offset += plen; used -= plen; ctx->used -= plen; if (sg[i].length) return; put_page(sg_page(sg + i)); sg_assign_page(sg + i, NULL); } list_del(&sgl->list); sock_kfree_s(sk, sgl, sizeof(*sgl) + sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1)); } if (!ctx->used) ctx->merge = 0; } static void skcipher_free_sgl(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; skcipher_pull_sgl(sk, ctx->used); } static int skcipher_wait_for_wmem(struct sock *sk, unsigned flags) { long timeout; DEFINE_WAIT(wait); int err = -ERESTARTSYS; if (flags & MSG_DONTWAIT) return -EAGAIN; set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); for (;;) { if (signal_pending(current)) break; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); timeout = MAX_SCHEDULE_TIMEOUT; if (sk_wait_event(sk, &timeout, skcipher_writable(sk))) { err = 0; break; } } finish_wait(sk_sleep(sk), &wait); return err; } static void skcipher_wmem_wakeup(struct sock *sk) { struct socket_wq *wq; if (!skcipher_writable(sk)) return; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static int skcipher_wait_for_data(struct sock *sk, unsigned flags) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; long timeout; DEFINE_WAIT(wait); int err = -ERESTARTSYS; if (flags & MSG_DONTWAIT) { return -EAGAIN; } set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); for (;;) { if (signal_pending(current)) break; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); timeout = MAX_SCHEDULE_TIMEOUT; if (sk_wait_event(sk, &timeout, ctx->used)) { err = 0; break; } } finish_wait(sk_sleep(sk), &wait); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); return err; } static void skcipher_data_wakeup(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; struct socket_wq *wq; if (!ctx->used) return; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); rcu_read_unlock(); } static int skcipher_sendmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t size) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req); unsigned ivsize = crypto_ablkcipher_ivsize(tfm); struct skcipher_sg_list *sgl; struct af_alg_control con = {}; long copied = 0; bool enc = 0; int err; int i; if (msg->msg_controllen) { err = af_alg_cmsg_send(msg, &con); if (err) return err; switch (con.op) { case ALG_OP_ENCRYPT: enc = 1; break; case ALG_OP_DECRYPT: enc = 0; break; default: return -EINVAL; } if (con.iv && con.iv->ivlen != ivsize) return -EINVAL; } err = -EINVAL; lock_sock(sk); if (!ctx->more && ctx->used) goto unlock; if (!ctx->used) { ctx->enc = enc; if (con.iv) memcpy(ctx->iv, con.iv->iv, ivsize); } while (size) { struct scatterlist *sg; unsigned long len = size; int plen; if (ctx->merge) { sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list); sg = sgl->sg + sgl->cur - 1; len = min_t(unsigned long, len, PAGE_SIZE - sg->offset - sg->length); err = memcpy_fromiovec(page_address(sg_page(sg)) + sg->offset + sg->length, msg->msg_iov, len); if (err) goto unlock; sg->length += len; ctx->merge = (sg->offset + sg->length) & (PAGE_SIZE - 1); ctx->used += len; copied += len; size -= len; continue; } if (!skcipher_writable(sk)) { err = skcipher_wait_for_wmem(sk, msg->msg_flags); if (err) goto unlock; } len = min_t(unsigned long, len, skcipher_sndbuf(sk)); err = skcipher_alloc_sgl(sk); if (err) goto unlock; sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list); sg = sgl->sg; do { i = sgl->cur; plen = min_t(int, len, PAGE_SIZE); sg_assign_page(sg + i, alloc_page(GFP_KERNEL)); err = -ENOMEM; if (!sg_page(sg + i)) goto unlock; err = memcpy_fromiovec(page_address(sg_page(sg + i)), msg->msg_iov, plen); if (err) { __free_page(sg_page(sg + i)); sg_assign_page(sg + i, NULL); goto unlock; } sg[i].length = plen; len -= plen; ctx->used += plen; copied += plen; size -= plen; sgl->cur++; } while (len && sgl->cur < MAX_SGL_ENTS); ctx->merge = plen & (PAGE_SIZE - 1); } err = 0; ctx->more = msg->msg_flags & MSG_MORE; if (!ctx->more && !list_empty(&ctx->tsgl)) sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list); unlock: skcipher_data_wakeup(sk); release_sock(sk); return copied ?: err; } static ssize_t skcipher_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 skcipher_ctx *ctx = ask->private; struct skcipher_sg_list *sgl; int err = -EINVAL; lock_sock(sk); if (!ctx->more && ctx->used) goto unlock; if (!size) goto done; if (!skcipher_writable(sk)) { err = skcipher_wait_for_wmem(sk, flags); if (err) goto unlock; } err = skcipher_alloc_sgl(sk); if (err) goto unlock; ctx->merge = 0; sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list); get_page(page); sg_set_page(sgl->sg + sgl->cur, page, size, offset); sgl->cur++; ctx->used += size; done: ctx->more = flags & MSG_MORE; if (!ctx->more && !list_empty(&ctx->tsgl)) sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list); unlock: skcipher_data_wakeup(sk); release_sock(sk); return err ?: size; } static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t ignored, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm( &ctx->req)); struct skcipher_sg_list *sgl; struct scatterlist *sg; unsigned long iovlen; struct iovec *iov; int err = -EAGAIN; int used; long copied = 0; lock_sock(sk); msg->msg_namelen = 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) { sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list, list); sg = sgl->sg; while (!sg->length) sg++; used = ctx->used; if (!used) { err = skcipher_wait_for_data(sk, flags); if (err) goto unlock; } used = min_t(unsigned long, used, seglen); used = af_alg_make_sg(&ctx->rsgl, from, used, 1); err = used; if (err < 0) goto unlock; if (ctx->more || used < ctx->used) used -= used % bs; err = -EINVAL; if (!used) goto free; ablkcipher_request_set_crypt(&ctx->req, sg, ctx->rsgl.sg, used, ctx->iv); err = af_alg_wait_for_completion( ctx->enc ? crypto_ablkcipher_encrypt(&ctx->req) : crypto_ablkcipher_decrypt(&ctx->req), &ctx->completion); free: af_alg_free_sg(&ctx->rsgl); if (err) goto unlock; copied += used; from += used; seglen -= used; skcipher_pull_sgl(sk, used); } } err = 0; unlock: skcipher_wmem_wakeup(sk); release_sock(sk); return copied ?: err; } static unsigned int skcipher_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; unsigned int mask; sock_poll_wait(file, sk_sleep(sk), wait); mask = 0; if (ctx->used) mask |= POLLIN | POLLRDNORM; if (skcipher_writable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; return mask; } static struct proto_ops algif_skcipher_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, .accept = sock_no_accept, .setsockopt = sock_no_setsockopt, .release = af_alg_release, .sendmsg = skcipher_sendmsg, .sendpage = skcipher_sendpage, .recvmsg = skcipher_recvmsg, .poll = skcipher_poll, }; static void *skcipher_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_ablkcipher(name, type, mask); } static void skcipher_release(void *private) { crypto_free_ablkcipher(private); } static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_ablkcipher_setkey(private, key, keylen); } static void skcipher_sock_destruct(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req); skcipher_free_sgl(sk); sock_kfree_s(sk, ctx->iv, crypto_ablkcipher_ivsize(tfm)); sock_kfree_s(sk, ctx, ctx->len); af_alg_release_parent(sk); } static int skcipher_accept_parent(void *private, struct sock *sk) { struct skcipher_ctx *ctx; struct alg_sock *ask = alg_sk(sk); unsigned int len = sizeof(*ctx) + crypto_ablkcipher_reqsize(private); ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->iv = sock_kmalloc(sk, crypto_ablkcipher_ivsize(private), GFP_KERNEL); if (!ctx->iv) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->iv, 0, crypto_ablkcipher_ivsize(private)); INIT_LIST_HEAD(&ctx->tsgl); ctx->len = len; ctx->used = 0; ctx->more = 0; ctx->merge = 0; ctx->enc = 0; af_alg_init_completion(&ctx->completion); ask->private = ctx; ablkcipher_request_set_tfm(&ctx->req, private); ablkcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = skcipher_sock_destruct; return 0; } static const struct af_alg_type algif_type_skcipher = { .bind = skcipher_bind, .release = skcipher_release, .setkey = skcipher_setkey, .accept = skcipher_accept_parent, .ops = &algif_skcipher_ops, .name = "skcipher", .owner = THIS_MODULE }; static int __init algif_skcipher_init(void) { return af_alg_register_type(&algif_type_skcipher); } static void __exit algif_skcipher_exit(void) { int err = af_alg_unregister_type(&algif_type_skcipher); BUG_ON(err); } module_init(algif_skcipher_init); module_exit(algif_skcipher_exit); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_5678_1
crossvul-cpp_data_good_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, HIDE_ERRORED_LINE_CONTENT)) == 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/good_4074_2
crossvul-cpp_data_bad_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; 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; 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/bad_1508_4
crossvul-cpp_data_bad_5048_0
/*****************************************************************************/ /* * devio.c -- User space communication with USB devices. * * Copyright (C) 1999-2000 Thomas Sailer (sailer@ife.ee.ethz.ch) * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * This file implements the usbfs/x/y files, where * x is the bus number and y the device number. * * It allows user space programs/"drivers" to communicate directly * with USB devices without intervening kernel driver. * * Revision history * 22.12.1999 0.1 Initial release (split from proc_usb.c) * 04.01.2000 0.2 Turned into its own filesystem * 30.09.2005 0.3 Fix user-triggerable oops in async URB delivery * (CAN-2005-3055) */ /*****************************************************************************/ #include <linux/fs.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/signal.h> #include <linux/poll.h> #include <linux/module.h> #include <linux/string.h> #include <linux/usb.h> #include <linux/usbdevice_fs.h> #include <linux/usb/hcd.h> /* for usbcore internals */ #include <linux/cdev.h> #include <linux/notifier.h> #include <linux/security.h> #include <linux/user_namespace.h> #include <linux/scatterlist.h> #include <linux/uaccess.h> #include <linux/dma-mapping.h> #include <asm/byteorder.h> #include <linux/moduleparam.h> #include "usb.h" #define USB_MAXBUS 64 #define USB_DEVICE_MAX (USB_MAXBUS * 128) #define USB_SG_SIZE 16384 /* split-size for large txs */ /* Mutual exclusion for removal, open, and release */ DEFINE_MUTEX(usbfs_mutex); struct usb_dev_state { struct list_head list; /* state list */ struct usb_device *dev; struct file *file; spinlock_t lock; /* protects the async urb lists */ struct list_head async_pending; struct list_head async_completed; struct list_head memory_list; wait_queue_head_t wait; /* wake up if a request completed */ unsigned int discsignr; struct pid *disc_pid; const struct cred *cred; void __user *disccontext; unsigned long ifclaimed; u32 secid; u32 disabled_bulk_eps; bool privileges_dropped; unsigned long interface_allowed_mask; }; struct usb_memory { struct list_head memlist; int vma_use_count; int urb_use_count; u32 size; void *mem; dma_addr_t dma_handle; unsigned long vm_start; struct usb_dev_state *ps; }; struct async { struct list_head asynclist; struct usb_dev_state *ps; struct pid *pid; const struct cred *cred; unsigned int signr; unsigned int ifnum; void __user *userbuffer; void __user *userurb; struct urb *urb; struct usb_memory *usbm; unsigned int mem_usage; int status; u32 secid; u8 bulk_addr; u8 bulk_status; }; static bool usbfs_snoop; module_param(usbfs_snoop, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(usbfs_snoop, "true to log all usbfs traffic"); static unsigned usbfs_snoop_max = 65536; module_param(usbfs_snoop_max, uint, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(usbfs_snoop_max, "maximum number of bytes to print while snooping"); #define snoop(dev, format, arg...) \ do { \ if (usbfs_snoop) \ dev_info(dev, format, ## arg); \ } while (0) enum snoop_when { SUBMIT, COMPLETE }; #define USB_DEVICE_DEV MKDEV(USB_DEVICE_MAJOR, 0) /* Limit on the total amount of memory we can allocate for transfers */ static unsigned usbfs_memory_mb = 16; module_param(usbfs_memory_mb, uint, 0644); MODULE_PARM_DESC(usbfs_memory_mb, "maximum MB allowed for usbfs buffers (0 = no limit)"); /* Hard limit, necessary to avoid arithmetic overflow */ #define USBFS_XFER_MAX (UINT_MAX / 2 - 1000000) static atomic_t usbfs_memory_usage; /* Total memory currently allocated */ /* Check whether it's okay to allocate more memory for a transfer */ static int usbfs_increase_memory_usage(unsigned amount) { unsigned lim; /* * Convert usbfs_memory_mb to bytes, avoiding overflows. * 0 means use the hard limit (effectively unlimited). */ lim = ACCESS_ONCE(usbfs_memory_mb); if (lim == 0 || lim > (USBFS_XFER_MAX >> 20)) lim = USBFS_XFER_MAX; else lim <<= 20; atomic_add(amount, &usbfs_memory_usage); if (atomic_read(&usbfs_memory_usage) <= lim) return 0; atomic_sub(amount, &usbfs_memory_usage); return -ENOMEM; } /* Memory for a transfer is being deallocated */ static void usbfs_decrease_memory_usage(unsigned amount) { atomic_sub(amount, &usbfs_memory_usage); } static int connected(struct usb_dev_state *ps) { return (!list_empty(&ps->list) && ps->dev->state != USB_STATE_NOTATTACHED); } static void dec_usb_memory_use_count(struct usb_memory *usbm, int *count) { struct usb_dev_state *ps = usbm->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); --*count; if (usbm->urb_use_count == 0 && usbm->vma_use_count == 0) { list_del(&usbm->memlist); spin_unlock_irqrestore(&ps->lock, flags); usb_free_coherent(ps->dev, usbm->size, usbm->mem, usbm->dma_handle); usbfs_decrease_memory_usage( usbm->size + sizeof(struct usb_memory)); kfree(usbm); } else { spin_unlock_irqrestore(&ps->lock, flags); } } static void usbdev_vm_open(struct vm_area_struct *vma) { struct usb_memory *usbm = vma->vm_private_data; unsigned long flags; spin_lock_irqsave(&usbm->ps->lock, flags); ++usbm->vma_use_count; spin_unlock_irqrestore(&usbm->ps->lock, flags); } static void usbdev_vm_close(struct vm_area_struct *vma) { struct usb_memory *usbm = vma->vm_private_data; dec_usb_memory_use_count(usbm, &usbm->vma_use_count); } static struct vm_operations_struct usbdev_vm_ops = { .open = usbdev_vm_open, .close = usbdev_vm_close }; static int usbdev_mmap(struct file *file, struct vm_area_struct *vma) { struct usb_memory *usbm = NULL; struct usb_dev_state *ps = file->private_data; size_t size = vma->vm_end - vma->vm_start; void *mem; unsigned long flags; dma_addr_t dma_handle; int ret; ret = usbfs_increase_memory_usage(size + sizeof(struct usb_memory)); if (ret) goto error; usbm = kzalloc(sizeof(struct usb_memory), GFP_KERNEL); if (!usbm) { ret = -ENOMEM; goto error_decrease_mem; } mem = usb_alloc_coherent(ps->dev, size, GFP_USER, &dma_handle); if (!mem) { ret = -ENOMEM; goto error_free_usbm; } memset(mem, 0, size); usbm->mem = mem; usbm->dma_handle = dma_handle; usbm->size = size; usbm->ps = ps; usbm->vm_start = vma->vm_start; usbm->vma_use_count = 1; INIT_LIST_HEAD(&usbm->memlist); if (remap_pfn_range(vma, vma->vm_start, virt_to_phys(usbm->mem) >> PAGE_SHIFT, size, vma->vm_page_prot) < 0) { dec_usb_memory_use_count(usbm, &usbm->vma_use_count); return -EAGAIN; } vma->vm_flags |= VM_IO; vma->vm_flags |= (VM_DONTEXPAND | VM_DONTDUMP); vma->vm_ops = &usbdev_vm_ops; vma->vm_private_data = usbm; spin_lock_irqsave(&ps->lock, flags); list_add_tail(&usbm->memlist, &ps->memory_list); spin_unlock_irqrestore(&ps->lock, flags); return 0; error_free_usbm: kfree(usbm); error_decrease_mem: usbfs_decrease_memory_usage(size + sizeof(struct usb_memory)); error: return ret; } static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct usb_dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; ssize_t ret = 0; unsigned len; loff_t pos; int i; pos = *ppos; usb_lock_device(dev); if (!connected(ps)) { ret = -ENODEV; goto err; } else if (pos < 0) { ret = -EINVAL; goto err; } if (pos < sizeof(struct usb_device_descriptor)) { /* 18 bytes - fits on the stack */ struct usb_device_descriptor temp_desc; memcpy(&temp_desc, &dev->descriptor, sizeof(dev->descriptor)); le16_to_cpus(&temp_desc.bcdUSB); le16_to_cpus(&temp_desc.idVendor); le16_to_cpus(&temp_desc.idProduct); le16_to_cpus(&temp_desc.bcdDevice); len = sizeof(struct usb_device_descriptor) - pos; if (len > nbytes) len = nbytes; if (copy_to_user(buf, ((char *)&temp_desc) + pos, len)) { ret = -EFAULT; goto err; } *ppos += len; buf += len; nbytes -= len; ret += len; } pos = sizeof(struct usb_device_descriptor); for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) { struct usb_config_descriptor *config = (struct usb_config_descriptor *)dev->rawdescriptors[i]; unsigned int length = le16_to_cpu(config->wTotalLength); if (*ppos < pos + length) { /* The descriptor may claim to be longer than it * really is. Here is the actual allocated length. */ unsigned alloclen = le16_to_cpu(dev->config[i].desc.wTotalLength); len = length - (*ppos - pos); if (len > nbytes) len = nbytes; /* Simply don't write (skip over) unallocated parts */ if (alloclen > (*ppos - pos)) { alloclen -= (*ppos - pos); if (copy_to_user(buf, dev->rawdescriptors[i] + (*ppos - pos), min(len, alloclen))) { ret = -EFAULT; goto err; } } *ppos += len; buf += len; nbytes -= len; ret += len; } pos += length; } err: usb_unlock_device(dev); return ret; } /* * async list handling */ static struct async *alloc_async(unsigned int numisoframes) { struct async *as; as = kzalloc(sizeof(struct async), GFP_KERNEL); if (!as) return NULL; as->urb = usb_alloc_urb(numisoframes, GFP_KERNEL); if (!as->urb) { kfree(as); return NULL; } return as; } static void free_async(struct async *as) { int i; put_pid(as->pid); if (as->cred) put_cred(as->cred); for (i = 0; i < as->urb->num_sgs; i++) { if (sg_page(&as->urb->sg[i])) kfree(sg_virt(&as->urb->sg[i])); } kfree(as->urb->sg); if (as->usbm == NULL) kfree(as->urb->transfer_buffer); else dec_usb_memory_use_count(as->usbm, &as->usbm->urb_use_count); kfree(as->urb->setup_packet); usb_free_urb(as->urb); usbfs_decrease_memory_usage(as->mem_usage); kfree(as); } static void async_newpending(struct async *as) { struct usb_dev_state *ps = as->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); list_add_tail(&as->asynclist, &ps->async_pending); spin_unlock_irqrestore(&ps->lock, flags); } static void async_removepending(struct async *as) { struct usb_dev_state *ps = as->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); list_del_init(&as->asynclist); spin_unlock_irqrestore(&ps->lock, flags); } static struct async *async_getcompleted(struct usb_dev_state *ps) { unsigned long flags; struct async *as = NULL; spin_lock_irqsave(&ps->lock, flags); if (!list_empty(&ps->async_completed)) { as = list_entry(ps->async_completed.next, struct async, asynclist); list_del_init(&as->asynclist); } spin_unlock_irqrestore(&ps->lock, flags); return as; } static struct async *async_getpending(struct usb_dev_state *ps, void __user *userurb) { struct async *as; list_for_each_entry(as, &ps->async_pending, asynclist) if (as->userurb == userurb) { list_del_init(&as->asynclist); return as; } return NULL; } static void snoop_urb(struct usb_device *udev, void __user *userurb, int pipe, unsigned length, int timeout_or_status, enum snoop_when when, unsigned char *data, unsigned data_len) { static const char *types[] = {"isoc", "int", "ctrl", "bulk"}; static const char *dirs[] = {"out", "in"}; int ep; const char *t, *d; if (!usbfs_snoop) return; ep = usb_pipeendpoint(pipe); t = types[usb_pipetype(pipe)]; d = dirs[!!usb_pipein(pipe)]; if (userurb) { /* Async */ if (when == SUBMIT) dev_info(&udev->dev, "userurb %p, ep%d %s-%s, " "length %u\n", userurb, ep, t, d, length); else dev_info(&udev->dev, "userurb %p, ep%d %s-%s, " "actual_length %u status %d\n", userurb, ep, t, d, length, timeout_or_status); } else { if (when == SUBMIT) dev_info(&udev->dev, "ep%d %s-%s, length %u, " "timeout %d\n", ep, t, d, length, timeout_or_status); else dev_info(&udev->dev, "ep%d %s-%s, actual_length %u, " "status %d\n", ep, t, d, length, timeout_or_status); } data_len = min(data_len, usbfs_snoop_max); if (data && data_len > 0) { print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1, data, data_len, 1); } } static void snoop_urb_data(struct urb *urb, unsigned len) { int i, size; len = min(len, usbfs_snoop_max); if (!usbfs_snoop || len == 0) return; if (urb->num_sgs == 0) { print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1, urb->transfer_buffer, len, 1); return; } for (i = 0; i < urb->num_sgs && len; i++) { size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len; print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1, sg_virt(&urb->sg[i]), size, 1); len -= size; } } static int copy_urb_data_to_user(u8 __user *userbuffer, struct urb *urb) { unsigned i, len, size; if (urb->number_of_packets > 0) /* Isochronous */ len = urb->transfer_buffer_length; else /* Non-Isoc */ len = urb->actual_length; if (urb->num_sgs == 0) { if (copy_to_user(userbuffer, urb->transfer_buffer, len)) return -EFAULT; return 0; } for (i = 0; i < urb->num_sgs && len; i++) { size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len; if (copy_to_user(userbuffer, sg_virt(&urb->sg[i]), size)) return -EFAULT; userbuffer += size; len -= size; } return 0; } #define AS_CONTINUATION 1 #define AS_UNLINK 2 static void cancel_bulk_urbs(struct usb_dev_state *ps, unsigned bulk_addr) __releases(ps->lock) __acquires(ps->lock) { struct urb *urb; struct async *as; /* Mark all the pending URBs that match bulk_addr, up to but not * including the first one without AS_CONTINUATION. If such an * URB is encountered then a new transfer has already started so * the endpoint doesn't need to be disabled; otherwise it does. */ list_for_each_entry(as, &ps->async_pending, asynclist) { if (as->bulk_addr == bulk_addr) { if (as->bulk_status != AS_CONTINUATION) goto rescan; as->bulk_status = AS_UNLINK; as->bulk_addr = 0; } } ps->disabled_bulk_eps |= (1 << bulk_addr); /* Now carefully unlink all the marked pending URBs */ rescan: list_for_each_entry(as, &ps->async_pending, asynclist) { if (as->bulk_status == AS_UNLINK) { as->bulk_status = 0; /* Only once */ urb = as->urb; usb_get_urb(urb); spin_unlock(&ps->lock); /* Allow completions */ usb_unlink_urb(urb); usb_put_urb(urb); spin_lock(&ps->lock); goto rescan; } } } static void async_completed(struct urb *urb) { struct async *as = urb->context; struct usb_dev_state *ps = as->ps; struct siginfo sinfo; struct pid *pid = NULL; u32 secid = 0; const struct cred *cred = NULL; int signr; spin_lock(&ps->lock); list_move_tail(&as->asynclist, &ps->async_completed); as->status = urb->status; signr = as->signr; if (signr) { memset(&sinfo, 0, sizeof(sinfo)); sinfo.si_signo = as->signr; sinfo.si_errno = as->status; sinfo.si_code = SI_ASYNCIO; sinfo.si_addr = as->userurb; pid = get_pid(as->pid); cred = get_cred(as->cred); secid = as->secid; } snoop(&urb->dev->dev, "urb complete\n"); snoop_urb(urb->dev, as->userurb, urb->pipe, urb->actual_length, as->status, COMPLETE, NULL, 0); if ((urb->transfer_flags & URB_DIR_MASK) == URB_DIR_IN) snoop_urb_data(urb, urb->actual_length); if (as->status < 0 && as->bulk_addr && as->status != -ECONNRESET && as->status != -ENOENT) cancel_bulk_urbs(ps, as->bulk_addr); spin_unlock(&ps->lock); if (signr) { kill_pid_info_as_cred(sinfo.si_signo, &sinfo, pid, cred, secid); put_pid(pid); put_cred(cred); } wake_up(&ps->wait); } static void destroy_async(struct usb_dev_state *ps, struct list_head *list) { struct urb *urb; struct async *as; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); while (!list_empty(list)) { as = list_entry(list->next, struct async, asynclist); list_del_init(&as->asynclist); urb = as->urb; usb_get_urb(urb); /* drop the spinlock so the completion handler can run */ spin_unlock_irqrestore(&ps->lock, flags); usb_kill_urb(urb); usb_put_urb(urb); spin_lock_irqsave(&ps->lock, flags); } spin_unlock_irqrestore(&ps->lock, flags); } static void destroy_async_on_interface(struct usb_dev_state *ps, unsigned int ifnum) { struct list_head *p, *q, hitlist; unsigned long flags; INIT_LIST_HEAD(&hitlist); spin_lock_irqsave(&ps->lock, flags); list_for_each_safe(p, q, &ps->async_pending) if (ifnum == list_entry(p, struct async, asynclist)->ifnum) list_move_tail(p, &hitlist); spin_unlock_irqrestore(&ps->lock, flags); destroy_async(ps, &hitlist); } static void destroy_all_async(struct usb_dev_state *ps) { destroy_async(ps, &ps->async_pending); } /* * interface claims are made only at the request of user level code, * which can also release them (explicitly or by closing files). * they're also undone when devices disconnect. */ static int driver_probe(struct usb_interface *intf, const struct usb_device_id *id) { return -ENODEV; } static void driver_disconnect(struct usb_interface *intf) { struct usb_dev_state *ps = usb_get_intfdata(intf); unsigned int ifnum = intf->altsetting->desc.bInterfaceNumber; if (!ps) return; /* NOTE: this relies on usbcore having canceled and completed * all pending I/O requests; 2.6 does that. */ if (likely(ifnum < 8*sizeof(ps->ifclaimed))) clear_bit(ifnum, &ps->ifclaimed); else dev_warn(&intf->dev, "interface number %u out of range\n", ifnum); usb_set_intfdata(intf, NULL); /* force async requests to complete */ destroy_async_on_interface(ps, ifnum); } /* The following routines are merely placeholders. There is no way * to inform a user task about suspend or resumes. */ static int driver_suspend(struct usb_interface *intf, pm_message_t msg) { return 0; } static int driver_resume(struct usb_interface *intf) { return 0; } struct usb_driver usbfs_driver = { .name = "usbfs", .probe = driver_probe, .disconnect = driver_disconnect, .suspend = driver_suspend, .resume = driver_resume, }; static int claimintf(struct usb_dev_state *ps, unsigned int ifnum) { struct usb_device *dev = ps->dev; struct usb_interface *intf; int err; if (ifnum >= 8*sizeof(ps->ifclaimed)) return -EINVAL; /* already claimed */ if (test_bit(ifnum, &ps->ifclaimed)) return 0; if (ps->privileges_dropped && !test_bit(ifnum, &ps->interface_allowed_mask)) return -EACCES; intf = usb_ifnum_to_if(dev, ifnum); if (!intf) err = -ENOENT; else err = usb_driver_claim_interface(&usbfs_driver, intf, ps); if (err == 0) set_bit(ifnum, &ps->ifclaimed); return err; } static int releaseintf(struct usb_dev_state *ps, unsigned int ifnum) { struct usb_device *dev; struct usb_interface *intf; int err; err = -EINVAL; if (ifnum >= 8*sizeof(ps->ifclaimed)) return err; dev = ps->dev; intf = usb_ifnum_to_if(dev, ifnum); if (!intf) err = -ENOENT; else if (test_and_clear_bit(ifnum, &ps->ifclaimed)) { usb_driver_release_interface(&usbfs_driver, intf); err = 0; } return err; } static int checkintf(struct usb_dev_state *ps, unsigned int ifnum) { if (ps->dev->state != USB_STATE_CONFIGURED) return -EHOSTUNREACH; if (ifnum >= 8*sizeof(ps->ifclaimed)) return -EINVAL; if (test_bit(ifnum, &ps->ifclaimed)) return 0; /* if not yet claimed, claim it for the driver */ dev_warn(&ps->dev->dev, "usbfs: process %d (%s) did not claim " "interface %u before use\n", task_pid_nr(current), current->comm, ifnum); return claimintf(ps, ifnum); } static int findintfep(struct usb_device *dev, unsigned int ep) { unsigned int i, j, e; struct usb_interface *intf; struct usb_host_interface *alts; struct usb_endpoint_descriptor *endpt; if (ep & ~(USB_DIR_IN|0xf)) return -EINVAL; if (!dev->actconfig) return -ESRCH; for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { intf = dev->actconfig->interface[i]; for (j = 0; j < intf->num_altsetting; j++) { alts = &intf->altsetting[j]; for (e = 0; e < alts->desc.bNumEndpoints; e++) { endpt = &alts->endpoint[e].desc; if (endpt->bEndpointAddress == ep) return alts->desc.bInterfaceNumber; } } } return -ENOENT; } static int check_ctrlrecip(struct usb_dev_state *ps, unsigned int requesttype, unsigned int request, unsigned int index) { int ret = 0; struct usb_host_interface *alt_setting; if (ps->dev->state != USB_STATE_UNAUTHENTICATED && ps->dev->state != USB_STATE_ADDRESS && ps->dev->state != USB_STATE_CONFIGURED) return -EHOSTUNREACH; if (USB_TYPE_VENDOR == (USB_TYPE_MASK & requesttype)) return 0; /* * check for the special corner case 'get_device_id' in the printer * class specification, which we always want to allow as it is used * to query things like ink level, etc. */ if (requesttype == 0xa1 && request == 0) { alt_setting = usb_find_alt_setting(ps->dev->actconfig, index >> 8, index & 0xff); if (alt_setting && alt_setting->desc.bInterfaceClass == USB_CLASS_PRINTER) return 0; } index &= 0xff; switch (requesttype & USB_RECIP_MASK) { case USB_RECIP_ENDPOINT: if ((index & ~USB_DIR_IN) == 0) return 0; ret = findintfep(ps->dev, index); if (ret < 0) { /* * Some not fully compliant Win apps seem to get * index wrong and have the endpoint number here * rather than the endpoint address (with the * correct direction). Win does let this through, * so we'll not reject it here but leave it to * the device to not break KVM. But we warn. */ ret = findintfep(ps->dev, index ^ 0x80); if (ret >= 0) dev_info(&ps->dev->dev, "%s: process %i (%s) requesting ep %02x but needs %02x\n", __func__, task_pid_nr(current), current->comm, index, index ^ 0x80); } if (ret >= 0) ret = checkintf(ps, ret); break; case USB_RECIP_INTERFACE: ret = checkintf(ps, index); break; } return ret; } static struct usb_host_endpoint *ep_to_host_endpoint(struct usb_device *dev, unsigned char ep) { if (ep & USB_ENDPOINT_DIR_MASK) return dev->ep_in[ep & USB_ENDPOINT_NUMBER_MASK]; else return dev->ep_out[ep & USB_ENDPOINT_NUMBER_MASK]; } static int parse_usbdevfs_streams(struct usb_dev_state *ps, struct usbdevfs_streams __user *streams, unsigned int *num_streams_ret, unsigned int *num_eps_ret, struct usb_host_endpoint ***eps_ret, struct usb_interface **intf_ret) { unsigned int i, num_streams, num_eps; struct usb_host_endpoint **eps; struct usb_interface *intf = NULL; unsigned char ep; int ifnum, ret; if (get_user(num_streams, &streams->num_streams) || get_user(num_eps, &streams->num_eps)) return -EFAULT; if (num_eps < 1 || num_eps > USB_MAXENDPOINTS) return -EINVAL; /* The XHCI controller allows max 2 ^ 16 streams */ if (num_streams_ret && (num_streams < 2 || num_streams > 65536)) return -EINVAL; eps = kmalloc(num_eps * sizeof(*eps), GFP_KERNEL); if (!eps) return -ENOMEM; for (i = 0; i < num_eps; i++) { if (get_user(ep, &streams->eps[i])) { ret = -EFAULT; goto error; } eps[i] = ep_to_host_endpoint(ps->dev, ep); if (!eps[i]) { ret = -EINVAL; goto error; } /* usb_alloc/free_streams operate on an usb_interface */ ifnum = findintfep(ps->dev, ep); if (ifnum < 0) { ret = ifnum; goto error; } if (i == 0) { ret = checkintf(ps, ifnum); if (ret < 0) goto error; intf = usb_ifnum_to_if(ps->dev, ifnum); } else { /* Verify all eps belong to the same interface */ if (ifnum != intf->altsetting->desc.bInterfaceNumber) { ret = -EINVAL; goto error; } } } if (num_streams_ret) *num_streams_ret = num_streams; *num_eps_ret = num_eps; *eps_ret = eps; *intf_ret = intf; return 0; error: kfree(eps); return ret; } static int match_devt(struct device *dev, void *data) { return dev->devt == (dev_t) (unsigned long) data; } static struct usb_device *usbdev_lookup_by_devt(dev_t devt) { struct device *dev; dev = bus_find_device(&usb_bus_type, NULL, (void *) (unsigned long) devt, match_devt); if (!dev) return NULL; return to_usb_device(dev); } /* * file operations */ static int usbdev_open(struct inode *inode, struct file *file) { struct usb_device *dev = NULL; struct usb_dev_state *ps; int ret; ret = -ENOMEM; ps = kzalloc(sizeof(struct usb_dev_state), GFP_KERNEL); if (!ps) goto out_free_ps; ret = -ENODEV; /* Protect against simultaneous removal or release */ mutex_lock(&usbfs_mutex); /* usbdev device-node */ if (imajor(inode) == USB_DEVICE_MAJOR) dev = usbdev_lookup_by_devt(inode->i_rdev); mutex_unlock(&usbfs_mutex); if (!dev) goto out_free_ps; usb_lock_device(dev); if (dev->state == USB_STATE_NOTATTACHED) goto out_unlock_device; ret = usb_autoresume_device(dev); if (ret) goto out_unlock_device; ps->dev = dev; ps->file = file; ps->interface_allowed_mask = 0xFFFFFFFF; /* 32 bits */ spin_lock_init(&ps->lock); INIT_LIST_HEAD(&ps->list); INIT_LIST_HEAD(&ps->async_pending); INIT_LIST_HEAD(&ps->async_completed); INIT_LIST_HEAD(&ps->memory_list); init_waitqueue_head(&ps->wait); ps->disc_pid = get_pid(task_pid(current)); ps->cred = get_current_cred(); security_task_getsecid(current, &ps->secid); smp_wmb(); list_add_tail(&ps->list, &dev->filelist); file->private_data = ps; usb_unlock_device(dev); snoop(&dev->dev, "opened by process %d: %s\n", task_pid_nr(current), current->comm); return ret; out_unlock_device: usb_unlock_device(dev); usb_put_dev(dev); out_free_ps: kfree(ps); return ret; } static int usbdev_release(struct inode *inode, struct file *file) { struct usb_dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; unsigned int ifnum; struct async *as; usb_lock_device(dev); usb_hub_release_all_ports(dev, ps); list_del_init(&ps->list); for (ifnum = 0; ps->ifclaimed && ifnum < 8*sizeof(ps->ifclaimed); ifnum++) { if (test_bit(ifnum, &ps->ifclaimed)) releaseintf(ps, ifnum); } destroy_all_async(ps); usb_autosuspend_device(dev); usb_unlock_device(dev); usb_put_dev(dev); put_pid(ps->disc_pid); put_cred(ps->cred); as = async_getcompleted(ps); while (as) { free_async(as); as = async_getcompleted(ps); } kfree(ps); return 0; } static int proc_control(struct usb_dev_state *ps, void __user *arg) { struct usb_device *dev = ps->dev; struct usbdevfs_ctrltransfer ctrl; unsigned int tmo; unsigned char *tbuf; unsigned wLength; int i, pipe, ret; if (copy_from_user(&ctrl, arg, sizeof(ctrl))) return -EFAULT; ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.bRequest, ctrl.wIndex); if (ret) return ret; wLength = ctrl.wLength; /* To suppress 64k PAGE_SIZE warning */ if (wLength > PAGE_SIZE) return -EINVAL; ret = usbfs_increase_memory_usage(PAGE_SIZE + sizeof(struct urb) + sizeof(struct usb_ctrlrequest)); if (ret) return ret; tbuf = (unsigned char *)__get_free_page(GFP_KERNEL); if (!tbuf) { ret = -ENOMEM; goto done; } tmo = ctrl.timeout; snoop(&dev->dev, "control urb: bRequestType=%02x " "bRequest=%02x wValue=%04x " "wIndex=%04x wLength=%04x\n", ctrl.bRequestType, ctrl.bRequest, ctrl.wValue, ctrl.wIndex, ctrl.wLength); if (ctrl.bRequestType & 0x80) { if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data, ctrl.wLength)) { ret = -EINVAL; goto done; } pipe = usb_rcvctrlpipe(dev, 0); snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, NULL, 0); usb_unlock_device(dev); i = usb_control_msg(dev, pipe, ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, tbuf, max(i, 0)); if ((i > 0) && ctrl.wLength) { if (copy_to_user(ctrl.data, tbuf, i)) { ret = -EFAULT; goto done; } } } else { if (ctrl.wLength) { if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) { ret = -EFAULT; goto done; } } pipe = usb_sndctrlpipe(dev, 0); snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, tbuf, ctrl.wLength); usb_unlock_device(dev); i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, NULL, 0); } if (i < 0 && i != -EPIPE) { dev_printk(KERN_DEBUG, &dev->dev, "usbfs: USBDEVFS_CONTROL " "failed cmd %s rqt %u rq %u len %u ret %d\n", current->comm, ctrl.bRequestType, ctrl.bRequest, ctrl.wLength, i); } ret = i; done: free_page((unsigned long) tbuf); usbfs_decrease_memory_usage(PAGE_SIZE + sizeof(struct urb) + sizeof(struct usb_ctrlrequest)); return ret; } static int proc_bulk(struct usb_dev_state *ps, void __user *arg) { struct usb_device *dev = ps->dev; struct usbdevfs_bulktransfer bulk; unsigned int tmo, len1, pipe; int len2; unsigned char *tbuf; int i, ret; if (copy_from_user(&bulk, arg, sizeof(bulk))) return -EFAULT; ret = findintfep(ps->dev, bulk.ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; if (bulk.ep & USB_DIR_IN) pipe = usb_rcvbulkpipe(dev, bulk.ep & 0x7f); else pipe = usb_sndbulkpipe(dev, bulk.ep & 0x7f); if (!usb_maxpacket(dev, pipe, !(bulk.ep & USB_DIR_IN))) return -EINVAL; len1 = bulk.len; if (len1 >= USBFS_XFER_MAX) return -EINVAL; ret = usbfs_increase_memory_usage(len1 + sizeof(struct urb)); if (ret) return ret; tbuf = kmalloc(len1, GFP_KERNEL); if (!tbuf) { ret = -ENOMEM; goto done; } tmo = bulk.timeout; if (bulk.ep & 0x80) { if (len1 && !access_ok(VERIFY_WRITE, bulk.data, len1)) { ret = -EINVAL; goto done; } snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, NULL, 0); usb_unlock_device(dev); i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, tbuf, len2); if (!i && len2) { if (copy_to_user(bulk.data, tbuf, len2)) { ret = -EFAULT; goto done; } } } else { if (len1) { if (copy_from_user(tbuf, bulk.data, len1)) { ret = -EFAULT; goto done; } } snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, tbuf, len1); usb_unlock_device(dev); i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, NULL, 0); } ret = (i < 0 ? i : len2); done: kfree(tbuf); usbfs_decrease_memory_usage(len1 + sizeof(struct urb)); return ret; } static void check_reset_of_active_ep(struct usb_device *udev, unsigned int epnum, char *ioctl_name) { struct usb_host_endpoint **eps; struct usb_host_endpoint *ep; eps = (epnum & USB_DIR_IN) ? udev->ep_in : udev->ep_out; ep = eps[epnum & 0x0f]; if (ep && !list_empty(&ep->urb_list)) dev_warn(&udev->dev, "Process %d (%s) called USBDEVFS_%s for active endpoint 0x%02x\n", task_pid_nr(current), current->comm, ioctl_name, epnum); } static int proc_resetep(struct usb_dev_state *ps, void __user *arg) { unsigned int ep; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; check_reset_of_active_ep(ps->dev, ep, "RESETEP"); usb_reset_endpoint(ps->dev, ep); return 0; } static int proc_clearhalt(struct usb_dev_state *ps, void __user *arg) { unsigned int ep; int pipe; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; check_reset_of_active_ep(ps->dev, ep, "CLEAR_HALT"); if (ep & USB_DIR_IN) pipe = usb_rcvbulkpipe(ps->dev, ep & 0x7f); else pipe = usb_sndbulkpipe(ps->dev, ep & 0x7f); return usb_clear_halt(ps->dev, pipe); } static int proc_getdriver(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_getdriver gd; struct usb_interface *intf; int ret; if (copy_from_user(&gd, arg, sizeof(gd))) return -EFAULT; intf = usb_ifnum_to_if(ps->dev, gd.interface); if (!intf || !intf->dev.driver) ret = -ENODATA; else { strlcpy(gd.driver, intf->dev.driver->name, sizeof(gd.driver)); ret = (copy_to_user(arg, &gd, sizeof(gd)) ? -EFAULT : 0); } return ret; } static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_connectinfo ci = { .devnum = ps->dev->devnum, .slow = ps->dev->speed == USB_SPEED_LOW }; if (copy_to_user(arg, &ci, sizeof(ci))) return -EFAULT; return 0; } static int proc_resetdevice(struct usb_dev_state *ps) { struct usb_host_config *actconfig = ps->dev->actconfig; struct usb_interface *interface; int i, number; /* Don't allow a device reset if the process has dropped the * privilege to do such things and any of the interfaces are * currently claimed. */ if (ps->privileges_dropped && actconfig) { for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) { interface = actconfig->interface[i]; number = interface->cur_altsetting->desc.bInterfaceNumber; if (usb_interface_claimed(interface) && !test_bit(number, &ps->ifclaimed)) { dev_warn(&ps->dev->dev, "usbfs: interface %d claimed by %s while '%s' resets device\n", number, interface->dev.driver->name, current->comm); return -EACCES; } } } return usb_reset_device(ps->dev); } static int proc_setintf(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_setinterface setintf; int ret; if (copy_from_user(&setintf, arg, sizeof(setintf))) return -EFAULT; ret = checkintf(ps, setintf.interface); if (ret) return ret; destroy_async_on_interface(ps, setintf.interface); return usb_set_interface(ps->dev, setintf.interface, setintf.altsetting); } static int proc_setconfig(struct usb_dev_state *ps, void __user *arg) { int u; int status = 0; struct usb_host_config *actconfig; if (get_user(u, (int __user *)arg)) return -EFAULT; actconfig = ps->dev->actconfig; /* Don't touch the device if any interfaces are claimed. * It could interfere with other drivers' operations, and if * an interface is claimed by usbfs it could easily deadlock. */ if (actconfig) { int i; for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) { if (usb_interface_claimed(actconfig->interface[i])) { dev_warn(&ps->dev->dev, "usbfs: interface %d claimed by %s " "while '%s' sets config #%d\n", actconfig->interface[i] ->cur_altsetting ->desc.bInterfaceNumber, actconfig->interface[i] ->dev.driver->name, current->comm, u); status = -EBUSY; break; } } } /* SET_CONFIGURATION is often abused as a "cheap" driver reset, * so avoid usb_set_configuration()'s kick to sysfs */ if (status == 0) { if (actconfig && actconfig->desc.bConfigurationValue == u) status = usb_reset_configuration(ps->dev); else status = usb_set_configuration(ps->dev, u); } return status; } static struct usb_memory * find_memory_area(struct usb_dev_state *ps, const struct usbdevfs_urb *uurb) { struct usb_memory *usbm = NULL, *iter; unsigned long flags; unsigned long uurb_start = (unsigned long)uurb->buffer; spin_lock_irqsave(&ps->lock, flags); list_for_each_entry(iter, &ps->memory_list, memlist) { if (uurb_start >= iter->vm_start && uurb_start < iter->vm_start + iter->size) { if (uurb->buffer_length > iter->vm_start + iter->size - uurb_start) { usbm = ERR_PTR(-EINVAL); } else { usbm = iter; usbm->urb_use_count++; } break; } } spin_unlock_irqrestore(&ps->lock, flags); return usbm; } static int proc_do_submiturb(struct usb_dev_state *ps, struct usbdevfs_urb *uurb, struct usbdevfs_iso_packet_desc __user *iso_frame_desc, void __user *arg) { struct usbdevfs_iso_packet_desc *isopkt = NULL; struct usb_host_endpoint *ep; struct async *as = NULL; struct usb_ctrlrequest *dr = NULL; unsigned int u, totlen, isofrmlen; int i, ret, is_in, num_sgs = 0, ifnum = -1; int number_of_packets = 0; unsigned int stream_id = 0; void *buf; if (uurb->flags & ~(USBDEVFS_URB_ISO_ASAP | USBDEVFS_URB_SHORT_NOT_OK | USBDEVFS_URB_BULK_CONTINUATION | USBDEVFS_URB_NO_FSBR | USBDEVFS_URB_ZERO_PACKET | USBDEVFS_URB_NO_INTERRUPT)) return -EINVAL; if (uurb->buffer_length > 0 && !uurb->buffer) return -EINVAL; if (!(uurb->type == USBDEVFS_URB_TYPE_CONTROL && (uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) == 0)) { ifnum = findintfep(ps->dev, uurb->endpoint); if (ifnum < 0) return ifnum; ret = checkintf(ps, ifnum); if (ret) return ret; } ep = ep_to_host_endpoint(ps->dev, uurb->endpoint); if (!ep) return -ENOENT; is_in = (uurb->endpoint & USB_ENDPOINT_DIR_MASK) != 0; u = 0; switch (uurb->type) { case USBDEVFS_URB_TYPE_CONTROL: if (!usb_endpoint_xfer_control(&ep->desc)) return -EINVAL; /* min 8 byte setup packet */ if (uurb->buffer_length < 8) return -EINVAL; dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL); if (!dr) return -ENOMEM; if (copy_from_user(dr, uurb->buffer, 8)) { ret = -EFAULT; goto error; } if (uurb->buffer_length < (le16_to_cpup(&dr->wLength) + 8)) { ret = -EINVAL; goto error; } ret = check_ctrlrecip(ps, dr->bRequestType, dr->bRequest, le16_to_cpup(&dr->wIndex)); if (ret) goto error; uurb->buffer_length = le16_to_cpup(&dr->wLength); uurb->buffer += 8; if ((dr->bRequestType & USB_DIR_IN) && uurb->buffer_length) { is_in = 1; uurb->endpoint |= USB_DIR_IN; } else { is_in = 0; uurb->endpoint &= ~USB_DIR_IN; } snoop(&ps->dev->dev, "control urb: bRequestType=%02x " "bRequest=%02x wValue=%04x " "wIndex=%04x wLength=%04x\n", dr->bRequestType, dr->bRequest, __le16_to_cpup(&dr->wValue), __le16_to_cpup(&dr->wIndex), __le16_to_cpup(&dr->wLength)); u = sizeof(struct usb_ctrlrequest); break; case USBDEVFS_URB_TYPE_BULK: switch (usb_endpoint_type(&ep->desc)) { case USB_ENDPOINT_XFER_CONTROL: case USB_ENDPOINT_XFER_ISOC: return -EINVAL; case USB_ENDPOINT_XFER_INT: /* allow single-shot interrupt transfers */ uurb->type = USBDEVFS_URB_TYPE_INTERRUPT; goto interrupt_urb; } num_sgs = DIV_ROUND_UP(uurb->buffer_length, USB_SG_SIZE); if (num_sgs == 1 || num_sgs > ps->dev->bus->sg_tablesize) num_sgs = 0; if (ep->streams) stream_id = uurb->stream_id; break; case USBDEVFS_URB_TYPE_INTERRUPT: if (!usb_endpoint_xfer_int(&ep->desc)) return -EINVAL; interrupt_urb: break; case USBDEVFS_URB_TYPE_ISO: /* arbitrary limit */ if (uurb->number_of_packets < 1 || uurb->number_of_packets > 128) return -EINVAL; if (!usb_endpoint_xfer_isoc(&ep->desc)) return -EINVAL; number_of_packets = uurb->number_of_packets; isofrmlen = sizeof(struct usbdevfs_iso_packet_desc) * number_of_packets; isopkt = memdup_user(iso_frame_desc, isofrmlen); if (IS_ERR(isopkt)) { ret = PTR_ERR(isopkt); isopkt = NULL; goto error; } for (totlen = u = 0; u < number_of_packets; u++) { /* * arbitrary limit need for USB 3.0 * bMaxBurst (0~15 allowed, 1~16 packets) * bmAttributes (bit 1:0, mult 0~2, 1~3 packets) * sizemax: 1024 * 16 * 3 = 49152 */ if (isopkt[u].length > 49152) { ret = -EINVAL; goto error; } totlen += isopkt[u].length; } u *= sizeof(struct usb_iso_packet_descriptor); uurb->buffer_length = totlen; break; default: return -EINVAL; } if (uurb->buffer_length >= USBFS_XFER_MAX) { ret = -EINVAL; goto error; } if (uurb->buffer_length > 0 && !access_ok(is_in ? VERIFY_WRITE : VERIFY_READ, uurb->buffer, uurb->buffer_length)) { ret = -EFAULT; goto error; } as = alloc_async(number_of_packets); if (!as) { ret = -ENOMEM; goto error; } as->usbm = find_memory_area(ps, uurb); if (IS_ERR(as->usbm)) { ret = PTR_ERR(as->usbm); as->usbm = NULL; goto error; } /* do not use SG buffers when memory mapped segments * are in use */ if (as->usbm) num_sgs = 0; u += sizeof(struct async) + sizeof(struct urb) + uurb->buffer_length + num_sgs * sizeof(struct scatterlist); ret = usbfs_increase_memory_usage(u); if (ret) goto error; as->mem_usage = u; if (num_sgs) { as->urb->sg = kmalloc(num_sgs * sizeof(struct scatterlist), GFP_KERNEL); if (!as->urb->sg) { ret = -ENOMEM; goto error; } as->urb->num_sgs = num_sgs; sg_init_table(as->urb->sg, as->urb->num_sgs); totlen = uurb->buffer_length; for (i = 0; i < as->urb->num_sgs; i++) { u = (totlen > USB_SG_SIZE) ? USB_SG_SIZE : totlen; buf = kmalloc(u, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto error; } sg_set_buf(&as->urb->sg[i], buf, u); if (!is_in) { if (copy_from_user(buf, uurb->buffer, u)) { ret = -EFAULT; goto error; } uurb->buffer += u; } totlen -= u; } } else if (uurb->buffer_length > 0) { if (as->usbm) { unsigned long uurb_start = (unsigned long)uurb->buffer; as->urb->transfer_buffer = as->usbm->mem + (uurb_start - as->usbm->vm_start); } else { as->urb->transfer_buffer = kmalloc(uurb->buffer_length, GFP_KERNEL); if (!as->urb->transfer_buffer) { ret = -ENOMEM; goto error; } if (!is_in) { if (copy_from_user(as->urb->transfer_buffer, uurb->buffer, uurb->buffer_length)) { ret = -EFAULT; goto error; } } else if (uurb->type == USBDEVFS_URB_TYPE_ISO) { /* * Isochronous input data may end up being * discontiguous if some of the packets are * short. Clear the buffer so that the gaps * don't leak kernel data to userspace. */ memset(as->urb->transfer_buffer, 0, uurb->buffer_length); } } } as->urb->dev = ps->dev; as->urb->pipe = (uurb->type << 30) | __create_pipe(ps->dev, uurb->endpoint & 0xf) | (uurb->endpoint & USB_DIR_IN); /* This tedious sequence is necessary because the URB_* flags * are internal to the kernel and subject to change, whereas * the USBDEVFS_URB_* flags are a user API and must not be changed. */ u = (is_in ? URB_DIR_IN : URB_DIR_OUT); if (uurb->flags & USBDEVFS_URB_ISO_ASAP) u |= URB_ISO_ASAP; if (uurb->flags & USBDEVFS_URB_SHORT_NOT_OK && is_in) u |= URB_SHORT_NOT_OK; if (uurb->flags & USBDEVFS_URB_NO_FSBR) u |= URB_NO_FSBR; if (uurb->flags & USBDEVFS_URB_ZERO_PACKET) u |= URB_ZERO_PACKET; if (uurb->flags & USBDEVFS_URB_NO_INTERRUPT) u |= URB_NO_INTERRUPT; as->urb->transfer_flags = u; as->urb->transfer_buffer_length = uurb->buffer_length; as->urb->setup_packet = (unsigned char *)dr; dr = NULL; as->urb->start_frame = uurb->start_frame; as->urb->number_of_packets = number_of_packets; as->urb->stream_id = stream_id; if (uurb->type == USBDEVFS_URB_TYPE_ISO || ps->dev->speed == USB_SPEED_HIGH) as->urb->interval = 1 << min(15, ep->desc.bInterval - 1); else as->urb->interval = ep->desc.bInterval; as->urb->context = as; as->urb->complete = async_completed; for (totlen = u = 0; u < number_of_packets; u++) { as->urb->iso_frame_desc[u].offset = totlen; as->urb->iso_frame_desc[u].length = isopkt[u].length; totlen += isopkt[u].length; } kfree(isopkt); isopkt = NULL; as->ps = ps; as->userurb = arg; if (as->usbm) { unsigned long uurb_start = (unsigned long)uurb->buffer; as->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; as->urb->transfer_dma = as->usbm->dma_handle + (uurb_start - as->usbm->vm_start); } else if (is_in && uurb->buffer_length > 0) as->userbuffer = uurb->buffer; as->signr = uurb->signr; as->ifnum = ifnum; as->pid = get_pid(task_pid(current)); as->cred = get_current_cred(); security_task_getsecid(current, &as->secid); snoop_urb(ps->dev, as->userurb, as->urb->pipe, as->urb->transfer_buffer_length, 0, SUBMIT, NULL, 0); if (!is_in) snoop_urb_data(as->urb, as->urb->transfer_buffer_length); async_newpending(as); if (usb_endpoint_xfer_bulk(&ep->desc)) { spin_lock_irq(&ps->lock); /* Not exactly the endpoint address; the direction bit is * shifted to the 0x10 position so that the value will be * between 0 and 31. */ as->bulk_addr = usb_endpoint_num(&ep->desc) | ((ep->desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK) >> 3); /* If this bulk URB is the start of a new transfer, re-enable * the endpoint. Otherwise mark it as a continuation URB. */ if (uurb->flags & USBDEVFS_URB_BULK_CONTINUATION) as->bulk_status = AS_CONTINUATION; else ps->disabled_bulk_eps &= ~(1 << as->bulk_addr); /* Don't accept continuation URBs if the endpoint is * disabled because of an earlier error. */ if (ps->disabled_bulk_eps & (1 << as->bulk_addr)) ret = -EREMOTEIO; else ret = usb_submit_urb(as->urb, GFP_ATOMIC); spin_unlock_irq(&ps->lock); } else { ret = usb_submit_urb(as->urb, GFP_KERNEL); } if (ret) { dev_printk(KERN_DEBUG, &ps->dev->dev, "usbfs: usb_submit_urb returned %d\n", ret); snoop_urb(ps->dev, as->userurb, as->urb->pipe, 0, ret, COMPLETE, NULL, 0); async_removepending(as); goto error; } return 0; error: if (as && as->usbm) dec_usb_memory_use_count(as->usbm, &as->usbm->urb_use_count); kfree(isopkt); kfree(dr); if (as) free_async(as); return ret; } static int proc_submiturb(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_urb uurb; if (copy_from_user(&uurb, arg, sizeof(uurb))) return -EFAULT; return proc_do_submiturb(ps, &uurb, (((struct usbdevfs_urb __user *)arg)->iso_frame_desc), arg); } static int proc_unlinkurb(struct usb_dev_state *ps, void __user *arg) { struct urb *urb; struct async *as; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); as = async_getpending(ps, arg); if (!as) { spin_unlock_irqrestore(&ps->lock, flags); return -EINVAL; } urb = as->urb; usb_get_urb(urb); spin_unlock_irqrestore(&ps->lock, flags); usb_kill_urb(urb); usb_put_urb(urb); return 0; } static int processcompl(struct async *as, void __user * __user *arg) { struct urb *urb = as->urb; struct usbdevfs_urb __user *userurb = as->userurb; void __user *addr = as->userurb; unsigned int i; if (as->userbuffer && urb->actual_length) { if (copy_urb_data_to_user(as->userbuffer, urb)) goto err_out; } if (put_user(as->status, &userurb->status)) goto err_out; if (put_user(urb->actual_length, &userurb->actual_length)) goto err_out; if (put_user(urb->error_count, &userurb->error_count)) goto err_out; if (usb_endpoint_xfer_isoc(&urb->ep->desc)) { for (i = 0; i < urb->number_of_packets; i++) { if (put_user(urb->iso_frame_desc[i].actual_length, &userurb->iso_frame_desc[i].actual_length)) goto err_out; if (put_user(urb->iso_frame_desc[i].status, &userurb->iso_frame_desc[i].status)) goto err_out; } } if (put_user(addr, (void __user * __user *)arg)) return -EFAULT; return 0; err_out: return -EFAULT; } static struct async *reap_as(struct usb_dev_state *ps) { DECLARE_WAITQUEUE(wait, current); struct async *as = NULL; struct usb_device *dev = ps->dev; add_wait_queue(&ps->wait, &wait); for (;;) { __set_current_state(TASK_INTERRUPTIBLE); as = async_getcompleted(ps); if (as || !connected(ps)) break; if (signal_pending(current)) break; usb_unlock_device(dev); schedule(); usb_lock_device(dev); } remove_wait_queue(&ps->wait, &wait); set_current_state(TASK_RUNNING); return as; } static int proc_reapurb(struct usb_dev_state *ps, void __user *arg) { struct async *as = reap_as(ps); if (as) { int retval; snoop(&ps->dev->dev, "reap %p\n", as->userurb); retval = processcompl(as, (void __user * __user *)arg); free_async(as); return retval; } if (signal_pending(current)) return -EINTR; return -ENODEV; } static int proc_reapurbnonblock(struct usb_dev_state *ps, void __user *arg) { int retval; struct async *as; as = async_getcompleted(ps); if (as) { snoop(&ps->dev->dev, "reap %p\n", as->userurb); retval = processcompl(as, (void __user * __user *)arg); free_async(as); } else { retval = (connected(ps) ? -EAGAIN : -ENODEV); } return retval; } #ifdef CONFIG_COMPAT static int proc_control_compat(struct usb_dev_state *ps, struct usbdevfs_ctrltransfer32 __user *p32) { struct usbdevfs_ctrltransfer __user *p; __u32 udata; p = compat_alloc_user_space(sizeof(*p)); if (copy_in_user(p, p32, (sizeof(*p32) - sizeof(compat_caddr_t))) || get_user(udata, &p32->data) || put_user(compat_ptr(udata), &p->data)) return -EFAULT; return proc_control(ps, p); } static int proc_bulk_compat(struct usb_dev_state *ps, struct usbdevfs_bulktransfer32 __user *p32) { struct usbdevfs_bulktransfer __user *p; compat_uint_t n; compat_caddr_t addr; p = compat_alloc_user_space(sizeof(*p)); if (get_user(n, &p32->ep) || put_user(n, &p->ep) || get_user(n, &p32->len) || put_user(n, &p->len) || get_user(n, &p32->timeout) || put_user(n, &p->timeout) || get_user(addr, &p32->data) || put_user(compat_ptr(addr), &p->data)) return -EFAULT; return proc_bulk(ps, p); } static int proc_disconnectsignal_compat(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_disconnectsignal32 ds; if (copy_from_user(&ds, arg, sizeof(ds))) return -EFAULT; ps->discsignr = ds.signr; ps->disccontext = compat_ptr(ds.context); return 0; } static int get_urb32(struct usbdevfs_urb *kurb, struct usbdevfs_urb32 __user *uurb) { __u32 uptr; if (!access_ok(VERIFY_READ, uurb, sizeof(*uurb)) || __get_user(kurb->type, &uurb->type) || __get_user(kurb->endpoint, &uurb->endpoint) || __get_user(kurb->status, &uurb->status) || __get_user(kurb->flags, &uurb->flags) || __get_user(kurb->buffer_length, &uurb->buffer_length) || __get_user(kurb->actual_length, &uurb->actual_length) || __get_user(kurb->start_frame, &uurb->start_frame) || __get_user(kurb->number_of_packets, &uurb->number_of_packets) || __get_user(kurb->error_count, &uurb->error_count) || __get_user(kurb->signr, &uurb->signr)) return -EFAULT; if (__get_user(uptr, &uurb->buffer)) return -EFAULT; kurb->buffer = compat_ptr(uptr); if (__get_user(uptr, &uurb->usercontext)) return -EFAULT; kurb->usercontext = compat_ptr(uptr); return 0; } static int proc_submiturb_compat(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_urb uurb; if (get_urb32(&uurb, (struct usbdevfs_urb32 __user *)arg)) return -EFAULT; return proc_do_submiturb(ps, &uurb, ((struct usbdevfs_urb32 __user *)arg)->iso_frame_desc, arg); } static int processcompl_compat(struct async *as, void __user * __user *arg) { struct urb *urb = as->urb; struct usbdevfs_urb32 __user *userurb = as->userurb; void __user *addr = as->userurb; unsigned int i; if (as->userbuffer && urb->actual_length) { if (copy_urb_data_to_user(as->userbuffer, urb)) return -EFAULT; } if (put_user(as->status, &userurb->status)) return -EFAULT; if (put_user(urb->actual_length, &userurb->actual_length)) return -EFAULT; if (put_user(urb->error_count, &userurb->error_count)) return -EFAULT; if (usb_endpoint_xfer_isoc(&urb->ep->desc)) { for (i = 0; i < urb->number_of_packets; i++) { if (put_user(urb->iso_frame_desc[i].actual_length, &userurb->iso_frame_desc[i].actual_length)) return -EFAULT; if (put_user(urb->iso_frame_desc[i].status, &userurb->iso_frame_desc[i].status)) return -EFAULT; } } if (put_user(ptr_to_compat(addr), (u32 __user *)arg)) return -EFAULT; return 0; } static int proc_reapurb_compat(struct usb_dev_state *ps, void __user *arg) { struct async *as = reap_as(ps); if (as) { int retval; snoop(&ps->dev->dev, "reap %p\n", as->userurb); retval = processcompl_compat(as, (void __user * __user *)arg); free_async(as); return retval; } if (signal_pending(current)) return -EINTR; return -ENODEV; } static int proc_reapurbnonblock_compat(struct usb_dev_state *ps, void __user *arg) { int retval; struct async *as; as = async_getcompleted(ps); if (as) { snoop(&ps->dev->dev, "reap %p\n", as->userurb); retval = processcompl_compat(as, (void __user * __user *)arg); free_async(as); } else { retval = (connected(ps) ? -EAGAIN : -ENODEV); } return retval; } #endif static int proc_disconnectsignal(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_disconnectsignal ds; if (copy_from_user(&ds, arg, sizeof(ds))) return -EFAULT; ps->discsignr = ds.signr; ps->disccontext = ds.context; return 0; } static int proc_claiminterface(struct usb_dev_state *ps, void __user *arg) { unsigned int ifnum; if (get_user(ifnum, (unsigned int __user *)arg)) return -EFAULT; return claimintf(ps, ifnum); } static int proc_releaseinterface(struct usb_dev_state *ps, void __user *arg) { unsigned int ifnum; int ret; if (get_user(ifnum, (unsigned int __user *)arg)) return -EFAULT; ret = releaseintf(ps, ifnum); if (ret < 0) return ret; destroy_async_on_interface(ps, ifnum); return 0; } static int proc_ioctl(struct usb_dev_state *ps, struct usbdevfs_ioctl *ctl) { int size; void *buf = NULL; int retval = 0; struct usb_interface *intf = NULL; struct usb_driver *driver = NULL; if (ps->privileges_dropped) return -EACCES; /* alloc buffer */ size = _IOC_SIZE(ctl->ioctl_code); if (size > 0) { buf = kmalloc(size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; if ((_IOC_DIR(ctl->ioctl_code) & _IOC_WRITE)) { if (copy_from_user(buf, ctl->data, size)) { kfree(buf); return -EFAULT; } } else { memset(buf, 0, size); } } if (!connected(ps)) { kfree(buf); return -ENODEV; } if (ps->dev->state != USB_STATE_CONFIGURED) retval = -EHOSTUNREACH; else if (!(intf = usb_ifnum_to_if(ps->dev, ctl->ifno))) retval = -EINVAL; else switch (ctl->ioctl_code) { /* disconnect kernel driver from interface */ case USBDEVFS_DISCONNECT: if (intf->dev.driver) { driver = to_usb_driver(intf->dev.driver); dev_dbg(&intf->dev, "disconnect by usbfs\n"); usb_driver_release_interface(driver, intf); } else retval = -ENODATA; break; /* let kernel drivers try to (re)bind to the interface */ case USBDEVFS_CONNECT: if (!intf->dev.driver) retval = device_attach(&intf->dev); else retval = -EBUSY; break; /* talk directly to the interface's driver */ default: if (intf->dev.driver) driver = to_usb_driver(intf->dev.driver); if (driver == NULL || driver->unlocked_ioctl == NULL) { retval = -ENOTTY; } else { retval = driver->unlocked_ioctl(intf, ctl->ioctl_code, buf); if (retval == -ENOIOCTLCMD) retval = -ENOTTY; } } /* cleanup and return */ if (retval >= 0 && (_IOC_DIR(ctl->ioctl_code) & _IOC_READ) != 0 && size > 0 && copy_to_user(ctl->data, buf, size) != 0) retval = -EFAULT; kfree(buf); return retval; } static int proc_ioctl_default(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_ioctl ctrl; if (copy_from_user(&ctrl, arg, sizeof(ctrl))) return -EFAULT; return proc_ioctl(ps, &ctrl); } #ifdef CONFIG_COMPAT static int proc_ioctl_compat(struct usb_dev_state *ps, compat_uptr_t arg) { struct usbdevfs_ioctl32 __user *uioc; struct usbdevfs_ioctl ctrl; u32 udata; uioc = compat_ptr((long)arg); if (!access_ok(VERIFY_READ, uioc, sizeof(*uioc)) || __get_user(ctrl.ifno, &uioc->ifno) || __get_user(ctrl.ioctl_code, &uioc->ioctl_code) || __get_user(udata, &uioc->data)) return -EFAULT; ctrl.data = compat_ptr(udata); return proc_ioctl(ps, &ctrl); } #endif static int proc_claim_port(struct usb_dev_state *ps, void __user *arg) { unsigned portnum; int rc; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; rc = usb_hub_claim_port(ps->dev, portnum, ps); if (rc == 0) snoop(&ps->dev->dev, "port %d claimed by process %d: %s\n", portnum, task_pid_nr(current), current->comm); return rc; } static int proc_release_port(struct usb_dev_state *ps, void __user *arg) { unsigned portnum; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; return usb_hub_release_port(ps->dev, portnum, ps); } static int proc_get_capabilities(struct usb_dev_state *ps, void __user *arg) { __u32 caps; caps = USBDEVFS_CAP_ZERO_PACKET | USBDEVFS_CAP_NO_PACKET_SIZE_LIM | USBDEVFS_CAP_REAP_AFTER_DISCONNECT | USBDEVFS_CAP_MMAP | USBDEVFS_CAP_DROP_PRIVILEGES; if (!ps->dev->bus->no_stop_on_short) caps |= USBDEVFS_CAP_BULK_CONTINUATION; if (ps->dev->bus->sg_tablesize) caps |= USBDEVFS_CAP_BULK_SCATTER_GATHER; if (put_user(caps, (__u32 __user *)arg)) return -EFAULT; return 0; } static int proc_disconnect_claim(struct usb_dev_state *ps, void __user *arg) { struct usbdevfs_disconnect_claim dc; struct usb_interface *intf; if (copy_from_user(&dc, arg, sizeof(dc))) return -EFAULT; intf = usb_ifnum_to_if(ps->dev, dc.interface); if (!intf) return -EINVAL; if (intf->dev.driver) { struct usb_driver *driver = to_usb_driver(intf->dev.driver); if (ps->privileges_dropped) return -EACCES; if ((dc.flags & USBDEVFS_DISCONNECT_CLAIM_IF_DRIVER) && strncmp(dc.driver, intf->dev.driver->name, sizeof(dc.driver)) != 0) return -EBUSY; if ((dc.flags & USBDEVFS_DISCONNECT_CLAIM_EXCEPT_DRIVER) && strncmp(dc.driver, intf->dev.driver->name, sizeof(dc.driver)) == 0) return -EBUSY; dev_dbg(&intf->dev, "disconnect by usbfs\n"); usb_driver_release_interface(driver, intf); } return claimintf(ps, dc.interface); } static int proc_alloc_streams(struct usb_dev_state *ps, void __user *arg) { unsigned num_streams, num_eps; struct usb_host_endpoint **eps; struct usb_interface *intf; int r; r = parse_usbdevfs_streams(ps, arg, &num_streams, &num_eps, &eps, &intf); if (r) return r; destroy_async_on_interface(ps, intf->altsetting[0].desc.bInterfaceNumber); r = usb_alloc_streams(intf, eps, num_eps, num_streams, GFP_KERNEL); kfree(eps); return r; } static int proc_free_streams(struct usb_dev_state *ps, void __user *arg) { unsigned num_eps; struct usb_host_endpoint **eps; struct usb_interface *intf; int r; r = parse_usbdevfs_streams(ps, arg, NULL, &num_eps, &eps, &intf); if (r) return r; destroy_async_on_interface(ps, intf->altsetting[0].desc.bInterfaceNumber); r = usb_free_streams(intf, eps, num_eps, GFP_KERNEL); kfree(eps); return r; } static int proc_drop_privileges(struct usb_dev_state *ps, void __user *arg) { u32 data; if (copy_from_user(&data, arg, sizeof(data))) return -EFAULT; /* This is an one way operation. Once privileges are * dropped, you cannot regain them. You may however reissue * this ioctl to shrink the allowed interfaces mask. */ ps->interface_allowed_mask &= data; ps->privileges_dropped = true; return 0; } /* * NOTE: All requests here that have interface numbers as parameters * are assuming that somehow the configuration has been prevented from * changing. But there's no mechanism to ensure that... */ static long usbdev_do_ioctl(struct file *file, unsigned int cmd, void __user *p) { struct usb_dev_state *ps = file->private_data; struct inode *inode = file_inode(file); struct usb_device *dev = ps->dev; int ret = -ENOTTY; if (!(file->f_mode & FMODE_WRITE)) return -EPERM; usb_lock_device(dev); /* Reap operations are allowed even after disconnection */ switch (cmd) { case USBDEVFS_REAPURB: snoop(&dev->dev, "%s: REAPURB\n", __func__); ret = proc_reapurb(ps, p); goto done; case USBDEVFS_REAPURBNDELAY: snoop(&dev->dev, "%s: REAPURBNDELAY\n", __func__); ret = proc_reapurbnonblock(ps, p); goto done; #ifdef CONFIG_COMPAT case USBDEVFS_REAPURB32: snoop(&dev->dev, "%s: REAPURB32\n", __func__); ret = proc_reapurb_compat(ps, p); goto done; case USBDEVFS_REAPURBNDELAY32: snoop(&dev->dev, "%s: REAPURBNDELAY32\n", __func__); ret = proc_reapurbnonblock_compat(ps, p); goto done; #endif } if (!connected(ps)) { usb_unlock_device(dev); return -ENODEV; } switch (cmd) { case USBDEVFS_CONTROL: snoop(&dev->dev, "%s: CONTROL\n", __func__); ret = proc_control(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_BULK: snoop(&dev->dev, "%s: BULK\n", __func__); ret = proc_bulk(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_RESETEP: snoop(&dev->dev, "%s: RESETEP\n", __func__); ret = proc_resetep(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_RESET: snoop(&dev->dev, "%s: RESET\n", __func__); ret = proc_resetdevice(ps); break; case USBDEVFS_CLEAR_HALT: snoop(&dev->dev, "%s: CLEAR_HALT\n", __func__); ret = proc_clearhalt(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_GETDRIVER: snoop(&dev->dev, "%s: GETDRIVER\n", __func__); ret = proc_getdriver(ps, p); break; case USBDEVFS_CONNECTINFO: snoop(&dev->dev, "%s: CONNECTINFO\n", __func__); ret = proc_connectinfo(ps, p); break; case USBDEVFS_SETINTERFACE: snoop(&dev->dev, "%s: SETINTERFACE\n", __func__); ret = proc_setintf(ps, p); break; case USBDEVFS_SETCONFIGURATION: snoop(&dev->dev, "%s: SETCONFIGURATION\n", __func__); ret = proc_setconfig(ps, p); break; case USBDEVFS_SUBMITURB: snoop(&dev->dev, "%s: SUBMITURB\n", __func__); ret = proc_submiturb(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; #ifdef CONFIG_COMPAT case USBDEVFS_CONTROL32: snoop(&dev->dev, "%s: CONTROL32\n", __func__); ret = proc_control_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_BULK32: snoop(&dev->dev, "%s: BULK32\n", __func__); ret = proc_bulk_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_DISCSIGNAL32: snoop(&dev->dev, "%s: DISCSIGNAL32\n", __func__); ret = proc_disconnectsignal_compat(ps, p); break; case USBDEVFS_SUBMITURB32: snoop(&dev->dev, "%s: SUBMITURB32\n", __func__); ret = proc_submiturb_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_IOCTL32: snoop(&dev->dev, "%s: IOCTL32\n", __func__); ret = proc_ioctl_compat(ps, ptr_to_compat(p)); break; #endif case USBDEVFS_DISCARDURB: snoop(&dev->dev, "%s: DISCARDURB %p\n", __func__, p); ret = proc_unlinkurb(ps, p); break; case USBDEVFS_DISCSIGNAL: snoop(&dev->dev, "%s: DISCSIGNAL\n", __func__); ret = proc_disconnectsignal(ps, p); break; case USBDEVFS_CLAIMINTERFACE: snoop(&dev->dev, "%s: CLAIMINTERFACE\n", __func__); ret = proc_claiminterface(ps, p); break; case USBDEVFS_RELEASEINTERFACE: snoop(&dev->dev, "%s: RELEASEINTERFACE\n", __func__); ret = proc_releaseinterface(ps, p); break; case USBDEVFS_IOCTL: snoop(&dev->dev, "%s: IOCTL\n", __func__); ret = proc_ioctl_default(ps, p); break; case USBDEVFS_CLAIM_PORT: snoop(&dev->dev, "%s: CLAIM_PORT\n", __func__); ret = proc_claim_port(ps, p); break; case USBDEVFS_RELEASE_PORT: snoop(&dev->dev, "%s: RELEASE_PORT\n", __func__); ret = proc_release_port(ps, p); break; case USBDEVFS_GET_CAPABILITIES: ret = proc_get_capabilities(ps, p); break; case USBDEVFS_DISCONNECT_CLAIM: ret = proc_disconnect_claim(ps, p); break; case USBDEVFS_ALLOC_STREAMS: ret = proc_alloc_streams(ps, p); break; case USBDEVFS_FREE_STREAMS: ret = proc_free_streams(ps, p); break; case USBDEVFS_DROP_PRIVILEGES: ret = proc_drop_privileges(ps, p); break; } done: usb_unlock_device(dev); if (ret >= 0) inode->i_atime = CURRENT_TIME; return ret; } static long usbdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret; ret = usbdev_do_ioctl(file, cmd, (void __user *)arg); return ret; } #ifdef CONFIG_COMPAT static long usbdev_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret; ret = usbdev_do_ioctl(file, cmd, compat_ptr(arg)); return ret; } #endif /* No kernel lock - fine */ static unsigned int usbdev_poll(struct file *file, struct poll_table_struct *wait) { struct usb_dev_state *ps = file->private_data; unsigned int mask = 0; poll_wait(file, &ps->wait, wait); if (file->f_mode & FMODE_WRITE && !list_empty(&ps->async_completed)) mask |= POLLOUT | POLLWRNORM; if (!connected(ps)) mask |= POLLERR | POLLHUP; return mask; } const struct file_operations usbdev_file_operations = { .owner = THIS_MODULE, .llseek = no_seek_end_llseek, .read = usbdev_read, .poll = usbdev_poll, .unlocked_ioctl = usbdev_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = usbdev_compat_ioctl, #endif .mmap = usbdev_mmap, .open = usbdev_open, .release = usbdev_release, }; static void usbdev_remove(struct usb_device *udev) { struct usb_dev_state *ps; struct siginfo sinfo; while (!list_empty(&udev->filelist)) { ps = list_entry(udev->filelist.next, struct usb_dev_state, list); destroy_all_async(ps); wake_up_all(&ps->wait); list_del_init(&ps->list); if (ps->discsignr) { memset(&sinfo, 0, sizeof(sinfo)); sinfo.si_signo = ps->discsignr; sinfo.si_errno = EPIPE; sinfo.si_code = SI_ASYNCIO; sinfo.si_addr = ps->disccontext; kill_pid_info_as_cred(ps->discsignr, &sinfo, ps->disc_pid, ps->cred, ps->secid); } } } static int usbdev_notify(struct notifier_block *self, unsigned long action, void *dev) { switch (action) { case USB_DEVICE_ADD: break; case USB_DEVICE_REMOVE: usbdev_remove(dev); break; } return NOTIFY_OK; } static struct notifier_block usbdev_nb = { .notifier_call = usbdev_notify, }; static struct cdev usb_device_cdev; int __init usb_devio_init(void) { int retval; retval = register_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX, "usb_device"); if (retval) { printk(KERN_ERR "Unable to register minors for usb_device\n"); goto out; } cdev_init(&usb_device_cdev, &usbdev_file_operations); retval = cdev_add(&usb_device_cdev, USB_DEVICE_DEV, USB_DEVICE_MAX); if (retval) { printk(KERN_ERR "Unable to get usb_device major %d\n", USB_DEVICE_MAJOR); goto error_cdev; } usb_register_notify(&usbdev_nb); out: return retval; error_cdev: unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX); goto out; } void usb_devio_cleanup(void) { usb_unregister_notify(&usbdev_nb); cdev_del(&usb_device_cdev); unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5048_0
crossvul-cpp_data_bad_867_0
/* * Copyright (C) 2014-2018 Yubico AB - See COPYING */ /* Define which PAM interfaces we provide */ #define PAM_SM_AUTH /* Include PAM headers */ #include <security/pam_appl.h> #include <security/pam_modules.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <syslog.h> #include <pwd.h> #include <string.h> #include <errno.h> #include "util.h" /* If secure_getenv is not defined, define it here */ #ifndef HAVE_SECURE_GETENV char *secure_getenv(const char *); char *secure_getenv(const char *name) { (void)name; return NULL; } #endif static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) { int i; memset(cfg, 0, sizeof(cfg_t)); cfg->debug_file = stderr; for (i = 0; i < argc; i++) { if (strncmp(argv[i], "max_devices=", 12) == 0) sscanf(argv[i], "max_devices=%u", &cfg->max_devs); if (strcmp(argv[i], "manual") == 0) cfg->manual = 1; if (strcmp(argv[i], "debug") == 0) cfg->debug = 1; if (strcmp(argv[i], "nouserok") == 0) cfg->nouserok = 1; if (strcmp(argv[i], "openasuser") == 0) cfg->openasuser = 1; if (strcmp(argv[i], "alwaysok") == 0) cfg->alwaysok = 1; if (strcmp(argv[i], "interactive") == 0) cfg->interactive = 1; if (strcmp(argv[i], "cue") == 0) cfg->cue = 1; if (strcmp(argv[i], "nodetect") == 0) cfg->nodetect = 1; if (strncmp(argv[i], "authfile=", 9) == 0) cfg->auth_file = argv[i] + 9; if (strncmp(argv[i], "authpending_file=", 17) == 0) cfg->authpending_file = argv[i] + 17; if (strncmp(argv[i], "origin=", 7) == 0) cfg->origin = argv[i] + 7; if (strncmp(argv[i], "appid=", 6) == 0) cfg->appid = argv[i] + 6; if (strncmp(argv[i], "prompt=", 7) == 0) cfg->prompt = argv[i] + 7; if (strncmp (argv[i], "debug_file=", 11) == 0) { const char *filename = argv[i] + 11; if(strncmp (filename, "stdout", 6) == 0) { cfg->debug_file = stdout; } else if(strncmp (filename, "stderr", 6) == 0) { cfg->debug_file = stderr; } else if( strncmp (filename, "syslog", 6) == 0) { cfg->debug_file = (FILE *)-1; } else { struct stat st; FILE *file; if(lstat(filename, &st) == 0) { if(S_ISREG(st.st_mode)) { file = fopen(filename, "a"); if(file != NULL) { cfg->debug_file = file; } } } } } } if (cfg->debug) { D(cfg->debug_file, "called."); D(cfg->debug_file, "flags %d argc %d", flags, argc); for (i = 0; i < argc; i++) { D(cfg->debug_file, "argv[%d]=%s", i, argv[i]); } D(cfg->debug_file, "max_devices=%d", cfg->max_devs); D(cfg->debug_file, "debug=%d", cfg->debug); D(cfg->debug_file, "interactive=%d", cfg->interactive); D(cfg->debug_file, "cue=%d", cfg->cue); D(cfg->debug_file, "nodetect=%d", cfg->nodetect); D(cfg->debug_file, "manual=%d", cfg->manual); D(cfg->debug_file, "nouserok=%d", cfg->nouserok); D(cfg->debug_file, "openasuser=%d", cfg->openasuser); D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok); D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)"); D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)"); D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)"); D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)"); D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)"); } } #ifdef DBG #undef DBG #endif #define DBG(...) \ if (cfg->debug) { \ D(cfg->debug_file, __VA_ARGS__); \ } /* PAM entry point for authentication verification */ int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) { struct passwd *pw = NULL, pw_s; const char *user = NULL; cfg_t cfg_st; cfg_t *cfg = &cfg_st; char buffer[BUFSIZE]; char *buf = NULL; char *authfile_dir; size_t authfile_dir_len; int pgu_ret, gpn_ret; int retval = PAM_IGNORE; device_t *devices = NULL; unsigned n_devices = 0; int openasuser; int should_free_origin = 0; int should_free_appid = 0; int should_free_auth_file = 0; int should_free_authpending_file = 0; parse_cfg(flags, argc, argv, cfg); if (!cfg->origin) { strcpy(buffer, DEFAULT_ORIGIN_PREFIX); if (gethostname(buffer + strlen(DEFAULT_ORIGIN_PREFIX), BUFSIZE - strlen(DEFAULT_ORIGIN_PREFIX)) == -1) { DBG("Unable to get host name"); goto done; } DBG("Origin not specified, using \"%s\"", buffer); cfg->origin = strdup(buffer); if (!cfg->origin) { DBG("Unable to allocate memory"); goto done; } else { should_free_origin = 1; } } if (!cfg->appid) { DBG("Appid not specified, using the same value of origin (%s)", cfg->origin); cfg->appid = strdup(cfg->origin); if (!cfg->appid) { DBG("Unable to allocate memory") goto done; } else { should_free_appid = 1; } } if (cfg->max_devs == 0) { DBG("Maximum devices number not set. Using default (%d)", MAX_DEVS); cfg->max_devs = MAX_DEVS; } devices = malloc(sizeof(device_t) * cfg->max_devs); if (!devices) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } pgu_ret = pam_get_user(pamh, &user, NULL); if (pgu_ret != PAM_SUCCESS || user == NULL) { DBG("Unable to access user %s", user); retval = PAM_CONV_ERR; goto done; } DBG("Requesting authentication for user %s", user); gpn_ret = getpwnam_r(user, &pw_s, buffer, sizeof(buffer), &pw); if (gpn_ret != 0 || pw == NULL || pw->pw_dir == NULL || pw->pw_dir[0] != '/') { DBG("Unable to retrieve credentials for user %s, (%s)", user, strerror(errno)); retval = PAM_USER_UNKNOWN; goto done; } DBG("Found user %s", user); DBG("Home directory for %s is %s", user, pw->pw_dir); if (!cfg->auth_file) { buf = NULL; authfile_dir = secure_getenv(DEFAULT_AUTHFILE_DIR_VAR); if (!authfile_dir) { DBG("Variable %s is not set. Using default value ($HOME/.config/)", DEFAULT_AUTHFILE_DIR_VAR); authfile_dir_len = strlen(pw->pw_dir) + strlen("/.config") + strlen(DEFAULT_AUTHFILE) + 1; buf = malloc(sizeof(char) * (authfile_dir_len)); if (!buf) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } snprintf(buf, authfile_dir_len, "%s/.config%s", pw->pw_dir, DEFAULT_AUTHFILE); } else { DBG("Variable %s set to %s", DEFAULT_AUTHFILE_DIR_VAR, authfile_dir); authfile_dir_len = strlen(authfile_dir) + strlen(DEFAULT_AUTHFILE) + 1; buf = malloc(sizeof(char) * (authfile_dir_len)); if (!buf) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } snprintf(buf, authfile_dir_len, "%s%s", authfile_dir, DEFAULT_AUTHFILE); } DBG("Using default authentication file %s", buf); cfg->auth_file = buf; /* cfg takes ownership */ should_free_auth_file = 1; buf = NULL; } else { DBG("Using authentication file %s", cfg->auth_file); } openasuser = geteuid() == 0 && cfg->openasuser; if (openasuser) { if (seteuid(pw_s.pw_uid)) { DBG("Unable to switch user to uid %i", pw_s.pw_uid); retval = PAM_IGNORE; goto done; } DBG("Switched to uid %i", pw_s.pw_uid); } retval = get_devices_from_authfile(cfg->auth_file, user, cfg->max_devs, cfg->debug, cfg->debug_file, devices, &n_devices); if (openasuser) { if (seteuid(0)) { DBG("Unable to switch back to uid 0"); retval = PAM_IGNORE; goto done; } DBG("Switched back to uid 0"); } if (retval != 1) { // for nouserok; make sure errors in get_devices_from_authfile don't // result in valid devices n_devices = 0; } if (n_devices == 0) { if (cfg->nouserok) { DBG("Found no devices but nouserok specified. Skipping authentication"); retval = PAM_SUCCESS; goto done; } else if (retval != 1) { DBG("Unable to get devices from file %s", cfg->auth_file); retval = PAM_AUTHINFO_UNAVAIL; goto done; } else { DBG("Found no devices. Aborting."); retval = PAM_AUTHINFO_UNAVAIL; goto done; } } // Determine the full path for authpending_file in order to emit touch request notifications if (!cfg->authpending_file) { int actual_size = snprintf(buffer, BUFSIZE, DEFAULT_AUTHPENDING_FILE_PATH, getuid()); if (actual_size >= 0 && actual_size < BUFSIZE) { cfg->authpending_file = strdup(buffer); } if (!cfg->authpending_file) { DBG("Unable to allocate memory for the authpending_file, touch request notifications will not be emitted"); } else { should_free_authpending_file = 1; } } else { if (strlen(cfg->authpending_file) == 0) { DBG("authpending_file is set to an empty value, touch request notifications will be disabled"); cfg->authpending_file = NULL; } } int authpending_file_descriptor = -1; if (cfg->authpending_file) { DBG("Using file '%s' for emitting touch request notifications", cfg->authpending_file); // Open (or create) the authpending_file to indicate that we start waiting for a touch authpending_file_descriptor = open(cfg->authpending_file, O_RDONLY | O_CREAT, 0664); if (authpending_file_descriptor < 0) { DBG("Unable to emit 'authentication started' notification by opening the file '%s', (%s)", cfg->authpending_file, strerror(errno)); } } if (cfg->manual == 0) { if (cfg->interactive) { converse(pamh, PAM_PROMPT_ECHO_ON, cfg->prompt != NULL ? cfg->prompt : DEFAULT_PROMPT); } retval = do_authentication(cfg, devices, n_devices, pamh); } else { retval = do_manual_authentication(cfg, devices, n_devices, pamh); } // Close the authpending_file to indicate that we stop waiting for a touch if (authpending_file_descriptor >= 0) { if (close(authpending_file_descriptor) < 0) { DBG("Unable to emit 'authentication stopped' notification by closing the file '%s', (%s)", cfg->authpending_file, strerror(errno)); } } if (retval != 1) { DBG("do_authentication returned %d", retval); retval = PAM_AUTH_ERR; goto done; } retval = PAM_SUCCESS; done: free_devices(devices, n_devices); if (buf) { free(buf); buf = NULL; } if (should_free_origin) { free((char *) cfg->origin); cfg->origin = NULL; } if (should_free_appid) { free((char *) cfg->appid); cfg->appid = NULL; } if (should_free_auth_file) { free((char *) cfg->auth_file); cfg->auth_file = NULL; } if (should_free_authpending_file) { free((char *) cfg->authpending_file); cfg->authpending_file = NULL; } if (cfg->alwaysok && retval != PAM_SUCCESS) { DBG("alwaysok needed (otherwise return with %d)", retval); retval = PAM_SUCCESS; } DBG("done. [%s]", pam_strerror(pamh, retval)); return retval; } PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) { (void)pamh; (void)flags; (void)argc; (void)argv; return PAM_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_867_0
crossvul-cpp_data_good_368_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/good_368_0
crossvul-cpp_data_good_3837_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 TTY. */ #include <linux/module.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/rfcomm.h> #define RFCOMM_TTY_MAGIC 0x6d02 /* magic number for rfcomm struct */ #define RFCOMM_TTY_PORTS RFCOMM_MAX_DEV /* whole lotta rfcomm devices */ #define RFCOMM_TTY_MAJOR 216 /* device node major id of the usb/bluetooth.c driver */ #define RFCOMM_TTY_MINOR 0 static struct tty_driver *rfcomm_tty_driver; struct rfcomm_dev { struct tty_port port; struct list_head list; char name[12]; int id; unsigned long flags; int err; bdaddr_t src; bdaddr_t dst; u8 channel; uint modem_status; struct rfcomm_dlc *dlc; wait_queue_head_t wait; struct device *tty_dev; atomic_t wmem_alloc; struct sk_buff_head pending; }; static LIST_HEAD(rfcomm_dev_list); static DEFINE_SPINLOCK(rfcomm_dev_lock); static void rfcomm_dev_data_ready(struct rfcomm_dlc *dlc, struct sk_buff *skb); static void rfcomm_dev_state_change(struct rfcomm_dlc *dlc, int err); static void rfcomm_dev_modem_status(struct rfcomm_dlc *dlc, u8 v24_sig); /* ---- Device functions ---- */ /* * The reason this isn't actually a race, as you no doubt have a little voice * screaming at you in your head, is that the refcount should never actually * reach zero unless the device has already been taken off the list, in * rfcomm_dev_del(). And if that's not true, we'll hit the BUG() in * rfcomm_dev_destruct() anyway. */ static void rfcomm_dev_destruct(struct tty_port *port) { struct rfcomm_dev *dev = container_of(port, struct rfcomm_dev, port); struct rfcomm_dlc *dlc = dev->dlc; BT_DBG("dev %p dlc %p", dev, dlc); /* Refcount should only hit zero when called from rfcomm_dev_del() which will have taken us off the list. Everything else are refcounting bugs. */ BUG_ON(!list_empty(&dev->list)); rfcomm_dlc_lock(dlc); /* Detach DLC if it's owned by this dev */ if (dlc->owner == dev) dlc->owner = NULL; rfcomm_dlc_unlock(dlc); rfcomm_dlc_put(dlc); tty_unregister_device(rfcomm_tty_driver, dev->id); kfree(dev); /* It's safe to call module_put() here because socket still holds reference to this module. */ module_put(THIS_MODULE); } static const struct tty_port_operations rfcomm_port_ops = { .destruct = rfcomm_dev_destruct, }; static struct rfcomm_dev *__rfcomm_dev_get(int id) { struct rfcomm_dev *dev; list_for_each_entry(dev, &rfcomm_dev_list, list) if (dev->id == id) return dev; return NULL; } static struct rfcomm_dev *rfcomm_dev_get(int id) { struct rfcomm_dev *dev; spin_lock(&rfcomm_dev_lock); dev = __rfcomm_dev_get(id); if (dev) { if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags)) dev = NULL; else tty_port_get(&dev->port); } spin_unlock(&rfcomm_dev_lock); return dev; } static struct device *rfcomm_get_device(struct rfcomm_dev *dev) { struct hci_dev *hdev; struct hci_conn *conn; hdev = hci_get_route(&dev->dst, &dev->src); if (!hdev) return NULL; conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &dev->dst); hci_dev_put(hdev); return conn ? &conn->dev : NULL; } static ssize_t show_address(struct device *tty_dev, struct device_attribute *attr, char *buf) { struct rfcomm_dev *dev = dev_get_drvdata(tty_dev); return sprintf(buf, "%s\n", batostr(&dev->dst)); } static ssize_t show_channel(struct device *tty_dev, struct device_attribute *attr, char *buf) { struct rfcomm_dev *dev = dev_get_drvdata(tty_dev); return sprintf(buf, "%d\n", dev->channel); } static DEVICE_ATTR(address, S_IRUGO, show_address, NULL); static DEVICE_ATTR(channel, S_IRUGO, show_channel, NULL); static int rfcomm_dev_add(struct rfcomm_dev_req *req, struct rfcomm_dlc *dlc) { struct rfcomm_dev *dev, *entry; struct list_head *head = &rfcomm_dev_list; int err = 0; BT_DBG("id %d channel %d", req->dev_id, req->channel); dev = kzalloc(sizeof(struct rfcomm_dev), GFP_KERNEL); if (!dev) return -ENOMEM; spin_lock(&rfcomm_dev_lock); if (req->dev_id < 0) { dev->id = 0; list_for_each_entry(entry, &rfcomm_dev_list, list) { if (entry->id != dev->id) break; dev->id++; head = &entry->list; } } else { dev->id = req->dev_id; list_for_each_entry(entry, &rfcomm_dev_list, list) { if (entry->id == dev->id) { err = -EADDRINUSE; goto out; } if (entry->id > dev->id - 1) break; head = &entry->list; } } if ((dev->id < 0) || (dev->id > RFCOMM_MAX_DEV - 1)) { err = -ENFILE; goto out; } sprintf(dev->name, "rfcomm%d", dev->id); list_add(&dev->list, head); bacpy(&dev->src, &req->src); bacpy(&dev->dst, &req->dst); dev->channel = req->channel; dev->flags = req->flags & ((1 << RFCOMM_RELEASE_ONHUP) | (1 << RFCOMM_REUSE_DLC)); tty_port_init(&dev->port); dev->port.ops = &rfcomm_port_ops; init_waitqueue_head(&dev->wait); skb_queue_head_init(&dev->pending); rfcomm_dlc_lock(dlc); if (req->flags & (1 << RFCOMM_REUSE_DLC)) { struct sock *sk = dlc->owner; struct sk_buff *skb; BUG_ON(!sk); rfcomm_dlc_throttle(dlc); while ((skb = skb_dequeue(&sk->sk_receive_queue))) { skb_orphan(skb); skb_queue_tail(&dev->pending, skb); atomic_sub(skb->len, &sk->sk_rmem_alloc); } } dlc->data_ready = rfcomm_dev_data_ready; dlc->state_change = rfcomm_dev_state_change; dlc->modem_status = rfcomm_dev_modem_status; dlc->owner = dev; dev->dlc = dlc; rfcomm_dev_modem_status(dlc, dlc->remote_v24_sig); rfcomm_dlc_unlock(dlc); /* It's safe to call __module_get() here because socket already holds reference to this module. */ __module_get(THIS_MODULE); out: spin_unlock(&rfcomm_dev_lock); if (err < 0) goto free; dev->tty_dev = tty_register_device(rfcomm_tty_driver, dev->id, NULL); if (IS_ERR(dev->tty_dev)) { err = PTR_ERR(dev->tty_dev); list_del(&dev->list); goto free; } dev_set_drvdata(dev->tty_dev, dev); if (device_create_file(dev->tty_dev, &dev_attr_address) < 0) BT_ERR("Failed to create address attribute"); if (device_create_file(dev->tty_dev, &dev_attr_channel) < 0) BT_ERR("Failed to create channel attribute"); return dev->id; free: kfree(dev); return err; } static void rfcomm_dev_del(struct rfcomm_dev *dev) { unsigned long flags; BT_DBG("dev %p", dev); BUG_ON(test_and_set_bit(RFCOMM_TTY_RELEASED, &dev->flags)); spin_lock_irqsave(&dev->port.lock, flags); if (dev->port.count > 0) { spin_unlock_irqrestore(&dev->port.lock, flags); return; } spin_unlock_irqrestore(&dev->port.lock, flags); spin_lock(&rfcomm_dev_lock); list_del_init(&dev->list); spin_unlock(&rfcomm_dev_lock); tty_port_put(&dev->port); } /* ---- Send buffer ---- */ static inline unsigned int rfcomm_room(struct rfcomm_dlc *dlc) { /* We can't let it be zero, because we don't get a callback when tx_credits becomes nonzero, hence we'd never wake up */ return dlc->mtu * (dlc->tx_credits?:1); } static void rfcomm_wfree(struct sk_buff *skb) { struct rfcomm_dev *dev = (void *) skb->sk; struct tty_struct *tty = dev->port.tty; atomic_sub(skb->truesize, &dev->wmem_alloc); if (test_bit(RFCOMM_TTY_ATTACHED, &dev->flags) && tty) tty_wakeup(tty); tty_port_put(&dev->port); } static void rfcomm_set_owner_w(struct sk_buff *skb, struct rfcomm_dev *dev) { tty_port_get(&dev->port); atomic_add(skb->truesize, &dev->wmem_alloc); skb->sk = (void *) dev; skb->destructor = rfcomm_wfree; } static struct sk_buff *rfcomm_wmalloc(struct rfcomm_dev *dev, unsigned long size, gfp_t priority) { if (atomic_read(&dev->wmem_alloc) < rfcomm_room(dev->dlc)) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { rfcomm_set_owner_w(skb, dev); return skb; } } return NULL; } /* ---- Device IOCTLs ---- */ #define NOCAP_FLAGS ((1 << RFCOMM_REUSE_DLC) | (1 << RFCOMM_RELEASE_ONHUP)) static int rfcomm_create_dev(struct sock *sk, void __user *arg) { struct rfcomm_dev_req req; struct rfcomm_dlc *dlc; int id; if (copy_from_user(&req, arg, sizeof(req))) return -EFAULT; BT_DBG("sk %p dev_id %d flags 0x%x", sk, req.dev_id, req.flags); if (req.flags != NOCAP_FLAGS && !capable(CAP_NET_ADMIN)) return -EPERM; if (req.flags & (1 << RFCOMM_REUSE_DLC)) { /* Socket must be connected */ if (sk->sk_state != BT_CONNECTED) return -EBADFD; dlc = rfcomm_pi(sk)->dlc; rfcomm_dlc_hold(dlc); } else { dlc = rfcomm_dlc_alloc(GFP_KERNEL); if (!dlc) return -ENOMEM; } id = rfcomm_dev_add(&req, dlc); if (id < 0) { rfcomm_dlc_put(dlc); return id; } if (req.flags & (1 << RFCOMM_REUSE_DLC)) { /* DLC is now used by device. * Socket must be disconnected */ sk->sk_state = BT_CLOSED; } return id; } static int rfcomm_release_dev(void __user *arg) { struct rfcomm_dev_req req; struct rfcomm_dev *dev; if (copy_from_user(&req, arg, sizeof(req))) return -EFAULT; BT_DBG("dev_id %d flags 0x%x", req.dev_id, req.flags); dev = rfcomm_dev_get(req.dev_id); if (!dev) return -ENODEV; if (dev->flags != NOCAP_FLAGS && !capable(CAP_NET_ADMIN)) { tty_port_put(&dev->port); return -EPERM; } if (req.flags & (1 << RFCOMM_HANGUP_NOW)) rfcomm_dlc_close(dev->dlc, 0); /* Shut down TTY synchronously before freeing rfcomm_dev */ if (dev->port.tty) tty_vhangup(dev->port.tty); if (!test_bit(RFCOMM_RELEASE_ONHUP, &dev->flags)) rfcomm_dev_del(dev); tty_port_put(&dev->port); return 0; } static int rfcomm_get_dev_list(void __user *arg) { struct rfcomm_dev *dev; struct rfcomm_dev_list_req *dl; struct rfcomm_dev_info *di; int n = 0, size, err; u16 dev_num; BT_DBG(""); if (get_user(dev_num, (u16 __user *) arg)) return -EFAULT; if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di)) return -EINVAL; size = sizeof(*dl) + dev_num * sizeof(*di); dl = kzalloc(size, GFP_KERNEL); if (!dl) return -ENOMEM; di = dl->dev_info; spin_lock(&rfcomm_dev_lock); list_for_each_entry(dev, &rfcomm_dev_list, list) { if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags)) continue; (di + n)->id = dev->id; (di + n)->flags = dev->flags; (di + n)->state = dev->dlc->state; (di + n)->channel = dev->channel; bacpy(&(di + n)->src, &dev->src); bacpy(&(di + n)->dst, &dev->dst); if (++n >= dev_num) break; } spin_unlock(&rfcomm_dev_lock); dl->dev_num = n; size = sizeof(*dl) + n * sizeof(*di); err = copy_to_user(arg, dl, size); kfree(dl); return err ? -EFAULT : 0; } static int rfcomm_get_dev_info(void __user *arg) { struct rfcomm_dev *dev; struct rfcomm_dev_info di; int err = 0; BT_DBG(""); if (copy_from_user(&di, arg, sizeof(di))) return -EFAULT; dev = rfcomm_dev_get(di.id); if (!dev) return -ENODEV; di.flags = dev->flags; di.channel = dev->channel; di.state = dev->dlc->state; bacpy(&di.src, &dev->src); bacpy(&di.dst, &dev->dst); if (copy_to_user(arg, &di, sizeof(di))) err = -EFAULT; tty_port_put(&dev->port); return err; } int rfcomm_dev_ioctl(struct sock *sk, unsigned int cmd, void __user *arg) { BT_DBG("cmd %d arg %p", cmd, arg); switch (cmd) { case RFCOMMCREATEDEV: return rfcomm_create_dev(sk, arg); case RFCOMMRELEASEDEV: return rfcomm_release_dev(arg); case RFCOMMGETDEVLIST: return rfcomm_get_dev_list(arg); case RFCOMMGETDEVINFO: return rfcomm_get_dev_info(arg); } return -EINVAL; } /* ---- DLC callbacks ---- */ static void rfcomm_dev_data_ready(struct rfcomm_dlc *dlc, struct sk_buff *skb) { struct rfcomm_dev *dev = dlc->owner; struct tty_struct *tty; if (!dev) { kfree_skb(skb); return; } tty = dev->port.tty; if (!tty || !skb_queue_empty(&dev->pending)) { skb_queue_tail(&dev->pending, skb); return; } BT_DBG("dlc %p tty %p len %d", dlc, tty, skb->len); tty_insert_flip_string(tty, skb->data, skb->len); tty_flip_buffer_push(tty); kfree_skb(skb); } static void rfcomm_dev_state_change(struct rfcomm_dlc *dlc, int err) { struct rfcomm_dev *dev = dlc->owner; if (!dev) return; BT_DBG("dlc %p dev %p err %d", dlc, dev, err); dev->err = err; wake_up_interruptible(&dev->wait); if (dlc->state == BT_CLOSED) { if (!dev->port.tty) { if (test_bit(RFCOMM_RELEASE_ONHUP, &dev->flags)) { /* Drop DLC lock here to avoid deadlock * 1. rfcomm_dev_get will take rfcomm_dev_lock * but in rfcomm_dev_add there's lock order: * rfcomm_dev_lock -> dlc lock * 2. tty_port_put will deadlock if it's * the last reference */ rfcomm_dlc_unlock(dlc); if (rfcomm_dev_get(dev->id) == NULL) { rfcomm_dlc_lock(dlc); return; } rfcomm_dev_del(dev); tty_port_put(&dev->port); rfcomm_dlc_lock(dlc); } } else tty_hangup(dev->port.tty); } } static void rfcomm_dev_modem_status(struct rfcomm_dlc *dlc, u8 v24_sig) { struct rfcomm_dev *dev = dlc->owner; if (!dev) return; BT_DBG("dlc %p dev %p v24_sig 0x%02x", dlc, dev, v24_sig); if ((dev->modem_status & TIOCM_CD) && !(v24_sig & RFCOMM_V24_DV)) { if (dev->port.tty && !C_CLOCAL(dev->port.tty)) tty_hangup(dev->port.tty); } dev->modem_status = ((v24_sig & RFCOMM_V24_RTC) ? (TIOCM_DSR | TIOCM_DTR) : 0) | ((v24_sig & RFCOMM_V24_RTR) ? (TIOCM_RTS | TIOCM_CTS) : 0) | ((v24_sig & RFCOMM_V24_IC) ? TIOCM_RI : 0) | ((v24_sig & RFCOMM_V24_DV) ? TIOCM_CD : 0); } /* ---- TTY functions ---- */ static void rfcomm_tty_copy_pending(struct rfcomm_dev *dev) { struct tty_struct *tty = dev->port.tty; struct sk_buff *skb; int inserted = 0; if (!tty) return; BT_DBG("dev %p tty %p", dev, tty); rfcomm_dlc_lock(dev->dlc); while ((skb = skb_dequeue(&dev->pending))) { inserted += tty_insert_flip_string(tty, skb->data, skb->len); kfree_skb(skb); } rfcomm_dlc_unlock(dev->dlc); if (inserted > 0) tty_flip_buffer_push(tty); } static int rfcomm_tty_open(struct tty_struct *tty, struct file *filp) { DECLARE_WAITQUEUE(wait, current); struct rfcomm_dev *dev; struct rfcomm_dlc *dlc; unsigned long flags; int err, id; id = tty->index; BT_DBG("tty %p id %d", tty, id); /* We don't leak this refcount. For reasons which are not entirely clear, the TTY layer will call our ->close() method even if the open fails. We decrease the refcount there, and decreasing it here too would cause breakage. */ dev = rfcomm_dev_get(id); if (!dev) return -ENODEV; BT_DBG("dev %p dst %s channel %d opened %d", dev, batostr(&dev->dst), dev->channel, dev->port.count); spin_lock_irqsave(&dev->port.lock, flags); if (++dev->port.count > 1) { spin_unlock_irqrestore(&dev->port.lock, flags); return 0; } spin_unlock_irqrestore(&dev->port.lock, flags); dlc = dev->dlc; /* Attach TTY and open DLC */ rfcomm_dlc_lock(dlc); tty->driver_data = dev; dev->port.tty = tty; rfcomm_dlc_unlock(dlc); set_bit(RFCOMM_TTY_ATTACHED, &dev->flags); err = rfcomm_dlc_open(dlc, &dev->src, &dev->dst, dev->channel); if (err < 0) return err; /* Wait for DLC to connect */ add_wait_queue(&dev->wait, &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (dlc->state == BT_CLOSED) { err = -dev->err; break; } if (dlc->state == BT_CONNECTED) break; if (signal_pending(current)) { err = -EINTR; break; } tty_unlock(); schedule(); tty_lock(); } set_current_state(TASK_RUNNING); remove_wait_queue(&dev->wait, &wait); if (err == 0) device_move(dev->tty_dev, rfcomm_get_device(dev), DPM_ORDER_DEV_AFTER_PARENT); rfcomm_tty_copy_pending(dev); rfcomm_dlc_unthrottle(dev->dlc); return err; } static void rfcomm_tty_close(struct tty_struct *tty, struct file *filp) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; unsigned long flags; if (!dev) return; BT_DBG("tty %p dev %p dlc %p opened %d", tty, dev, dev->dlc, dev->port.count); spin_lock_irqsave(&dev->port.lock, flags); if (!--dev->port.count) { spin_unlock_irqrestore(&dev->port.lock, flags); if (dev->tty_dev->parent) device_move(dev->tty_dev, NULL, DPM_ORDER_DEV_LAST); /* Close DLC and dettach TTY */ rfcomm_dlc_close(dev->dlc, 0); clear_bit(RFCOMM_TTY_ATTACHED, &dev->flags); rfcomm_dlc_lock(dev->dlc); tty->driver_data = NULL; dev->port.tty = NULL; rfcomm_dlc_unlock(dev->dlc); if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags)) { spin_lock(&rfcomm_dev_lock); list_del_init(&dev->list); spin_unlock(&rfcomm_dev_lock); tty_port_put(&dev->port); } } else spin_unlock_irqrestore(&dev->port.lock, flags); tty_port_put(&dev->port); } static int rfcomm_tty_write(struct tty_struct *tty, const unsigned char *buf, int count) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; struct rfcomm_dlc *dlc = dev->dlc; struct sk_buff *skb; int err = 0, sent = 0, size; BT_DBG("tty %p count %d", tty, count); while (count) { size = min_t(uint, count, dlc->mtu); skb = rfcomm_wmalloc(dev, size + RFCOMM_SKB_RESERVE, GFP_ATOMIC); if (!skb) break; skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE); memcpy(skb_put(skb, size), buf + sent, size); err = rfcomm_dlc_send(dlc, skb); if (err < 0) { kfree_skb(skb); break; } sent += size; count -= size; } return sent ? sent : err; } static int rfcomm_tty_write_room(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; int room; BT_DBG("tty %p", tty); if (!dev || !dev->dlc) return 0; room = rfcomm_room(dev->dlc) - atomic_read(&dev->wmem_alloc); if (room < 0) room = 0; return room; } static int rfcomm_tty_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { BT_DBG("tty %p cmd 0x%02x", tty, cmd); switch (cmd) { case TCGETS: BT_DBG("TCGETS is not supported"); return -ENOIOCTLCMD; case TCSETS: BT_DBG("TCSETS is not supported"); return -ENOIOCTLCMD; case TIOCMIWAIT: BT_DBG("TIOCMIWAIT"); break; case TIOCGSERIAL: BT_ERR("TIOCGSERIAL is not supported"); return -ENOIOCTLCMD; case TIOCSSERIAL: BT_ERR("TIOCSSERIAL is not supported"); return -ENOIOCTLCMD; case TIOCSERGSTRUCT: BT_ERR("TIOCSERGSTRUCT is not supported"); return -ENOIOCTLCMD; case TIOCSERGETLSR: BT_ERR("TIOCSERGETLSR is not supported"); return -ENOIOCTLCMD; case TIOCSERCONFIG: BT_ERR("TIOCSERCONFIG is not supported"); return -ENOIOCTLCMD; default: return -ENOIOCTLCMD; /* ioctls which we must ignore */ } return -ENOIOCTLCMD; } static void rfcomm_tty_set_termios(struct tty_struct *tty, struct ktermios *old) { struct ktermios *new = tty->termios; int old_baud_rate = tty_termios_baud_rate(old); int new_baud_rate = tty_termios_baud_rate(new); u8 baud, data_bits, stop_bits, parity, x_on, x_off; u16 changes = 0; struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p termios %p", tty, old); if (!dev || !dev->dlc || !dev->dlc->session) return; /* Handle turning off CRTSCTS */ if ((old->c_cflag & CRTSCTS) && !(new->c_cflag & CRTSCTS)) BT_DBG("Turning off CRTSCTS unsupported"); /* Parity on/off and when on, odd/even */ if (((old->c_cflag & PARENB) != (new->c_cflag & PARENB)) || ((old->c_cflag & PARODD) != (new->c_cflag & PARODD))) { changes |= RFCOMM_RPN_PM_PARITY; BT_DBG("Parity change detected."); } /* Mark and space parity are not supported! */ if (new->c_cflag & PARENB) { if (new->c_cflag & PARODD) { BT_DBG("Parity is ODD"); parity = RFCOMM_RPN_PARITY_ODD; } else { BT_DBG("Parity is EVEN"); parity = RFCOMM_RPN_PARITY_EVEN; } } else { BT_DBG("Parity is OFF"); parity = RFCOMM_RPN_PARITY_NONE; } /* Setting the x_on / x_off characters */ if (old->c_cc[VSTOP] != new->c_cc[VSTOP]) { BT_DBG("XOFF custom"); x_on = new->c_cc[VSTOP]; changes |= RFCOMM_RPN_PM_XON; } else { BT_DBG("XOFF default"); x_on = RFCOMM_RPN_XON_CHAR; } if (old->c_cc[VSTART] != new->c_cc[VSTART]) { BT_DBG("XON custom"); x_off = new->c_cc[VSTART]; changes |= RFCOMM_RPN_PM_XOFF; } else { BT_DBG("XON default"); x_off = RFCOMM_RPN_XOFF_CHAR; } /* Handle setting of stop bits */ if ((old->c_cflag & CSTOPB) != (new->c_cflag & CSTOPB)) changes |= RFCOMM_RPN_PM_STOP; /* POSIX does not support 1.5 stop bits and RFCOMM does not * support 2 stop bits. So a request for 2 stop bits gets * translated to 1.5 stop bits */ if (new->c_cflag & CSTOPB) stop_bits = RFCOMM_RPN_STOP_15; else stop_bits = RFCOMM_RPN_STOP_1; /* Handle number of data bits [5-8] */ if ((old->c_cflag & CSIZE) != (new->c_cflag & CSIZE)) changes |= RFCOMM_RPN_PM_DATA; switch (new->c_cflag & CSIZE) { case CS5: data_bits = RFCOMM_RPN_DATA_5; break; case CS6: data_bits = RFCOMM_RPN_DATA_6; break; case CS7: data_bits = RFCOMM_RPN_DATA_7; break; case CS8: data_bits = RFCOMM_RPN_DATA_8; break; default: data_bits = RFCOMM_RPN_DATA_8; break; } /* Handle baudrate settings */ if (old_baud_rate != new_baud_rate) changes |= RFCOMM_RPN_PM_BITRATE; switch (new_baud_rate) { case 2400: baud = RFCOMM_RPN_BR_2400; break; case 4800: baud = RFCOMM_RPN_BR_4800; break; case 7200: baud = RFCOMM_RPN_BR_7200; break; case 9600: baud = RFCOMM_RPN_BR_9600; break; case 19200: baud = RFCOMM_RPN_BR_19200; break; case 38400: baud = RFCOMM_RPN_BR_38400; break; case 57600: baud = RFCOMM_RPN_BR_57600; break; case 115200: baud = RFCOMM_RPN_BR_115200; break; case 230400: baud = RFCOMM_RPN_BR_230400; break; default: /* 9600 is standard accordinag to the RFCOMM specification */ baud = RFCOMM_RPN_BR_9600; break; } if (changes) rfcomm_send_rpn(dev->dlc->session, 1, dev->dlc->dlci, baud, data_bits, stop_bits, parity, RFCOMM_RPN_FLOW_NONE, x_on, x_off, changes); } static void rfcomm_tty_throttle(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p dev %p", tty, dev); rfcomm_dlc_throttle(dev->dlc); } static void rfcomm_tty_unthrottle(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p dev %p", tty, dev); rfcomm_dlc_unthrottle(dev->dlc); } static int rfcomm_tty_chars_in_buffer(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p dev %p", tty, dev); if (!dev || !dev->dlc) return 0; if (!skb_queue_empty(&dev->dlc->tx_queue)) return dev->dlc->mtu; return 0; } static void rfcomm_tty_flush_buffer(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p dev %p", tty, dev); if (!dev || !dev->dlc) return; skb_queue_purge(&dev->dlc->tx_queue); tty_wakeup(tty); } static void rfcomm_tty_send_xchar(struct tty_struct *tty, char ch) { BT_DBG("tty %p ch %c", tty, ch); } static void rfcomm_tty_wait_until_sent(struct tty_struct *tty, int timeout) { BT_DBG("tty %p timeout %d", tty, timeout); } static void rfcomm_tty_hangup(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p dev %p", tty, dev); if (!dev) return; rfcomm_tty_flush_buffer(tty); if (test_bit(RFCOMM_RELEASE_ONHUP, &dev->flags)) { if (rfcomm_dev_get(dev->id) == NULL) return; rfcomm_dev_del(dev); tty_port_put(&dev->port); } } static int rfcomm_tty_tiocmget(struct tty_struct *tty) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p dev %p", tty, dev); return dev->modem_status; } static int rfcomm_tty_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; struct rfcomm_dlc *dlc = dev->dlc; u8 v24_sig; BT_DBG("tty %p dev %p set 0x%02x clear 0x%02x", tty, dev, set, clear); rfcomm_dlc_get_modem_status(dlc, &v24_sig); if (set & TIOCM_DSR || set & TIOCM_DTR) v24_sig |= RFCOMM_V24_RTC; if (set & TIOCM_RTS || set & TIOCM_CTS) v24_sig |= RFCOMM_V24_RTR; if (set & TIOCM_RI) v24_sig |= RFCOMM_V24_IC; if (set & TIOCM_CD) v24_sig |= RFCOMM_V24_DV; if (clear & TIOCM_DSR || clear & TIOCM_DTR) v24_sig &= ~RFCOMM_V24_RTC; if (clear & TIOCM_RTS || clear & TIOCM_CTS) v24_sig &= ~RFCOMM_V24_RTR; if (clear & TIOCM_RI) v24_sig &= ~RFCOMM_V24_IC; if (clear & TIOCM_CD) v24_sig &= ~RFCOMM_V24_DV; rfcomm_dlc_set_modem_status(dlc, v24_sig); return 0; } /* ---- TTY structure ---- */ static const struct tty_operations rfcomm_ops = { .open = rfcomm_tty_open, .close = rfcomm_tty_close, .write = rfcomm_tty_write, .write_room = rfcomm_tty_write_room, .chars_in_buffer = rfcomm_tty_chars_in_buffer, .flush_buffer = rfcomm_tty_flush_buffer, .ioctl = rfcomm_tty_ioctl, .throttle = rfcomm_tty_throttle, .unthrottle = rfcomm_tty_unthrottle, .set_termios = rfcomm_tty_set_termios, .send_xchar = rfcomm_tty_send_xchar, .hangup = rfcomm_tty_hangup, .wait_until_sent = rfcomm_tty_wait_until_sent, .tiocmget = rfcomm_tty_tiocmget, .tiocmset = rfcomm_tty_tiocmset, }; int __init rfcomm_init_ttys(void) { int error; rfcomm_tty_driver = alloc_tty_driver(RFCOMM_TTY_PORTS); if (!rfcomm_tty_driver) return -ENOMEM; rfcomm_tty_driver->driver_name = "rfcomm"; rfcomm_tty_driver->name = "rfcomm"; rfcomm_tty_driver->major = RFCOMM_TTY_MAJOR; rfcomm_tty_driver->minor_start = RFCOMM_TTY_MINOR; rfcomm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL; rfcomm_tty_driver->subtype = SERIAL_TYPE_NORMAL; rfcomm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV; rfcomm_tty_driver->init_termios = tty_std_termios; rfcomm_tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL; rfcomm_tty_driver->init_termios.c_lflag &= ~ICANON; tty_set_operations(rfcomm_tty_driver, &rfcomm_ops); error = tty_register_driver(rfcomm_tty_driver); if (error) { BT_ERR("Can't register RFCOMM TTY driver"); put_tty_driver(rfcomm_tty_driver); return error; } BT_INFO("RFCOMM TTY layer initialized"); return 0; } void rfcomm_cleanup_ttys(void) { tty_unregister_driver(rfcomm_tty_driver); put_tty_driver(rfcomm_tty_driver); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3837_0
crossvul-cpp_data_bad_3417_0
/* * AVI demuxer * Copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/bswap.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "avformat.h" #include "avi.h" #include "dv.h" #include "internal.h" #include "isom.h" #include "riff.h" #include "libavcodec/bytestream.h" #include "libavcodec/exif.h" #include "libavcodec/internal.h" typedef struct AVIStream { int64_t frame_offset; /* current frame (video) or byte (audio) counter * (used to compute the pts) */ int remaining; int packet_size; uint32_t handler; uint32_t scale; uint32_t rate; int sample_size; /* size of one sample (or packet) * (in the rate/scale sense) in bytes */ int64_t cum_len; /* temporary storage (used during seek) */ int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */ int prefix_count; uint32_t pal[256]; int has_pal; int dshow_block_align; /* block align variable used to emulate bugs in * the MS dshow demuxer */ AVFormatContext *sub_ctx; AVPacket sub_pkt; uint8_t *sub_buffer; int64_t seek_pos; } AVIStream; typedef struct AVIContext { const AVClass *class; int64_t riff_end; int64_t movi_end; int64_t fsize; int64_t io_fsize; int64_t movi_list; int64_t last_pkt_pos; int index_loaded; int is_odml; int non_interleaved; int stream_index; DVDemuxContext *dv_demux; int odml_depth; int use_odml; #define MAX_ODML_DEPTH 1000 int64_t dts_max; } AVIContext; static const AVOption options[] = { { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM}, { NULL }, }; static const AVClass demuxer_class = { .class_name = "avi", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, .category = AV_CLASS_CATEGORY_DEMUXER, }; static const char avi_headers[][8] = { { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' }, { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' }, { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 }, { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' }, { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' }, { 0 } }; static const AVMetadataConv avi_metadata_conv[] = { { "strn", "title" }, { 0 }, }; static int avi_load_index(AVFormatContext *s); static int guess_ni_flag(AVFormatContext *s); #define print_tag(str, tag, size) \ av_log(NULL, AV_LOG_TRACE, "pos:%"PRIX64" %s: tag=%s size=0x%x\n", \ avio_tell(pb), str, av_fourcc2str(tag), size) \ static inline int get_duration(AVIStream *ast, int len) { if (ast->sample_size) return len; else if (ast->dshow_block_align) return (len + ast->dshow_block_align - 1) / ast->dshow_block_align; else return 1; } static int get_riff(AVFormatContext *s, AVIOContext *pb) { AVIContext *avi = s->priv_data; char header[8] = {0}; int i; /* check RIFF header */ avio_read(pb, header, 4); avi->riff_end = avio_rl32(pb); /* RIFF chunk size */ avi->riff_end += avio_tell(pb); /* RIFF chunk end */ avio_read(pb, header + 4, 4); for (i = 0; avi_headers[i][0]; i++) if (!memcmp(header, avi_headers[i], 8)) break; if (!avi_headers[i][0]) return AVERROR_INVALIDDATA; if (header[7] == 0x19) av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n"); return 0; } static int read_odml_index(AVFormatContext *s, int frame_num) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; int longs_per_entry = avio_rl16(pb); int index_sub_type = avio_r8(pb); int index_type = avio_r8(pb); int entries_in_use = avio_rl32(pb); int chunk_id = avio_rl32(pb); int64_t base = avio_rl64(pb); int stream_id = ((chunk_id & 0xFF) - '0') * 10 + ((chunk_id >> 8 & 0xFF) - '0'); AVStream *st; AVIStream *ast; int i; int64_t last_pos = -1; int64_t filesize = avi->fsize; av_log(s, AV_LOG_TRACE, "longs_per_entry:%d index_type:%d entries_in_use:%d " "chunk_id:%X base:%16"PRIX64" frame_num:%d\n", longs_per_entry, index_type, entries_in_use, chunk_id, base, frame_num); if (stream_id >= s->nb_streams || stream_id < 0) return AVERROR_INVALIDDATA; st = s->streams[stream_id]; ast = st->priv_data; if (index_sub_type) return AVERROR_INVALIDDATA; avio_rl32(pb); if (index_type && longs_per_entry != 2) return AVERROR_INVALIDDATA; if (index_type > 1) return AVERROR_INVALIDDATA; if (filesize > 0 && base >= filesize) { av_log(s, AV_LOG_ERROR, "ODML index invalid\n"); if (base >> 32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF) base &= 0xFFFFFFFF; else return AVERROR_INVALIDDATA; } for (i = 0; i < entries_in_use; i++) { if (index_type) { int64_t pos = avio_rl32(pb) + base - 8; int len = avio_rl32(pb); int key = len >= 0; len &= 0x7FFFFFFF; av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len); if (avio_feof(pb)) return AVERROR_INVALIDDATA; if (last_pos == pos || pos == base - 8) avi->non_interleaved = 1; if (last_pos != pos && len) av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0); ast->cum_len += get_duration(ast, len); last_pos = pos; } else { int64_t offset, pos; int duration; offset = avio_rl64(pb); avio_rl32(pb); /* size */ duration = avio_rl32(pb); if (avio_feof(pb)) return AVERROR_INVALIDDATA; pos = avio_tell(pb); if (avi->odml_depth > MAX_ODML_DEPTH) { av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n"); return AVERROR_INVALIDDATA; } if (avio_seek(pb, offset + 8, SEEK_SET) < 0) return -1; avi->odml_depth++; read_odml_index(s, frame_num); avi->odml_depth--; frame_num += duration; if (avio_seek(pb, pos, SEEK_SET) < 0) { av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n"); return -1; } } } avi->index_loaded = 2; return 0; } static void clean_index(AVFormatContext *s) { int i; int64_t j; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVIStream *ast = st->priv_data; int n = st->nb_index_entries; int max = ast->sample_size; int64_t pos, size, ts; if (n != 1 || ast->sample_size == 0) continue; while (max < 1024) max += max; pos = st->index_entries[0].pos; size = st->index_entries[0].size; ts = st->index_entries[0].timestamp; for (j = 0; j < size; j += max) av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0, AVINDEX_KEYFRAME); } } static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size) { AVIOContext *pb = s->pb; char key[5] = { 0 }; char *value; size += (size & 1); if (size == UINT_MAX) return AVERROR(EINVAL); value = av_malloc(size + 1); if (!value) return AVERROR(ENOMEM); if (avio_read(pb, value, size) != size) return AVERROR_INVALIDDATA; value[size] = 0; AV_WL32(key, tag); return av_dict_set(st ? &st->metadata : &s->metadata, key, value, AV_DICT_DONT_STRDUP_VAL); } static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static void avi_metadata_creation_time(AVDictionary **metadata, char *date) { char month[4], time[9], buffer[64]; int i, day, year; /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */ if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d", month, &day, time, &year) == 4) { for (i = 0; i < 12; i++) if (!av_strcasecmp(month, months[i])) { snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s", year, i + 1, day, time); av_dict_set(metadata, "creation_time", buffer, 0); } } else if (date[4] == '/' && date[7] == '/') { date[4] = date[7] = '-'; av_dict_set(metadata, "creation_time", date, 0); } } static void avi_read_nikon(AVFormatContext *s, uint64_t end) { while (avio_tell(s->pb) < end && !avio_feof(s->pb)) { uint32_t tag = avio_rl32(s->pb); uint32_t size = avio_rl32(s->pb); switch (tag) { case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */ { uint64_t tag_end = avio_tell(s->pb) + size; while (avio_tell(s->pb) < tag_end && !avio_feof(s->pb)) { uint16_t tag = avio_rl16(s->pb); uint16_t size = avio_rl16(s->pb); const char *name = NULL; char buffer[64] = { 0 }; size = FFMIN(size, tag_end - avio_tell(s->pb)); size -= avio_read(s->pb, buffer, FFMIN(size, sizeof(buffer) - 1)); switch (tag) { case 0x03: name = "maker"; break; case 0x04: name = "model"; break; case 0x13: name = "creation_time"; if (buffer[4] == ':' && buffer[7] == ':') buffer[4] = buffer[7] = '-'; break; } if (name) av_dict_set(&s->metadata, name, buffer, 0); avio_skip(s->pb, size); } break; } default: avio_skip(s->pb, size); break; } } } static int avi_extract_stream_metadata(AVFormatContext *s, AVStream *st) { GetByteContext gb; uint8_t *data = st->codecpar->extradata; int data_size = st->codecpar->extradata_size; int tag, offset; if (!data || data_size < 8) { return AVERROR_INVALIDDATA; } bytestream2_init(&gb, data, data_size); tag = bytestream2_get_le32(&gb); switch (tag) { case MKTAG('A', 'V', 'I', 'F'): // skip 4 byte padding bytestream2_skip(&gb, 4); offset = bytestream2_tell(&gb); bytestream2_init(&gb, data + offset, data_size - offset); // decode EXIF tags from IFD, AVI is always little-endian return avpriv_exif_decode_ifd(s, &gb, 1, 0, &st->metadata); break; case MKTAG('C', 'A', 'S', 'I'): avpriv_request_sample(s, "RIFF stream data tag type CASI (%u)", tag); break; case MKTAG('Z', 'o', 'r', 'a'): avpriv_request_sample(s, "RIFF stream data tag type Zora (%u)", tag); break; default: break; } return 0; } static int calculate_bitrate(AVFormatContext *s) { AVIContext *avi = s->priv_data; int i, j; int64_t lensum = 0; int64_t maxpos = 0; for (i = 0; i<s->nb_streams; i++) { int64_t len = 0; AVStream *st = s->streams[i]; if (!st->nb_index_entries) continue; for (j = 0; j < st->nb_index_entries; j++) len += st->index_entries[j].size; maxpos = FFMAX(maxpos, st->index_entries[j-1].pos); lensum += len; } if (maxpos < avi->io_fsize*9/10) // index does not cover the whole file return 0; if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch return 0; for (i = 0; i<s->nb_streams; i++) { int64_t len = 0; AVStream *st = s->streams[i]; int64_t duration; int64_t bitrate; for (j = 0; j < st->nb_index_entries; j++) len += st->index_entries[j].size; if (st->nb_index_entries < 2 || st->codecpar->bit_rate > 0) continue; duration = st->index_entries[j-1].timestamp - st->index_entries[0].timestamp; bitrate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num); if (bitrate <= INT_MAX && bitrate > 0) { st->codecpar->bit_rate = bitrate; } } return 1; } static int avi_read_header(AVFormatContext *s) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; unsigned int tag, tag1, handler; int codec_type, stream_index, frame_period; unsigned int size; int i; AVStream *st; AVIStream *ast = NULL; int avih_width = 0, avih_height = 0; int amv_file_format = 0; uint64_t list_end = 0; int64_t pos; int ret; AVDictionaryEntry *dict_entry; avi->stream_index = -1; ret = get_riff(s, pb); if (ret < 0) return ret; av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml); avi->io_fsize = avi->fsize = avio_size(pb); if (avi->fsize <= 0 || avi->fsize < avi->riff_end) avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end; /* first list tag */ stream_index = -1; codec_type = -1; frame_period = 0; for (;;) { if (avio_feof(pb)) goto fail; tag = avio_rl32(pb); size = avio_rl32(pb); print_tag("tag", tag, size); switch (tag) { case MKTAG('L', 'I', 'S', 'T'): list_end = avio_tell(pb) + size; /* Ignored, except at start of video packets. */ tag1 = avio_rl32(pb); print_tag("list", tag1, 0); if (tag1 == MKTAG('m', 'o', 'v', 'i')) { avi->movi_list = avio_tell(pb) - 4; if (size) avi->movi_end = avi->movi_list + size + (size & 1); else avi->movi_end = avi->fsize; av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end); goto end_of_header; } else if (tag1 == MKTAG('I', 'N', 'F', 'O')) ff_read_riff_info(s, size - 4); else if (tag1 == MKTAG('n', 'c', 'd', 't')) avi_read_nikon(s, list_end); break; case MKTAG('I', 'D', 'I', 'T'): { unsigned char date[64] = { 0 }; size += (size & 1); size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1)); avio_skip(pb, size); avi_metadata_creation_time(&s->metadata, date); break; } case MKTAG('d', 'm', 'l', 'h'): avi->is_odml = 1; avio_skip(pb, size + (size & 1)); break; case MKTAG('a', 'm', 'v', 'h'): amv_file_format = 1; case MKTAG('a', 'v', 'i', 'h'): /* AVI header */ /* using frame_period is bad idea */ frame_period = avio_rl32(pb); avio_rl32(pb); /* max. bytes per second */ avio_rl32(pb); avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX; avio_skip(pb, 2 * 4); avio_rl32(pb); avio_rl32(pb); avih_width = avio_rl32(pb); avih_height = avio_rl32(pb); avio_skip(pb, size - 10 * 4); break; case MKTAG('s', 't', 'r', 'h'): /* stream header */ tag1 = avio_rl32(pb); handler = avio_rl32(pb); /* codec tag */ if (tag1 == MKTAG('p', 'a', 'd', 's')) { avio_skip(pb, size - 8); break; } else { stream_index++; st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = stream_index; ast = av_mallocz(sizeof(AVIStream)); if (!ast) goto fail; st->priv_data = ast; } if (amv_file_format) tag1 = stream_index ? MKTAG('a', 'u', 'd', 's') : MKTAG('v', 'i', 'd', 's'); print_tag("strh", tag1, -1); if (tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')) { int64_t dv_dur; /* After some consideration -- I don't think we * have to support anything but DV in type1 AVIs. */ if (s->nb_streams != 1) goto fail; if (handler != MKTAG('d', 'v', 's', 'd') && handler != MKTAG('d', 'v', 'h', 'd') && handler != MKTAG('d', 'v', 's', 'l')) goto fail; ast = s->streams[0]->priv_data; av_freep(&s->streams[0]->codecpar->extradata); av_freep(&s->streams[0]->codecpar); #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS av_freep(&s->streams[0]->codec); FF_ENABLE_DEPRECATION_WARNINGS #endif if (s->streams[0]->info) av_freep(&s->streams[0]->info->duration_error); av_freep(&s->streams[0]->info); if (s->streams[0]->internal) av_freep(&s->streams[0]->internal->avctx); av_freep(&s->streams[0]->internal); av_freep(&s->streams[0]); s->nb_streams = 0; if (CONFIG_DV_DEMUXER) { avi->dv_demux = avpriv_dv_init_demux(s); if (!avi->dv_demux) goto fail; } else goto fail; s->streams[0]->priv_data = ast; avio_skip(pb, 3 * 4); ast->scale = avio_rl32(pb); ast->rate = avio_rl32(pb); avio_skip(pb, 4); /* start time */ dv_dur = avio_rl32(pb); if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) { dv_dur *= AV_TIME_BASE; s->duration = av_rescale(dv_dur, ast->scale, ast->rate); } /* else, leave duration alone; timing estimation in utils.c * will make a guess based on bitrate. */ stream_index = s->nb_streams - 1; avio_skip(pb, size - 9 * 4); break; } av_assert0(stream_index < s->nb_streams); ast->handler = handler; avio_rl32(pb); /* flags */ avio_rl16(pb); /* priority */ avio_rl16(pb); /* language */ avio_rl32(pb); /* initial frame */ ast->scale = avio_rl32(pb); ast->rate = avio_rl32(pb); if (!(ast->scale && ast->rate)) { av_log(s, AV_LOG_WARNING, "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. " "(This file has been generated by broken software.)\n", ast->scale, ast->rate); if (frame_period) { ast->rate = 1000000; ast->scale = frame_period; } else { ast->rate = 25; ast->scale = 1; } } avpriv_set_pts_info(st, 64, ast->scale, ast->rate); ast->cum_len = avio_rl32(pb); /* start */ st->nb_frames = avio_rl32(pb); st->start_time = 0; avio_rl32(pb); /* buffer size */ avio_rl32(pb); /* quality */ if (ast->cum_len*ast->scale/ast->rate > 3600) { av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n"); ast->cum_len = 0; } ast->sample_size = avio_rl32(pb); ast->cum_len *= FFMAX(1, ast->sample_size); av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n", ast->rate, ast->scale, ast->sample_size); switch (tag1) { case MKTAG('v', 'i', 'd', 's'): codec_type = AVMEDIA_TYPE_VIDEO; ast->sample_size = 0; st->avg_frame_rate = av_inv_q(st->time_base); break; case MKTAG('a', 'u', 'd', 's'): codec_type = AVMEDIA_TYPE_AUDIO; break; case MKTAG('t', 'x', 't', 's'): codec_type = AVMEDIA_TYPE_SUBTITLE; break; case MKTAG('d', 'a', 't', 's'): codec_type = AVMEDIA_TYPE_DATA; break; default: av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1); } if (ast->sample_size < 0) { if (s->error_recognition & AV_EF_EXPLODE) { av_log(s, AV_LOG_ERROR, "Invalid sample_size %d at stream %d\n", ast->sample_size, stream_index); goto fail; } av_log(s, AV_LOG_WARNING, "Invalid sample_size %d at stream %d " "setting it to 0\n", ast->sample_size, stream_index); ast->sample_size = 0; } if (ast->sample_size == 0) { st->duration = st->nb_frames; if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) { av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n"); st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end); } } ast->frame_offset = ast->cum_len; avio_skip(pb, size - 12 * 4); break; case MKTAG('s', 't', 'r', 'f'): /* stream header */ if (!size && (codec_type == AVMEDIA_TYPE_AUDIO || codec_type == AVMEDIA_TYPE_VIDEO)) break; if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) { avio_skip(pb, size); } else { uint64_t cur_pos = avio_tell(pb); unsigned esize; if (cur_pos < list_end) size = FFMIN(size, list_end - cur_pos); st = s->streams[stream_index]; if (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN) { avio_skip(pb, size); break; } switch (codec_type) { case AVMEDIA_TYPE_VIDEO: if (amv_file_format) { st->codecpar->width = avih_width; st->codecpar->height = avih_height; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_AMV; avio_skip(pb, size); break; } tag1 = ff_get_bmp_header(pb, st, &esize); if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D', 'X', 'S', 'A')) { st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; st->codecpar->codec_tag = tag1; st->codecpar->codec_id = AV_CODEC_ID_XSUB; break; } if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) { if (esize == size-1 && (esize&1)) { st->codecpar->extradata_size = esize - 10 * 4; } else st->codecpar->extradata_size = size - 10 * 4; if (st->codecpar->extradata) { av_log(s, AV_LOG_WARNING, "New extradata in strf chunk, freeing previous one.\n"); av_freep(&st->codecpar->extradata); } if (ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); } // FIXME: check if the encoder really did this correctly if (st->codecpar->extradata_size & 1) avio_r8(pb); /* Extract palette from extradata if bpp <= 8. * This code assumes that extradata contains only palette. * This is true for all paletted codecs implemented in * FFmpeg. */ if (st->codecpar->extradata_size && (st->codecpar->bits_per_coded_sample <= 8)) { int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2; const uint8_t *pal_src; pal_size = FFMIN(pal_size, st->codecpar->extradata_size); pal_src = st->codecpar->extradata + st->codecpar->extradata_size - pal_size; /* Exclude the "BottomUp" field from the palette */ if (pal_src - st->codecpar->extradata >= 9 && !memcmp(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9)) pal_src -= 9; for (i = 0; i < pal_size / 4; i++) ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src + 4 * i); ast->has_pal = 1; } print_tag("video", tag1, 0); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_tag = tag1; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1); /* If codec is not found yet, try with the mov tags. */ if (!st->codecpar->codec_id) { st->codecpar->codec_id = ff_codec_get_id(ff_codec_movvideo_tags, tag1); if (st->codecpar->codec_id) av_log(s, AV_LOG_WARNING, "mov tag found in avi (fourcc %s)\n", av_fourcc2str(tag1)); } /* This is needed to get the pict type which is necessary * for generating correct pts. */ st->need_parsing = AVSTREAM_PARSE_HEADERS; if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 && ast->handler == MKTAG('X', 'V', 'I', 'D')) st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D'); if (st->codecpar->codec_tag == MKTAG('V', 'S', 'S', 'H')) st->need_parsing = AVSTREAM_PARSE_FULL; if (st->codecpar->codec_id == AV_CODEC_ID_RV40) st->need_parsing = AVSTREAM_PARSE_NONE; if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 && st->codecpar->extradata_size < 1U << 30) { st->codecpar->extradata_size += 9; if ((ret = av_reallocp(&st->codecpar->extradata, st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) { st->codecpar->extradata_size = 0; return ret; } else memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9); } st->codecpar->height = FFABS(st->codecpar->height); // avio_skip(pb, size - 5 * 4); break; case AVMEDIA_TYPE_AUDIO: ret = ff_get_wav_header(s, pb, st->codecpar, size, 0); if (ret < 0) return ret; ast->dshow_block_align = st->codecpar->block_align; if (ast->sample_size && st->codecpar->block_align && ast->sample_size != st->codecpar->block_align) { av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codecpar->block_align); ast->sample_size = st->codecpar->block_align; } /* 2-aligned * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */ if (size & 1) avio_skip(pb, 1); /* Force parsing as several audio frames can be in * one packet and timestamps refer to packet start. */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; /* ADTS header is in extradata, AAC without header must be * stored as exact frames. Parser not needed and it will * fail. */ if (st->codecpar->codec_id == AV_CODEC_ID_AAC && st->codecpar->extradata_size) st->need_parsing = AVSTREAM_PARSE_NONE; // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) st->need_parsing = AVSTREAM_PARSE_NONE; /* AVI files with Xan DPCM audio (wrongly) declare PCM * audio in the header but have Axan as stream_code_tag. */ if (ast->handler == AV_RL32("Axan")) { st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM; st->codecpar->codec_tag = 0; ast->dshow_block_align = 0; } if (amv_file_format) { st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV; ast->dshow_block_align = 0; } if ((st->codecpar->codec_id == AV_CODEC_ID_AAC || st->codecpar->codec_id == AV_CODEC_ID_FLAC || st->codecpar->codec_id == AV_CODEC_ID_MP2 ) && ast->dshow_block_align <= 4 && ast->dshow_block_align) { av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align); ast->dshow_block_align = 0; } if (st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 || st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 || st->codecpar->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) { av_log(s, AV_LOG_DEBUG, "overriding sample_size\n"); ast->sample_size = 0; } break; case AVMEDIA_TYPE_SUBTITLE: st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; st->request_probe= 1; avio_skip(pb, size); break; default: st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->codecpar->codec_id = AV_CODEC_ID_NONE; st->codecpar->codec_tag = 0; avio_skip(pb, size); break; } } break; case MKTAG('s', 't', 'r', 'd'): if (stream_index >= (unsigned)s->nb_streams || s->streams[stream_index]->codecpar->extradata_size || s->streams[stream_index]->codecpar->codec_tag == MKTAG('H','2','6','4')) { avio_skip(pb, size); } else { uint64_t cur_pos = avio_tell(pb); if (cur_pos < list_end) size = FFMIN(size, list_end - cur_pos); st = s->streams[stream_index]; if (size<(1<<30)) { if (st->codecpar->extradata) { av_log(s, AV_LOG_WARNING, "New extradata in strd chunk, freeing previous one.\n"); av_freep(&st->codecpar->extradata); } if (ff_get_extradata(s, st->codecpar, pb, size) < 0) return AVERROR(ENOMEM); } if (st->codecpar->extradata_size & 1) //FIXME check if the encoder really did this correctly avio_r8(pb); ret = avi_extract_stream_metadata(s, st); if (ret < 0) { av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n"); } } break; case MKTAG('i', 'n', 'd', 'x'): pos = avio_tell(pb); if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml && read_odml_index(s, 0) < 0 && (s->error_recognition & AV_EF_EXPLODE)) goto fail; avio_seek(pb, pos + size, SEEK_SET); break; case MKTAG('v', 'p', 'r', 'p'): if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) { AVRational active, active_aspect; st = s->streams[stream_index]; avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); active_aspect.den = avio_rl16(pb); active_aspect.num = avio_rl16(pb); active.num = avio_rl32(pb); active.den = avio_rl32(pb); avio_rl32(pb); // nbFieldsPerFrame if (active_aspect.num && active_aspect.den && active.num && active.den) { st->sample_aspect_ratio = av_div_q(active_aspect, active); av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den); } size -= 9 * 4; } avio_skip(pb, size); break; case MKTAG('s', 't', 'r', 'n'): if (s->nb_streams) { ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size); if (ret < 0) return ret; break; } default: if (size > 1000000) { av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, " "tag %s has size %u, " "I will ignore it and try to continue anyway.\n", av_fourcc2str(tag), size); if (s->error_recognition & AV_EF_EXPLODE) goto fail; avi->movi_list = avio_tell(pb) - 4; avi->movi_end = avi->fsize; goto end_of_header; } /* Do not fail for very large idx1 tags */ case MKTAG('i', 'd', 'x', '1'): /* skip tag */ size += (size & 1); avio_skip(pb, size); break; } } end_of_header: /* check stream number */ if (stream_index != s->nb_streams - 1) { fail: return AVERROR_INVALIDDATA; } if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL)) avi_load_index(s); calculate_bitrate(s); avi->index_loaded |= 1; if ((ret = guess_ni_flag(s)) < 0) return ret; avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS); dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0); if (dict_entry && !strcmp(dict_entry->value, "PotEncoder")) for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if ( st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO || st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) st->need_parsing = AVSTREAM_PARSE_FULL; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->nb_index_entries) break; } // DV-in-AVI cannot be non-interleaved, if set this must be // a mis-detection. if (avi->dv_demux) avi->non_interleaved = 0; if (i == s->nb_streams && avi->non_interleaved) { av_log(s, AV_LOG_WARNING, "Non-interleaved AVI without index, switching to interleaved\n"); avi->non_interleaved = 0; } if (avi->non_interleaved) { av_log(s, AV_LOG_INFO, "non-interleaved AVI\n"); clean_index(s); } ff_metadata_conv_ctx(s, NULL, avi_metadata_conv); ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv); return 0; } static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt) { if (pkt->size >= 7 && pkt->size < INT_MAX - AVPROBE_PADDING_SIZE && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) { uint8_t desc[256]; int score = AVPROBE_SCORE_EXTENSION, ret; AVIStream *ast = st->priv_data; AVInputFormat *sub_demuxer; AVRational time_base; int size; AVIOContext *pb = avio_alloc_context(pkt->data + 7, pkt->size - 7, 0, NULL, NULL, NULL, NULL); AVProbeData pd; unsigned int desc_len = avio_rl32(pb); if (desc_len > pb->buf_end - pb->buf_ptr) goto error; ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc)); avio_skip(pb, desc_len - ret); if (*desc) av_dict_set(&st->metadata, "title", desc, 0); avio_rl16(pb); /* flags? */ avio_rl32(pb); /* data size */ size = pb->buf_end - pb->buf_ptr; pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE), .buf_size = size }; if (!pd.buf) goto error; memcpy(pd.buf, pb->buf_ptr, size); sub_demuxer = av_probe_input_format2(&pd, 1, &score); av_freep(&pd.buf); if (!sub_demuxer) goto error; if (!(ast->sub_ctx = avformat_alloc_context())) goto error; ast->sub_ctx->pb = pb; if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0) goto error; if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) { if (ast->sub_ctx->nb_streams != 1) goto error; ff_read_packet(ast->sub_ctx, &ast->sub_pkt); avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar); time_base = ast->sub_ctx->streams[0]->time_base; avpriv_set_pts_info(st, 64, time_base.num, time_base.den); } ast->sub_buffer = pkt->data; memset(pkt, 0, sizeof(*pkt)); return 1; error: av_freep(&ast->sub_ctx); av_freep(&pb); } return 0; } static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st, AVPacket *pkt) { AVIStream *ast, *next_ast = next_st->priv_data; int64_t ts, next_ts, ts_min = INT64_MAX; AVStream *st, *sub_st = NULL; int i; next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base, AV_TIME_BASE_Q); for (i = 0; i < s->nb_streams; i++) { st = s->streams[i]; ast = st->priv_data; if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) { ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q); if (ts <= next_ts && ts < ts_min) { ts_min = ts; sub_st = st; } } } if (sub_st) { ast = sub_st->priv_data; *pkt = ast->sub_pkt; pkt->stream_index = sub_st->index; if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0) ast->sub_pkt.data = NULL; } return sub_st; } static int get_stream_idx(const unsigned *d) { if (d[0] >= '0' && d[0] <= '9' && d[1] >= '0' && d[1] <= '9') { return (d[0] - '0') * 10 + (d[1] - '0'); } else { return 100; // invalid stream ID } } /** * * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet */ static int avi_sync(AVFormatContext *s, int exit_early) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; int n; unsigned int d[8]; unsigned int size; int64_t i, sync; start_sync: memset(d, -1, sizeof(d)); for (i = sync = avio_tell(pb); !avio_feof(pb); i++) { int j; for (j = 0; j < 7; j++) d[j] = d[j + 1]; d[7] = avio_r8(pb); size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24); n = get_stream_idx(d + 2); ff_tlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n); if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127) continue; // parse ix## if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) || // parse JUNK (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') || (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1') || (d[0] == 'i' && d[1] == 'n' && d[2] == 'd' && d[3] == 'x')) { avio_skip(pb, size); goto start_sync; } // parse stray LIST if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') { avio_skip(pb, 4); goto start_sync; } n = get_stream_idx(d); if (!((i - avi->last_pkt_pos) & 1) && get_stream_idx(d + 1) < s->nb_streams) continue; // detect ##ix chunk and skip if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) { avio_skip(pb, size); goto start_sync; } if (avi->dv_demux && n != 0) continue; // parse ##dc/##wb if (n < s->nb_streams) { AVStream *st; AVIStream *ast; st = s->streams[n]; ast = st->priv_data; if (!ast) { av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n); continue; } if (s->nb_streams >= 2) { AVStream *st1 = s->streams[1]; AVIStream *ast1 = st1->priv_data; // workaround for broken small-file-bug402.avi if ( d[2] == 'w' && d[3] == 'b' && n == 0 && st ->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && ast->prefix == 'd'*256+'c' && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count) ) { n = 1; st = st1; ast = ast1; av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n"); } } if (!avi->dv_demux && ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* || // FIXME: needs a little reordering (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY)) */ || st->discard >= AVDISCARD_ALL)) { if (!exit_early) { ast->frame_offset += get_duration(ast, size); avio_skip(pb, size); goto start_sync; } } if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) { int k = avio_r8(pb); int last = (k + avio_r8(pb) - 1) & 0xFF; avio_rl16(pb); // flags // b + (g << 8) + (r << 16); for (; k <= last; k++) ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8; ast->has_pal = 1; goto start_sync; } else if (((ast->prefix_count < 5 || sync + 9 > i) && d[2] < 128 && d[3] < 128) || d[2] * 256 + d[3] == ast->prefix /* || (d[2] == 'd' && d[3] == 'c') || (d[2] == 'w' && d[3] == 'b') */) { if (exit_early) return 0; if (d[2] * 256 + d[3] == ast->prefix) ast->prefix_count++; else { ast->prefix = d[2] * 256 + d[3]; ast->prefix_count = 0; } avi->stream_index = n; ast->packet_size = size + 8; ast->remaining = size; if (size) { uint64_t pos = avio_tell(pb) - 8; if (!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos) { av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME); } } return 0; } } } if (pb->error) return pb->error; return AVERROR_EOF; } static int ni_prepare_read(AVFormatContext *s) { AVIContext *avi = s->priv_data; int best_stream_index = 0; AVStream *best_st = NULL; AVIStream *best_ast; int64_t best_ts = INT64_MAX; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVIStream *ast = st->priv_data; int64_t ts = ast->frame_offset; int64_t last_ts; if (!st->nb_index_entries) continue; last_ts = st->index_entries[st->nb_index_entries - 1].timestamp; if (!ast->remaining && ts > last_ts) continue; ts = av_rescale_q(ts, st->time_base, (AVRational) { FFMAX(1, ast->sample_size), AV_TIME_BASE }); av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset); if (ts < best_ts) { best_ts = ts; best_st = st; best_stream_index = i; } } if (!best_st) return AVERROR_EOF; best_ast = best_st->priv_data; best_ts = best_ast->frame_offset; if (best_ast->remaining) { i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD); } else { i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY); if (i >= 0) best_ast->frame_offset = best_st->index_entries[i].timestamp; } if (i >= 0) { int64_t pos = best_st->index_entries[i].pos; pos += best_ast->packet_size - best_ast->remaining; if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0) return AVERROR_EOF; av_assert0(best_ast->remaining <= best_ast->packet_size); avi->stream_index = best_stream_index; if (!best_ast->remaining) best_ast->packet_size = best_ast->remaining = best_st->index_entries[i].size; } else return AVERROR_EOF; return 0; } static int avi_read_packet(AVFormatContext *s, AVPacket *pkt) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; int err; if (CONFIG_DV_DEMUXER && avi->dv_demux) { int size = avpriv_dv_get_packet(avi->dv_demux, pkt); if (size >= 0) return size; else goto resync; } if (avi->non_interleaved) { err = ni_prepare_read(s); if (err < 0) return err; } resync: if (avi->stream_index >= 0) { AVStream *st = s->streams[avi->stream_index]; AVIStream *ast = st->priv_data; int size, err; if (get_subtitle_pkt(s, st, pkt)) return 0; // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM if (ast->sample_size <= 1) size = INT_MAX; else if (ast->sample_size < 32) // arbitrary multiplier to avoid tiny packets for raw PCM data size = 1024 * ast->sample_size; else size = ast->sample_size; if (size > ast->remaining) size = ast->remaining; avi->last_pkt_pos = avio_tell(pb); err = av_get_packet(pb, pkt, size); if (err < 0) return err; size = err; if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) { uint8_t *pal; pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); if (!pal) { av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n"); } else { memcpy(pal, ast->pal, AVPALETTE_SIZE); ast->has_pal = 0; } } if (CONFIG_DV_DEMUXER && avi->dv_demux) { AVBufferRef *avbuf = pkt->buf; size = avpriv_dv_produce_packet(avi->dv_demux, pkt, pkt->data, pkt->size, pkt->pos); pkt->buf = avbuf; pkt->flags |= AV_PKT_FLAG_KEY; if (size < 0) av_packet_unref(pkt); } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE && !st->codecpar->codec_tag && read_gab2_sub(s, st, pkt)) { ast->frame_offset++; avi->stream_index = -1; ast->remaining = 0; goto resync; } else { /* XXX: How to handle B-frames in AVI? */ pkt->dts = ast->frame_offset; // pkt->dts += ast->start; if (ast->sample_size) pkt->dts /= ast->sample_size; pkt->stream_index = avi->stream_index; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) { AVIndexEntry *e; int index; index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY); e = &st->index_entries[index]; if (index >= 0 && e->timestamp == ast->frame_offset) { if (index == st->nb_index_entries-1) { int key=1; uint32_t state=-1; if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) { const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256); while (ptr < end) { ptr = avpriv_find_start_code(ptr, end, &state); if (state == 0x1B6 && ptr < end) { key = !(*ptr & 0xC0); break; } } } if (!key) e->flags &= ~AVINDEX_KEYFRAME; } if (e->flags & AVINDEX_KEYFRAME) pkt->flags |= AV_PKT_FLAG_KEY; } } else { pkt->flags |= AV_PKT_FLAG_KEY; } ast->frame_offset += get_duration(ast, pkt->size); } ast->remaining -= err; if (!ast->remaining) { avi->stream_index = -1; ast->packet_size = 0; } if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) { av_packet_unref(pkt); goto resync; } ast->seek_pos= 0; if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) { int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q); if (avi->dts_max - dts > 2*AV_TIME_BASE) { avi->non_interleaved= 1; av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n"); }else if (avi->dts_max < dts) avi->dts_max = dts; } return 0; } if ((err = avi_sync(s, 0)) < 0) return err; goto resync; } /* XXX: We make the implicit supposition that the positions are sorted * for each stream. */ static int avi_read_idx1(AVFormatContext *s, int size) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; int nb_index_entries, i; AVStream *st; AVIStream *ast; int64_t pos; unsigned int index, tag, flags, len, first_packet = 1; int64_t last_pos = -1; unsigned last_idx = -1; int64_t idx1_pos, first_packet_pos = 0, data_offset = 0; int anykey = 0; nb_index_entries = size / 16; if (nb_index_entries <= 0) return AVERROR_INVALIDDATA; idx1_pos = avio_tell(pb); avio_seek(pb, avi->movi_list + 4, SEEK_SET); if (avi_sync(s, 1) == 0) first_packet_pos = avio_tell(pb) - 8; avi->stream_index = -1; avio_seek(pb, idx1_pos, SEEK_SET); if (s->nb_streams == 1 && s->streams[0]->codecpar->codec_tag == AV_RL32("MMES")) { first_packet_pos = 0; data_offset = avi->movi_list; } /* Read the entries and sort them in each stream component. */ for (i = 0; i < nb_index_entries; i++) { if (avio_feof(pb)) return -1; tag = avio_rl32(pb); flags = avio_rl32(pb); pos = avio_rl32(pb); len = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%"PRIx64" len=%d/", i, tag, flags, pos, len); index = ((tag & 0xff) - '0') * 10; index += (tag >> 8 & 0xff) - '0'; if (index >= s->nb_streams) continue; st = s->streams[index]; ast = st->priv_data; /* Skip 'xxpc' palette change entries in the index until a logic * to process these is properly implemented. */ if ((tag >> 16 & 0xff) == 'p' && (tag >> 24 & 0xff) == 'c') continue; if (first_packet && first_packet_pos) { if (avi->movi_list + 4 != pos || pos + 500 > first_packet_pos) data_offset = first_packet_pos - pos; first_packet = 0; } pos += data_offset; av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len); // even if we have only a single stream, we should // switch to non-interleaved to get correct timestamps if (last_pos == pos) avi->non_interleaved = 1; if (last_idx != pos && len) { av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0); last_idx= pos; } ast->cum_len += get_duration(ast, len); last_pos = pos; anykey |= flags&AVIIF_INDEX; } if (!anykey) { for (index = 0; index < s->nb_streams; index++) { st = s->streams[index]; if (st->nb_index_entries) st->index_entries[0].flags |= AVINDEX_KEYFRAME; } } return 0; } /* Scan the index and consider any file with streams more than * 2 seconds or 64MB apart non-interleaved. */ static int check_stream_max_drift(AVFormatContext *s) { int64_t min_pos, pos; int i; int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx)); if (!idx) return AVERROR(ENOMEM); for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) { int64_t max_dts = INT64_MIN / 2; int64_t min_dts = INT64_MAX / 2; int64_t max_buffer = 0; min_pos = INT64_MAX; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVIStream *ast = st->priv_data; int n = st->nb_index_entries; while (idx[i] < n && st->index_entries[idx[i]].pos < pos) idx[i]++; if (idx[i] < n) { int64_t dts; dts = av_rescale_q(st->index_entries[idx[i]].timestamp / FFMAX(ast->sample_size, 1), st->time_base, AV_TIME_BASE_Q); min_dts = FFMIN(min_dts, dts); min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVIStream *ast = st->priv_data; if (idx[i] && min_dts != INT64_MAX / 2) { int64_t dts; dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp / FFMAX(ast->sample_size, 1), st->time_base, AV_TIME_BASE_Q); max_dts = FFMAX(max_dts, dts); max_buffer = FFMAX(max_buffer, av_rescale(dts - min_dts, st->codecpar->bit_rate, AV_TIME_BASE)); } } if (max_dts - min_dts > 2 * AV_TIME_BASE || max_buffer > 1024 * 1024 * 8 * 8) { av_free(idx); return 1; } } av_free(idx); return 0; } static int guess_ni_flag(AVFormatContext *s) { int i; int64_t last_start = 0; int64_t first_end = INT64_MAX; int64_t oldpos = avio_tell(s->pb); for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; int n = st->nb_index_entries; unsigned int size; if (n <= 0) continue; if (n >= 2) { int64_t pos = st->index_entries[0].pos; unsigned tag[2]; avio_seek(s->pb, pos, SEEK_SET); tag[0] = avio_r8(s->pb); tag[1] = avio_r8(s->pb); avio_rl16(s->pb); size = avio_rl32(s->pb); if (get_stream_idx(tag) == i && pos + size > st->index_entries[1].pos) last_start = INT64_MAX; if (get_stream_idx(tag) == i && size == st->index_entries[0].size + 8) last_start = INT64_MAX; } if (st->index_entries[0].pos > last_start) last_start = st->index_entries[0].pos; if (st->index_entries[n - 1].pos < first_end) first_end = st->index_entries[n - 1].pos; } avio_seek(s->pb, oldpos, SEEK_SET); if (last_start > first_end) return 1; return check_stream_max_drift(s); } static int avi_load_index(AVFormatContext *s) { AVIContext *avi = s->priv_data; AVIOContext *pb = s->pb; uint32_t tag, size; int64_t pos = avio_tell(pb); int64_t next; int ret = -1; if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0) goto the_end; // maybe truncated file av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end); for (;;) { tag = avio_rl32(pb); size = avio_rl32(pb); if (avio_feof(pb)) break; next = avio_tell(pb) + size + (size & 1); if (tag == MKTAG('i', 'd', 'x', '1') && avi_read_idx1(s, size) >= 0) { avi->index_loaded=2; ret = 0; }else if (tag == MKTAG('L', 'I', 'S', 'T')) { uint32_t tag1 = avio_rl32(pb); if (tag1 == MKTAG('I', 'N', 'F', 'O')) ff_read_riff_info(s, size - 4); }else if (!ret) break; if (avio_seek(pb, next, SEEK_SET) < 0) break; // something is wrong here } the_end: avio_seek(pb, pos, SEEK_SET); return ret; } static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp) { AVIStream *ast2 = st2->priv_data; int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base); av_packet_unref(&ast2->sub_pkt); if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 || avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0) ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt); } static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { AVIContext *avi = s->priv_data; AVStream *st; int i, index; int64_t pos, pos_min; AVIStream *ast; /* Does not matter which stream is requested dv in avi has the * stream information in the first video stream. */ if (avi->dv_demux) stream_index = 0; if (!avi->index_loaded) { /* we only load the index on demand */ avi_load_index(s); avi->index_loaded |= 1; } av_assert0(stream_index >= 0); st = s->streams[stream_index]; ast = st->priv_data; index = av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags); if (index < 0) { if (st->nb_index_entries > 0) av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n", timestamp * FFMAX(ast->sample_size, 1), st->index_entries[0].timestamp, st->index_entries[st->nb_index_entries - 1].timestamp); return AVERROR_INVALIDDATA; } /* find the position */ pos = st->index_entries[index].pos; timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1); av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp); if (CONFIG_DV_DEMUXER && avi->dv_demux) { /* One and only one real stream for DV in AVI, and it has video */ /* offsets. Calling with other stream indexes should have failed */ /* the av_index_search_timestamp call above. */ if (avio_seek(s->pb, pos, SEEK_SET) < 0) return -1; /* Feed the DV video stream version of the timestamp to the */ /* DV demux so it can synthesize correct timestamps. */ ff_dv_offset_reset(avi->dv_demux, timestamp); avi->stream_index = -1; return 0; } pos_min = pos; for (i = 0; i < s->nb_streams; i++) { AVStream *st2 = s->streams[i]; AVIStream *ast2 = st2->priv_data; ast2->packet_size = ast2->remaining = 0; if (ast2->sub_ctx) { seek_subtitle(st, st2, timestamp); continue; } if (st2->nb_index_entries <= 0) continue; // av_assert1(st2->codecpar->block_align); index = av_index_search_timestamp(st2, av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1), flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0)); if (index < 0) index = 0; ast2->seek_pos = st2->index_entries[index].pos; pos_min = FFMIN(pos_min,ast2->seek_pos); } for (i = 0; i < s->nb_streams; i++) { AVStream *st2 = s->streams[i]; AVIStream *ast2 = st2->priv_data; if (ast2->sub_ctx || st2->nb_index_entries <= 0) continue; index = av_index_search_timestamp( st2, av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1), flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0)); if (index < 0) index = 0; while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min) index--; ast2->frame_offset = st2->index_entries[index].timestamp; } /* do the seek */ if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) { av_log(s, AV_LOG_ERROR, "Seek failed\n"); return -1; } avi->stream_index = -1; avi->dts_max = INT_MIN; return 0; } static int avi_read_close(AVFormatContext *s) { int i; AVIContext *avi = s->priv_data; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVIStream *ast = st->priv_data; if (ast) { if (ast->sub_ctx) { av_freep(&ast->sub_ctx->pb); avformat_close_input(&ast->sub_ctx); } av_freep(&ast->sub_buffer); av_packet_unref(&ast->sub_pkt); } } av_freep(&avi->dv_demux); return 0; } static int avi_probe(AVProbeData *p) { int i; /* check file header */ for (i = 0; avi_headers[i][0]; i++) if (AV_RL32(p->buf ) == AV_RL32(avi_headers[i] ) && AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4)) return AVPROBE_SCORE_MAX; return 0; } AVInputFormat ff_avi_demuxer = { .name = "avi", .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"), .priv_data_size = sizeof(AVIContext), .extensions = "avi", .read_probe = avi_probe, .read_header = avi_read_header, .read_packet = avi_read_packet, .read_close = avi_read_close, .read_seek = avi_read_seek, .priv_class = &demuxer_class, };
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3417_0
crossvul-cpp_data_bad_438_4
/* * 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: Configuration file parser/reader. Place into the dynamic * data structure representation the conf file representing * the loadbalanced server pool. * * 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 <stdint.h> #include <stdbool.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <ctype.h> #ifdef _HAVE_SCHED_RT_ #include <sched.h> #endif #include <strings.h> #ifdef _WITH_SNMP_ #include "snmp.h" #endif #include "global_parser.h" #include "global_data.h" #include "main.h" #include "parser.h" #include "smtp.h" #include "utils.h" #include "logger.h" #if HAVE_DECL_CLONE_NEWNET #include "namespaces.h" #endif #define LVS_MAX_TIMEOUT (86400*31) /* 31 days */ /* data handlers */ /* Global def handlers */ static void use_polling_handler(vector_t *strvec) { if (!strvec) return; global_data->linkbeat_use_polling = true; } static void routerid_handler(vector_t *strvec) { FREE_PTR(global_data->router_id); global_data->router_id = set_value(strvec); } static void emailfrom_handler(vector_t *strvec) { FREE_PTR(global_data->email_from); global_data->email_from = set_value(strvec); } static void smtpto_handler(vector_t *strvec) { unsigned timeout; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &timeout, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "smtp_connect_timeout '%s' must be in [0, %d] - ignoring", FMT_STR_VSLOT(strvec, 1), UINT_MAX / TIMER_HZ); return; } if (timeout == 0) { report_config_error(CONFIG_GENERAL_ERROR, "smtp_conect_timeout must be greater than 0, setting to 1"); timeout = 1; } global_data->smtp_connection_to = timeout * TIMER_HZ; } #ifdef _WITH_VRRP_ static void dynamic_interfaces_handler(vector_t *strvec) { char *str; global_data->dynamic_interfaces = true; if (vector_size(strvec) >= 2) { str = strvec_slot(strvec, 1); if (!strcmp(str, "allow_if_changes")) global_data->allow_if_changes = true; else report_config_error(CONFIG_GENERAL_ERROR, "Unknown dynamic_interfaces option '%s'",str); } } static void no_email_faults_handler(__attribute__((unused))vector_t *strvec) { global_data->no_email_faults = true; } #endif static void smtpserver_handler(vector_t *strvec) { int ret = -1; char *port_str = SMTP_PORT_STR; /* Has a port number been specified? */ if (vector_size(strvec) >= 3) port_str = strvec_slot(strvec,2); /* It can't be an IP address if it contains '-' or '/' */ if (!strpbrk(strvec_slot(strvec, 1), "-/")) ret = inet_stosockaddr(strvec_slot(strvec, 1), port_str, &global_data->smtp_server); if (ret < 0) domain_stosockaddr(strvec_slot(strvec, 1), port_str, &global_data->smtp_server); if (global_data->smtp_server.ss_family == AF_UNSPEC) report_config_error(CONFIG_GENERAL_ERROR, "Invalid smtp server %s %s", FMT_STR_VSLOT(strvec, 1), port_str); } static void smtphelo_handler(vector_t *strvec) { char *helo_name; if (vector_size(strvec) < 2) return; helo_name = MALLOC(strlen(strvec_slot(strvec, 1)) + 1); if (!helo_name) return; strcpy(helo_name, strvec_slot(strvec, 1)); global_data->smtp_helo_name = helo_name; } static void email_handler(vector_t *strvec) { vector_t *email_vec = read_value_block(strvec); unsigned int i; char *str; if (!email_vec) { report_config_error(CONFIG_GENERAL_ERROR, "Warning - empty notification_email block"); return; } for (i = 0; i < vector_size(email_vec); i++) { str = vector_slot(email_vec, i); alloc_email(str); } free_strvec(email_vec); } static void smtp_alert_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global smtp_alert specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->smtp_alert = res; } #ifdef _WITH_VRRP_ static void smtp_alert_vrrp_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global smtp_alert_vrrp specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->smtp_alert_vrrp = res; } #endif #ifdef _WITH_LVS_ static void smtp_alert_checker_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global smtp_alert_checker specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->smtp_alert_checker = res; } #endif #ifdef _WITH_VRRP_ static void default_interface_handler(vector_t *strvec) { if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "default_interface requires interface name"); return; } FREE_PTR(global_data->default_ifname); global_data->default_ifname = set_value(strvec); /* On a reload, the VRRP process needs the default_ifp */ #ifndef _DEBUG_ if (prog_type == PROG_TYPE_VRRP) #endif { global_data->default_ifp = if_get_by_ifname(global_data->default_ifname, IF_CREATE_IF_DYNAMIC); if (!global_data->default_ifp) report_config_error(CONFIG_GENERAL_ERROR, "WARNING - default interface %s doesn't exist", global_data->default_ifname); } } #endif #ifdef _WITH_LVS_ static void lvs_timeouts(vector_t *strvec) { unsigned val; size_t i; if (vector_size(strvec) < 3) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_timeouts requires at least one option"); return; } for (i = 1; i < vector_size(strvec); i++) { if (!strcmp(strvec_slot(strvec, i), "tcp")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout tcp - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout tcp (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_tcp_timeout = val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "tcpfin")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout tcpfin - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout tcpfin (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_tcpfin_timeout = val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "udp")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout udp - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout udp (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_udp_timeout = val; i++; /* skip over value */ continue; } report_config_error(CONFIG_GENERAL_ERROR, "Unknown option %s specified for lvs_timeouts", FMT_STR_VSLOT(strvec, i)); } } #if defined _WITH_LVS_ && defined _WITH_VRRP_ static void lvs_syncd_handler(vector_t *strvec) { unsigned val; size_t i; if (global_data->lvs_syncd.ifname) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon has already been specified as %s %s - ignoring", global_data->lvs_syncd.ifname, global_data->lvs_syncd.vrrp_name); return; } if (vector_size(strvec) < 3) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon requires interface, VRRP instance"); return; } if (strlen(strvec_slot(strvec, 1)) >= IP_VS_IFNAME_MAXLEN) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon interface name '%s' too long - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } if (strlen(strvec_slot(strvec, 2)) >= IP_VS_IFNAME_MAXLEN) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon vrrp interface name '%s' too long - ignoring", FMT_STR_VSLOT(strvec, 2)); return; } global_data->lvs_syncd.ifname = set_value(strvec); global_data->lvs_syncd.vrrp_name = MALLOC(strlen(strvec_slot(strvec, 2)) + 1); if (!global_data->lvs_syncd.vrrp_name) return; strcpy(global_data->lvs_syncd.vrrp_name, strvec_slot(strvec, 2)); /* This is maintained for backwards compatibility, prior to adding "id" option */ if (vector_size(strvec) >= 4 && isdigit(FMT_STR_VSLOT(strvec, 3)[0])) { report_config_error(CONFIG_GENERAL_ERROR, "Please use keyword \"id\" before lvs_sync_daemon syncid value"); if (!read_unsigned_strvec(strvec, 3, &val, 0, 255, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid syncid (%s) - defaulting to vrid", FMT_STR_VSLOT(strvec, 3)); else global_data->lvs_syncd.syncid = val; i = 4; } else i = 3; for ( ; i < vector_size(strvec); i++) { if (!strcmp(strvec_slot(strvec, i), "id")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon id, defaulting to vrid"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 255, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid syncid (%s) - defaulting to vrid", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.syncid = val; i++; /* skip over value */ continue; } #ifdef _HAVE_IPVS_SYNCD_ATTRIBUTES_ if (!strcmp(strvec_slot(strvec, i), "maxlen")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon maxlen - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 65535 - 20 - 8, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon maxlen (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.sync_maxlen = (uint16_t)val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "port")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon port - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 65535, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon port (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.mcast_port = (uint16_t)val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "ttl")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon ttl - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, 255, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon ttl (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_syncd.mcast_ttl = (uint8_t)val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "group")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_sync_daemon group - ignoring"); continue; } if (inet_stosockaddr(strvec_slot(strvec, i+1), NULL, &global_data->lvs_syncd.mcast_group) < 0) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_sync_daemon group (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); if ((global_data->lvs_syncd.mcast_group.ss_family == AF_INET && !IN_MULTICAST(htonl(((struct sockaddr_in *)&global_data->lvs_syncd.mcast_group)->sin_addr.s_addr))) || (global_data->lvs_syncd.mcast_group.ss_family == AF_INET6 && !IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&global_data->lvs_syncd.mcast_group)->sin6_addr))) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_sync_daemon group address %s is not multicast - ignoring", FMT_STR_VSLOT(strvec, i+1)); global_data->lvs_syncd.mcast_group.ss_family = AF_UNSPEC; } i++; /* skip over value */ continue; } #endif report_config_error(CONFIG_GENERAL_ERROR, "Unknown option %s specified for lvs_sync_daemon", FMT_STR_VSLOT(strvec, i)); } } #endif static void lvs_flush_handler(__attribute__((unused)) vector_t *strvec) { global_data->lvs_flush = true; } #endif #ifdef _HAVE_SCHED_RT_ static int get_realtime_priority(vector_t *strvec, const char *process) { int min_priority; int max_priority; int priority; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %s process real-time priority specified", process); return -1; } min_priority = sched_get_priority_min(SCHED_RR); max_priority = sched_get_priority_max(SCHED_RR); if (!read_int_strvec(strvec, 1, &priority, INT_MIN, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "%s process real-time priority '%s' invalid", process, FMT_STR_VSLOT(strvec, 1)); return -1; } if (priority < min_priority) { report_config_error(CONFIG_GENERAL_ERROR, "%s process real-time priority %d less than minimum %d - setting to minimum", process, priority, min_priority); priority = min_priority; } else if (priority > max_priority) { report_config_error(CONFIG_GENERAL_ERROR, "%s process real-time priority %d greater than maximum %d - setting to maximum", process, priority, max_priority); priority = max_priority; } return priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static rlim_t get_rt_rlimit(vector_t *strvec, const char *process) { unsigned limit; rlim_t rlim; if (!read_unsigned_strvec(strvec, 1, &limit, 1, UINT32_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid %s real-time limit - %s", process, FMT_STR_VSLOT(strvec, 1)); return 0; } rlim = limit; return rlim; } #endif #endif static int8_t get_priority(vector_t *strvec, const char *process) { int priority; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %s process priority specified", process); return 0; } if (!read_int_strvec(strvec, 1, &priority, -20, 19, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid %s process priority specified", process); return 0; } return (int8_t)priority; } #ifdef _WITH_VRRP_ static void vrrp_mcast_group4_handler(vector_t *strvec) { struct sockaddr_in *mcast = &global_data->vrrp_mcast_group4; int ret; ret = inet_stosockaddr(strvec_slot(strvec, 1), 0, (struct sockaddr_storage *)mcast); if (ret < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: Cant parse vrrp_mcast_group4 [%s]. Skipping" , FMT_STR_VSLOT(strvec, 1)); } } static void vrrp_mcast_group6_handler(vector_t *strvec) { struct sockaddr_in6 *mcast = &global_data->vrrp_mcast_group6; int ret; ret = inet_stosockaddr(strvec_slot(strvec, 1), 0, (struct sockaddr_storage *)mcast); if (ret < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: Cant parse vrrp_mcast_group6 [%s]. Skipping" , FMT_STR_VSLOT(strvec, 1)); } } static void vrrp_garp_delay_handler(vector_t *strvec) { unsigned timeout; if (!read_unsigned_strvec(strvec, 1, &timeout, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_delay '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } global_data->vrrp_garp_delay = timeout * TIMER_HZ; } static void vrrp_garp_rep_handler(vector_t *strvec) { unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_repeat '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_repeat must be greater than 0, setting to 1"); repeats = 1; } global_data->vrrp_garp_rep = repeats; } static void vrrp_garp_refresh_handler(vector_t *strvec) { unsigned refresh; if (!read_unsigned_strvec(strvec, 1, &refresh, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_garp_master_refresh '%s' - ignoring", FMT_STR_VSLOT(strvec, 1)); global_data->vrrp_garp_refresh.tv_sec = 0; } else global_data->vrrp_garp_refresh.tv_sec = refresh; global_data->vrrp_garp_refresh.tv_usec = 0; } static void vrrp_garp_refresh_rep_handler(vector_t *strvec) { unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_refresh_repeat '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_master_refresh_repeat must be greater than 0, setting to 1"); repeats = 1; } global_data->vrrp_garp_refresh_rep = repeats; } static void vrrp_garp_lower_prio_delay_handler(vector_t *strvec) { unsigned delay; if (!read_unsigned_strvec(strvec, 1, &delay, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_lower_prio_delay '%s' invalid - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } global_data->vrrp_garp_lower_prio_delay = delay * TIMER_HZ; } static void vrrp_garp_lower_prio_rep_handler(vector_t *strvec) { unsigned garp_lower_prio_rep; if (!read_unsigned_strvec(strvec, 1, &garp_lower_prio_rep, 0, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_garp_lower_prio_repeat '%s'", FMT_STR_VSLOT(strvec, 1)); return; } global_data->vrrp_garp_lower_prio_rep = garp_lower_prio_rep; } static void vrrp_garp_interval_handler(vector_t *strvec) { double interval; if (!read_double_strvec(strvec, 1, &interval, 1.0 / TIMER_HZ, UINT_MAX / TIMER_HZ, true)) report_config_error(CONFIG_GENERAL_ERROR, "vrrp_garp_interval '%s' is invalid", FMT_STR_VSLOT(strvec, 1)); else global_data->vrrp_garp_interval = (unsigned)(interval * TIMER_HZ); if (global_data->vrrp_garp_interval >= 1 * TIMER_HZ) log_message(LOG_INFO, "The vrrp_garp_interval is very large - %s seconds", FMT_STR_VSLOT(strvec, 1)); } static void vrrp_gna_interval_handler(vector_t *strvec) { double interval; if (!read_double_strvec(strvec, 1, &interval, 1.0 / TIMER_HZ, UINT_MAX / TIMER_HZ, true)) report_config_error(CONFIG_GENERAL_ERROR, "vrrp_gna_interval '%s' is invalid", FMT_STR_VSLOT(strvec, 1)); else global_data->vrrp_gna_interval = (unsigned)(interval * TIMER_HZ); if (global_data->vrrp_gna_interval >= 1 * TIMER_HZ) log_message(LOG_INFO, "The vrrp_gna_interval is very large - %s seconds", FMT_STR_VSLOT(strvec, 1)); } static void vrrp_lower_prio_no_advert_handler(vector_t *strvec) { int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) report_config_error(CONFIG_GENERAL_ERROR, "Invalid value for vrrp_lower_prio_no_advert specified"); else global_data->vrrp_lower_prio_no_advert = res; } else global_data->vrrp_lower_prio_no_advert = true; } static void vrrp_higher_prio_send_advert_handler(vector_t *strvec) { int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) report_config_error(CONFIG_GENERAL_ERROR, "Invalid value for vrrp_higher_prio_send_advert specified"); else global_data->vrrp_higher_prio_send_advert = res; } else global_data->vrrp_higher_prio_send_advert = true; } static void vrrp_iptables_handler(vector_t *strvec) { global_data->vrrp_iptables_inchain[0] = '\0'; global_data->vrrp_iptables_outchain[0] = '\0'; if (vector_size(strvec) >= 2) { if (strlen(strvec_slot(strvec,1)) >= sizeof(global_data->vrrp_iptables_inchain)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : iptables in chain name too long - ignored"); return; } strcpy(global_data->vrrp_iptables_inchain, strvec_slot(strvec,1)); } if (vector_size(strvec) >= 3) { if (strlen(strvec_slot(strvec,2)) >= sizeof(global_data->vrrp_iptables_outchain)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : iptables out chain name too long - ignored"); return; } strcpy(global_data->vrrp_iptables_outchain, strvec_slot(strvec,2)); } } #ifdef _HAVE_LIBIPSET_ static void vrrp_ipsets_handler(vector_t *strvec) { size_t len; if (vector_size(strvec) >= 2) { if (strlen(strvec_slot(strvec,1)) >= sizeof(global_data->vrrp_ipset_address)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : ipset address name too long - ignored"); return; } strcpy(global_data->vrrp_ipset_address, strvec_slot(strvec,1)); } else { global_data->using_ipsets = false; return; } if (vector_size(strvec) >= 3) { if (strlen(strvec_slot(strvec,2)) >= sizeof(global_data->vrrp_ipset_address6)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : ipset IPv6 address name too long - ignored"); return; } strcpy(global_data->vrrp_ipset_address6, strvec_slot(strvec,2)); } else { /* No second set specified, copy first name and add "6" */ strcpy(global_data->vrrp_ipset_address6, global_data->vrrp_ipset_address); global_data->vrrp_ipset_address6[sizeof(global_data->vrrp_ipset_address6) - 2] = '\0'; strcat(global_data->vrrp_ipset_address6, "6"); } if (vector_size(strvec) >= 4) { if (strlen(strvec_slot(strvec,3)) >= sizeof(global_data->vrrp_ipset_address_iface6)-1) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error : ipset IPv6 address_iface name too long - ignored"); return; } strcpy(global_data->vrrp_ipset_address_iface6, strvec_slot(strvec,3)); } else { /* No third set specified, copy second name and add "_if6" */ strcpy(global_data->vrrp_ipset_address_iface6, global_data->vrrp_ipset_address6); len = strlen(global_data->vrrp_ipset_address_iface6); if (global_data->vrrp_ipset_address_iface6[len-1] == '6') global_data->vrrp_ipset_address_iface6[--len] = '\0'; global_data->vrrp_ipset_address_iface6[sizeof(global_data->vrrp_ipset_address_iface6) - 5] = '\0'; strcat(global_data->vrrp_ipset_address_iface6, "_if6"); } } #endif static void vrrp_version_handler(vector_t *strvec) { int version; if (!read_int_strvec(strvec, 1, &version, 2, 3, true)) { report_config_error(CONFIG_GENERAL_ERROR, "VRRP Error: Version must be either 2 or 3"); return; } global_data->vrrp_version = version; } static void vrrp_check_unicast_src_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_check_unicast_src = 1; } static void vrrp_check_adv_addr_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_skip_check_adv_addr = 1; } static void vrrp_strict_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_strict = 1; } static void vrrp_prio_handler(vector_t *strvec) { global_data->vrrp_process_priority = get_priority(strvec, "vrrp"); } static void vrrp_no_swap_handler(__attribute__((unused)) vector_t *strvec) { global_data->vrrp_no_swap = true; } #ifdef _HAVE_SCHED_RT_ static void vrrp_rt_priority_handler(vector_t *strvec) { int priority = get_realtime_priority(strvec, "vrrp"); if (priority >= 0) global_data->vrrp_realtime_priority = priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static void vrrp_rt_rlimit_handler(vector_t *strvec) { global_data->vrrp_rlimit_rt = get_rt_rlimit(strvec, "vrrp"); } #endif #endif #endif static void notify_fifo(vector_t *strvec, const char *type, notify_fifo_t *fifo) { if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %snotify_fifo name specified", type); return; } if (fifo->name) { report_config_error(CONFIG_GENERAL_ERROR, "%snotify_fifo already specified - ignoring %s", type, FMT_STR_VSLOT(strvec,1)); return; } fifo->name = MALLOC(strlen(strvec_slot(strvec, 1)) + 1); strcpy(fifo->name, strvec_slot(strvec, 1)); } static void notify_fifo_script(vector_t *strvec, const char *type, notify_fifo_t *fifo) { char *id_str; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No %snotify_fifo_script specified", type); return; } if (fifo->script) { report_config_error(CONFIG_GENERAL_ERROR, "%snotify_fifo_script already specified - ignoring %s", type, FMT_STR_VSLOT(strvec,1)); return; } id_str = MALLOC(strlen(type) + strlen("notify_fifo") + 1); strcpy(id_str, type); strcat(id_str, "notify_fifo"); fifo->script = notify_script_init(1, id_str); FREE(id_str); } static void global_notify_fifo(vector_t *strvec) { notify_fifo(strvec, "", &global_data->notify_fifo); } static void global_notify_fifo_script(vector_t *strvec) { notify_fifo_script(strvec, "", &global_data->notify_fifo); } #ifdef _WITH_VRRP_ static void vrrp_notify_fifo(vector_t *strvec) { notify_fifo(strvec, "vrrp_", &global_data->vrrp_notify_fifo); } static void vrrp_notify_fifo_script(vector_t *strvec) { notify_fifo_script(strvec, "vrrp_", &global_data->vrrp_notify_fifo); } #endif #ifdef _WITH_LVS_ static void lvs_notify_fifo(vector_t *strvec) { notify_fifo(strvec, "lvs_", &global_data->lvs_notify_fifo); } static void lvs_notify_fifo_script(vector_t *strvec) { notify_fifo_script(strvec, "lvs_", &global_data->lvs_notify_fifo); } #endif #ifdef _WITH_LVS_ static void checker_prio_handler(vector_t *strvec) { global_data->checker_process_priority = get_priority(strvec, "checker"); } static void checker_no_swap_handler(__attribute__((unused)) vector_t *strvec) { global_data->checker_no_swap = true; } #ifdef _HAVE_SCHED_RT_ static void checker_rt_priority_handler(vector_t *strvec) { int priority = get_realtime_priority(strvec, "checker"); if (priority >= 0) global_data->checker_realtime_priority = priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static void checker_rt_rlimit_handler(vector_t *strvec) { global_data->checker_rlimit_rt = get_rt_rlimit(strvec, "checker"); } #endif #endif #endif #ifdef _WITH_BFD_ static void bfd_prio_handler(vector_t *strvec) { global_data->bfd_process_priority = get_priority(strvec, "bfd"); } static void bfd_no_swap_handler(__attribute__((unused)) vector_t *strvec) { global_data->bfd_no_swap = true; } #ifdef _HAVE_SCHED_RT_ static void bfd_rt_priority_handler(vector_t *strvec) { int priority = get_realtime_priority(strvec, "BFD"); if (priority >= 0) global_data->bfd_realtime_priority = priority; } #if HAVE_DECL_RLIMIT_RTTIME == 1 static void bfd_rt_rlimit_handler(vector_t *strvec) { global_data->bfd_rlimit_rt = get_rt_rlimit(strvec, "bfd"); } #endif #endif #endif #ifdef _WITH_SNMP_ static void snmp_socket_handler(vector_t *strvec) { if (vector_size(strvec) > 2) { report_config_error(CONFIG_GENERAL_ERROR, "Too many parameters specified for snmp_socket - ignoring"); return; } if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "SNMP error : snmp socket name missing"); return; } if (strlen(strvec_slot(strvec,1)) > PATH_MAX - 1) { report_config_error(CONFIG_GENERAL_ERROR, "SNMP error : snmp socket name too long - ignored"); return; } if (global_data->snmp_socket) { report_config_error(CONFIG_GENERAL_ERROR, "SNMP socket already set to %s - ignoring", global_data->snmp_socket); return; } global_data->snmp_socket = MALLOC(strlen(strvec_slot(strvec, 1) + 1)); strcpy(global_data->snmp_socket, strvec_slot(strvec,1)); } static void trap_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_traps = true; } #ifdef _WITH_SNMP_VRRP_ static void snmp_vrrp_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_vrrp = true; } #endif #ifdef _WITH_SNMP_RFC_ static void snmp_rfc_handler(__attribute__((unused)) vector_t *strvec) { #ifdef _WITH_SNMP_RFCV2_ global_data->enable_snmp_rfcv2 = true; #endif #ifdef _WITH_SNMP_RFCV3_ global_data->enable_snmp_rfcv3 = true; #endif } #endif #ifdef _WITH_SNMP_RFCV2_ static void snmp_rfcv2_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_rfcv2 = true; } #endif #ifdef _WITH_SNMP_RFCV3_ static void snmp_rfcv3_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_rfcv3 = true; } #endif #ifdef _WITH_SNMP_CHECKER_ static void snmp_checker_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_snmp_checker = true; } #endif #endif #if HAVE_DECL_CLONE_NEWNET static void net_namespace_handler(vector_t *strvec) { if (!strvec) return; /* If we are reloading, there has already been a check that the * namespace hasn't changed */ if (!reload) { if (!global_data->network_namespace) { global_data->network_namespace = set_value(strvec); use_pid_dir = true; } else report_config_error(CONFIG_GENERAL_ERROR, "Duplicate net_namespace definition %s - ignoring", FMT_STR_VSLOT(strvec, 1)); } } static void namespace_ipsets_handler(vector_t *strvec) { if (!strvec) return; global_data->namespace_with_ipsets = true; } #endif #ifdef _WITH_DBUS_ static void enable_dbus_handler(__attribute__((unused)) vector_t *strvec) { global_data->enable_dbus = true; } static void dbus_service_name_handler(vector_t *strvec) { FREE_PTR(global_data->dbus_service_name); global_data->dbus_service_name = set_value(strvec); } #endif static void instance_handler(vector_t *strvec) { if (!strvec) return; if (!reload) { if (!global_data->instance_name) { global_data->instance_name = set_value(strvec); use_pid_dir = true; } else report_config_error(CONFIG_GENERAL_ERROR, "Duplicate instance definition %s - ignoring", FMT_STR_VSLOT(strvec, 1)); } } static void use_pid_dir_handler(vector_t *strvec) { if (!strvec) return; use_pid_dir = true; } static void script_user_handler(vector_t *strvec) { if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No script username specified"); return; } if (set_default_script_user(strvec_slot(strvec, 1), vector_size(strvec) > 2 ? strvec_slot(strvec, 2) : NULL)) report_config_error(CONFIG_GENERAL_ERROR, "Error setting global script uid/gid"); } static void script_security_handler(__attribute__((unused)) vector_t *strvec) { script_security = true; } static void child_wait_handler(vector_t *strvec) { unsigned secs; if (!strvec) return; if (!read_unsigned_strvec(strvec, 1, &secs, 0, UINT_MAX, false)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid child_wait_time %s", FMT_STR_VSLOT(strvec, 1)); return; } child_wait_time = secs; } #ifdef _WITH_VRRP_ static void vrrp_rx_bufs_policy_handler(vector_t *strvec) { unsigned rx_buf_size; unsigned i; if (!strvec) return; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_rx_bufs_policy missing"); return; } for (i = 1; i < vector_size(strvec); i++) { if (!strcasecmp(strvec_slot(strvec, i), "MTU")) global_data->vrrp_rx_bufs_policy |= RX_BUFS_POLICY_MTU; else if (!strcasecmp(strvec_slot(strvec, i), "ADVERT")) global_data->vrrp_rx_bufs_policy |= RX_BUFS_POLICY_ADVERT; else { if (!read_unsigned_strvec(strvec, 1, &rx_buf_size, 0, UINT_MAX, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_rx_bufs_policy %s", FMT_STR_VSLOT(strvec, i)); else { global_data->vrrp_rx_bufs_size = rx_buf_size; global_data->vrrp_rx_bufs_policy |= RX_BUFS_SIZE; } } } if ((global_data->vrrp_rx_bufs_policy & RX_BUFS_SIZE) && (global_data->vrrp_rx_bufs_policy & (RX_BUFS_POLICY_MTU | RX_BUFS_POLICY_ADVERT))) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot set vrrp_rx_bufs_policy size and policy, ignoring policy"); global_data->vrrp_rx_bufs_policy &= ~(RX_BUFS_POLICY_MTU | RX_BUFS_POLICY_ADVERT); } else if ((global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_MTU) && (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_ADVERT)) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot set both vrrp_rx_bufs_policy MTU and ADVERT, ignoring ADVERT"); global_data->vrrp_rx_bufs_policy &= ~RX_BUFS_POLICY_ADVERT; } } static void vrrp_rx_bufs_multiplier_handler(vector_t *strvec) { unsigned rx_buf_mult; if (!strvec) return; if (vector_size(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_rx_bufs_multiplier"); return; } if (!read_unsigned_strvec(strvec, 1, &rx_buf_mult, 1, UINT_MAX, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_rx_bufs_multiplier %s", FMT_STR_VSLOT(strvec, 1)); else global_data->vrrp_rx_bufs_multiples = rx_buf_mult; } #endif #if defined _WITH_VRRP_ || defined _WITH_LVS_ static unsigned get_netlink_rcv_bufs_size(vector_t *strvec, const char *type) { unsigned val; if (!strvec) return 0; if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "%s_rcv_bufs size missing", type); return 0; } if (!read_unsigned_strvec(strvec, 1, &val, 0, UINT_MAX, false)) { report_config_error(CONFIG_GENERAL_ERROR, "%s_rcv_bufs size (%s) invalid", type, FMT_STR_VSLOT(strvec, 1)); return 0; } return val; } #endif #ifdef _WITH_VRRP_ static void vrrp_netlink_monitor_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "vrrp_netlink_monitor"); if (val) global_data->vrrp_netlink_monitor_rcv_bufs = val; } static void vrrp_netlink_monitor_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global vrrp_netlink_monitor_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->vrrp_netlink_monitor_rcv_bufs_force = res; } static void vrrp_netlink_cmd_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "vrrp_netlink_cmd"); if (val) global_data->vrrp_netlink_cmd_rcv_bufs = val; } static void vrrp_netlink_cmd_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global vrrp_netlink_cmd_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->vrrp_netlink_cmd_rcv_bufs_force = res; } #endif #ifdef _WITH_LVS_ static void lvs_netlink_monitor_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "lvs_netlink_monitor"); if (val) global_data->lvs_netlink_monitor_rcv_bufs = val; } static void lvs_netlink_monitor_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global lvs_netlink_monitor_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->lvs_netlink_monitor_rcv_bufs_force = res; } static void lvs_netlink_cmd_rcv_bufs_handler(vector_t *strvec) { unsigned val; if (!strvec) return; val = get_netlink_rcv_bufs_size(strvec, "lvs_netlink_cmd"); if (val) global_data->lvs_netlink_cmd_rcv_bufs = val; } static void lvs_netlink_cmd_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global lvs_netlink_cmd_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->lvs_netlink_cmd_rcv_bufs_force = res; } static void rs_init_notifies_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global rs_init_notifies specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->rs_init_notifies = res; } static void no_checker_emails_handler(vector_t *strvec) { int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global no_checker_emails specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->no_checker_emails = res; } #endif void init_global_keywords(bool global_active) { /* global definitions mapping */ install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active); #if HAVE_DECL_CLONE_NEWNET install_keyword_root("net_namespace", &net_namespace_handler, global_active); install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active); #endif install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active); install_keyword_root("instance", &instance_handler, global_active); install_keyword_root("child_wait_time", &child_wait_handler, global_active); install_keyword_root("global_defs", NULL, global_active); install_keyword("router_id", &routerid_handler); install_keyword("notification_email_from", &emailfrom_handler); install_keyword("smtp_server", &smtpserver_handler); install_keyword("smtp_helo_name", &smtphelo_handler); install_keyword("smtp_connect_timeout", &smtpto_handler); install_keyword("notification_email", &email_handler); install_keyword("smtp_alert", &smtp_alert_handler); #ifdef _WITH_VRRP_ install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler); #endif #ifdef _WITH_LVS_ install_keyword("smtp_alert_checker", &smtp_alert_checker_handler); #endif #ifdef _WITH_VRRP_ install_keyword("dynamic_interfaces", &dynamic_interfaces_handler); install_keyword("no_email_faults", &no_email_faults_handler); install_keyword("default_interface", &default_interface_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_timeouts", &lvs_timeouts); install_keyword("lvs_flush", &lvs_flush_handler); #ifdef _WITH_VRRP_ install_keyword("lvs_sync_daemon", &lvs_syncd_handler); #endif #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler); install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler); install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler); install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler); install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler); install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("vrrp_version", &vrrp_version_handler); install_keyword("vrrp_iptables", &vrrp_iptables_handler); #ifdef _HAVE_LIBIPSET_ install_keyword("vrrp_ipsets", &vrrp_ipsets_handler); #endif install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler); install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler); install_keyword("vrrp_strict", &vrrp_strict_handler); install_keyword("vrrp_priority", &vrrp_prio_handler); install_keyword("vrrp_no_swap", &vrrp_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler); #endif #endif #endif install_keyword("notify_fifo", &global_notify_fifo); install_keyword("notify_fifo_script", &global_notify_fifo_script); #ifdef _WITH_VRRP_ install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo); install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script); #endif #ifdef _WITH_LVS_ install_keyword("lvs_notify_fifo", &lvs_notify_fifo); install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script); install_keyword("checker_priority", &checker_prio_handler); install_keyword("checker_no_swap", &checker_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("checker_rt_priority", &checker_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_BFD_ install_keyword("bfd_priority", &bfd_prio_handler); install_keyword("bfd_no_swap", &bfd_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("bfd_rt_priority", &bfd_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_SNMP_ install_keyword("snmp_socket", &snmp_socket_handler); install_keyword("enable_traps", &trap_handler); #ifdef _WITH_SNMP_VRRP_ install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler); install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */ #endif #ifdef _WITH_SNMP_RFC_ install_keyword("enable_snmp_rfc", &snmp_rfc_handler); #endif #ifdef _WITH_SNMP_RFCV2_ install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler); #endif #ifdef _WITH_SNMP_RFCV3_ install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler); #endif #ifdef _WITH_SNMP_CHECKER_ install_keyword("enable_snmp_checker", &snmp_checker_handler); #endif #endif #ifdef _WITH_DBUS_ install_keyword("enable_dbus", &enable_dbus_handler); install_keyword("dbus_service_name", &dbus_service_name_handler); #endif install_keyword("script_user", &script_user_handler); install_keyword("enable_script_security", &script_security_handler); #ifdef _WITH_VRRP_ install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler); install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler); install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler); install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler); install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("rs_init_notifies", &rs_init_notifies_handler); install_keyword("no_checker_emails", &no_checker_emails_handler); #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler); install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler); #endif }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_438_4
crossvul-cpp_data_bad_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: /* 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: /* 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/bad_3568_10
crossvul-cpp_data_good_5636_1
/* * OpenVPN -- An application to securely tunnel IP networks * over a single TCP/UDP port, with support for SSL/TLS-based * session authentication and key exchange, * packet encryption, packet authentication, and * packet compression. * * Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net> * Copyright (C) 2010 Fox Crypto B.V. <openvpn@fox-it.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 (see the file COPYING included with this * distribution); if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #elif defined(_MSC_VER) #include "config-msvc.h" #endif #include "syshead.h" #ifdef ENABLE_CRYPTO #include "crypto.h" #include "error.h" #include "misc.h" #include "memdbg.h" /* * Encryption and Compression Routines. * * On entry, buf contains the input data and length. * On exit, it should be set to the output data and length. * * If buf->len is <= 0 we should return * If buf->len is set to 0 on exit it tells the caller to ignore the packet. * * work is a workspace buffer we are given of size BUF_SIZE. * work may be used to return output data, or the input buffer * may be modified and returned as output. If output data is * returned in work, the data should start after FRAME_HEADROOM bytes * of padding to leave room for downstream routines to prepend. * * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf * by all routines (encryption, decryption, compression, and decompression). * * Note that the buf_prepend return will assert if we try to * make a header bigger than FRAME_HEADROOM. This should not * happen unless the frame parameters are wrong. */ #define CRYPT_ERROR(format) \ do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false) /** * As memcmp(), but constant-time. * Returns 0 when data is equal, non-zero otherwise. */ static int memcmp_constant_time (const void *a, const void *b, size_t size) { const uint8_t * a1 = a; const uint8_t * b1 = b; int ret = 0; size_t i; for (i = 0; i < size; i++) { ret |= *a1++ ^ *b1++; } return ret; } void openvpn_encrypt (struct buffer *buf, struct buffer work, const struct crypto_options *opt, const struct frame* frame) { struct gc_arena gc; gc_init (&gc); if (buf->len > 0 && opt->key_ctx_bi) { struct key_ctx *ctx = &opt->key_ctx_bi->encrypt; /* Do Encrypt from buf -> work */ if (ctx->cipher) { uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH]; const int iv_size = cipher_ctx_iv_length (ctx->cipher); const unsigned int mode = cipher_ctx_mode (ctx->cipher); int outlen; if (mode == OPENVPN_MODE_CBC) { CLEAR (iv_buf); /* generate pseudo-random IV */ if (opt->flags & CO_USE_IV) prng_bytes (iv_buf, iv_size); /* Put packet ID in plaintext buffer or IV, depending on cipher mode */ if (opt->packet_id) { struct packet_id_net pin; packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)); ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true)); } } else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB) { struct packet_id_net pin; struct buffer b; ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */ ASSERT (opt->packet_id); /* for this mode. */ packet_id_alloc_outgoing (&opt->packet_id->send, &pin, true); memset (iv_buf, 0, iv_size); buf_set_write (&b, iv_buf, iv_size); ASSERT (packet_id_write (&pin, &b, true, false)); } else /* We only support CBC, CFB, or OFB modes right now */ { ASSERT (0); } /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */ ASSERT (buf_init (&work, FRAME_HEADROOM (frame))); /* set the IV pseudo-randomly */ if (opt->flags & CO_USE_IV) dmsg (D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc)); dmsg (D_PACKET_CONTENT, "ENCRYPT FROM: %s", format_hex (BPTR (buf), BLEN (buf), 80, &gc)); /* cipher_ctx was already initialized with key & keylen */ ASSERT (cipher_ctx_reset(ctx->cipher, iv_buf)); /* Buffer overflow check */ if (!buf_safe (&work, buf->len + cipher_ctx_block_size(ctx->cipher))) { msg (D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d", buf->capacity, buf->offset, buf->len, work.capacity, work.offset, work.len, cipher_ctx_block_size (ctx->cipher)); goto err; } /* Encrypt packet ID, payload */ ASSERT (cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf))); work.len += outlen; /* Flush the encryption buffer */ ASSERT(cipher_ctx_final(ctx->cipher, BPTR (&work) + outlen, &outlen)); work.len += outlen; ASSERT (outlen == iv_size); /* prepend the IV to the ciphertext */ if (opt->flags & CO_USE_IV) { uint8_t *output = buf_prepend (&work, iv_size); ASSERT (output); memcpy (output, iv_buf, iv_size); } dmsg (D_PACKET_CONTENT, "ENCRYPT TO: %s", format_hex (BPTR (&work), BLEN (&work), 80, &gc)); } else /* No Encryption */ { if (opt->packet_id) { struct packet_id_net pin; packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)); ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true)); } work = *buf; } /* HMAC the ciphertext (or plaintext if !cipher) */ if (ctx->hmac) { uint8_t *output = NULL; hmac_ctx_reset (ctx->hmac); hmac_ctx_update (ctx->hmac, BPTR(&work), BLEN(&work)); output = buf_prepend (&work, hmac_ctx_size(ctx->hmac)); ASSERT (output); hmac_ctx_final (ctx->hmac, output); } *buf = work; } gc_free (&gc); return; err: crypto_clear_error(); buf->len = 0; gc_free (&gc); return; } /* * If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet. * * Set buf->len to 0 and return false on decrypt error. * * On success, buf is set to point to plaintext, true * is returned. */ bool openvpn_decrypt (struct buffer *buf, struct buffer work, const struct crypto_options *opt, const struct frame* frame) { static const char error_prefix[] = "Authenticate/Decrypt packet error"; struct gc_arena gc; gc_init (&gc); if (buf->len > 0 && opt->key_ctx_bi) { struct key_ctx *ctx = &opt->key_ctx_bi->decrypt; struct packet_id_net pin; bool have_pin = false; /* Verify the HMAC */ if (ctx->hmac) { int hmac_len; uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */ hmac_ctx_reset(ctx->hmac); /* Assume the length of the input HMAC */ hmac_len = hmac_ctx_size (ctx->hmac); /* Authentication fails if insufficient data in packet for HMAC */ if (buf->len < hmac_len) CRYPT_ERROR ("missing authentication info"); hmac_ctx_update (ctx->hmac, BPTR (buf) + hmac_len, BLEN (buf) - hmac_len); hmac_ctx_final (ctx->hmac, local_hmac); /* Compare locally computed HMAC with packet HMAC */ if (memcmp_constant_time (local_hmac, BPTR (buf), hmac_len)) CRYPT_ERROR ("packet HMAC authentication failed"); ASSERT (buf_advance (buf, hmac_len)); } /* Decrypt packet ID + payload */ if (ctx->cipher) { const unsigned int mode = cipher_ctx_mode (ctx->cipher); const int iv_size = cipher_ctx_iv_length (ctx->cipher); uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH]; int outlen; /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */ ASSERT (buf_init (&work, FRAME_HEADROOM_ADJ (frame, FRAME_HEADROOM_MARKER_DECRYPT))); /* use IV if user requested it */ CLEAR (iv_buf); if (opt->flags & CO_USE_IV) { if (buf->len < iv_size) CRYPT_ERROR ("missing IV info"); memcpy (iv_buf, BPTR (buf), iv_size); ASSERT (buf_advance (buf, iv_size)); } /* show the IV's initial state */ if (opt->flags & CO_USE_IV) dmsg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc)); if (buf->len < 1) CRYPT_ERROR ("missing payload"); /* ctx->cipher was already initialized with key & keylen */ if (!cipher_ctx_reset (ctx->cipher, iv_buf)) CRYPT_ERROR ("cipher init failed"); /* Buffer overflow check (should never happen) */ if (!buf_safe (&work, buf->len)) CRYPT_ERROR ("buffer overflow"); /* Decrypt packet ID, payload */ if (!cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf))) CRYPT_ERROR ("cipher update failed"); work.len += outlen; /* Flush the decryption buffer */ if (!cipher_ctx_final (ctx->cipher, BPTR (&work) + outlen, &outlen)) CRYPT_ERROR ("cipher final failed"); work.len += outlen; dmsg (D_PACKET_CONTENT, "DECRYPT TO: %s", format_hex (BPTR (&work), BLEN (&work), 80, &gc)); /* Get packet ID from plaintext buffer or IV, depending on cipher mode */ { if (mode == OPENVPN_MODE_CBC) { if (opt->packet_id) { if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM))) CRYPT_ERROR ("error reading CBC packet-id"); have_pin = true; } } else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB) { struct buffer b; ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */ ASSERT (opt->packet_id); /* for this mode. */ buf_set_read (&b, iv_buf, iv_size); if (!packet_id_read (&pin, &b, true)) CRYPT_ERROR ("error reading CFB/OFB packet-id"); have_pin = true; } else /* We only support CBC, CFB, or OFB modes right now */ { ASSERT (0); } } } else { work = *buf; if (opt->packet_id) { if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM))) CRYPT_ERROR ("error reading packet-id"); have_pin = !BOOL_CAST (opt->flags & CO_IGNORE_PACKET_ID); } } if (have_pin) { packet_id_reap_test (&opt->packet_id->rec); if (packet_id_test (&opt->packet_id->rec, &pin)) { packet_id_add (&opt->packet_id->rec, &pin); if (opt->pid_persist && (opt->flags & CO_PACKET_ID_LONG_FORM)) packet_id_persist_save_obj (opt->pid_persist, opt->packet_id); } else { if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS)) msg (D_REPLAY_ERRORS, "%s: bad packet ID (may be a replay): %s -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings", error_prefix, packet_id_net_print (&pin, true, &gc)); goto error_exit; } } *buf = work; } gc_free (&gc); return true; error_exit: crypto_clear_error(); buf->len = 0; gc_free (&gc); return false; } /* * How many bytes will we add to frame buffer for a given * set of crypto options? */ void crypto_adjust_frame_parameters(struct frame *frame, const struct key_type* kt, bool cipher_defined, bool use_iv, bool packet_id, bool packet_id_long_form) { frame_add_to_extra_frame (frame, (packet_id ? packet_id_size (packet_id_long_form) : 0) + ((cipher_defined && use_iv) ? cipher_kt_iv_size (kt->cipher) : 0) + (cipher_defined ? cipher_kt_block_size (kt->cipher) : 0) + /* worst case padding expansion */ kt->hmac_length); } /* * Build a struct key_type. */ void init_key_type (struct key_type *kt, const char *ciphername, bool ciphername_defined, const char *authname, bool authname_defined, int keysize, bool cfb_ofb_allowed, bool warn) { CLEAR (*kt); if (ciphername && ciphername_defined) { kt->cipher = cipher_kt_get (translate_cipher_name_from_openvpn(ciphername)); kt->cipher_length = cipher_kt_key_size (kt->cipher); if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH) kt->cipher_length = keysize; /* check legal cipher mode */ { const unsigned int mode = cipher_kt_mode (kt->cipher); if (!(mode == OPENVPN_MODE_CBC #ifdef ALLOW_NON_CBC_CIPHERS || (cfb_ofb_allowed && (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)) #endif )) #ifdef ENABLE_SMALL msg (M_FATAL, "Cipher '%s' mode not supported", ciphername); #else msg (M_FATAL, "Cipher '%s' uses a mode not supported by " PACKAGE_NAME " in your current configuration. CBC mode is always supported, while CFB and OFB modes are supported only when using SSL/TLS authentication and key exchange mode, and when " PACKAGE_NAME " has been built with ALLOW_NON_CBC_CIPHERS.", ciphername); #endif } } else { if (warn) msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used"); } if (authname && authname_defined) { kt->digest = md_kt_get (authname); kt->hmac_length = md_kt_size (kt->digest); } else { if (warn) msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used"); } } /* given a key and key_type, build a key_ctx */ void init_key_ctx (struct key_ctx *ctx, struct key *key, const struct key_type *kt, int enc, const char *prefix) { struct gc_arena gc = gc_new (); CLEAR (*ctx); if (kt->cipher && kt->cipher_length > 0) { ALLOC_OBJ(ctx->cipher, cipher_ctx_t); cipher_ctx_init (ctx->cipher, key->cipher, kt->cipher_length, kt->cipher, enc); msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key", prefix, cipher_kt_name(kt->cipher), kt->cipher_length *8); dmsg (D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix, format_hex (key->cipher, kt->cipher_length, 0, &gc)); dmsg (D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d", prefix, cipher_kt_block_size(kt->cipher), cipher_kt_iv_size(kt->cipher)); } if (kt->digest && kt->hmac_length > 0) { ALLOC_OBJ(ctx->hmac, hmac_ctx_t); hmac_ctx_init (ctx->hmac, key->hmac, kt->hmac_length, kt->digest); msg (D_HANDSHAKE, "%s: Using %d bit message hash '%s' for HMAC authentication", prefix, md_kt_size(kt->digest) * 8, md_kt_name(kt->digest)); dmsg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix, format_hex (key->hmac, kt->hmac_length, 0, &gc)); dmsg (D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d", prefix, md_kt_size(kt->digest), hmac_ctx_size(ctx->hmac)); } gc_free (&gc); } void free_key_ctx (struct key_ctx *ctx) { if (ctx->cipher) { cipher_ctx_cleanup(ctx->cipher); free(ctx->cipher); ctx->cipher = NULL; } if (ctx->hmac) { hmac_ctx_cleanup(ctx->hmac); free(ctx->hmac); ctx->hmac = NULL; } } void free_key_ctx_bi (struct key_ctx_bi *ctx) { free_key_ctx(&ctx->encrypt); free_key_ctx(&ctx->decrypt); } static bool key_is_zero (struct key *key, const struct key_type *kt) { int i; for (i = 0; i < kt->cipher_length; ++i) if (key->cipher[i]) return false; msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected"); return true; } /* * Make sure that cipher key is a valid key for current key_type. */ bool check_key (struct key *key, const struct key_type *kt) { if (kt->cipher) { /* * Check for zero key */ if (key_is_zero(key, kt)) return false; /* * Check for weak or semi-weak DES keys. */ { const int ndc = key_des_num_cblocks (kt->cipher); if (ndc) return key_des_check (key->cipher, kt->cipher_length, ndc); else return true; } } return true; } /* * Make safe mutations to key to ensure it is valid, * such as ensuring correct parity on DES keys. * * This routine cannot guarantee it will generate a good * key. You must always call check_key after this routine * to make sure. */ void fixup_key (struct key *key, const struct key_type *kt) { struct gc_arena gc = gc_new (); if (kt->cipher) { #ifdef ENABLE_DEBUG const struct key orig = *key; #endif const int ndc = key_des_num_cblocks (kt->cipher); if (ndc) key_des_fixup (key->cipher, kt->cipher_length, ndc); #ifdef ENABLE_DEBUG if (check_debug_level (D_CRYPTO_DEBUG)) { if (memcmp (orig.cipher, key->cipher, kt->cipher_length)) dmsg (D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s", format_hex (orig.cipher, kt->cipher_length, 0, &gc), format_hex (key->cipher, kt->cipher_length, 0, &gc)); } #endif } gc_free (&gc); } void check_replay_iv_consistency (const struct key_type *kt, bool packet_id, bool use_iv) { if (cfb_ofb_mode (kt) && !(packet_id && use_iv)) msg (M_FATAL, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher"); } bool cfb_ofb_mode (const struct key_type* kt) { if (kt && kt->cipher) { const unsigned int mode = cipher_kt_mode (kt->cipher); return mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB; } return false; } /* * Generate a random key. If key_type is provided, make * sure generated key is valid for key_type. */ void generate_key_random (struct key *key, const struct key_type *kt) { int cipher_len = MAX_CIPHER_KEY_LENGTH; int hmac_len = MAX_HMAC_KEY_LENGTH; struct gc_arena gc = gc_new (); do { CLEAR (*key); if (kt) { if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len) cipher_len = kt->cipher_length; if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len) hmac_len = kt->hmac_length; } if (!rand_bytes (key->cipher, cipher_len) || !rand_bytes (key->hmac, hmac_len)) msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation"); dmsg (D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex (key->cipher, cipher_len, 0, &gc)); dmsg (D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex (key->hmac, hmac_len, 0, &gc)); if (kt) fixup_key (key, kt); } while (kt && !check_key (key, kt)); gc_free (&gc); } /* * Print key material */ void key2_print (const struct key2* k, const struct key_type *kt, const char* prefix0, const char* prefix1) { struct gc_arena gc = gc_new (); ASSERT (k->n == 2); dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s", prefix0, format_hex (k->keys[0].cipher, kt->cipher_length, 0, &gc)); dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s", prefix0, format_hex (k->keys[0].hmac, kt->hmac_length, 0, &gc)); dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s", prefix1, format_hex (k->keys[1].cipher, kt->cipher_length, 0, &gc)); dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s", prefix1, format_hex (k->keys[1].hmac, kt->hmac_length, 0, &gc)); gc_free (&gc); } void test_crypto (const struct crypto_options *co, struct frame* frame) { int i, j; struct gc_arena gc = gc_new (); struct buffer src = alloc_buf_gc (TUN_MTU_SIZE (frame), &gc); struct buffer work = alloc_buf_gc (BUF_SIZE (frame), &gc); struct buffer encrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc); struct buffer decrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc); struct buffer buf = clear_buf(); /* init work */ ASSERT (buf_init (&work, FRAME_HEADROOM (frame))); msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode."); for (i = 1; i <= TUN_MTU_SIZE (frame); ++i) { update_time (); msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i); /* * Load src with random data. */ ASSERT (buf_init (&src, 0)); ASSERT (i <= src.capacity); src.len = i; ASSERT (rand_bytes (BPTR (&src), BLEN (&src))); /* copy source to input buf */ buf = work; memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src)); /* encrypt */ openvpn_encrypt (&buf, encrypt_workspace, co, frame); /* decrypt */ openvpn_decrypt (&buf, decrypt_workspace, co, frame); /* compare */ if (buf.len != src.len) msg (M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len); for (j = 0; j < i; ++j) { const uint8_t in = *(BPTR (&src) + j); const uint8_t out = *(BPTR (&buf) + j); if (in != out) msg (M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out); } } msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED."); gc_free (&gc); } #ifdef ENABLE_SSL void get_tls_handshake_key (const struct key_type *key_type, struct key_ctx_bi *ctx, const char *passphrase_file, const int key_direction, const unsigned int flags) { if (passphrase_file && key_type->hmac_length) { struct key2 key2; struct key_type kt = *key_type; struct key_direction_state kds; /* for control channel we are only authenticating, not encrypting */ kt.cipher_length = 0; kt.cipher = NULL; if (flags & GHK_INLINE) { /* key was specified inline, key text is in passphrase_file */ read_key_file (&key2, passphrase_file, RKF_INLINE|RKF_MUST_SUCCEED); /* succeeded? */ if (key2.n == 2) msg (M_INFO, "Control Channel Authentication: tls-auth using INLINE static key file"); else msg (M_FATAL, "INLINE tls-auth file lacks the requisite 2 keys"); } else { /* first try to parse as an OpenVPN static key file */ read_key_file (&key2, passphrase_file, 0); /* succeeded? */ if (key2.n == 2) { msg (M_INFO, "Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file", passphrase_file); } else { int hash_size; CLEAR (key2); /* failed, now try to get hash from a freeform file */ hash_size = read_passphrase_hash (passphrase_file, kt.digest, key2.keys[0].hmac, MAX_HMAC_KEY_LENGTH); ASSERT (hash_size == kt.hmac_length); /* suceeded */ key2.n = 1; msg (M_INFO, "Control Channel Authentication: using '%s' as a free-form passphrase file", passphrase_file); } } /* handle key direction */ key_direction_state_init (&kds, key_direction); must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys); /* initialize hmac key in both directions */ init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, OPENVPN_OP_ENCRYPT, "Outgoing Control Channel Authentication"); init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, OPENVPN_OP_DECRYPT, "Incoming Control Channel Authentication"); CLEAR (key2); } else { CLEAR (*ctx); } } #endif /* header and footer for static key file */ static const char static_key_head[] = "-----BEGIN OpenVPN Static key V1-----"; static const char static_key_foot[] = "-----END OpenVPN Static key V1-----"; static const char printable_char_fmt[] = "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)"; static const char unprintable_char_fmt[] = "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)"; /* read key from file */ void read_key_file (struct key2 *key2, const char *file, const unsigned int flags) { struct gc_arena gc = gc_new (); struct buffer in; int fd, size; uint8_t hex_byte[3] = {0, 0, 0}; const char *error_filename = file; /* parse info */ const unsigned char *cp; int hb_index = 0; int line_num = 1; int line_index = 0; int match = 0; /* output */ uint8_t* out = (uint8_t*) &key2->keys; const int keylen = sizeof (key2->keys); int count = 0; /* parse states */ # define PARSE_INITIAL 0 # define PARSE_HEAD 1 # define PARSE_DATA 2 # define PARSE_DATA_COMPLETE 3 # define PARSE_FOOT 4 # define PARSE_FINISHED 5 int state = PARSE_INITIAL; /* constants */ const int hlen = strlen (static_key_head); const int flen = strlen (static_key_foot); const int onekeylen = sizeof (key2->keys[0]); CLEAR (*key2); /* * Key can be provided as a filename in 'file' or if RKF_INLINE * is set, the actual key data itself in ascii form. */ if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */ { size = strlen (file) + 1; buf_set_read (&in, (const uint8_t *)file, size); error_filename = INLINE_FILE_TAG; } else /* 'file' is a filename which refers to a file containing the ascii key */ { in = alloc_buf_gc (2048, &gc); fd = platform_open (file, O_RDONLY, 0); if (fd == -1) msg (M_ERR, "Cannot open file key file '%s'", file); size = read (fd, in.data, in.capacity); if (size < 0) msg (M_FATAL, "Read error on key file ('%s')", file); if (size == in.capacity) msg (M_FATAL, "Key file ('%s') can be a maximum of %d bytes", file, (int)in.capacity); close (fd); } cp = (unsigned char *)in.data; while (size > 0) { const unsigned char c = *cp; #if 0 msg (M_INFO, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d", c, (int)c, state, line_num, line_index, match, count); #endif if (c == '\n') { line_index = match = 0; ++line_num; } else { /* first char of new line */ if (!line_index) { /* first char of line after header line? */ if (state == PARSE_HEAD) state = PARSE_DATA; /* first char of footer */ if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-') state = PARSE_FOOT; } /* compare read chars with header line */ if (state == PARSE_INITIAL) { if (line_index < hlen && c == static_key_head[line_index]) { if (++match == hlen) state = PARSE_HEAD; } } /* compare read chars with footer line */ if (state == PARSE_FOOT) { if (line_index < flen && c == static_key_foot[line_index]) { if (++match == flen) state = PARSE_FINISHED; } } /* reading key */ if (state == PARSE_DATA) { if (isxdigit(c)) { ASSERT (hb_index >= 0 && hb_index < 2); hex_byte[hb_index++] = c; if (hb_index == 2) { unsigned int u; ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1); *out++ = u; hb_index = 0; if (++count == keylen) state = PARSE_DATA_COMPLETE; } } else if (isspace(c)) ; else { msg (M_FATAL, (isprint (c) ? printable_char_fmt : unprintable_char_fmt), c, line_num, error_filename, count, onekeylen, keylen); } } ++line_index; } ++cp; --size; } /* * Normally we will read either 1 or 2 keys from file. */ key2->n = count / onekeylen; ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys)); if (flags & RKF_MUST_SUCCEED) { if (!key2->n) msg (M_FATAL, "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)", error_filename, count, onekeylen, keylen); if (state != PARSE_FINISHED) msg (M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)", error_filename, count, onekeylen, keylen); } /* zero file read buffer if not an inline file */ if (!(flags & RKF_INLINE)) buf_clear (&in); if (key2->n) warn_if_group_others_accessible (error_filename); #if 0 /* DEBUGGING */ { int i; printf ("KEY READ, n=%d\n", key2->n); for (i = 0; i < (int) SIZE (key2->keys); ++i) { /* format key as ascii */ const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i], sizeof (key2->keys[i]), 0, 16, "\n", &gc); printf ("[%d]\n%s\n\n", i, fmt); } } #endif /* pop our garbage collection level */ gc_free (&gc); } int read_passphrase_hash (const char *passphrase_file, const md_kt_t *digest, uint8_t *output, int len) { unsigned int outlen = 0; md_ctx_t md; ASSERT (len >= md_kt_size(digest)); memset (output, 0, len); md_ctx_init(&md, digest); /* read passphrase file */ { const int min_passphrase_size = 8; uint8_t buf[64]; int total_size = 0; int fd = platform_open (passphrase_file, O_RDONLY, 0); if (fd == -1) msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file); for (;;) { int size = read (fd, buf, sizeof (buf)); if (size == 0) break; if (size == -1) msg (M_ERR, "Read error on passphrase file: '%s'", passphrase_file); md_ctx_update(&md, buf, size); total_size += size; } close (fd); warn_if_group_others_accessible (passphrase_file); if (total_size < min_passphrase_size) msg (M_FATAL, "Passphrase file '%s' is too small (must have at least %d characters)", passphrase_file, min_passphrase_size); } md_ctx_final(&md, output); md_ctx_cleanup(&md); return md_kt_size(digest); } /* * Write key to file, return number of random bits * written. */ int write_key_file (const int nkeys, const char *filename) { struct gc_arena gc = gc_new (); int fd, i; int nbits = 0; /* must be large enough to hold full key file */ struct buffer out = alloc_buf_gc (2048, &gc); struct buffer nbits_head_text = alloc_buf_gc (128, &gc); /* how to format the ascii file representation of key */ const int bytes_per_line = 16; /* open key file */ fd = platform_open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); if (fd == -1) msg (M_ERR, "Cannot open shared secret file '%s' for write", filename); buf_printf (&out, "%s\n", static_key_head); for (i = 0; i < nkeys; ++i) { struct key key; char* fmt; /* generate random bits */ generate_key_random (&key, NULL); /* format key as ascii */ fmt = format_hex_ex ((const uint8_t*)&key, sizeof (key), 0, bytes_per_line, "\n", &gc); /* increment random bits counter */ nbits += sizeof (key) * 8; /* write to holding buffer */ buf_printf (&out, "%s\n", fmt); /* zero memory which held key component (will be freed by GC) */ memset (fmt, 0, strlen(fmt)); CLEAR (key); } buf_printf (&out, "%s\n", static_key_foot); /* write number of bits */ buf_printf (&nbits_head_text, "#\n# %d bit OpenVPN static key\n#\n", nbits); buf_write_string_file (&nbits_head_text, filename, fd); /* write key file, now formatted in out, to file */ buf_write_string_file (&out, filename, fd); if (close (fd)) msg (M_ERR, "Close error on shared secret file %s", filename); /* zero memory which held file content (memory will be freed by GC) */ buf_clear (&out); /* pop our garbage collection level */ gc_free (&gc); return nbits; } void must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n) { if (key2->n < n) { #ifdef ENABLE_SMALL msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n); #else msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d] -- try generating a new key file with '" PACKAGE " --genkey --secret [file]', or use the existing key file in bidirectional mode by specifying --%s without a key direction parameter", filename, option, key2->n, n, option); #endif } } int ascii2keydirection (int msglevel, const char *str) { if (!str) return KEY_DIRECTION_BIDIRECTIONAL; else if (!strcmp (str, "0")) return KEY_DIRECTION_NORMAL; else if (!strcmp (str, "1")) return KEY_DIRECTION_INVERSE; else { msg (msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str); return -1; } return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */ } const char * keydirection2ascii (int kd, bool remote) { if (kd == KEY_DIRECTION_BIDIRECTIONAL) return NULL; else if (kd == KEY_DIRECTION_NORMAL) return remote ? "1" : "0"; else if (kd == KEY_DIRECTION_INVERSE) return remote ? "0" : "1"; else { ASSERT (0); } return NULL; /* NOTREACHED */ } void key_direction_state_init (struct key_direction_state *kds, int key_direction) { CLEAR (*kds); switch (key_direction) { case KEY_DIRECTION_NORMAL: kds->out_key = 0; kds->in_key = 1; kds->need_keys = 2; break; case KEY_DIRECTION_INVERSE: kds->out_key = 1; kds->in_key = 0; kds->need_keys = 2; break; case KEY_DIRECTION_BIDIRECTIONAL: kds->out_key = 0; kds->in_key = 0; kds->need_keys = 1; break; default: ASSERT (0); } } void verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file) { int i; for (i = 0; i < key2->n; ++i) { /* Fix parity for DES keys and make sure not a weak key */ fixup_key (&key2->keys[i], kt); /* This should be a very improbable failure */ if (!check_key (&key2->keys[i], kt)) msg (M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.", i+1, shared_secret_file); } } /* given a key and key_type, write key to buffer */ bool write_key (const struct key *key, const struct key_type *kt, struct buffer *buf) { ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH && kt->hmac_length <= MAX_HMAC_KEY_LENGTH); if (!buf_write (buf, &kt->cipher_length, 1)) return false; if (!buf_write (buf, &kt->hmac_length, 1)) return false; if (!buf_write (buf, key->cipher, kt->cipher_length)) return false; if (!buf_write (buf, key->hmac, kt->hmac_length)) return false; return true; } /* * Given a key_type and buffer, read key from buffer. * Return: 1 on success * -1 read failure * 0 on key length mismatch */ int read_key (struct key *key, const struct key_type *kt, struct buffer *buf) { uint8_t cipher_length; uint8_t hmac_length; CLEAR (*key); if (!buf_read (buf, &cipher_length, 1)) goto read_err; if (!buf_read (buf, &hmac_length, 1)) goto read_err; if (!buf_read (buf, key->cipher, cipher_length)) goto read_err; if (!buf_read (buf, key->hmac, hmac_length)) goto read_err; if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length) goto key_len_err; return 1; read_err: msg (D_TLS_ERRORS, "TLS Error: error reading key from remote"); return -1; key_len_err: msg (D_TLS_ERRORS, "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d", kt->cipher_length, kt->hmac_length, cipher_length, hmac_length); return 0; } /* * Random number functions, used in cases where we want * reasonably strong cryptographic random number generation * without depleting our entropy pool. Used for random * IV values and a number of other miscellaneous tasks. */ static uint8_t *nonce_data = NULL; /* GLOBAL */ static const md_kt_t *nonce_md = NULL; /* GLOBAL */ static int nonce_secret_len = 0; /* GLOBAL */ /* Reset the nonce value, also done periodically to refresh entropy */ static void prng_reset_nonce () { const int size = md_kt_size (nonce_md) + nonce_secret_len; #if 1 /* Must be 1 for real usage */ if (!rand_bytes (nonce_data, size)) msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG"); #else /* Only for testing -- will cause a predictable PRNG sequence */ { int i; for (i = 0; i < size; ++i) nonce_data[i] = (uint8_t) i; } #endif } void prng_init (const char *md_name, const int nonce_secret_len_parm) { prng_uninit (); nonce_md = md_name ? md_kt_get (md_name) : NULL; if (nonce_md) { ASSERT (nonce_secret_len_parm >= NONCE_SECRET_LEN_MIN && nonce_secret_len_parm <= NONCE_SECRET_LEN_MAX); nonce_secret_len = nonce_secret_len_parm; { const int size = md_kt_size(nonce_md) + nonce_secret_len; dmsg (D_CRYPTO_DEBUG, "PRNG init md=%s size=%d", md_kt_name(nonce_md), size); nonce_data = (uint8_t*) malloc (size); check_malloc_return (nonce_data); prng_reset_nonce(); } } } void prng_uninit (void) { free (nonce_data); nonce_data = NULL; nonce_md = NULL; nonce_secret_len = 0; } void prng_bytes (uint8_t *output, int len) { static size_t processed = 0; if (nonce_md) { const int md_size = md_kt_size (nonce_md); while (len > 0) { unsigned int outlen = 0; const int blen = min_int (len, md_size); md_full(nonce_md, nonce_data, md_size + nonce_secret_len, nonce_data); memcpy (output, nonce_data, blen); output += blen; len -= blen; /* Ensure that random data is reset regularly */ processed += blen; if(processed > PRNG_NONCE_RESET_BYTES) { prng_reset_nonce(); processed = 0; } } } else rand_bytes (output, len); } /* an analogue to the random() function, but use prng_bytes */ long int get_random() { long int l; prng_bytes ((unsigned char *)&l, sizeof(l)); if (l < 0) l = -l; return l; } #ifndef ENABLE_SSL void init_ssl_lib (void) { crypto_init_lib (); } void free_ssl_lib (void) { crypto_uninit_lib (); prng_uninit(); } #endif /* ENABLE_SSL */ /* * md5 functions */ const char * md5sum (uint8_t *buf, int len, int n_print_chars, struct gc_arena *gc) { uint8_t digest[MD5_DIGEST_LENGTH]; const md_kt_t *md5_kt = md_kt_get("MD5"); md_full(md5_kt, buf, len, digest); return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars, gc); } void md5_state_init (struct md5_state *s) { const md_kt_t *md5_kt = md_kt_get("MD5"); md_ctx_init(&s->ctx, md5_kt); } void md5_state_update (struct md5_state *s, void *data, size_t len) { md_ctx_update(&s->ctx, data, len); } void md5_state_final (struct md5_state *s, struct md5_digest *out) { md_ctx_final(&s->ctx, out->digest); md_ctx_cleanup(&s->ctx); } void md5_digest_clear (struct md5_digest *digest) { CLEAR (*digest); } bool md5_digest_defined (const struct md5_digest *digest) { int i; for (i = 0; i < MD5_DIGEST_LENGTH; ++i) if (digest->digest[i]) return true; return false; } bool md5_digest_equal (const struct md5_digest *d1, const struct md5_digest *d2) { return memcmp(d1->digest, d2->digest, MD5_DIGEST_LENGTH) == 0; } #endif /* ENABLE_CRYPTO */
./CrossVul/dataset_final_sorted/CWE-200/c/good_5636_1
crossvul-cpp_data_good_725_1
/* * Univention Directory Notifier * * Copyright 2004-2019 Univention GmbH * * http://www.univention.de/ * * All rights reserved. * * The source code of this program is made available * under the terms of the GNU Affero General Public License version 3 * (GNU AGPL V3) as published by the Free Software Foundation. * * Binary versions of this program provided by Univention to you as * well as other copyrighted, protected or trademarked materials like * Logos, graphics, fonts, specific documentations and configurations, * cryptographic keys etc. are subject to a license agreement between * you and Univention and not subject to the GNU AGPL V3. * * In the case you use this program under the terms of the GNU AGPL V3, * the program is provided 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License with the Debian GNU/Linux or Univention distribution in file * /usr/share/common-licenses/AGPL-3; if not, see * <http://www.gnu.org/licenses/>. */ #define __USE_GNU #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/un.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/stat.h> #include <fcntl.h> #include <stdint.h> #include <univention/debug.h> #include "notify.h" #include "network.h" #include "cache.h" #include "sem.h" extern int sem_id; extern fd_set readfds; extern NotifyId_t notify_last_id; extern unsigned long SCHEMA_ID; /* read one line from network packages*/ int get_network_line(char *packet, char *network_line) { int i=0; memset(network_line, 0, 8192); while ( packet[i] != '\0' && packet[i] != '\n' ) { network_line[i]=packet[i]; i+=1; } if ( packet[i] == '\0' ) { return 0; } if ( i == 0 ) { network_line[i]='\0'; } network_line[i+1]='\0'; return 1; } int data_on_connection(int fd, callback_remove_handler remove) { int nread; char *network_packet; char network_line[8192]; char *p; unsigned long id; char string[1024]; unsigned long msg_id = UINT32_MAX; enum network_protocol version = network_client_get_version(fd); ioctl(fd, FIONREAD, &nread); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "new connection data = %d\n",nread); if(nread == 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "%d failed, got 0 close connection to listener ", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); network_client_dump (); return 0; } if ( nread >= 8192 ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, more than 8192 close connection to listener ", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; } /* read the whole package */ network_packet=malloc((nread+1) * sizeof(char)); read(fd, network_packet, nread); network_packet[nread]='\0'; memset(network_line, 0, 8192); p=network_packet; p_sem(sem_id); while ( get_network_line(p, network_line) ) { if ( strlen(network_line) > 0 ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "line = [%s]",network_line); } if ( !strncmp(network_line, "MSGID: ", strlen("MSGID: ")) ) { /* read message id */ msg_id=strtoul(&(network_line[strlen("MSGID: ")]), NULL, 10); p+=strlen(network_line); } else if ( !strncmp(network_line, "Version: ", strlen("Version: ")) ) { char *head = network_line, *end; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: VERSION"); version = strtoul(head + 9, &end, 10); if (!head[9] || *end) goto failed; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "VERSION=%d", version); if (version < network_procotol_version) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Forbidden VERSION=%d < %d, close connection to listener", version, network_procotol_version); goto close; } else if (version >= PROTOCOL_LAST) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Future VERSION=%d", version); version = PROTOCOL_LAST - 1; } network_client_set_version(fd, version); /* reset message id */ msg_id = UINT32_MAX; p+=strlen(network_line); } else if ( !strncmp(network_line, "Capabilities: ", strlen("Capabilities: ")) ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: Capabilities"); if ( version > PROTOCOL_UNKNOWN ) { memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), "Version: %d\nCapabilities: \n\n", version); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "SEND: %s", string); write(fd, string, strlen(string)); } else { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "Capabilities recv, but no version line"); } p+=strlen(network_line); } else if ( !strncmp(network_line, "GET_DN ", strlen("GET_DN ")) && msg_id != UINT32_MAX && version > PROTOCOL_UNKNOWN && version < PROTOCOL_3) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_DN"); id=strtoul(&(network_line[strlen("GET_DN ")]), NULL, 10); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld",id); if ( id <= notify_last_id.id) { char *dn_string = NULL; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "try to read %ld from cache", id); /* try to read from cache */ if ( (dn_string = notifier_cache_get(id)) == NULL ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld not found in cache", id); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld get one dn", id); /* read from transaction file, because not in cache */ if( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld failed ", id); /* TODO: maybe close connection? */ univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, close connection to listener ", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; } } if ( dn_string != NULL ) { snprintf(string, sizeof(string), "MSGID: %ld\n%s\n\n",msg_id,dn_string); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string); write(fd, string, strlen(string)); free(dn_string); } } else { /* set wanted id */ network_client_set_next_id(fd, id); network_client_set_msg_id(fd, msg_id); } p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if (!strncmp(p, "WAIT_ID ", 8) && msg_id != UINT32_MAX && version >= PROTOCOL_3) { char *head = network_line, *end; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: WAIT_ID"); id = strtoul(head + 8, &end, 10); if (!head[8] || *end) goto failed; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld", id); if (id <= notify_last_id.id) { snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n", msg_id, notify_last_id.id); write(fd, string, strlen(string)); } else { /* set wanted id */ network_client_set_next_id(fd, id); network_client_set_msg_id(fd, msg_id); } p += strlen(network_line) + 1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, "GET_ID", strlen("GET_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_ID"); memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,notify_last_id.id); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, "GET_SCHEMA_ID", strlen("GET_SCHEMA_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_SCHEMA_ID"); memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,SCHEMA_ID); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, "ALIVE", strlen("ALIVE")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: ALIVE"); snprintf(string, sizeof(string), "MSGID: %ld\nOKAY\n\n",msg_id); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else { p+=strlen(network_line); if (strlen(network_line) == 0 ) { p+=1; } else { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "Drop package [%s]", network_line); } } } v_sem(sem_id); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "END Package"); network_client_dump (); return 0; failed: univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Failed parsing [%s]", p); close: close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_725_1
crossvul-cpp_data_good_2454_0
/* * slcan.c - serial line CAN interface driver (using tty line discipline) * * This file is derived from linux/drivers/net/slip/slip.c * * slip.c Authors : Laurence Culhane <loz@holmes.demon.co.uk> * Fred N. van Kempen <waltje@uwalt.nl.mugnet.org> * slcan.c Author : Oliver Hartkopp <socketcan@hartkopp.net> * * 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, see http://www.gnu.org/licenses/gpl.html * * 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 <linux/module.h> #include <linux/moduleparam.h> #include <linux/uaccess.h> #include <linux/bitops.h> #include <linux/string.h> #include <linux/tty.h> #include <linux/errno.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/workqueue.h> #include <linux/can.h> #include <linux/can/skb.h> #include <linux/can/can-ml.h> MODULE_ALIAS_LDISC(N_SLCAN); MODULE_DESCRIPTION("serial line CAN interface"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>"); #define SLCAN_MAGIC 0x53CA static int maxdev = 10; /* MAX number of SLCAN channels; This can be overridden with insmod slcan.ko maxdev=nnn */ module_param(maxdev, int, 0); MODULE_PARM_DESC(maxdev, "Maximum number of slcan interfaces"); /* maximum rx buffer len: extended CAN frame with timestamp */ #define SLC_MTU (sizeof("T1111222281122334455667788EA5F\r")+1) #define SLC_CMD_LEN 1 #define SLC_SFF_ID_LEN 3 #define SLC_EFF_ID_LEN 8 struct slcan { int magic; /* Various fields. */ struct tty_struct *tty; /* ptr to TTY structure */ struct net_device *dev; /* easy for intr handling */ spinlock_t lock; struct work_struct tx_work; /* Flushes transmit buffer */ /* These are pointers to the malloc()ed frame buffers. */ unsigned char rbuff[SLC_MTU]; /* receiver buffer */ int rcount; /* received chars counter */ unsigned char xbuff[SLC_MTU]; /* transmitter buffer */ unsigned char *xhead; /* pointer to next XMIT byte */ int xleft; /* bytes left in XMIT queue */ unsigned long flags; /* Flag values/ mode etc */ #define SLF_INUSE 0 /* Channel in use */ #define SLF_ERROR 1 /* Parity, etc. error */ }; static struct net_device **slcan_devs; /************************************************************************ * SLCAN ENCAPSULATION FORMAT * ************************************************************************/ /* * A CAN frame has a can_id (11 bit standard frame format OR 29 bit extended * frame format) a data length code (can_dlc) which can be from 0 to 8 * and up to <can_dlc> data bytes as payload. * Additionally a CAN frame may become a remote transmission frame if the * RTR-bit is set. This causes another ECU to send a CAN frame with the * given can_id. * * The SLCAN ASCII representation of these different frame types is: * <type> <id> <dlc> <data>* * * Extended frames (29 bit) are defined by capital characters in the type. * RTR frames are defined as 'r' types - normal frames have 't' type: * t => 11 bit data frame * r => 11 bit RTR frame * T => 29 bit data frame * R => 29 bit RTR frame * * The <id> is 3 (standard) or 8 (extended) bytes in ASCII Hex (base64). * The <dlc> is a one byte ASCII number ('0' - '8') * The <data> section has at much ASCII Hex bytes as defined by the <dlc> * * Examples: * * t1230 : can_id 0x123, can_dlc 0, no data * t4563112233 : can_id 0x456, can_dlc 3, data 0x11 0x22 0x33 * T12ABCDEF2AA55 : extended can_id 0x12ABCDEF, can_dlc 2, data 0xAA 0x55 * r1230 : can_id 0x123, can_dlc 0, no data, remote transmission request * */ /************************************************************************ * STANDARD SLCAN DECAPSULATION * ************************************************************************/ /* Send one completely decapsulated can_frame to the network layer */ static void slc_bump(struct slcan *sl) { struct sk_buff *skb; struct can_frame cf; int i, tmp; u32 tmpid; char *cmd = sl->rbuff; memset(&cf, 0, sizeof(cf)); switch (*cmd) { case 'r': cf.can_id = CAN_RTR_FLAG; /* fallthrough */ case 't': /* store dlc ASCII value and terminate SFF CAN ID string */ cf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN]; sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0; /* point to payload data behind the dlc */ cmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1; break; case 'R': cf.can_id = CAN_RTR_FLAG; /* fallthrough */ case 'T': cf.can_id |= CAN_EFF_FLAG; /* store dlc ASCII value and terminate EFF CAN ID string */ cf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN]; sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0; /* point to payload data behind the dlc */ cmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1; break; default: return; } if (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid)) return; cf.can_id |= tmpid; /* get can_dlc from sanitized ASCII value */ if (cf.can_dlc >= '0' && cf.can_dlc < '9') cf.can_dlc -= '0'; else return; /* RTR frames may have a dlc > 0 but they never have any data bytes */ if (!(cf.can_id & CAN_RTR_FLAG)) { for (i = 0; i < cf.can_dlc; i++) { tmp = hex_to_bin(*cmd++); if (tmp < 0) return; cf.data[i] = (tmp << 4); tmp = hex_to_bin(*cmd++); if (tmp < 0) return; cf.data[i] |= tmp; } } skb = dev_alloc_skb(sizeof(struct can_frame) + sizeof(struct can_skb_priv)); if (!skb) return; skb->dev = sl->dev; skb->protocol = htons(ETH_P_CAN); skb->pkt_type = PACKET_BROADCAST; skb->ip_summed = CHECKSUM_UNNECESSARY; can_skb_reserve(skb); can_skb_prv(skb)->ifindex = sl->dev->ifindex; can_skb_prv(skb)->skbcnt = 0; skb_put_data(skb, &cf, sizeof(struct can_frame)); sl->dev->stats.rx_packets++; sl->dev->stats.rx_bytes += cf.can_dlc; netif_rx_ni(skb); } /* parse tty input stream */ static void slcan_unesc(struct slcan *sl, unsigned char s) { if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */ if (!test_and_clear_bit(SLF_ERROR, &sl->flags) && (sl->rcount > 4)) { slc_bump(sl); } sl->rcount = 0; } else { if (!test_bit(SLF_ERROR, &sl->flags)) { if (sl->rcount < SLC_MTU) { sl->rbuff[sl->rcount++] = s; return; } else { sl->dev->stats.rx_over_errors++; set_bit(SLF_ERROR, &sl->flags); } } } } /************************************************************************ * STANDARD SLCAN ENCAPSULATION * ************************************************************************/ /* Encapsulate one can_frame and stuff into a TTY queue. */ static void slc_encaps(struct slcan *sl, struct can_frame *cf) { int actual, i; unsigned char *pos; unsigned char *endpos; canid_t id = cf->can_id; pos = sl->xbuff; if (cf->can_id & CAN_RTR_FLAG) *pos = 'R'; /* becomes 'r' in standard frame format (SFF) */ else *pos = 'T'; /* becomes 't' in standard frame format (SSF) */ /* determine number of chars for the CAN-identifier */ if (cf->can_id & CAN_EFF_FLAG) { id &= CAN_EFF_MASK; endpos = pos + SLC_EFF_ID_LEN; } else { *pos |= 0x20; /* convert R/T to lower case for SFF */ id &= CAN_SFF_MASK; endpos = pos + SLC_SFF_ID_LEN; } /* build 3 (SFF) or 8 (EFF) digit CAN identifier */ pos++; while (endpos >= pos) { *endpos-- = hex_asc_upper[id & 0xf]; id >>= 4; } pos += (cf->can_id & CAN_EFF_FLAG) ? SLC_EFF_ID_LEN : SLC_SFF_ID_LEN; *pos++ = cf->can_dlc + '0'; /* RTR frames may have a dlc > 0 but they never have any data bytes */ if (!(cf->can_id & CAN_RTR_FLAG)) { for (i = 0; i < cf->can_dlc; i++) pos = hex_byte_pack_upper(pos, cf->data[i]); } *pos++ = '\r'; /* Order of next two lines is *very* important. * When we are sending a little amount of data, * the transfer may be completed inside the ops->write() * routine, because it's running with interrupts enabled. * In this case we *never* got WRITE_WAKEUP event, * if we did not request it before write operation. * 14 Oct 1994 Dmitry Gorodchanin. */ set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags); actual = sl->tty->ops->write(sl->tty, sl->xbuff, pos - sl->xbuff); sl->xleft = (pos - sl->xbuff) - actual; sl->xhead = sl->xbuff + actual; sl->dev->stats.tx_bytes += cf->can_dlc; } /* Write out any remaining transmit buffer. Scheduled when tty is writable */ static void slcan_transmit(struct work_struct *work) { struct slcan *sl = container_of(work, struct slcan, tx_work); int actual; spin_lock_bh(&sl->lock); /* First make sure we're connected. */ if (!sl->tty || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev)) { spin_unlock_bh(&sl->lock); return; } if (sl->xleft <= 0) { /* Now serial buffer is almost free & we can start * transmission of another packet */ sl->dev->stats.tx_packets++; clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags); spin_unlock_bh(&sl->lock); netif_wake_queue(sl->dev); return; } actual = sl->tty->ops->write(sl->tty, sl->xhead, sl->xleft); sl->xleft -= actual; sl->xhead += actual; spin_unlock_bh(&sl->lock); } /* * Called by the driver when there's room for more data. * Schedule the transmit. */ static void slcan_write_wakeup(struct tty_struct *tty) { struct slcan *sl; rcu_read_lock(); sl = rcu_dereference(tty->disc_data); if (sl) schedule_work(&sl->tx_work); rcu_read_unlock(); } /* Send a can_frame to a TTY queue. */ static netdev_tx_t slc_xmit(struct sk_buff *skb, struct net_device *dev) { struct slcan *sl = netdev_priv(dev); if (skb->len != CAN_MTU) goto out; spin_lock(&sl->lock); if (!netif_running(dev)) { spin_unlock(&sl->lock); printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name); goto out; } if (sl->tty == NULL) { spin_unlock(&sl->lock); goto out; } netif_stop_queue(sl->dev); slc_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */ spin_unlock(&sl->lock); out: kfree_skb(skb); return NETDEV_TX_OK; } /****************************************** * Routines looking at netdevice side. ******************************************/ /* Netdevice UP -> DOWN routine */ static int slc_close(struct net_device *dev) { struct slcan *sl = netdev_priv(dev); spin_lock_bh(&sl->lock); if (sl->tty) { /* TTY discipline is running. */ clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags); } netif_stop_queue(dev); sl->rcount = 0; sl->xleft = 0; spin_unlock_bh(&sl->lock); return 0; } /* Netdevice DOWN -> UP routine */ static int slc_open(struct net_device *dev) { struct slcan *sl = netdev_priv(dev); if (sl->tty == NULL) return -ENODEV; sl->flags &= (1 << SLF_INUSE); netif_start_queue(dev); return 0; } /* Hook the destructor so we can free slcan devs at the right point in time */ static void slc_free_netdev(struct net_device *dev) { int i = dev->base_addr; slcan_devs[i] = NULL; } static int slcan_change_mtu(struct net_device *dev, int new_mtu) { return -EINVAL; } static const struct net_device_ops slc_netdev_ops = { .ndo_open = slc_open, .ndo_stop = slc_close, .ndo_start_xmit = slc_xmit, .ndo_change_mtu = slcan_change_mtu, }; static void slc_setup(struct net_device *dev) { dev->netdev_ops = &slc_netdev_ops; dev->needs_free_netdev = true; dev->priv_destructor = slc_free_netdev; dev->hard_header_len = 0; dev->addr_len = 0; dev->tx_queue_len = 10; dev->mtu = CAN_MTU; dev->type = ARPHRD_CAN; /* New-style flags. */ dev->flags = IFF_NOARP; dev->features = NETIF_F_HW_CSUM; } /****************************************** Routines looking at TTY side. ******************************************/ /* * Handle the 'receiver data ready' interrupt. * This function is called by the 'tty_io' module in the kernel when * a block of SLCAN data has been received, which can now be decapsulated * and sent on to some IP layer for further processing. This will not * be re-entered while running but other ldisc functions may be called * in parallel */ static void slcan_receive_buf(struct tty_struct *tty, const unsigned char *cp, char *fp, int count) { struct slcan *sl = (struct slcan *) tty->disc_data; if (!sl || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev)) return; /* Read the characters out of the buffer */ while (count--) { if (fp && *fp++) { if (!test_and_set_bit(SLF_ERROR, &sl->flags)) sl->dev->stats.rx_errors++; cp++; continue; } slcan_unesc(sl, *cp++); } } /************************************ * slcan_open helper routines. ************************************/ /* Collect hanged up channels */ static void slc_sync(void) { int i; struct net_device *dev; struct slcan *sl; for (i = 0; i < maxdev; i++) { dev = slcan_devs[i]; if (dev == NULL) break; sl = netdev_priv(dev); if (sl->tty) continue; if (dev->flags & IFF_UP) dev_close(dev); } } /* Find a free SLCAN channel, and link in this `tty' line. */ static struct slcan *slc_alloc(void) { int i; char name[IFNAMSIZ]; struct net_device *dev = NULL; struct slcan *sl; int size; for (i = 0; i < maxdev; i++) { dev = slcan_devs[i]; if (dev == NULL) break; } /* Sorry, too many, all slots in use */ if (i >= maxdev) return NULL; sprintf(name, "slcan%d", i); size = ALIGN(sizeof(*sl), NETDEV_ALIGN) + sizeof(struct can_ml_priv); dev = alloc_netdev(size, name, NET_NAME_UNKNOWN, slc_setup); if (!dev) return NULL; dev->base_addr = i; sl = netdev_priv(dev); dev->ml_priv = (void *)sl + ALIGN(sizeof(*sl), NETDEV_ALIGN); /* Initialize channel control data */ sl->magic = SLCAN_MAGIC; sl->dev = dev; spin_lock_init(&sl->lock); INIT_WORK(&sl->tx_work, slcan_transmit); slcan_devs[i] = dev; return sl; } /* * Open the high-level part of the SLCAN channel. * This function is called by the TTY module when the * SLCAN line discipline is called for. Because we are * sure the tty line exists, we only have to link it to * a free SLCAN channel... * * Called in process context serialized from other ldisc calls. */ static int slcan_open(struct tty_struct *tty) { struct slcan *sl; int err; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (tty->ops->write == NULL) return -EOPNOTSUPP; /* RTnetlink lock is misused here to serialize concurrent opens of slcan channels. There are better ways, but it is the simplest one. */ rtnl_lock(); /* Collect hanged up channels. */ slc_sync(); sl = tty->disc_data; err = -EEXIST; /* First make sure we're not already connected. */ if (sl && sl->magic == SLCAN_MAGIC) goto err_exit; /* OK. Find a free SLCAN channel to use. */ err = -ENFILE; sl = slc_alloc(); if (sl == NULL) goto err_exit; sl->tty = tty; tty->disc_data = sl; if (!test_bit(SLF_INUSE, &sl->flags)) { /* Perform the low-level SLCAN initialization. */ sl->rcount = 0; sl->xleft = 0; set_bit(SLF_INUSE, &sl->flags); err = register_netdevice(sl->dev); if (err) goto err_free_chan; } /* Done. We have linked the TTY line to a channel. */ rtnl_unlock(); tty->receive_room = 65536; /* We don't flow control */ /* TTY layer expects 0 on success */ return 0; err_free_chan: sl->tty = NULL; tty->disc_data = NULL; clear_bit(SLF_INUSE, &sl->flags); slc_free_netdev(sl->dev); /* do not call free_netdev before rtnl_unlock */ rtnl_unlock(); free_netdev(sl->dev); return err; err_exit: rtnl_unlock(); /* Count references from TTY module */ return err; } /* * Close down a SLCAN channel. * This means flushing out any pending queues, and then returning. This * call is serialized against other ldisc functions. * * We also use this method for a hangup event. */ static void slcan_close(struct tty_struct *tty) { struct slcan *sl = (struct slcan *) tty->disc_data; /* First make sure we're connected. */ if (!sl || sl->magic != SLCAN_MAGIC || sl->tty != tty) return; spin_lock_bh(&sl->lock); rcu_assign_pointer(tty->disc_data, NULL); sl->tty = NULL; spin_unlock_bh(&sl->lock); synchronize_rcu(); flush_work(&sl->tx_work); /* Flush network side */ unregister_netdev(sl->dev); /* This will complete via sl_free_netdev */ } static int slcan_hangup(struct tty_struct *tty) { slcan_close(tty); return 0; } /* Perform I/O control on an active SLCAN channel. */ static int slcan_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg) { struct slcan *sl = (struct slcan *) tty->disc_data; unsigned int tmp; /* First make sure we're connected. */ if (!sl || sl->magic != SLCAN_MAGIC) return -EINVAL; switch (cmd) { case SIOCGIFNAME: tmp = strlen(sl->dev->name) + 1; if (copy_to_user((void __user *)arg, sl->dev->name, tmp)) return -EFAULT; return 0; case SIOCSIFHWADDR: return -EINVAL; default: return tty_mode_ioctl(tty, file, cmd, arg); } } static struct tty_ldisc_ops slc_ldisc = { .owner = THIS_MODULE, .magic = TTY_LDISC_MAGIC, .name = "slcan", .open = slcan_open, .close = slcan_close, .hangup = slcan_hangup, .ioctl = slcan_ioctl, .receive_buf = slcan_receive_buf, .write_wakeup = slcan_write_wakeup, }; static int __init slcan_init(void) { int status; if (maxdev < 4) maxdev = 4; /* Sanity */ pr_info("slcan: serial line CAN interface driver\n"); pr_info("slcan: %d dynamic interface channels.\n", maxdev); slcan_devs = kcalloc(maxdev, sizeof(struct net_device *), GFP_KERNEL); if (!slcan_devs) return -ENOMEM; /* Fill in our line protocol discipline, and register it */ status = tty_register_ldisc(N_SLCAN, &slc_ldisc); if (status) { printk(KERN_ERR "slcan: can't register line discipline\n"); kfree(slcan_devs); } return status; } static void __exit slcan_exit(void) { int i; struct net_device *dev; struct slcan *sl; unsigned long timeout = jiffies + HZ; int busy = 0; if (slcan_devs == NULL) return; /* First of all: check for active disciplines and hangup them. */ do { if (busy) msleep_interruptible(100); busy = 0; for (i = 0; i < maxdev; i++) { dev = slcan_devs[i]; if (!dev) continue; sl = netdev_priv(dev); spin_lock_bh(&sl->lock); if (sl->tty) { busy++; tty_hangup(sl->tty); } spin_unlock_bh(&sl->lock); } } while (busy && time_before(jiffies, timeout)); /* FIXME: hangup is async so we should wait when doing this second phase */ for (i = 0; i < maxdev; i++) { dev = slcan_devs[i]; if (!dev) continue; slcan_devs[i] = NULL; sl = netdev_priv(dev); if (sl->tty) { printk(KERN_ERR "%s: tty discipline still running\n", dev->name); } unregister_netdev(dev); } kfree(slcan_devs); slcan_devs = NULL; i = tty_unregister_ldisc(N_SLCAN); if (i) printk(KERN_ERR "slcan: can't unregister ldisc (err %d)\n", i); } module_init(slcan_init); module_exit(slcan_exit);
./CrossVul/dataset_final_sorted/CWE-200/c/good_2454_0
crossvul-cpp_data_bad_3842_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3842_0
crossvul-cpp_data_good_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 "problem_api.h" #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 (g_settings_privatereports) { struct stat statbuf; if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) { error_msg("Path '%s' isn't directory", dirname); return 404; /* Not Found */ } /* Get ABRT's group gid */ struct group *gr = getgrnam("abrt"); if (!gr) { error_msg("Group 'abrt' does not exist"); return 500; } if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname); return 403; } struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY); const bool complete = dd && problem_dump_dir_is_complete(dd); dd_close(dd); if (complete) { error_msg("Problem directory '%s' has already been processed", dirname); return 403; } } else 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, g_settings_privatereports ? 0 : 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/good_1508_0
crossvul-cpp_data_bad_1781_0
/* * Copyright (C) 2007 Oracle. 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 v2 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 021110-1307, USA. */ #include <linux/kernel.h> #include <linux/bio.h> #include <linux/buffer_head.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/time.h> #include <linux/init.h> #include <linux/string.h> #include <linux/backing-dev.h> #include <linux/mpage.h> #include <linux/swap.h> #include <linux/writeback.h> #include <linux/statfs.h> #include <linux/compat.h> #include <linux/bit_spinlock.h> #include <linux/xattr.h> #include <linux/posix_acl.h> #include <linux/falloc.h> #include <linux/slab.h> #include <linux/ratelimit.h> #include <linux/mount.h> #include <linux/btrfs.h> #include <linux/blkdev.h> #include <linux/posix_acl_xattr.h> #include <linux/uio.h> #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "btrfs_inode.h" #include "print-tree.h" #include "ordered-data.h" #include "xattr.h" #include "tree-log.h" #include "volumes.h" #include "compression.h" #include "locking.h" #include "free-space-cache.h" #include "inode-map.h" #include "backref.h" #include "hash.h" #include "props.h" #include "qgroup.h" struct btrfs_iget_args { struct btrfs_key *location; struct btrfs_root *root; }; static const struct inode_operations btrfs_dir_inode_operations; static const struct inode_operations btrfs_symlink_inode_operations; static const struct inode_operations btrfs_dir_ro_inode_operations; static const struct inode_operations btrfs_special_inode_operations; static const struct inode_operations btrfs_file_inode_operations; static const struct address_space_operations btrfs_aops; static const struct address_space_operations btrfs_symlink_aops; static const struct file_operations btrfs_dir_file_operations; static struct extent_io_ops btrfs_extent_io_ops; static struct kmem_cache *btrfs_inode_cachep; static struct kmem_cache *btrfs_delalloc_work_cachep; struct kmem_cache *btrfs_trans_handle_cachep; struct kmem_cache *btrfs_transaction_cachep; struct kmem_cache *btrfs_path_cachep; struct kmem_cache *btrfs_free_space_cachep; #define S_SHIFT 12 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = { [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE, [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR, [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV, [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV, [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO, [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK, [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK, }; static int btrfs_setsize(struct inode *inode, struct iattr *attr); static int btrfs_truncate(struct inode *inode); static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent); static noinline int cow_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock); static struct extent_map *create_pinned_em(struct inode *inode, u64 start, u64 len, u64 orig_start, u64 block_start, u64 block_len, u64 orig_block_len, u64 ram_bytes, int type); static int btrfs_dirty_inode(struct inode *inode); #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS void btrfs_test_inode_set_ops(struct inode *inode) { BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; } #endif static int btrfs_init_inode_security(struct btrfs_trans_handle *trans, struct inode *inode, struct inode *dir, const struct qstr *qstr) { int err; err = btrfs_init_acl(trans, inode, dir); if (!err) err = btrfs_xattr_security_init(trans, inode, dir, qstr); return err; } /* * this does all the hard work for inserting an inline extent into * the btree. The caller should have done a btrfs_drop_extents so that * no overlapping inline items exist in the btree */ static int insert_inline_extent(struct btrfs_trans_handle *trans, struct btrfs_path *path, int extent_inserted, struct btrfs_root *root, struct inode *inode, u64 start, size_t size, size_t compressed_size, int compress_type, struct page **compressed_pages) { struct extent_buffer *leaf; struct page *page = NULL; char *kaddr; unsigned long ptr; struct btrfs_file_extent_item *ei; int err = 0; int ret; size_t cur_size = size; unsigned long offset; if (compressed_size && compressed_pages) cur_size = compressed_size; inode_add_bytes(inode, size); if (!extent_inserted) { struct btrfs_key key; size_t datasize; key.objectid = btrfs_ino(inode); key.offset = start; key.type = BTRFS_EXTENT_DATA_KEY; datasize = btrfs_file_extent_calc_inline_size(cur_size); path->leave_spinning = 1; ret = btrfs_insert_empty_item(trans, root, path, &key, datasize); if (ret) { err = ret; goto fail; } } leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, ei, trans->transid); btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); btrfs_set_file_extent_encryption(leaf, ei, 0); btrfs_set_file_extent_other_encoding(leaf, ei, 0); btrfs_set_file_extent_ram_bytes(leaf, ei, size); ptr = btrfs_file_extent_inline_start(ei); if (compress_type != BTRFS_COMPRESS_NONE) { struct page *cpage; int i = 0; while (compressed_size > 0) { cpage = compressed_pages[i]; cur_size = min_t(unsigned long, compressed_size, PAGE_CACHE_SIZE); kaddr = kmap_atomic(cpage); write_extent_buffer(leaf, kaddr, ptr, cur_size); kunmap_atomic(kaddr); i++; ptr += cur_size; compressed_size -= cur_size; } btrfs_set_file_extent_compression(leaf, ei, compress_type); } else { page = find_get_page(inode->i_mapping, start >> PAGE_CACHE_SHIFT); btrfs_set_file_extent_compression(leaf, ei, 0); kaddr = kmap_atomic(page); offset = start & (PAGE_CACHE_SIZE - 1); write_extent_buffer(leaf, kaddr + offset, ptr, size); kunmap_atomic(kaddr); page_cache_release(page); } btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); /* * we're an inline extent, so nobody can * extend the file past i_size without locking * a page we already have locked. * * We must do any isize and inode updates * before we unlock the pages. Otherwise we * could end up racing with unlink. */ BTRFS_I(inode)->disk_i_size = inode->i_size; ret = btrfs_update_inode(trans, root, inode); return ret; fail: return err; } /* * conditionally insert an inline extent into the file. This * does the checks required to make sure the data is small enough * to fit as an inline extent. */ static noinline int cow_file_range_inline(struct btrfs_root *root, struct inode *inode, u64 start, u64 end, size_t compressed_size, int compress_type, struct page **compressed_pages) { struct btrfs_trans_handle *trans; u64 isize = i_size_read(inode); u64 actual_end = min(end + 1, isize); u64 inline_len = actual_end - start; u64 aligned_end = ALIGN(end, root->sectorsize); u64 data_len = inline_len; int ret; struct btrfs_path *path; int extent_inserted = 0; u32 extent_item_size; if (compressed_size) data_len = compressed_size; if (start > 0 || actual_end > PAGE_CACHE_SIZE || data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) || (!compressed_size && (actual_end & (root->sectorsize - 1)) == 0) || end + 1 < isize || data_len > root->fs_info->max_inline) { return 1; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { btrfs_free_path(path); return PTR_ERR(trans); } trans->block_rsv = &root->fs_info->delalloc_block_rsv; if (compressed_size && compressed_pages) extent_item_size = btrfs_file_extent_calc_inline_size( compressed_size); else extent_item_size = btrfs_file_extent_calc_inline_size( inline_len); ret = __btrfs_drop_extents(trans, root, inode, path, start, aligned_end, NULL, 1, 1, extent_item_size, &extent_inserted); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } if (isize > actual_end) inline_len = min_t(u64, isize, actual_end); ret = insert_inline_extent(trans, path, extent_inserted, root, inode, start, inline_len, compressed_size, compress_type, compressed_pages); if (ret && ret != -ENOSPC) { btrfs_abort_transaction(trans, root, ret); goto out; } else if (ret == -ENOSPC) { ret = 1; goto out; } set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); btrfs_delalloc_release_metadata(inode, end + 1 - start); btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0); out: btrfs_free_path(path); btrfs_end_transaction(trans, root); return ret; } struct async_extent { u64 start; u64 ram_size; u64 compressed_size; struct page **pages; unsigned long nr_pages; int compress_type; struct list_head list; }; struct async_cow { struct inode *inode; struct btrfs_root *root; struct page *locked_page; u64 start; u64 end; struct list_head extents; struct btrfs_work work; }; static noinline int add_async_extent(struct async_cow *cow, u64 start, u64 ram_size, u64 compressed_size, struct page **pages, unsigned long nr_pages, int compress_type) { struct async_extent *async_extent; async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS); BUG_ON(!async_extent); /* -ENOMEM */ async_extent->start = start; async_extent->ram_size = ram_size; async_extent->compressed_size = compressed_size; async_extent->pages = pages; async_extent->nr_pages = nr_pages; async_extent->compress_type = compress_type; list_add_tail(&async_extent->list, &cow->extents); return 0; } static inline int inode_need_compress(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; /* force compress */ if (btrfs_test_opt(root, FORCE_COMPRESS)) return 1; /* bad compression ratios */ if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) return 0; if (btrfs_test_opt(root, COMPRESS) || BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS || BTRFS_I(inode)->force_compress) return 1; return 0; } /* * we create compressed extents in two phases. The first * phase compresses a range of pages that have already been * locked (both pages and state bits are locked). * * This is done inside an ordered work queue, and the compression * is spread across many cpus. The actual IO submission is step * two, and the ordered work queue takes care of making sure that * happens in the same order things were put onto the queue by * writepages and friends. * * If this code finds it can't get good compression, it puts an * entry onto the work queue to write the uncompressed bytes. This * makes sure that both compressed inodes and uncompressed inodes * are written in the same order that the flusher thread sent them * down. */ static noinline void compress_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, struct async_cow *async_cow, int *num_added) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 num_bytes; u64 blocksize = root->sectorsize; u64 actual_end; u64 isize = i_size_read(inode); int ret = 0; struct page **pages = NULL; unsigned long nr_pages; unsigned long nr_pages_ret = 0; unsigned long total_compressed = 0; unsigned long total_in = 0; unsigned long max_compressed = 128 * 1024; unsigned long max_uncompressed = 128 * 1024; int i; int will_compress; int compress_type = root->fs_info->compress_type; int redirty = 0; /* if this is a small write inside eof, kick off a defrag */ if ((end - start + 1) < 16 * 1024 && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) btrfs_add_inode_defrag(NULL, inode); actual_end = min_t(u64, isize, end + 1); again: will_compress = 0; nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1; nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE); /* * we don't want to send crud past the end of i_size through * compression, that's just a waste of CPU time. So, if the * end of the file is before the start of our current * requested range of bytes, we bail out to the uncompressed * cleanup code that can deal with all of this. * * It isn't really the fastest way to fix things, but this is a * very uncommon corner. */ if (actual_end <= start) goto cleanup_and_bail_uncompressed; total_compressed = actual_end - start; /* * skip compression for a small file range(<=blocksize) that * isn't an inline extent, since it dosen't save disk space at all. */ if (total_compressed <= blocksize && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) goto cleanup_and_bail_uncompressed; /* we want to make sure that amount of ram required to uncompress * an extent is reasonable, so we limit the total size in ram * of a compressed extent to 128k. This is a crucial number * because it also controls how easily we can spread reads across * cpus for decompression. * * We also want to make sure the amount of IO required to do * a random read is reasonably small, so we limit the size of * a compressed extent to 128k. */ total_compressed = min(total_compressed, max_uncompressed); num_bytes = ALIGN(end - start + 1, blocksize); num_bytes = max(blocksize, num_bytes); total_in = 0; ret = 0; /* * we do compression for mount -o compress and when the * inode has not been flagged as nocompress. This flag can * change at any time if we discover bad compression ratios. */ if (inode_need_compress(inode)) { WARN_ON(pages); pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS); if (!pages) { /* just bail out to the uncompressed code */ goto cont; } if (BTRFS_I(inode)->force_compress) compress_type = BTRFS_I(inode)->force_compress; /* * we need to call clear_page_dirty_for_io on each * page in the range. Otherwise applications with the file * mmap'd can wander in and change the page contents while * we are compressing them. * * If the compression fails for any reason, we set the pages * dirty again later on. */ extent_range_clear_dirty_for_io(inode, start, end); redirty = 1; ret = btrfs_compress_pages(compress_type, inode->i_mapping, start, total_compressed, pages, nr_pages, &nr_pages_ret, &total_in, &total_compressed, max_compressed); if (!ret) { unsigned long offset = total_compressed & (PAGE_CACHE_SIZE - 1); struct page *page = pages[nr_pages_ret - 1]; char *kaddr; /* zero the tail end of the last page, we might be * sending it down to disk */ if (offset) { kaddr = kmap_atomic(page); memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset); kunmap_atomic(kaddr); } will_compress = 1; } } cont: if (start == 0) { /* lets try to make an inline extent */ if (ret || total_in < (actual_end - start)) { /* we didn't compress the entire range, try * to make an uncompressed inline extent. */ ret = cow_file_range_inline(root, inode, start, end, 0, 0, NULL); } else { /* try making a compressed inline extent */ ret = cow_file_range_inline(root, inode, start, end, total_compressed, compress_type, pages); } if (ret <= 0) { unsigned long clear_flags = EXTENT_DELALLOC | EXTENT_DEFRAG; unsigned long page_error_op; clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0; page_error_op = ret < 0 ? PAGE_SET_ERROR : 0; /* * inline extent creation worked or returned error, * we don't need to create any more async work items. * Unlock and free up our temp pages. */ extent_clear_unlock_delalloc(inode, start, end, NULL, clear_flags, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | page_error_op | PAGE_END_WRITEBACK); goto free_pages_out; } } if (will_compress) { /* * we aren't doing an inline extent round the compressed size * up to a block size boundary so the allocator does sane * things */ total_compressed = ALIGN(total_compressed, blocksize); /* * one last check to make sure the compression is really a * win, compare the page count read with the blocks on disk */ total_in = ALIGN(total_in, PAGE_CACHE_SIZE); if (total_compressed >= total_in) { will_compress = 0; } else { num_bytes = total_in; } } if (!will_compress && pages) { /* * the compression code ran but failed to make things smaller, * free any pages it allocated and our page pointer array */ for (i = 0; i < nr_pages_ret; i++) { WARN_ON(pages[i]->mapping); page_cache_release(pages[i]); } kfree(pages); pages = NULL; total_compressed = 0; nr_pages_ret = 0; /* flag the file so we don't compress in the future */ if (!btrfs_test_opt(root, FORCE_COMPRESS) && !(BTRFS_I(inode)->force_compress)) { BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; } } if (will_compress) { *num_added += 1; /* the async work queues will take care of doing actual * allocation on disk for these compressed pages, * and will submit them to the elevator. */ add_async_extent(async_cow, start, num_bytes, total_compressed, pages, nr_pages_ret, compress_type); if (start + num_bytes < end) { start += num_bytes; pages = NULL; cond_resched(); goto again; } } else { cleanup_and_bail_uncompressed: /* * No compression, but we still need to write the pages in * the file we've been given so far. redirty the locked * page if it corresponds to our extent and set things up * for the async work queue to run cow_file_range to do * the normal delalloc dance */ if (page_offset(locked_page) >= start && page_offset(locked_page) <= end) { __set_page_dirty_nobuffers(locked_page); /* unlocked later on in the async handlers */ } if (redirty) extent_range_redirty_for_io(inode, start, end); add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0, BTRFS_COMPRESS_NONE); *num_added += 1; } return; free_pages_out: for (i = 0; i < nr_pages_ret; i++) { WARN_ON(pages[i]->mapping); page_cache_release(pages[i]); } kfree(pages); } static void free_async_extent_pages(struct async_extent *async_extent) { int i; if (!async_extent->pages) return; for (i = 0; i < async_extent->nr_pages; i++) { WARN_ON(async_extent->pages[i]->mapping); page_cache_release(async_extent->pages[i]); } kfree(async_extent->pages); async_extent->nr_pages = 0; async_extent->pages = NULL; } /* * phase two of compressed writeback. This is the ordered portion * of the code, which only gets called in the order the work was * queued. We walk all the async extents created by compress_file_range * and send them down to the disk. */ static noinline void submit_compressed_extents(struct inode *inode, struct async_cow *async_cow) { struct async_extent *async_extent; u64 alloc_hint = 0; struct btrfs_key ins; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree; int ret = 0; again: while (!list_empty(&async_cow->extents)) { async_extent = list_entry(async_cow->extents.next, struct async_extent, list); list_del(&async_extent->list); io_tree = &BTRFS_I(inode)->io_tree; retry: /* did the compression code fall back to uncompressed IO? */ if (!async_extent->pages) { int page_started = 0; unsigned long nr_written = 0; lock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); /* allocate blocks */ ret = cow_file_range(inode, async_cow->locked_page, async_extent->start, async_extent->start + async_extent->ram_size - 1, &page_started, &nr_written, 0); /* JDM XXX */ /* * if page_started, cow_file_range inserted an * inline extent and took care of all the unlocking * and IO for us. Otherwise, we need to submit * all those pages down to the drive. */ if (!page_started && !ret) extent_write_locked_range(io_tree, inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, btrfs_get_extent, WB_SYNC_ALL); else if (ret) unlock_page(async_cow->locked_page); kfree(async_extent); cond_resched(); continue; } lock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); ret = btrfs_reserve_extent(root, async_extent->compressed_size, async_extent->compressed_size, 0, alloc_hint, &ins, 1, 1); if (ret) { free_async_extent_pages(async_extent); if (ret == -ENOSPC) { unlock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); /* * we need to redirty the pages if we decide to * fallback to uncompressed IO, otherwise we * will not submit these pages down to lower * layers. */ extent_range_redirty_for_io(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1); goto retry; } goto out_free; } /* * here we're doing allocation and writeback of the * compressed pages */ btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); em = alloc_extent_map(); if (!em) { ret = -ENOMEM; goto out_free_reserve; } em->start = async_extent->start; em->len = async_extent->ram_size; em->orig_start = em->start; em->mod_start = em->start; em->mod_len = em->len; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->ram_bytes = async_extent->ram_size; em->bdev = root->fs_info->fs_devices->latest_bdev; em->compress_type = async_extent->compress_type; set_bit(EXTENT_FLAG_PINNED, &em->flags); set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 1); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); } if (ret) goto out_free_reserve; ret = btrfs_add_ordered_extent_compress(inode, async_extent->start, ins.objectid, async_extent->ram_size, ins.offset, BTRFS_ORDERED_COMPRESSED, async_extent->compress_type); if (ret) { btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); goto out_free_reserve; } /* * clear dirty, set writeback and unlock the pages. */ extent_clear_unlock_delalloc(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, NULL, EXTENT_LOCKED | EXTENT_DELALLOC, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK); ret = btrfs_submit_compressed_write(inode, async_extent->start, async_extent->ram_size, ins.objectid, ins.offset, async_extent->pages, async_extent->nr_pages); if (ret) { struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree; struct page *p = async_extent->pages[0]; const u64 start = async_extent->start; const u64 end = start + async_extent->ram_size - 1; p->mapping = inode->i_mapping; tree->ops->writepage_end_io_hook(p, start, end, NULL, 0); p->mapping = NULL; extent_clear_unlock_delalloc(inode, start, end, NULL, 0, PAGE_END_WRITEBACK | PAGE_SET_ERROR); free_async_extent_pages(async_extent); } alloc_hint = ins.objectid + ins.offset; kfree(async_extent); cond_resched(); } return; out_free_reserve: btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1); out_free: extent_clear_unlock_delalloc(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, NULL, EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK | PAGE_SET_ERROR); free_async_extent_pages(async_extent); kfree(async_extent); goto again; } static u64 get_extent_allocation_hint(struct inode *inode, u64 start, u64 num_bytes) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_map *em; u64 alloc_hint = 0; read_lock(&em_tree->lock); em = search_extent_mapping(em_tree, start, num_bytes); if (em) { /* * if block start isn't an actual block number then find the * first block in this inode and use that as a hint. If that * block is also bogus then just don't worry about it. */ if (em->block_start >= EXTENT_MAP_LAST_BYTE) { free_extent_map(em); em = search_extent_mapping(em_tree, 0, 0); if (em && em->block_start < EXTENT_MAP_LAST_BYTE) alloc_hint = em->block_start; if (em) free_extent_map(em); } else { alloc_hint = em->block_start; free_extent_map(em); } } read_unlock(&em_tree->lock); return alloc_hint; } /* * when extent_io.c finds a delayed allocation range in the file, * the call backs end up in this code. The basic idea is to * allocate extents on disk for the range, and create ordered data structs * in ram to track those extents. * * locked_page is the page that writepage had locked already. We use * it to make sure we don't do extra locks or unlocks. * * *page_started is set to one if we unlock locked_page and do everything * required to start IO on it. It may be clean and already done with * IO when we return. */ static noinline int cow_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 alloc_hint = 0; u64 num_bytes; unsigned long ram_size; u64 disk_num_bytes; u64 cur_alloc_size; u64 blocksize = root->sectorsize; struct btrfs_key ins; struct extent_map *em; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; int ret = 0; if (btrfs_is_free_space_inode(inode)) { WARN_ON_ONCE(1); ret = -EINVAL; goto out_unlock; } num_bytes = ALIGN(end - start + 1, blocksize); num_bytes = max(blocksize, num_bytes); disk_num_bytes = num_bytes; /* if this is a small write inside eof, kick off defrag */ if (num_bytes < 64 * 1024 && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) btrfs_add_inode_defrag(NULL, inode); if (start == 0) { /* lets try to make an inline extent */ ret = cow_file_range_inline(root, inode, start, end, 0, 0, NULL); if (ret == 0) { extent_clear_unlock_delalloc(inode, start, end, NULL, EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DEFRAG, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK); *nr_written = *nr_written + (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE; *page_started = 1; goto out; } else if (ret < 0) { goto out_unlock; } } BUG_ON(disk_num_bytes > btrfs_super_total_bytes(root->fs_info->super_copy)); alloc_hint = get_extent_allocation_hint(inode, start, num_bytes); btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0); while (disk_num_bytes > 0) { unsigned long op; cur_alloc_size = disk_num_bytes; ret = btrfs_reserve_extent(root, cur_alloc_size, root->sectorsize, 0, alloc_hint, &ins, 1, 1); if (ret < 0) goto out_unlock; em = alloc_extent_map(); if (!em) { ret = -ENOMEM; goto out_reserve; } em->start = start; em->orig_start = em->start; ram_size = ins.offset; em->len = ins.offset; em->mod_start = em->start; em->mod_len = em->len; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->ram_bytes = ram_size; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PINNED, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 1); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0); } if (ret) goto out_reserve; cur_alloc_size = ins.offset; ret = btrfs_add_ordered_extent(inode, start, ins.objectid, ram_size, cur_alloc_size, 0); if (ret) goto out_drop_extent_cache; if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) { ret = btrfs_reloc_clone_csums(inode, start, cur_alloc_size); if (ret) goto out_drop_extent_cache; } if (disk_num_bytes < cur_alloc_size) break; /* we're not doing compressed IO, don't unlock the first * page (which the caller expects to stay locked), don't * clear any dirty bits and don't set any writeback bits * * Do set the Private2 bit so we know this page was properly * setup for writepage */ op = unlock ? PAGE_UNLOCK : 0; op |= PAGE_SET_PRIVATE2; extent_clear_unlock_delalloc(inode, start, start + ram_size - 1, locked_page, EXTENT_LOCKED | EXTENT_DELALLOC, op); disk_num_bytes -= cur_alloc_size; num_bytes -= cur_alloc_size; alloc_hint = ins.objectid + ins.offset; start += cur_alloc_size; } out: return ret; out_drop_extent_cache: btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0); out_reserve: btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1); out_unlock: extent_clear_unlock_delalloc(inode, start, end, locked_page, EXTENT_LOCKED | EXTENT_DO_ACCOUNTING | EXTENT_DELALLOC | EXTENT_DEFRAG, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK); goto out; } /* * work queue call back to started compression on a file and pages */ static noinline void async_cow_start(struct btrfs_work *work) { struct async_cow *async_cow; int num_added = 0; async_cow = container_of(work, struct async_cow, work); compress_file_range(async_cow->inode, async_cow->locked_page, async_cow->start, async_cow->end, async_cow, &num_added); if (num_added == 0) { btrfs_add_delayed_iput(async_cow->inode); async_cow->inode = NULL; } } /* * work queue call back to submit previously compressed pages */ static noinline void async_cow_submit(struct btrfs_work *work) { struct async_cow *async_cow; struct btrfs_root *root; unsigned long nr_pages; async_cow = container_of(work, struct async_cow, work); root = async_cow->root; nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >> PAGE_CACHE_SHIFT; /* * atomic_sub_return implies a barrier for waitqueue_active */ if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) < 5 * 1024 * 1024 && waitqueue_active(&root->fs_info->async_submit_wait)) wake_up(&root->fs_info->async_submit_wait); if (async_cow->inode) submit_compressed_extents(async_cow->inode, async_cow); } static noinline void async_cow_free(struct btrfs_work *work) { struct async_cow *async_cow; async_cow = container_of(work, struct async_cow, work); if (async_cow->inode) btrfs_add_delayed_iput(async_cow->inode); kfree(async_cow); } static int cow_file_range_async(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written) { struct async_cow *async_cow; struct btrfs_root *root = BTRFS_I(inode)->root; unsigned long nr_pages; u64 cur_end; int limit = 10 * 1024 * 1024; clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED, 1, 0, NULL, GFP_NOFS); while (start < end) { async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS); BUG_ON(!async_cow); /* -ENOMEM */ async_cow->inode = igrab(inode); async_cow->root = root; async_cow->locked_page = locked_page; async_cow->start = start; if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS && !btrfs_test_opt(root, FORCE_COMPRESS)) cur_end = end; else cur_end = min(end, start + 512 * 1024 - 1); async_cow->end = cur_end; INIT_LIST_HEAD(&async_cow->extents); btrfs_init_work(&async_cow->work, btrfs_delalloc_helper, async_cow_start, async_cow_submit, async_cow_free); nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >> PAGE_CACHE_SHIFT; atomic_add(nr_pages, &root->fs_info->async_delalloc_pages); btrfs_queue_work(root->fs_info->delalloc_workers, &async_cow->work); if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->async_delalloc_pages) < limit)); } while (atomic_read(&root->fs_info->async_submit_draining) && atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } *nr_written += nr_pages; start = cur_end + 1; } *page_started = 1; return 0; } static noinline int csum_exist_in_range(struct btrfs_root *root, u64 bytenr, u64 num_bytes) { int ret; struct btrfs_ordered_sum *sums; LIST_HEAD(list); ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr, bytenr + num_bytes - 1, &list, 0); if (ret == 0 && list_empty(&list)) return 0; while (!list_empty(&list)) { sums = list_entry(list.next, struct btrfs_ordered_sum, list); list_del(&sums->list); kfree(sums); } return 1; } /* * when nowcow writeback call back. This checks for snapshots or COW copies * of the extents that exist in the file, and COWs the file as required. * * If no cow copies or snapshots exist, we write directly to the existing * blocks on disk */ static noinline int run_delalloc_nocow(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, int force, unsigned long *nr_written) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; struct extent_buffer *leaf; struct btrfs_path *path; struct btrfs_file_extent_item *fi; struct btrfs_key found_key; u64 cow_start; u64 cur_offset; u64 extent_end; u64 extent_offset; u64 disk_bytenr; u64 num_bytes; u64 disk_num_bytes; u64 ram_bytes; int extent_type; int ret, err; int type; int nocow; int check_prev = 1; bool nolock; u64 ino = btrfs_ino(inode); path = btrfs_alloc_path(); if (!path) { extent_clear_unlock_delalloc(inode, start, end, locked_page, EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK); return -ENOMEM; } nolock = btrfs_is_free_space_inode(inode); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { extent_clear_unlock_delalloc(inode, start, end, locked_page, EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK); btrfs_free_path(path); return PTR_ERR(trans); } trans->block_rsv = &root->fs_info->delalloc_block_rsv; cow_start = (u64)-1; cur_offset = start; while (1) { ret = btrfs_lookup_file_extent(trans, root, path, ino, cur_offset, 0); if (ret < 0) goto error; if (ret > 0 && path->slots[0] > 0 && check_prev) { leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0] - 1); if (found_key.objectid == ino && found_key.type == BTRFS_EXTENT_DATA_KEY) path->slots[0]--; } check_prev = 0; next_slot: leaf = path->nodes[0]; if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) goto error; if (ret > 0) break; leaf = path->nodes[0]; } nocow = 0; disk_bytenr = 0; num_bytes = 0; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid > ino || found_key.type > BTRFS_EXTENT_DATA_KEY || found_key.offset > end) break; if (found_key.offset > cur_offset) { extent_end = found_key.offset; extent_type = 0; goto out_check; } fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi); if (extent_type == BTRFS_FILE_EXTENT_REG || extent_type == BTRFS_FILE_EXTENT_PREALLOC) { disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); extent_offset = btrfs_file_extent_offset(leaf, fi); extent_end = found_key.offset + btrfs_file_extent_num_bytes(leaf, fi); disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); if (extent_end <= start) { path->slots[0]++; goto next_slot; } if (disk_bytenr == 0) goto out_check; if (btrfs_file_extent_compression(leaf, fi) || btrfs_file_extent_encryption(leaf, fi) || btrfs_file_extent_other_encoding(leaf, fi)) goto out_check; if (extent_type == BTRFS_FILE_EXTENT_REG && !force) goto out_check; if (btrfs_extent_readonly(root, disk_bytenr)) goto out_check; if (btrfs_cross_ref_exist(trans, root, ino, found_key.offset - extent_offset, disk_bytenr)) goto out_check; disk_bytenr += extent_offset; disk_bytenr += cur_offset - found_key.offset; num_bytes = min(end + 1, extent_end) - cur_offset; /* * if there are pending snapshots for this root, * we fall into common COW way. */ if (!nolock) { err = btrfs_start_write_no_snapshoting(root); if (!err) goto out_check; } /* * force cow if csum exists in the range. * this ensure that csum for a given extent are * either valid or do not exist. */ if (csum_exist_in_range(root, disk_bytenr, num_bytes)) goto out_check; nocow = 1; } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { extent_end = found_key.offset + btrfs_file_extent_inline_len(leaf, path->slots[0], fi); extent_end = ALIGN(extent_end, root->sectorsize); } else { BUG_ON(1); } out_check: if (extent_end <= start) { path->slots[0]++; if (!nolock && nocow) btrfs_end_write_no_snapshoting(root); goto next_slot; } if (!nocow) { if (cow_start == (u64)-1) cow_start = cur_offset; cur_offset = extent_end; if (cur_offset > end) break; path->slots[0]++; goto next_slot; } btrfs_release_path(path); if (cow_start != (u64)-1) { ret = cow_file_range(inode, locked_page, cow_start, found_key.offset - 1, page_started, nr_written, 1); if (ret) { if (!nolock && nocow) btrfs_end_write_no_snapshoting(root); goto error; } cow_start = (u64)-1; } if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) { struct extent_map *em; struct extent_map_tree *em_tree; em_tree = &BTRFS_I(inode)->extent_tree; em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = cur_offset; em->orig_start = found_key.offset - extent_offset; em->len = num_bytes; em->block_len = num_bytes; em->block_start = disk_bytenr; em->orig_block_len = disk_num_bytes; em->ram_bytes = ram_bytes; em->bdev = root->fs_info->fs_devices->latest_bdev; em->mod_start = em->start; em->mod_len = em->len; set_bit(EXTENT_FLAG_PINNED, &em->flags); set_bit(EXTENT_FLAG_FILLING, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 1); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); } type = BTRFS_ORDERED_PREALLOC; } else { type = BTRFS_ORDERED_NOCOW; } ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr, num_bytes, num_bytes, type); BUG_ON(ret); /* -ENOMEM */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) { ret = btrfs_reloc_clone_csums(inode, cur_offset, num_bytes); if (ret) { if (!nolock && nocow) btrfs_end_write_no_snapshoting(root); goto error; } } extent_clear_unlock_delalloc(inode, cur_offset, cur_offset + num_bytes - 1, locked_page, EXTENT_LOCKED | EXTENT_DELALLOC, PAGE_UNLOCK | PAGE_SET_PRIVATE2); if (!nolock && nocow) btrfs_end_write_no_snapshoting(root); cur_offset = extent_end; if (cur_offset > end) break; } btrfs_release_path(path); if (cur_offset <= end && cow_start == (u64)-1) { cow_start = cur_offset; cur_offset = end; } if (cow_start != (u64)-1) { ret = cow_file_range(inode, locked_page, cow_start, end, page_started, nr_written, 1); if (ret) goto error; } error: err = btrfs_end_transaction(trans, root); if (!ret) ret = err; if (ret && cur_offset < end) extent_clear_unlock_delalloc(inode, cur_offset, end, locked_page, EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING, PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK); btrfs_free_path(path); return ret; } static inline int need_force_cow(struct inode *inode, u64 start, u64 end) { if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) && !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)) return 0; /* * @defrag_bytes is a hint value, no spinlock held here, * if is not zero, it means the file is defragging. * Force cow if given extent needs to be defragged. */ if (BTRFS_I(inode)->defrag_bytes && test_range_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_DEFRAG, 0, NULL)) return 1; return 0; } /* * extent_io.c call back to do delayed allocation processing */ static int run_delalloc_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written) { int ret; int force_cow = need_force_cow(inode, start, end); if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) { ret = run_delalloc_nocow(inode, locked_page, start, end, page_started, 1, nr_written); } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) { ret = run_delalloc_nocow(inode, locked_page, start, end, page_started, 0, nr_written); } else if (!inode_need_compress(inode)) { ret = cow_file_range(inode, locked_page, start, end, page_started, nr_written, 1); } else { set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &BTRFS_I(inode)->runtime_flags); ret = cow_file_range_async(inode, locked_page, start, end, page_started, nr_written); } return ret; } static void btrfs_split_extent_hook(struct inode *inode, struct extent_state *orig, u64 split) { u64 size; /* not delalloc, ignore it */ if (!(orig->state & EXTENT_DELALLOC)) return; size = orig->end - orig->start + 1; if (size > BTRFS_MAX_EXTENT_SIZE) { u64 num_extents; u64 new_size; /* * See the explanation in btrfs_merge_extent_hook, the same * applies here, just in reverse. */ new_size = orig->end - split + 1; num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE); new_size = split - orig->start; num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE); if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE) >= num_extents) return; } spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } /* * extent_io.c merge_extent_hook, used to track merged delayed allocation * extents so we can keep track of new extents that are just merged onto old * extents, such as when we are doing sequential writes, so we can properly * account for the metadata space we'll need. */ static void btrfs_merge_extent_hook(struct inode *inode, struct extent_state *new, struct extent_state *other) { u64 new_size, old_size; u64 num_extents; /* not delalloc, ignore it */ if (!(other->state & EXTENT_DELALLOC)) return; if (new->start > other->start) new_size = new->end - other->start + 1; else new_size = other->end - new->start + 1; /* we're not bigger than the max, unreserve the space and go */ if (new_size <= BTRFS_MAX_EXTENT_SIZE) { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents--; spin_unlock(&BTRFS_I(inode)->lock); return; } /* * We have to add up either side to figure out how many extents were * accounted for before we merged into one big extent. If the number of * extents we accounted for is <= the amount we need for the new range * then we can return, otherwise drop. Think of it like this * * [ 4k][MAX_SIZE] * * So we've grown the extent by a MAX_SIZE extent, this would mean we * need 2 outstanding extents, on one side we have 1 and the other side * we have 1 so they are == and we can return. But in this case * * [MAX_SIZE+4k][MAX_SIZE+4k] * * Each range on their own accounts for 2 extents, but merged together * they are only 3 extents worth of accounting, so we need to drop in * this case. */ old_size = other->end - other->start + 1; num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE); old_size = new->end - new->start + 1; num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE); if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE) >= num_extents) return; spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents--; spin_unlock(&BTRFS_I(inode)->lock); } static void btrfs_add_delalloc_inodes(struct btrfs_root *root, struct inode *inode) { spin_lock(&root->delalloc_lock); if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) { list_add_tail(&BTRFS_I(inode)->delalloc_inodes, &root->delalloc_inodes); set_bit(BTRFS_INODE_IN_DELALLOC_LIST, &BTRFS_I(inode)->runtime_flags); root->nr_delalloc_inodes++; if (root->nr_delalloc_inodes == 1) { spin_lock(&root->fs_info->delalloc_root_lock); BUG_ON(!list_empty(&root->delalloc_root)); list_add_tail(&root->delalloc_root, &root->fs_info->delalloc_roots); spin_unlock(&root->fs_info->delalloc_root_lock); } } spin_unlock(&root->delalloc_lock); } static void btrfs_del_delalloc_inode(struct btrfs_root *root, struct inode *inode) { spin_lock(&root->delalloc_lock); if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) { list_del_init(&BTRFS_I(inode)->delalloc_inodes); clear_bit(BTRFS_INODE_IN_DELALLOC_LIST, &BTRFS_I(inode)->runtime_flags); root->nr_delalloc_inodes--; if (!root->nr_delalloc_inodes) { spin_lock(&root->fs_info->delalloc_root_lock); BUG_ON(list_empty(&root->delalloc_root)); list_del_init(&root->delalloc_root); spin_unlock(&root->fs_info->delalloc_root_lock); } } spin_unlock(&root->delalloc_lock); } /* * extent_io.c set_bit_hook, used to track delayed allocation * bytes in this file, and to maintain the list of inodes that * have pending delalloc work to be done. */ static void btrfs_set_bit_hook(struct inode *inode, struct extent_state *state, unsigned *bits) { if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC)) WARN_ON(1); /* * set_bit and clear bit hooks normally require _irqsave/restore * but in this case, we are only testing for the DELALLOC * bit, which is only set or cleared with irqs on */ if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 len = state->end + 1 - state->start; bool do_list = !btrfs_is_free_space_inode(inode); if (*bits & EXTENT_FIRST_DELALLOC) { *bits &= ~EXTENT_FIRST_DELALLOC; } else { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } /* For sanity tests */ if (btrfs_test_is_dummy_root(root)) return; __percpu_counter_add(&root->fs_info->delalloc_bytes, len, root->fs_info->delalloc_batch); spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->delalloc_bytes += len; if (*bits & EXTENT_DEFRAG) BTRFS_I(inode)->defrag_bytes += len; if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST, &BTRFS_I(inode)->runtime_flags)) btrfs_add_delalloc_inodes(root, inode); spin_unlock(&BTRFS_I(inode)->lock); } } /* * extent_io.c clear_bit_hook, see set_bit_hook for why */ static void btrfs_clear_bit_hook(struct inode *inode, struct extent_state *state, unsigned *bits) { u64 len = state->end + 1 - state->start; u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1, BTRFS_MAX_EXTENT_SIZE); spin_lock(&BTRFS_I(inode)->lock); if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) BTRFS_I(inode)->defrag_bytes -= len; spin_unlock(&BTRFS_I(inode)->lock); /* * set_bit and clear bit hooks normally require _irqsave/restore * but in this case, we are only testing for the DELALLOC * bit, which is only set or cleared with irqs on */ if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { struct btrfs_root *root = BTRFS_I(inode)->root; bool do_list = !btrfs_is_free_space_inode(inode); if (*bits & EXTENT_FIRST_DELALLOC) { *bits &= ~EXTENT_FIRST_DELALLOC; } else if (!(*bits & EXTENT_DO_ACCOUNTING)) { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents -= num_extents; spin_unlock(&BTRFS_I(inode)->lock); } /* * We don't reserve metadata space for space cache inodes so we * don't need to call dellalloc_release_metadata if there is an * error. */ if (*bits & EXTENT_DO_ACCOUNTING && root != root->fs_info->tree_root) btrfs_delalloc_release_metadata(inode, len); /* For sanity tests. */ if (btrfs_test_is_dummy_root(root)) return; if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID && do_list && !(state->state & EXTENT_NORESERVE)) btrfs_free_reserved_data_space(inode, len); __percpu_counter_add(&root->fs_info->delalloc_bytes, -len, root->fs_info->delalloc_batch); spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->delalloc_bytes -= len; if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 && test_bit(BTRFS_INODE_IN_DELALLOC_LIST, &BTRFS_I(inode)->runtime_flags)) btrfs_del_delalloc_inode(root, inode); spin_unlock(&BTRFS_I(inode)->lock); } } /* * extent_io.c merge_bio_hook, this must check the chunk tree to make sure * we don't create bios that span stripes or chunks */ int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset, size_t size, struct bio *bio, unsigned long bio_flags) { struct btrfs_root *root = BTRFS_I(page->mapping->host)->root; u64 logical = (u64)bio->bi_iter.bi_sector << 9; u64 length = 0; u64 map_length; int ret; if (bio_flags & EXTENT_BIO_COMPRESSED) return 0; length = bio->bi_iter.bi_size; map_length = length; ret = btrfs_map_block(root->fs_info, rw, logical, &map_length, NULL, 0); /* Will always return 0 with map_multi == NULL */ BUG_ON(ret < 0); if (map_length < length + size) return 1; return 0; } /* * in order to insert checksums into the metadata in large chunks, * we wait until bio submission time. All the pages in the bio are * checksummed and sums are attached onto the ordered extent record. * * At IO completion time the cums attached on the ordered extent record * are inserted into the btree */ static int __btrfs_submit_bio_start(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; ret = btrfs_csum_one_bio(root, inode, bio, 0, 0); BUG_ON(ret); /* -ENOMEM */ return 0; } /* * in order to insert checksums into the metadata in large chunks, * we wait until bio submission time. All the pages in the bio are * checksummed and sums are attached onto the ordered extent record. * * At IO completion time the cums attached on the ordered extent record * are inserted into the btree */ static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret; ret = btrfs_map_bio(root, rw, bio, mirror_num, 1); if (ret) { bio->bi_error = ret; bio_endio(bio); } return ret; } /* * extent_io.c submission hook. This does the right thing for csum calculation * on write, or reading the csums from the tree before a read */ static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; int skip_sum; int metadata = 0; int async = !atomic_read(&BTRFS_I(inode)->sync_writers); skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; if (btrfs_is_free_space_inode(inode)) metadata = 2; if (!(rw & REQ_WRITE)) { ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata); if (ret) goto out; if (bio_flags & EXTENT_BIO_COMPRESSED) { ret = btrfs_submit_compressed_read(inode, bio, mirror_num, bio_flags); goto out; } else if (!skip_sum) { ret = btrfs_lookup_bio_sums(root, inode, bio, NULL); if (ret) goto out; } goto mapit; } else if (async && !skip_sum) { /* csum items have already been cloned */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) goto mapit; /* we're doing a write, do the async checksumming */ ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info, inode, rw, bio, mirror_num, bio_flags, bio_offset, __btrfs_submit_bio_start, __btrfs_submit_bio_done); goto out; } else if (!skip_sum) { ret = btrfs_csum_one_bio(root, inode, bio, 0, 0); if (ret) goto out; } mapit: ret = btrfs_map_bio(root, rw, bio, mirror_num, 0); out: if (ret < 0) { bio->bi_error = ret; bio_endio(bio); } return ret; } /* * given a list of ordered sums record them in the inode. This happens * at IO completion time based on sums calculated at bio submission time. */ static noinline int add_pending_csums(struct btrfs_trans_handle *trans, struct inode *inode, u64 file_offset, struct list_head *list) { struct btrfs_ordered_sum *sum; list_for_each_entry(sum, list, list) { trans->adding_csums = 1; btrfs_csum_file_blocks(trans, BTRFS_I(inode)->root->fs_info->csum_root, sum); trans->adding_csums = 0; } return 0; } int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end, struct extent_state **cached_state) { WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0); return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end, cached_state, GFP_NOFS); } /* see btrfs_writepage_start_hook for details on why this is required */ struct btrfs_writepage_fixup { struct page *page; struct btrfs_work work; }; static void btrfs_writepage_fixup_worker(struct btrfs_work *work) { struct btrfs_writepage_fixup *fixup; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; struct page *page; struct inode *inode; u64 page_start; u64 page_end; int ret; fixup = container_of(work, struct btrfs_writepage_fixup, work); page = fixup->page; again: lock_page(page); if (!page->mapping || !PageDirty(page) || !PageChecked(page)) { ClearPageChecked(page); goto out_page; } inode = page->mapping->host; page_start = page_offset(page); page_end = page_offset(page) + PAGE_CACHE_SIZE - 1; lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0, &cached_state); /* already ordered? We're done */ if (PagePrivate2(page)) goto out; ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (ret) { mapping_set_error(page->mapping, ret); end_extent_writepage(page, ret, page_start, page_end); ClearPageChecked(page); goto out; } btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); ClearPageChecked(page); set_page_dirty(page); out: unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_page: unlock_page(page); page_cache_release(page); kfree(fixup); } /* * There are a few paths in the higher layers of the kernel that directly * set the page dirty bit without asking the filesystem if it is a * good idea. This causes problems because we want to make sure COW * properly happens and the data=ordered rules are followed. * * In our case any range that doesn't have the ORDERED bit set * hasn't been properly setup for IO. We kick off an async process * to fix it up. The async helper will wait for ordered extents, set * the delalloc bit and make it safe to write the page. */ static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end) { struct inode *inode = page->mapping->host; struct btrfs_writepage_fixup *fixup; struct btrfs_root *root = BTRFS_I(inode)->root; /* this page is properly in the ordered list */ if (TestClearPagePrivate2(page)) return 0; if (PageChecked(page)) return -EAGAIN; fixup = kzalloc(sizeof(*fixup), GFP_NOFS); if (!fixup) return -EAGAIN; SetPageChecked(page); page_cache_get(page); btrfs_init_work(&fixup->work, btrfs_fixup_helper, btrfs_writepage_fixup_worker, NULL, NULL); fixup->page = page; btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work); return -EBUSY; } static int insert_reserved_file_extent(struct btrfs_trans_handle *trans, struct inode *inode, u64 file_pos, u64 disk_bytenr, u64 disk_num_bytes, u64 num_bytes, u64 ram_bytes, u8 compression, u8 encryption, u16 other_encoding, int extent_type) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *fi; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key ins; int extent_inserted = 0; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; /* * we may be replacing one extent in the tree with another. * The new extent is pinned in the extent map, and we don't want * to drop it from the cache until it is completely in the btree. * * So, tell btrfs_drop_extents to leave this extent in the cache. * the caller is expected to unpin it and allow it to be merged * with the others. */ ret = __btrfs_drop_extents(trans, root, inode, path, file_pos, file_pos + num_bytes, NULL, 0, 1, sizeof(*fi), &extent_inserted); if (ret) goto out; if (!extent_inserted) { ins.objectid = btrfs_ino(inode); ins.offset = file_pos; ins.type = BTRFS_EXTENT_DATA_KEY; path->leave_spinning = 1; ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi)); if (ret) goto out; } leaf = path->nodes[0]; fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, fi, trans->transid); btrfs_set_file_extent_type(leaf, fi, extent_type); btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr); btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes); btrfs_set_file_extent_offset(leaf, fi, 0); btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes); btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes); btrfs_set_file_extent_compression(leaf, fi, compression); btrfs_set_file_extent_encryption(leaf, fi, encryption); btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding); btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); inode_add_bytes(inode, num_bytes); ins.objectid = disk_bytenr; ins.offset = disk_num_bytes; ins.type = BTRFS_EXTENT_ITEM_KEY; ret = btrfs_alloc_reserved_file_extent(trans, root, root->root_key.objectid, btrfs_ino(inode), file_pos, &ins); out: btrfs_free_path(path); return ret; } /* snapshot-aware defrag */ struct sa_defrag_extent_backref { struct rb_node node; struct old_sa_defrag_extent *old; u64 root_id; u64 inum; u64 file_pos; u64 extent_offset; u64 num_bytes; u64 generation; }; struct old_sa_defrag_extent { struct list_head list; struct new_sa_defrag_extent *new; u64 extent_offset; u64 bytenr; u64 offset; u64 len; int count; }; struct new_sa_defrag_extent { struct rb_root root; struct list_head head; struct btrfs_path *path; struct inode *inode; u64 file_pos; u64 len; u64 bytenr; u64 disk_len; u8 compress_type; }; static int backref_comp(struct sa_defrag_extent_backref *b1, struct sa_defrag_extent_backref *b2) { if (b1->root_id < b2->root_id) return -1; else if (b1->root_id > b2->root_id) return 1; if (b1->inum < b2->inum) return -1; else if (b1->inum > b2->inum) return 1; if (b1->file_pos < b2->file_pos) return -1; else if (b1->file_pos > b2->file_pos) return 1; /* * [------------------------------] ===> (a range of space) * |<--->| |<---->| =============> (fs/file tree A) * |<---------------------------->| ===> (fs/file tree B) * * A range of space can refer to two file extents in one tree while * refer to only one file extent in another tree. * * So we may process a disk offset more than one time(two extents in A) * and locate at the same extent(one extent in B), then insert two same * backrefs(both refer to the extent in B). */ return 0; } static void backref_insert(struct rb_root *root, struct sa_defrag_extent_backref *backref) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct sa_defrag_extent_backref *entry; int ret; while (*p) { parent = *p; entry = rb_entry(parent, struct sa_defrag_extent_backref, node); ret = backref_comp(backref, entry); if (ret < 0) p = &(*p)->rb_left; else p = &(*p)->rb_right; } rb_link_node(&backref->node, parent, p); rb_insert_color(&backref->node, root); } /* * Note the backref might has changed, and in this case we just return 0. */ static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id, void *ctx) { struct btrfs_file_extent_item *extent; struct btrfs_fs_info *fs_info; struct old_sa_defrag_extent *old = ctx; struct new_sa_defrag_extent *new = old->new; struct btrfs_path *path = new->path; struct btrfs_key key; struct btrfs_root *root; struct sa_defrag_extent_backref *backref; struct extent_buffer *leaf; struct inode *inode = new->inode; int slot; int ret; u64 extent_offset; u64 num_bytes; if (BTRFS_I(inode)->root->root_key.objectid == root_id && inum == btrfs_ino(inode)) return 0; key.objectid = root_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; fs_info = BTRFS_I(inode)->root->fs_info; root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(root)) { if (PTR_ERR(root) == -ENOENT) return 0; WARN_ON(1); pr_debug("inum=%llu, offset=%llu, root_id=%llu\n", inum, offset, root_id); return PTR_ERR(root); } key.objectid = inum; key.type = BTRFS_EXTENT_DATA_KEY; if (offset > (u64)-1 << 32) key.offset = 0; else key.offset = offset; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (WARN_ON(ret < 0)) return ret; ret = 0; while (1) { cond_resched(); leaf = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) { goto out; } else if (ret > 0) { ret = 0; goto out; } continue; } path->slots[0]++; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.objectid > inum) goto out; if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY) continue; extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr) continue; /* * 'offset' refers to the exact key.offset, * NOT the 'offset' field in btrfs_extent_data_ref, ie. * (key.offset - extent_offset). */ if (key.offset != offset) continue; extent_offset = btrfs_file_extent_offset(leaf, extent); num_bytes = btrfs_file_extent_num_bytes(leaf, extent); if (extent_offset >= old->extent_offset + old->offset + old->len || extent_offset + num_bytes <= old->extent_offset + old->offset) continue; break; } backref = kmalloc(sizeof(*backref), GFP_NOFS); if (!backref) { ret = -ENOENT; goto out; } backref->root_id = root_id; backref->inum = inum; backref->file_pos = offset; backref->num_bytes = num_bytes; backref->extent_offset = extent_offset; backref->generation = btrfs_file_extent_generation(leaf, extent); backref->old = old; backref_insert(&new->root, backref); old->count++; out: btrfs_release_path(path); WARN_ON(ret); return ret; } static noinline bool record_extent_backrefs(struct btrfs_path *path, struct new_sa_defrag_extent *new) { struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info; struct old_sa_defrag_extent *old, *tmp; int ret; new->path = path; list_for_each_entry_safe(old, tmp, &new->head, list) { ret = iterate_inodes_from_logical(old->bytenr + old->extent_offset, fs_info, path, record_one_backref, old); if (ret < 0 && ret != -ENOENT) return false; /* no backref to be processed for this extent */ if (!old->count) { list_del(&old->list); kfree(old); } } if (list_empty(&new->head)) return false; return true; } static int relink_is_mergable(struct extent_buffer *leaf, struct btrfs_file_extent_item *fi, struct new_sa_defrag_extent *new) { if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr) return 0; if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG) return 0; if (btrfs_file_extent_compression(leaf, fi) != new->compress_type) return 0; if (btrfs_file_extent_encryption(leaf, fi) || btrfs_file_extent_other_encoding(leaf, fi)) return 0; return 1; } /* * Note the backref might has changed, and in this case we just return 0. */ static noinline int relink_extent_backref(struct btrfs_path *path, struct sa_defrag_extent_backref *prev, struct sa_defrag_extent_backref *backref) { struct btrfs_file_extent_item *extent; struct btrfs_file_extent_item *item; struct btrfs_ordered_extent *ordered; struct btrfs_trans_handle *trans; struct btrfs_fs_info *fs_info; struct btrfs_root *root; struct btrfs_key key; struct extent_buffer *leaf; struct old_sa_defrag_extent *old = backref->old; struct new_sa_defrag_extent *new = old->new; struct inode *src_inode = new->inode; struct inode *inode; struct extent_state *cached = NULL; int ret = 0; u64 start; u64 len; u64 lock_start; u64 lock_end; bool merge = false; int index; if (prev && prev->root_id == backref->root_id && prev->inum == backref->inum && prev->file_pos + prev->num_bytes == backref->file_pos) merge = true; /* step 1: get root */ key.objectid = backref->root_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; fs_info = BTRFS_I(src_inode)->root->fs_info; index = srcu_read_lock(&fs_info->subvol_srcu); root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(root)) { srcu_read_unlock(&fs_info->subvol_srcu, index); if (PTR_ERR(root) == -ENOENT) return 0; return PTR_ERR(root); } if (btrfs_root_readonly(root)) { srcu_read_unlock(&fs_info->subvol_srcu, index); return 0; } /* step 2: get inode */ key.objectid = backref->inum; key.type = BTRFS_INODE_ITEM_KEY; key.offset = 0; inode = btrfs_iget(fs_info->sb, &key, root, NULL); if (IS_ERR(inode)) { srcu_read_unlock(&fs_info->subvol_srcu, index); return 0; } srcu_read_unlock(&fs_info->subvol_srcu, index); /* step 3: relink backref */ lock_start = backref->file_pos; lock_end = backref->file_pos + backref->num_bytes - 1; lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end, 0, &cached); ordered = btrfs_lookup_first_ordered_extent(inode, lock_end); if (ordered) { btrfs_put_ordered_extent(ordered); goto out_unlock; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_unlock; } key.objectid = backref->inum; key.type = BTRFS_EXTENT_DATA_KEY; key.offset = backref->file_pos; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { goto out_free_path; } else if (ret > 0) { ret = 0; goto out_free_path; } extent = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_file_extent_item); if (btrfs_file_extent_generation(path->nodes[0], extent) != backref->generation) goto out_free_path; btrfs_release_path(path); start = backref->file_pos; if (backref->extent_offset < old->extent_offset + old->offset) start += old->extent_offset + old->offset - backref->extent_offset; len = min(backref->extent_offset + backref->num_bytes, old->extent_offset + old->offset + old->len); len -= max(backref->extent_offset, old->extent_offset + old->offset); ret = btrfs_drop_extents(trans, root, inode, start, start + len, 1); if (ret) goto out_free_path; again: key.objectid = btrfs_ino(inode); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = start; path->leave_spinning = 1; if (merge) { struct btrfs_file_extent_item *fi; u64 extent_len; struct btrfs_key found_key; ret = btrfs_search_slot(trans, root, &key, path, 0, 1); if (ret < 0) goto out_free_path; path->slots[0]--; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_len = btrfs_file_extent_num_bytes(leaf, fi); if (extent_len + found_key.offset == start && relink_is_mergable(leaf, fi, new)) { btrfs_set_file_extent_num_bytes(leaf, fi, extent_len + len); btrfs_mark_buffer_dirty(leaf); inode_add_bytes(inode, len); ret = 1; goto out_free_path; } else { merge = false; btrfs_release_path(path); goto again; } } ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent)); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_free_path; } leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr); btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len); btrfs_set_file_extent_offset(leaf, item, start - new->file_pos); btrfs_set_file_extent_num_bytes(leaf, item, len); btrfs_set_file_extent_ram_bytes(leaf, item, new->len); btrfs_set_file_extent_generation(leaf, item, trans->transid); btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG); btrfs_set_file_extent_compression(leaf, item, new->compress_type); btrfs_set_file_extent_encryption(leaf, item, 0); btrfs_set_file_extent_other_encoding(leaf, item, 0); btrfs_mark_buffer_dirty(leaf); inode_add_bytes(inode, len); btrfs_release_path(path); ret = btrfs_inc_extent_ref(trans, root, new->bytenr, new->disk_len, 0, backref->root_id, backref->inum, new->file_pos, 0); /* start - extent_offset */ if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_free_path; } ret = 1; out_free_path: btrfs_release_path(path); path->leave_spinning = 0; btrfs_end_transaction(trans, root); out_unlock: unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end, &cached, GFP_NOFS); iput(inode); return ret; } static void free_sa_defrag_extent(struct new_sa_defrag_extent *new) { struct old_sa_defrag_extent *old, *tmp; if (!new) return; list_for_each_entry_safe(old, tmp, &new->head, list) { list_del(&old->list); kfree(old); } kfree(new); } static void relink_file_extents(struct new_sa_defrag_extent *new) { struct btrfs_path *path; struct sa_defrag_extent_backref *backref; struct sa_defrag_extent_backref *prev = NULL; struct inode *inode; struct btrfs_root *root; struct rb_node *node; int ret; inode = new->inode; root = BTRFS_I(inode)->root; path = btrfs_alloc_path(); if (!path) return; if (!record_extent_backrefs(path, new)) { btrfs_free_path(path); goto out; } btrfs_release_path(path); while (1) { node = rb_first(&new->root); if (!node) break; rb_erase(node, &new->root); backref = rb_entry(node, struct sa_defrag_extent_backref, node); ret = relink_extent_backref(path, prev, backref); WARN_ON(ret < 0); kfree(prev); if (ret == 1) prev = backref; else prev = NULL; cond_resched(); } kfree(prev); btrfs_free_path(path); out: free_sa_defrag_extent(new); atomic_dec(&root->fs_info->defrag_running); wake_up(&root->fs_info->transaction_wait); } static struct new_sa_defrag_extent * record_old_file_extents(struct inode *inode, struct btrfs_ordered_extent *ordered) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_path *path; struct btrfs_key key; struct old_sa_defrag_extent *old; struct new_sa_defrag_extent *new; int ret; new = kmalloc(sizeof(*new), GFP_NOFS); if (!new) return NULL; new->inode = inode; new->file_pos = ordered->file_offset; new->len = ordered->len; new->bytenr = ordered->start; new->disk_len = ordered->disk_len; new->compress_type = ordered->compress_type; new->root = RB_ROOT; INIT_LIST_HEAD(&new->head); path = btrfs_alloc_path(); if (!path) goto out_kfree; key.objectid = btrfs_ino(inode); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = new->file_pos; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out_free_path; if (ret > 0 && path->slots[0] > 0) path->slots[0]--; /* find out all the old extents for the file range */ while (1) { struct btrfs_file_extent_item *extent; struct extent_buffer *l; int slot; u64 num_bytes; u64 offset; u64 end; u64 disk_bytenr; u64 extent_offset; l = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(l)) { ret = btrfs_next_leaf(root, path); if (ret < 0) goto out_free_path; else if (ret > 0) break; continue; } btrfs_item_key_to_cpu(l, &key, slot); if (key.objectid != btrfs_ino(inode)) break; if (key.type != BTRFS_EXTENT_DATA_KEY) break; if (key.offset >= new->file_pos + new->len) break; extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item); num_bytes = btrfs_file_extent_num_bytes(l, extent); if (key.offset + num_bytes < new->file_pos) goto next; disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent); if (!disk_bytenr) goto next; extent_offset = btrfs_file_extent_offset(l, extent); old = kmalloc(sizeof(*old), GFP_NOFS); if (!old) goto out_free_path; offset = max(new->file_pos, key.offset); end = min(new->file_pos + new->len, key.offset + num_bytes); old->bytenr = disk_bytenr; old->extent_offset = extent_offset; old->offset = offset - key.offset; old->len = end - offset; old->new = new; old->count = 0; list_add_tail(&old->list, &new->head); next: path->slots[0]++; cond_resched(); } btrfs_free_path(path); atomic_inc(&root->fs_info->defrag_running); return new; out_free_path: btrfs_free_path(path); out_kfree: free_sa_defrag_extent(new); return NULL; } static void btrfs_release_delalloc_bytes(struct btrfs_root *root, u64 start, u64 len) { struct btrfs_block_group_cache *cache; cache = btrfs_lookup_block_group(root->fs_info, start); ASSERT(cache); spin_lock(&cache->lock); cache->delalloc_bytes -= len; spin_unlock(&cache->lock); btrfs_put_block_group(cache); } /* as ordered data IO finishes, this gets called so we can finish * an ordered extent if the range of bytes in the file it covers are * fully written. */ static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent) { struct inode *inode = ordered_extent->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans = NULL; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_state *cached_state = NULL; struct new_sa_defrag_extent *new = NULL; int compress_type = 0; int ret = 0; u64 logical_len = ordered_extent->len; bool nolock; bool truncated = false; nolock = btrfs_is_free_space_inode(inode); if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) { ret = -EIO; goto out; } btrfs_free_io_failure_record(inode, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1); if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) { truncated = true; logical_len = ordered_extent->truncated_len; /* Truncated the entire extent, don't bother adding */ if (!logical_len) goto out; } if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) { BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */ btrfs_ordered_update_i_size(inode, 0, ordered_extent); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = btrfs_update_inode_fallback(trans, root, inode); if (ret) /* -ENOMEM or corruption */ btrfs_abort_transaction(trans, root, ret); goto out; } lock_extent_bits(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, 0, &cached_state); ret = test_range_bit(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, EXTENT_DEFRAG, 1, cached_state); if (ret) { u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item); if (0 && last_snapshot >= BTRFS_I(inode)->generation) /* the inode is shared */ new = record_old_file_extents(inode, ordered_extent); clear_extent_bit(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); } if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out_unlock; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags)) compress_type = ordered_extent->compress_type; if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) { BUG_ON(compress_type); ret = btrfs_mark_extent_written(trans, inode, ordered_extent->file_offset, ordered_extent->file_offset + logical_len); } else { BUG_ON(root == root->fs_info->tree_root); ret = insert_reserved_file_extent(trans, inode, ordered_extent->file_offset, ordered_extent->start, ordered_extent->disk_len, logical_len, logical_len, compress_type, 0, 0, BTRFS_FILE_EXTENT_REG); if (!ret) btrfs_release_delalloc_bytes(root, ordered_extent->start, ordered_extent->disk_len); } unpin_extent_cache(&BTRFS_I(inode)->extent_tree, ordered_extent->file_offset, ordered_extent->len, trans->transid); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } add_pending_csums(trans, inode, ordered_extent->file_offset, &ordered_extent->list); btrfs_ordered_update_i_size(inode, 0, ordered_extent); ret = btrfs_update_inode_fallback(trans, root, inode); if (ret) { /* -ENOMEM or corruption */ btrfs_abort_transaction(trans, root, ret); goto out_unlock; } ret = 0; out_unlock: unlock_extent_cached(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, &cached_state, GFP_NOFS); out: if (root != root->fs_info->tree_root) btrfs_delalloc_release_metadata(inode, ordered_extent->len); if (trans) btrfs_end_transaction(trans, root); if (ret || truncated) { u64 start, end; if (truncated) start = ordered_extent->file_offset + logical_len; else start = ordered_extent->file_offset; end = ordered_extent->file_offset + ordered_extent->len - 1; clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS); /* Drop the cache for the part of the extent we didn't write. */ btrfs_drop_extent_cache(inode, start, end, 0); /* * If the ordered extent had an IOERR or something else went * wrong we need to return the space for this ordered extent * back to the allocator. We only free the extent in the * truncated case if we didn't write out the extent at all. */ if ((ret || !logical_len) && !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) && !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) btrfs_free_reserved_extent(root, ordered_extent->start, ordered_extent->disk_len, 1); } /* * This needs to be done to make sure anybody waiting knows we are done * updating everything for this ordered extent. */ btrfs_remove_ordered_extent(inode, ordered_extent); /* for snapshot-aware defrag */ if (new) { if (ret) { free_sa_defrag_extent(new); atomic_dec(&root->fs_info->defrag_running); } else { relink_file_extents(new); } } /* once for us */ btrfs_put_ordered_extent(ordered_extent); /* once for the tree */ btrfs_put_ordered_extent(ordered_extent); return ret; } static void finish_ordered_fn(struct btrfs_work *work) { struct btrfs_ordered_extent *ordered_extent; ordered_extent = container_of(work, struct btrfs_ordered_extent, work); btrfs_finish_ordered_io(ordered_extent); } static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end, struct extent_state *state, int uptodate) { struct inode *inode = page->mapping->host; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ordered_extent *ordered_extent = NULL; struct btrfs_workqueue *wq; btrfs_work_func_t func; trace_btrfs_writepage_end_io_hook(page, start, end, uptodate); ClearPagePrivate2(page); if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start, end - start + 1, uptodate)) return 0; if (btrfs_is_free_space_inode(inode)) { wq = root->fs_info->endio_freespace_worker; func = btrfs_freespace_write_helper; } else { wq = root->fs_info->endio_write_workers; func = btrfs_endio_write_helper; } btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL, NULL); btrfs_queue_work(wq, &ordered_extent->work); return 0; } static int __readpage_endio_check(struct inode *inode, struct btrfs_io_bio *io_bio, int icsum, struct page *page, int pgoff, u64 start, size_t len) { char *kaddr; u32 csum_expected; u32 csum = ~(u32)0; csum_expected = *(((u32 *)io_bio->csum) + icsum); kaddr = kmap_atomic(page); csum = btrfs_csum_data(kaddr + pgoff, csum, len); btrfs_csum_final(csum, (char *)&csum); if (csum != csum_expected) goto zeroit; kunmap_atomic(kaddr); return 0; zeroit: btrfs_warn_rl(BTRFS_I(inode)->root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u", btrfs_ino(inode), start, csum, csum_expected); memset(kaddr + pgoff, 1, len); flush_dcache_page(page); kunmap_atomic(kaddr); if (csum_expected == 0) return 0; return -EIO; } /* * when reads are done, we need to check csums to verify the data is correct * if there's a match, we allow the bio to finish. If not, the code in * extent_io.c will try to find good copies for us. */ static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio, u64 phy_offset, struct page *page, u64 start, u64 end, int mirror) { size_t offset = start - page_offset(page); struct inode *inode = page->mapping->host; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_root *root = BTRFS_I(inode)->root; if (PageChecked(page)) { ClearPageChecked(page); return 0; } if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) return 0; if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID && test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) { clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM, GFP_NOFS); return 0; } phy_offset >>= inode->i_sb->s_blocksize_bits; return __readpage_endio_check(inode, io_bio, phy_offset, page, offset, start, (size_t)(end - start + 1)); } struct delayed_iput { struct list_head list; struct inode *inode; }; /* JDM: If this is fs-wide, why can't we add a pointer to * btrfs_inode instead and avoid the allocation? */ void btrfs_add_delayed_iput(struct inode *inode) { struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; struct delayed_iput *delayed; if (atomic_add_unless(&inode->i_count, -1, 1)) return; delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL); delayed->inode = inode; spin_lock(&fs_info->delayed_iput_lock); list_add_tail(&delayed->list, &fs_info->delayed_iputs); spin_unlock(&fs_info->delayed_iput_lock); } void btrfs_run_delayed_iputs(struct btrfs_root *root) { LIST_HEAD(list); struct btrfs_fs_info *fs_info = root->fs_info; struct delayed_iput *delayed; int empty; spin_lock(&fs_info->delayed_iput_lock); empty = list_empty(&fs_info->delayed_iputs); spin_unlock(&fs_info->delayed_iput_lock); if (empty) return; down_read(&fs_info->delayed_iput_sem); spin_lock(&fs_info->delayed_iput_lock); list_splice_init(&fs_info->delayed_iputs, &list); spin_unlock(&fs_info->delayed_iput_lock); while (!list_empty(&list)) { delayed = list_entry(list.next, struct delayed_iput, list); list_del(&delayed->list); iput(delayed->inode); kfree(delayed); } up_read(&root->fs_info->delayed_iput_sem); } /* * This is called in transaction commit time. If there are no orphan * files in the subvolume, it removes orphan item and frees block_rsv * structure. */ void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_block_rsv *block_rsv; int ret; if (atomic_read(&root->orphan_inodes) || root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) return; spin_lock(&root->orphan_lock); if (atomic_read(&root->orphan_inodes)) { spin_unlock(&root->orphan_lock); return; } if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) { spin_unlock(&root->orphan_lock); return; } block_rsv = root->orphan_block_rsv; root->orphan_block_rsv = NULL; spin_unlock(&root->orphan_lock); if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) && btrfs_root_refs(&root->root_item) > 0) { ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root, root->root_key.objectid); if (ret) btrfs_abort_transaction(trans, root, ret); else clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state); } if (block_rsv) { WARN_ON(block_rsv->size > 0); btrfs_free_block_rsv(root, block_rsv); } } /* * This creates an orphan entry for the given inode in case something goes * wrong in the middle of an unlink/truncate. * * NOTE: caller of this function should reserve 5 units of metadata for * this function. */ int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *block_rsv = NULL; int reserve = 0; int insert = 0; int ret; if (!root->orphan_block_rsv) { block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!block_rsv) return -ENOMEM; } spin_lock(&root->orphan_lock); if (!root->orphan_block_rsv) { root->orphan_block_rsv = block_rsv; } else if (block_rsv) { btrfs_free_block_rsv(root, block_rsv); block_rsv = NULL; } if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { #if 0 /* * For proper ENOSPC handling, we should do orphan * cleanup when mounting. But this introduces backward * compatibility issue. */ if (!xchg(&root->orphan_item_inserted, 1)) insert = 2; else insert = 1; #endif insert = 1; atomic_inc(&root->orphan_inodes); } if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags)) reserve = 1; spin_unlock(&root->orphan_lock); /* grab metadata reservation from transaction handle */ if (reserve) { ret = btrfs_orphan_reserve_metadata(trans, inode); BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */ } /* insert an orphan item to track this unlinked/truncated file */ if (insert >= 1) { ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode)); if (ret) { atomic_dec(&root->orphan_inodes); if (reserve) { clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags); btrfs_orphan_release_metadata(inode); } if (ret != -EEXIST) { clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags); btrfs_abort_transaction(trans, root, ret); return ret; } } ret = 0; } /* insert an orphan item to track subvolume contains orphan files */ if (insert >= 2) { ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root, root->root_key.objectid); if (ret && ret != -EEXIST) { btrfs_abort_transaction(trans, root, ret); return ret; } } return 0; } /* * We have done the truncate/delete so we can go ahead and remove the orphan * item for this particular inode. */ static int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; int delete_item = 0; int release_rsv = 0; int ret = 0; spin_lock(&root->orphan_lock); if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) delete_item = 1; if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags)) release_rsv = 1; spin_unlock(&root->orphan_lock); if (delete_item) { atomic_dec(&root->orphan_inodes); if (trans) ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode)); } if (release_rsv) btrfs_orphan_release_metadata(inode); return ret; } /* * this cleans up any orphans that may be left on the list from the last use * of this root. */ int btrfs_orphan_cleanup(struct btrfs_root *root) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key key, found_key; struct btrfs_trans_handle *trans; struct inode *inode; u64 last_objectid = 0; int ret = 0, nr_unlink = 0, nr_truncate = 0; if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED)) return 0; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->reada = -1; key.objectid = BTRFS_ORPHAN_OBJECTID; key.type = BTRFS_ORPHAN_ITEM_KEY; key.offset = (u64)-1; while (1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; /* * if ret == 0 means we found what we were searching for, which * is weird, but possible, so only screw with path if we didn't * find the key and see if we have stuff that matches */ if (ret > 0) { ret = 0; if (path->slots[0] == 0) break; path->slots[0]--; } /* pull out the item */ leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); /* make sure the item matches what we want */ if (found_key.objectid != BTRFS_ORPHAN_OBJECTID) break; if (found_key.type != BTRFS_ORPHAN_ITEM_KEY) break; /* release the path since we're done with it */ btrfs_release_path(path); /* * this is where we are basically btrfs_lookup, without the * crossing root thing. we store the inode number in the * offset of the orphan item. */ if (found_key.offset == last_objectid) { btrfs_err(root->fs_info, "Error removing orphan entry, stopping orphan cleanup"); ret = -EINVAL; goto out; } last_objectid = found_key.offset; found_key.objectid = found_key.offset; found_key.type = BTRFS_INODE_ITEM_KEY; found_key.offset = 0; inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL); ret = PTR_ERR_OR_ZERO(inode); if (ret && ret != -ESTALE) goto out; if (ret == -ESTALE && root == root->fs_info->tree_root) { struct btrfs_root *dead_root; struct btrfs_fs_info *fs_info = root->fs_info; int is_dead_root = 0; /* * this is an orphan in the tree root. Currently these * could come from 2 sources: * a) a snapshot deletion in progress * b) a free space cache inode * We need to distinguish those two, as the snapshot * orphan must not get deleted. * find_dead_roots already ran before us, so if this * is a snapshot deletion, we should find the root * in the dead_roots list */ spin_lock(&fs_info->trans_lock); list_for_each_entry(dead_root, &fs_info->dead_roots, root_list) { if (dead_root->root_key.objectid == found_key.objectid) { is_dead_root = 1; break; } } spin_unlock(&fs_info->trans_lock); if (is_dead_root) { /* prevent this orphan from being found again */ key.offset = found_key.objectid - 1; continue; } } /* * Inode is already gone but the orphan item is still there, * kill the orphan item. */ if (ret == -ESTALE) { trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } btrfs_debug(root->fs_info, "auto deleting %Lu", found_key.objectid); ret = btrfs_del_orphan_item(trans, root, found_key.objectid); btrfs_end_transaction(trans, root); if (ret) goto out; continue; } /* * add this inode to the orphan list so btrfs_orphan_del does * the proper thing when we hit it */ set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags); atomic_inc(&root->orphan_inodes); /* if we have links, this was a truncate, lets do that */ if (inode->i_nlink) { if (WARN_ON(!S_ISREG(inode->i_mode))) { iput(inode); continue; } nr_truncate++; /* 1 for the orphan item deletion. */ trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { iput(inode); ret = PTR_ERR(trans); goto out; } ret = btrfs_orphan_add(trans, inode); btrfs_end_transaction(trans, root); if (ret) { iput(inode); goto out; } ret = btrfs_truncate(inode); if (ret) btrfs_orphan_del(NULL, inode); } else { nr_unlink++; } /* this will do delete_inode and everything for us */ iput(inode); if (ret) goto out; } /* release the path since we're done with it */ btrfs_release_path(path); root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE; if (root->orphan_block_rsv) btrfs_block_rsv_release(root, root->orphan_block_rsv, (u64)-1); if (root->orphan_block_rsv || test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) { trans = btrfs_join_transaction(root); if (!IS_ERR(trans)) btrfs_end_transaction(trans, root); } if (nr_unlink) btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink); if (nr_truncate) btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate); out: if (ret) btrfs_err(root->fs_info, "could not do orphan cleanup %d", ret); btrfs_free_path(path); return ret; } /* * very simple check to peek ahead in the leaf looking for xattrs. If we * don't find any xattrs, we know there can't be any acls. * * slot is the slot the inode is in, objectid is the objectid of the inode */ static noinline int acls_after_inode_item(struct extent_buffer *leaf, int slot, u64 objectid, int *first_xattr_slot) { u32 nritems = btrfs_header_nritems(leaf); struct btrfs_key found_key; static u64 xattr_access = 0; static u64 xattr_default = 0; int scanned = 0; if (!xattr_access) { xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS, strlen(POSIX_ACL_XATTR_ACCESS)); xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT, strlen(POSIX_ACL_XATTR_DEFAULT)); } slot++; *first_xattr_slot = -1; while (slot < nritems) { btrfs_item_key_to_cpu(leaf, &found_key, slot); /* we found a different objectid, there must not be acls */ if (found_key.objectid != objectid) return 0; /* we found an xattr, assume we've got an acl */ if (found_key.type == BTRFS_XATTR_ITEM_KEY) { if (*first_xattr_slot == -1) *first_xattr_slot = slot; if (found_key.offset == xattr_access || found_key.offset == xattr_default) return 1; } /* * we found a key greater than an xattr key, there can't * be any acls later on */ if (found_key.type > BTRFS_XATTR_ITEM_KEY) return 0; slot++; scanned++; /* * it goes inode, inode backrefs, xattrs, extents, * so if there are a ton of hard links to an inode there can * be a lot of backrefs. Don't waste time searching too hard, * this is just an optimization */ if (scanned >= 8) break; } /* we hit the end of the leaf before we found an xattr or * something larger than an xattr. We have to assume the inode * has acls */ if (*first_xattr_slot == -1) *first_xattr_slot = slot; return 1; } /* * read an inode from the btree into the in-memory inode */ static void btrfs_read_locked_inode(struct inode *inode) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_inode_item *inode_item; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key location; unsigned long ptr; int maybe_acls; u32 rdev; int ret; bool filled = false; int first_xattr_slot; ret = btrfs_fill_inode(inode, &rdev); if (!ret) filled = true; path = btrfs_alloc_path(); if (!path) goto make_bad; memcpy(&location, &BTRFS_I(inode)->location, sizeof(location)); ret = btrfs_lookup_inode(NULL, root, path, &location, 0); if (ret) goto make_bad; leaf = path->nodes[0]; if (filled) goto cache_index; inode_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item); inode->i_mode = btrfs_inode_mode(leaf, inode_item); set_nlink(inode, btrfs_inode_nlink(leaf, inode_item)); i_uid_write(inode, btrfs_inode_uid(leaf, inode_item)); i_gid_write(inode, btrfs_inode_gid(leaf, inode_item)); btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item)); inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime); inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime); inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime); inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime); inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime); inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime); BTRFS_I(inode)->i_otime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->otime); BTRFS_I(inode)->i_otime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->otime); inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item)); BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item); BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item); inode->i_version = btrfs_inode_sequence(leaf, inode_item); inode->i_generation = BTRFS_I(inode)->generation; inode->i_rdev = 0; rdev = btrfs_inode_rdev(leaf, inode_item); BTRFS_I(inode)->index_cnt = (u64)-1; BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item); cache_index: /* * If we were modified in the current generation and evicted from memory * and then re-read we need to do a full sync since we don't have any * idea about which extents were modified before we were evicted from * cache. * * This is required for both inode re-read from disk and delayed inode * in delayed_nodes_tree. */ if (BTRFS_I(inode)->last_trans == root->fs_info->generation) set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); /* * We don't persist the id of the transaction where an unlink operation * against the inode was last made. So here we assume the inode might * have been evicted, and therefore the exact value of last_unlink_trans * lost, and set it to last_trans to avoid metadata inconsistencies * between the inode and its parent if the inode is fsync'ed and the log * replayed. For example, in the scenario: * * touch mydir/foo * ln mydir/foo mydir/bar * sync * unlink mydir/bar * echo 2 > /proc/sys/vm/drop_caches # evicts inode * xfs_io -c fsync mydir/foo * <power failure> * mount fs, triggers fsync log replay * * We must make sure that when we fsync our inode foo we also log its * parent inode, otherwise after log replay the parent still has the * dentry with the "bar" name but our inode foo has a link count of 1 * and doesn't have an inode ref with the name "bar" anymore. * * Setting last_unlink_trans to last_trans is a pessimistic approach, * but it guarantees correctness at the expense of ocassional full * transaction commits on fsync if our inode is a directory, or if our * inode is not a directory, logging its parent unnecessarily. */ BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans; path->slots[0]++; if (inode->i_nlink != 1 || path->slots[0] >= btrfs_header_nritems(leaf)) goto cache_acl; btrfs_item_key_to_cpu(leaf, &location, path->slots[0]); if (location.objectid != btrfs_ino(inode)) goto cache_acl; ptr = btrfs_item_ptr_offset(leaf, path->slots[0]); if (location.type == BTRFS_INODE_REF_KEY) { struct btrfs_inode_ref *ref; ref = (struct btrfs_inode_ref *)ptr; BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref); } else if (location.type == BTRFS_INODE_EXTREF_KEY) { struct btrfs_inode_extref *extref; extref = (struct btrfs_inode_extref *)ptr; BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf, extref); } cache_acl: /* * try to precache a NULL acl entry for files that don't have * any xattrs or acls */ maybe_acls = acls_after_inode_item(leaf, path->slots[0], btrfs_ino(inode), &first_xattr_slot); if (first_xattr_slot != -1) { path->slots[0] = first_xattr_slot; ret = btrfs_load_inode_props(inode, path); if (ret) btrfs_err(root->fs_info, "error loading props for ino %llu (root %llu): %d", btrfs_ino(inode), root->root_key.objectid, ret); } btrfs_free_path(path); if (!maybe_acls) cache_no_acl(inode); switch (inode->i_mode & S_IFMT) { case S_IFREG: inode->i_mapping->a_ops = &btrfs_aops; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; break; case S_IFDIR: inode->i_fop = &btrfs_dir_file_operations; if (root == root->fs_info->tree_root) inode->i_op = &btrfs_dir_ro_inode_operations; else inode->i_op = &btrfs_dir_inode_operations; break; case S_IFLNK: inode->i_op = &btrfs_symlink_inode_operations; inode->i_mapping->a_ops = &btrfs_symlink_aops; break; default: inode->i_op = &btrfs_special_inode_operations; init_special_inode(inode, inode->i_mode, rdev); break; } btrfs_update_iflags(inode); return; make_bad: btrfs_free_path(path); make_bad_inode(inode); } /* * given a leaf and an inode, copy the inode fields into the leaf */ static void fill_inode_item(struct btrfs_trans_handle *trans, struct extent_buffer *leaf, struct btrfs_inode_item *item, struct inode *inode) { struct btrfs_map_token token; btrfs_init_map_token(&token); btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token); btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token); btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size, &token); btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token); btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token); btrfs_set_token_timespec_sec(leaf, &item->atime, inode->i_atime.tv_sec, &token); btrfs_set_token_timespec_nsec(leaf, &item->atime, inode->i_atime.tv_nsec, &token); btrfs_set_token_timespec_sec(leaf, &item->mtime, inode->i_mtime.tv_sec, &token); btrfs_set_token_timespec_nsec(leaf, &item->mtime, inode->i_mtime.tv_nsec, &token); btrfs_set_token_timespec_sec(leaf, &item->ctime, inode->i_ctime.tv_sec, &token); btrfs_set_token_timespec_nsec(leaf, &item->ctime, inode->i_ctime.tv_nsec, &token); btrfs_set_token_timespec_sec(leaf, &item->otime, BTRFS_I(inode)->i_otime.tv_sec, &token); btrfs_set_token_timespec_nsec(leaf, &item->otime, BTRFS_I(inode)->i_otime.tv_nsec, &token); btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode), &token); btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation, &token); btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token); btrfs_set_token_inode_transid(leaf, item, trans->transid, &token); btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token); btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token); btrfs_set_token_inode_block_group(leaf, item, 0, &token); } /* * copy everything in the in-memory inode into the btree. */ static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { struct btrfs_inode_item *inode_item; struct btrfs_path *path; struct extent_buffer *leaf; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location, 1); if (ret) { if (ret > 0) ret = -ENOENT; goto failed; } leaf = path->nodes[0]; inode_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item); fill_inode_item(trans, leaf, inode_item, inode); btrfs_mark_buffer_dirty(leaf); btrfs_set_inode_last_trans(trans, inode); ret = 0; failed: btrfs_free_path(path); return ret; } /* * copy everything in the in-memory inode into the btree. */ noinline int btrfs_update_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { int ret; /* * If the inode is a free space inode, we can deadlock during commit * if we put it into the delayed code. * * The data relocation inode should also be directly updated * without delay */ if (!btrfs_is_free_space_inode(inode) && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID && !root->fs_info->log_root_recovering) { btrfs_update_root_times(trans, root); ret = btrfs_delayed_update_inode(trans, root, inode); if (!ret) btrfs_set_inode_last_trans(trans, inode); return ret; } return btrfs_update_inode_item(trans, root, inode); } noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { int ret; ret = btrfs_update_inode(trans, root, inode); if (ret == -ENOSPC) return btrfs_update_inode_item(trans, root, inode); return ret; } /* * unlink helper that gets used here in inode.c and in the tree logging * recovery code. It remove a link in a directory with a given name, and * also drops the back refs in the inode to the directory */ static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, struct inode *inode, const char *name, int name_len) { struct btrfs_path *path; int ret = 0; struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u64 index; u64 ino = btrfs_ino(inode); u64 dir_ino = btrfs_ino(dir); path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->leave_spinning = 1; di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, name_len, -1); if (IS_ERR(di)) { ret = PTR_ERR(di); goto err; } if (!di) { ret = -ENOENT; goto err; } leaf = path->nodes[0]; btrfs_dir_item_key_to_cpu(leaf, di, &key); ret = btrfs_delete_one_dir_name(trans, root, path, di); if (ret) goto err; btrfs_release_path(path); /* * If we don't have dir index, we have to get it by looking up * the inode ref, since we get the inode ref, remove it directly, * it is unnecessary to do delayed deletion. * * But if we have dir index, needn't search inode ref to get it. * Since the inode ref is close to the inode item, it is better * that we delay to delete it, and just do this deletion when * we update the inode item. */ if (BTRFS_I(inode)->dir_index) { ret = btrfs_delayed_delete_inode_ref(inode); if (!ret) { index = BTRFS_I(inode)->dir_index; goto skip_backref; } } ret = btrfs_del_inode_ref(trans, root, name, name_len, ino, dir_ino, &index); if (ret) { btrfs_info(root->fs_info, "failed to delete reference to %.*s, inode %llu parent %llu", name_len, name, ino, dir_ino); btrfs_abort_transaction(trans, root, ret); goto err; } skip_backref: ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode, dir_ino); if (ret != 0 && ret != -ENOENT) { btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir, index); if (ret == -ENOENT) ret = 0; else if (ret) btrfs_abort_transaction(trans, root, ret); err: btrfs_free_path(path); if (ret) goto out; btrfs_i_size_write(dir, dir->i_size - name_len * 2); inode_inc_iversion(inode); inode_inc_iversion(dir); inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, dir); out: return ret; } int btrfs_unlink_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, struct inode *inode, const char *name, int name_len) { int ret; ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len); if (!ret) { drop_nlink(inode); ret = btrfs_update_inode(trans, root, inode); } return ret; } /* * helper to start transaction for unlink and rmdir. * * unlink and rmdir are special in btrfs, they do not always free space, so * if we cannot make our reservations the normal way try and see if there is * plenty of slack room in the global reserve to migrate, otherwise we cannot * allow the unlink to occur. */ static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; int ret; /* * 1 for the possible orphan item * 1 for the dir item * 1 for the dir index * 1 for the inode ref * 1 for the inode */ trans = btrfs_start_transaction(root, 5); if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC) return trans; if (PTR_ERR(trans) == -ENOSPC) { u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5); trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) return trans; ret = btrfs_cond_migrate_bytes(root->fs_info, &root->fs_info->trans_block_rsv, num_bytes, 5); if (ret) { btrfs_end_transaction(trans, root); return ERR_PTR(ret); } trans->block_rsv = &root->fs_info->trans_block_rsv; trans->bytes_reserved = num_bytes; } return trans; } static int btrfs_unlink(struct inode *dir, struct dentry *dentry) { struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; struct inode *inode = d_inode(dentry); int ret; trans = __unlink_start_trans(dir); if (IS_ERR(trans)) return PTR_ERR(trans); btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0); ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry), dentry->d_name.name, dentry->d_name.len); if (ret) goto out; if (inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, inode); if (ret) goto out; } out: btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); return ret; } int btrfs_unlink_subvol(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, u64 objectid, const char *name, int name_len) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u64 index; int ret; u64 dir_ino = btrfs_ino(dir); path = btrfs_alloc_path(); if (!path) return -ENOMEM; di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, name_len, -1); if (IS_ERR_OR_NULL(di)) { if (!di) ret = -ENOENT; else ret = PTR_ERR(di); goto out; } leaf = path->nodes[0]; btrfs_dir_item_key_to_cpu(leaf, di, &key); WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid); ret = btrfs_delete_one_dir_name(trans, root, path, di); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } btrfs_release_path(path); ret = btrfs_del_root_ref(trans, root->fs_info->tree_root, objectid, root->root_key.objectid, dir_ino, &index, name, name_len); if (ret < 0) { if (ret != -ENOENT) { btrfs_abort_transaction(trans, root, ret); goto out; } di = btrfs_search_dir_index_item(root, path, dir_ino, name, name_len); if (IS_ERR_OR_NULL(di)) { if (!di) ret = -ENOENT; else ret = PTR_ERR(di); btrfs_abort_transaction(trans, root, ret); goto out; } leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); btrfs_release_path(path); index = key.offset; } btrfs_release_path(path); ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } btrfs_i_size_write(dir, dir->i_size - name_len * 2); inode_inc_iversion(dir); dir->i_mtime = dir->i_ctime = CURRENT_TIME; ret = btrfs_update_inode_fallback(trans, root, dir); if (ret) btrfs_abort_transaction(trans, root, ret); out: btrfs_free_path(path); return ret; } static int btrfs_rmdir(struct inode *dir, struct dentry *dentry) { struct inode *inode = d_inode(dentry); int err = 0; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) return -EPERM; trans = __unlink_start_trans(dir); if (IS_ERR(trans)) return PTR_ERR(trans); if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { err = btrfs_unlink_subvol(trans, root, dir, BTRFS_I(inode)->location.objectid, dentry->d_name.name, dentry->d_name.len); goto out; } err = btrfs_orphan_add(trans, inode); if (err) goto out; /* now the directory is empty */ err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry), dentry->d_name.name, dentry->d_name.len); if (!err) btrfs_i_size_write(inode, 0); out: btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); return err; } static int truncate_space_check(struct btrfs_trans_handle *trans, struct btrfs_root *root, u64 bytes_deleted) { int ret; bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted); ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv, bytes_deleted, BTRFS_RESERVE_NO_FLUSH); if (!ret) trans->bytes_reserved += bytes_deleted; return ret; } /* * this can truncate away extent items, csum items and directory items. * It starts at a high offset and removes keys until it can't find * any higher than new_size * * csum items that cross the new i_size are truncated to the new size * as well. * * min_type is the minimum key type to truncate down to. If set to 0, this * will kill all the items on this inode, including the INODE_ITEM_KEY. */ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 new_size, u32 min_type) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_file_extent_item *fi; struct btrfs_key key; struct btrfs_key found_key; u64 extent_start = 0; u64 extent_num_bytes = 0; u64 extent_offset = 0; u64 item_end = 0; u64 last_size = new_size; u32 found_type = (u8)-1; int found_extent; int del_item; int pending_del_nr = 0; int pending_del_slot = 0; int extent_type = -1; int ret; int err = 0; u64 ino = btrfs_ino(inode); u64 bytes_deleted = 0; bool be_nice = 0; bool should_throttle = 0; bool should_end = 0; BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); /* * for non-free space inodes and ref cows, we want to back off from * time to time */ if (!btrfs_is_free_space_inode(inode) && test_bit(BTRFS_ROOT_REF_COWS, &root->state)) be_nice = 1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = -1; /* * We want to drop from the next block forward in case this new size is * not block aligned since we will be keeping the last block of the * extent just the way it is. */ if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root) btrfs_drop_extent_cache(inode, ALIGN(new_size, root->sectorsize), (u64)-1, 0); /* * This function is also used to drop the items in the log tree before * we relog the inode, so if root != BTRFS_I(inode)->root, it means * it is used to drop the loged items. So we shouldn't kill the delayed * items. */ if (min_type == 0 && root == BTRFS_I(inode)->root) btrfs_kill_delayed_inode_items(inode); key.objectid = ino; key.offset = (u64)-1; key.type = (u8)-1; search_again: /* * with a 16K leaf size and 128MB extents, you can actually queue * up a huge file in a single leaf. Most of the time that * bytes_deleted is > 0, it will be huge by the time we get here */ if (be_nice && bytes_deleted > 32 * 1024 * 1024) { if (btrfs_should_end_transaction(trans, root)) { err = -EAGAIN; goto error; } } path->leave_spinning = 1; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) { err = ret; goto out; } if (ret > 0) { /* there are no items in the tree for us to truncate, we're * done */ if (path->slots[0] == 0) goto out; path->slots[0]--; } while (1) { fi = NULL; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = found_key.type; if (found_key.objectid != ino) break; if (found_type < min_type) break; item_end = found_key.offset; if (found_type == BTRFS_EXTENT_DATA_KEY) { fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type != BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_num_bytes(leaf, fi); } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_inline_len(leaf, path->slots[0], fi); } item_end--; } if (found_type > min_type) { del_item = 1; } else { if (item_end < new_size) break; if (found_key.offset >= new_size) del_item = 1; else del_item = 0; } found_extent = 0; /* FIXME, shrink the extent if the ref count is only 1 */ if (found_type != BTRFS_EXTENT_DATA_KEY) goto delete; if (del_item) last_size = found_key.offset; else last_size = new_size; if (extent_type != BTRFS_FILE_EXTENT_INLINE) { u64 num_dec; extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); if (!del_item) { u64 orig_num_bytes = btrfs_file_extent_num_bytes(leaf, fi); extent_num_bytes = ALIGN(new_size - found_key.offset, root->sectorsize); btrfs_set_file_extent_num_bytes(leaf, fi, extent_num_bytes); num_dec = (orig_num_bytes - extent_num_bytes); if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) && extent_start != 0) inode_sub_bytes(inode, num_dec); btrfs_mark_buffer_dirty(leaf); } else { extent_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); extent_offset = found_key.offset - btrfs_file_extent_offset(leaf, fi); /* FIXME blocksize != 4096 */ num_dec = btrfs_file_extent_num_bytes(leaf, fi); if (extent_start != 0) { found_extent = 1; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, num_dec); } } } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { /* * we can't truncate inline items that have had * special encodings */ if (!del_item && btrfs_file_extent_compression(leaf, fi) == 0 && btrfs_file_extent_encryption(leaf, fi) == 0 && btrfs_file_extent_other_encoding(leaf, fi) == 0) { u32 size = new_size - found_key.offset; if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) inode_sub_bytes(inode, item_end + 1 - new_size); /* * update the ram bytes to properly reflect * the new size of our item */ btrfs_set_file_extent_ram_bytes(leaf, fi, size); size = btrfs_file_extent_calc_inline_size(size); btrfs_truncate_item(root, path, size, 1); } else if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) { inode_sub_bytes(inode, item_end + 1 - found_key.offset); } } delete: if (del_item) { if (!pending_del_nr) { /* no pending yet, add ourselves */ pending_del_slot = path->slots[0]; pending_del_nr = 1; } else if (pending_del_nr && path->slots[0] + 1 == pending_del_slot) { /* hop on the pending chunk */ pending_del_nr++; pending_del_slot = path->slots[0]; } else { BUG(); } } else { break; } should_throttle = 0; if (found_extent && (test_bit(BTRFS_ROOT_REF_COWS, &root->state) || root == root->fs_info->tree_root)) { btrfs_set_path_blocking(path); bytes_deleted += extent_num_bytes; ret = btrfs_free_extent(trans, root, extent_start, extent_num_bytes, 0, btrfs_header_owner(leaf), ino, extent_offset, 0); BUG_ON(ret); if (btrfs_should_throttle_delayed_refs(trans, root)) btrfs_async_run_delayed_refs(root, trans->delayed_ref_updates * 2, 0); if (be_nice) { if (truncate_space_check(trans, root, extent_num_bytes)) { should_end = 1; } if (btrfs_should_throttle_delayed_refs(trans, root)) { should_throttle = 1; } } } if (found_type == BTRFS_INODE_ITEM_KEY) break; if (path->slots[0] == 0 || path->slots[0] != pending_del_slot || should_throttle || should_end) { if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } pending_del_nr = 0; } btrfs_release_path(path); if (should_throttle) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } /* * if we failed to refill our space rsv, bail out * and let the transaction restart */ if (should_end) { err = -EAGAIN; goto error; } goto search_again; } else { path->slots[0]--; } } out: if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) btrfs_abort_transaction(trans, root, ret); } error: if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) btrfs_ordered_update_i_size(inode, last_size, NULL); btrfs_free_path(path); if (be_nice && bytes_deleted > 32 * 1024 * 1024) { unsigned long updates = trans->delayed_ref_updates; if (updates) { trans->delayed_ref_updates = 0; ret = btrfs_run_delayed_refs(trans, root, updates * 2); if (ret && !err) err = ret; } } return err; } /* * btrfs_truncate_page - read, zero a chunk and write a page * @inode - inode that we're zeroing * @from - the offset to start zeroing * @len - the length to zero, 0 to zero the entire range respective to the * offset * @front - zero up to the offset instead of from the offset on * * This will find the page for the "from" offset and cow the page and zero the * part we want to zero. This is used with truncate and hole punching. */ int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len, int front) { struct address_space *mapping = inode->i_mapping; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; char *kaddr; u32 blocksize = root->sectorsize; pgoff_t index = from >> PAGE_CACHE_SHIFT; unsigned offset = from & (PAGE_CACHE_SIZE-1); struct page *page; gfp_t mask = btrfs_alloc_write_mask(mapping); int ret = 0; u64 page_start; u64 page_end; if ((offset & (blocksize - 1)) == 0 && (!len || ((len & (blocksize - 1)) == 0))) goto out; ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (ret) goto out; again: page = find_or_create_page(mapping, index, mask); if (!page) { btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); ret = -ENOMEM; goto out; } page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; if (!PageUptodate(page)) { ret = btrfs_readpage(NULL, page); lock_page(page); if (page->mapping != mapping) { unlock_page(page); page_cache_release(page); goto again; } if (!PageUptodate(page)) { ret = -EIO; goto out_unlock; } } wait_on_page_writeback(page); lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state); set_page_extent_mapped(page); ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); page_cache_release(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); ret = btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); if (ret) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); goto out_unlock; } if (offset != PAGE_CACHE_SIZE) { if (!len) len = PAGE_CACHE_SIZE - offset; kaddr = kmap(page); if (front) memset(kaddr, 0, offset); else memset(kaddr + offset, 0, len); flush_dcache_page(page); kunmap(page); } ClearPageChecked(page); set_page_dirty(page); unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_unlock: if (ret) btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); unlock_page(page); page_cache_release(page); out: return ret; } static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode, u64 offset, u64 len) { struct btrfs_trans_handle *trans; int ret; /* * Still need to make sure the inode looks like it's been updated so * that any holes get logged if we fsync. */ if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) { BTRFS_I(inode)->last_trans = root->fs_info->generation; BTRFS_I(inode)->last_sub_trans = root->log_transid; BTRFS_I(inode)->last_log_commit = root->last_log_commit; return 0; } /* * 1 - for the one we're dropping * 1 - for the one we're adding * 1 - for updating the inode. */ trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); return ret; } ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset, 0, 0, len, 0, len, 0, 0, 0); if (ret) btrfs_abort_transaction(trans, root, ret); else btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans, root); return ret; } /* * This function puts in dummy file extents for the area we're creating a hole * for. So if we are truncating this file to a larger size we need to insert * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for * the range between oldsize and size */ int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size) { struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em = NULL; struct extent_state *cached_state = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; u64 hole_start = ALIGN(oldsize, root->sectorsize); u64 block_end = ALIGN(size, root->sectorsize); u64 last_byte; u64 cur_offset; u64 hole_size; int err = 0; /* * If our size started in the middle of a page we need to zero out the * rest of the page before we expand the i_size, otherwise we could * expose stale data. */ err = btrfs_truncate_page(inode, oldsize, 0, 0); if (err) return err; if (size <= hole_start) return 0; while (1) { struct btrfs_ordered_extent *ordered; lock_extent_bits(io_tree, hole_start, block_end - 1, 0, &cached_state); ordered = btrfs_lookup_ordered_range(inode, hole_start, block_end - hole_start); if (!ordered) break; unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state, GFP_NOFS); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); } cur_offset = hole_start; while (1) { em = btrfs_get_extent(inode, NULL, 0, cur_offset, block_end - cur_offset, 0); if (IS_ERR(em)) { err = PTR_ERR(em); em = NULL; break; } last_byte = min(extent_map_end(em), block_end); last_byte = ALIGN(last_byte , root->sectorsize); if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) { struct extent_map *hole_em; hole_size = last_byte - cur_offset; err = maybe_insert_hole(root, inode, cur_offset, hole_size); if (err) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + hole_size - 1, 0); hole_em = alloc_extent_map(); if (!hole_em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); goto next; } hole_em->start = cur_offset; hole_em->len = hole_size; hole_em->orig_start = cur_offset; hole_em->block_start = EXTENT_MAP_HOLE; hole_em->block_len = 0; hole_em->orig_block_len = 0; hole_em->ram_bytes = hole_size; hole_em->bdev = root->fs_info->fs_devices->latest_bdev; hole_em->compress_type = BTRFS_COMPRESS_NONE; hole_em->generation = root->fs_info->generation; while (1) { write_lock(&em_tree->lock); err = add_extent_mapping(em_tree, hole_em, 1); write_unlock(&em_tree->lock); if (err != -EEXIST) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + hole_size - 1, 0); } free_extent_map(hole_em); } next: free_extent_map(em); em = NULL; cur_offset = last_byte; if (cur_offset >= block_end) break; } free_extent_map(em); unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state, GFP_NOFS); return err; } static int wait_snapshoting_atomic_t(atomic_t *a) { schedule(); return 0; } static void wait_for_snapshot_creation(struct btrfs_root *root) { while (true) { int ret; ret = btrfs_start_write_no_snapshoting(root); if (ret) break; wait_on_atomic_t(&root->will_be_snapshoted, wait_snapshoting_atomic_t, TASK_UNINTERRUPTIBLE); } } static int btrfs_setsize(struct inode *inode, struct iattr *attr) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; loff_t oldsize = i_size_read(inode); loff_t newsize = attr->ia_size; int mask = attr->ia_valid; int ret; /* * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a * special case where we need to update the times despite not having * these flags set. For all other operations the VFS set these flags * explicitly if it wants a timestamp update. */ if (newsize != oldsize) { inode_inc_iversion(inode); if (!(mask & (ATTR_CTIME | ATTR_MTIME))) inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb); } if (newsize > oldsize) { truncate_pagecache(inode, newsize); /* * Don't do an expanding truncate while snapshoting is ongoing. * This is to ensure the snapshot captures a fully consistent * state of this file - if the snapshot captures this expanding * truncation, it must capture all writes that happened before * this truncation. */ wait_for_snapshot_creation(root); ret = btrfs_cont_expand(inode, oldsize, newsize); if (ret) { btrfs_end_write_no_snapshoting(root); return ret; } trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { btrfs_end_write_no_snapshoting(root); return PTR_ERR(trans); } i_size_write(inode, newsize); btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL); ret = btrfs_update_inode(trans, root, inode); btrfs_end_write_no_snapshoting(root); btrfs_end_transaction(trans, root); } else { /* * We're truncating a file that used to have good data down to * zero. Make sure it gets into the ordered flush list so that * any new writes get down to disk quickly. */ if (newsize == 0) set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE, &BTRFS_I(inode)->runtime_flags); /* * 1 for the orphan item we're going to add * 1 for the orphan item deletion. */ trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) return PTR_ERR(trans); /* * We need to do this in case we fail at _any_ point during the * actual truncate. Once we do the truncate_setsize we could * invalidate pages which forces any outstanding ordered io to * be instantly completed which will give us extents that need * to be truncated. If we fail to get an orphan inode down we * could have left over extents that were never meant to live, * so we need to garuntee from this point on that everything * will be consistent. */ ret = btrfs_orphan_add(trans, inode); btrfs_end_transaction(trans, root); if (ret) return ret; /* we don't support swapfiles, so vmtruncate shouldn't fail */ truncate_setsize(inode, newsize); /* Disable nonlocked read DIO to avoid the end less truncate */ btrfs_inode_block_unlocked_dio(inode); inode_dio_wait(inode); btrfs_inode_resume_unlocked_dio(inode); ret = btrfs_truncate(inode); if (ret && inode->i_nlink) { int err; /* * failed to truncate, disk_i_size is only adjusted down * as we remove extents, so it should represent the true * size of the inode, so reset the in memory size and * delete our orphan entry. */ trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { btrfs_orphan_del(NULL, inode); return ret; } i_size_write(inode, BTRFS_I(inode)->disk_i_size); err = btrfs_orphan_del(trans, inode); if (err) btrfs_abort_transaction(trans, root, err); btrfs_end_transaction(trans, root); } } return ret; } static int btrfs_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = d_inode(dentry); struct btrfs_root *root = BTRFS_I(inode)->root; int err; if (btrfs_root_readonly(root)) return -EROFS; err = inode_change_ok(inode, attr); if (err) return err; if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) { err = btrfs_setsize(inode, attr); if (err) return err; } if (attr->ia_valid) { setattr_copy(inode, attr); inode_inc_iversion(inode); err = btrfs_dirty_inode(inode); if (!err && attr->ia_valid & ATTR_MODE) err = posix_acl_chmod(inode, inode->i_mode); } return err; } /* * While truncating the inode pages during eviction, we get the VFS calling * btrfs_invalidatepage() against each page of the inode. This is slow because * the calls to btrfs_invalidatepage() result in a huge amount of calls to * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting * extent_state structures over and over, wasting lots of time. * * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all * those expensive operations on a per page basis and do only the ordered io * finishing, while we release here the extent_map and extent_state structures, * without the excessive merging and splitting. */ static void evict_inode_truncate_pages(struct inode *inode) { struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree; struct rb_node *node; ASSERT(inode->i_state & I_FREEING); truncate_inode_pages_final(&inode->i_data); write_lock(&map_tree->lock); while (!RB_EMPTY_ROOT(&map_tree->map)) { struct extent_map *em; node = rb_first(&map_tree->map); em = rb_entry(node, struct extent_map, rb_node); clear_bit(EXTENT_FLAG_PINNED, &em->flags); clear_bit(EXTENT_FLAG_LOGGING, &em->flags); remove_extent_mapping(map_tree, em); free_extent_map(em); if (need_resched()) { write_unlock(&map_tree->lock); cond_resched(); write_lock(&map_tree->lock); } } write_unlock(&map_tree->lock); /* * Keep looping until we have no more ranges in the io tree. * We can have ongoing bios started by readpages (called from readahead) * that have their endio callback (extent_io.c:end_bio_extent_readpage) * still in progress (unlocked the pages in the bio but did not yet * unlocked the ranges in the io tree). Therefore this means some * ranges can still be locked and eviction started because before * submitting those bios, which are executed by a separate task (work * queue kthread), inode references (inode->i_count) were not taken * (which would be dropped in the end io callback of each bio). * Therefore here we effectively end up waiting for those bios and * anyone else holding locked ranges without having bumped the inode's * reference count - if we don't do it, when they access the inode's * io_tree to unlock a range it may be too late, leading to an * use-after-free issue. */ spin_lock(&io_tree->lock); while (!RB_EMPTY_ROOT(&io_tree->state)) { struct extent_state *state; struct extent_state *cached_state = NULL; u64 start; u64 end; node = rb_first(&io_tree->state); state = rb_entry(node, struct extent_state, rb_node); start = state->start; end = state->end; spin_unlock(&io_tree->lock); lock_extent_bits(io_tree, start, end, 0, &cached_state); clear_extent_bit(io_tree, start, end, EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, &cached_state, GFP_NOFS); cond_resched(); spin_lock(&io_tree->lock); } spin_unlock(&io_tree->lock); } void btrfs_evict_inode(struct inode *inode) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *rsv, *global_rsv; int steal_from_global = 0; u64 min_size = btrfs_calc_trunc_metadata_size(root, 1); int ret; trace_btrfs_inode_evict(inode); evict_inode_truncate_pages(inode); if (inode->i_nlink && ((btrfs_root_refs(&root->root_item) != 0 && root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) || btrfs_is_free_space_inode(inode))) goto no_delete; if (is_bad_inode(inode)) { btrfs_orphan_del(NULL, inode); goto no_delete; } /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */ if (!special_file(inode->i_mode)) btrfs_wait_ordered_range(inode, 0, (u64)-1); btrfs_free_io_failure_record(inode, 0, (u64)-1); if (root->fs_info->log_root_recovering) { BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)); goto no_delete; } if (inode->i_nlink > 0) { BUG_ON(btrfs_root_refs(&root->root_item) != 0 && root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID); goto no_delete; } ret = btrfs_commit_inode_delayed_inode(inode); if (ret) { btrfs_orphan_del(NULL, inode); goto no_delete; } rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!rsv) { btrfs_orphan_del(NULL, inode); goto no_delete; } rsv->size = min_size; rsv->failfast = 1; global_rsv = &root->fs_info->global_block_rsv; btrfs_i_size_write(inode, 0); /* * This is a bit simpler than btrfs_truncate since we've already * reserved our space for our orphan item in the unlink, so we just * need to reserve some slack space in case we add bytes and update * inode item when doing the truncate. */ while (1) { ret = btrfs_block_rsv_refill(root, rsv, min_size, BTRFS_RESERVE_FLUSH_LIMIT); /* * Try and steal from the global reserve since we will * likely not use this space anyway, we want to try as * hard as possible to get this to work. */ if (ret) steal_from_global++; else steal_from_global = 0; ret = 0; /* * steal_from_global == 0: we reserved stuff, hooray! * steal_from_global == 1: we didn't reserve stuff, boo! * steal_from_global == 2: we've committed, still not a lot of * room but maybe we'll have room in the global reserve this * time. * steal_from_global == 3: abandon all hope! */ if (steal_from_global > 2) { btrfs_warn(root->fs_info, "Could not get space for a delete, will truncate on mount %d", ret); btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } /* * We can't just steal from the global reserve, we need tomake * sure there is room to do it, if not we need to commit and try * again. */ if (steal_from_global) { if (!btrfs_check_space_for_delayed_refs(trans, root)) ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size); else ret = -ENOSPC; } /* * Couldn't steal from the global reserve, we have too much * pending stuff built up, commit the transaction and try it * again. */ if (ret) { ret = btrfs_commit_transaction(trans, root); if (ret) { btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } continue; } else { steal_from_global = 0; } trans->block_rsv = rsv; ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0); if (ret != -ENOSPC && ret != -EAGAIN) break; trans->block_rsv = &root->fs_info->trans_block_rsv; btrfs_end_transaction(trans, root); trans = NULL; btrfs_btree_balance_dirty(root); } btrfs_free_block_rsv(root, rsv); /* * Errors here aren't a big deal, it just means we leave orphan items * in the tree. They will be cleaned up on the next mount. */ if (ret == 0) { trans->block_rsv = root->orphan_block_rsv; btrfs_orphan_del(trans, inode); } else { btrfs_orphan_del(NULL, inode); } trans->block_rsv = &root->fs_info->trans_block_rsv; if (!(root == root->fs_info->tree_root || root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)) btrfs_return_ino(root, btrfs_ino(inode)); btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); no_delete: btrfs_remove_delayed_node(inode); clear_inode(inode); return; } /* * this returns the key found in the dir entry in the location pointer. * If no dir entries were found, location->objectid is 0. */ static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry, struct btrfs_key *location) { const char *name = dentry->d_name.name; int namelen = dentry->d_name.len; struct btrfs_dir_item *di; struct btrfs_path *path; struct btrfs_root *root = BTRFS_I(dir)->root; int ret = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name, namelen, 0); if (IS_ERR(di)) ret = PTR_ERR(di); if (IS_ERR_OR_NULL(di)) goto out_err; btrfs_dir_item_key_to_cpu(path->nodes[0], di, location); out: btrfs_free_path(path); return ret; out_err: location->objectid = 0; goto out; } /* * when we hit a tree root in a directory, the btrfs part of the inode * needs to be changed to reflect the root directory of the tree root. This * is kind of like crossing a mount point. */ static int fixup_tree_root_location(struct btrfs_root *root, struct inode *dir, struct dentry *dentry, struct btrfs_key *location, struct btrfs_root **sub_root) { struct btrfs_path *path; struct btrfs_root *new_root; struct btrfs_root_ref *ref; struct extent_buffer *leaf; struct btrfs_key key; int ret; int err = 0; path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out; } err = -ENOENT; key.objectid = BTRFS_I(dir)->root->root_key.objectid; key.type = BTRFS_ROOT_REF_KEY; key.offset = location->objectid; ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path, 0, 0); if (ret) { if (ret < 0) err = ret; goto out; } leaf = path->nodes[0]; ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref); if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) || btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len) goto out; ret = memcmp_extent_buffer(leaf, dentry->d_name.name, (unsigned long)(ref + 1), dentry->d_name.len); if (ret) goto out; btrfs_release_path(path); new_root = btrfs_read_fs_root_no_name(root->fs_info, location); if (IS_ERR(new_root)) { err = PTR_ERR(new_root); goto out; } *sub_root = new_root; location->objectid = btrfs_root_dirid(&new_root->root_item); location->type = BTRFS_INODE_ITEM_KEY; location->offset = 0; err = 0; out: btrfs_free_path(path); return err; } static void inode_tree_add(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_inode *entry; struct rb_node **p; struct rb_node *parent; struct rb_node *new = &BTRFS_I(inode)->rb_node; u64 ino = btrfs_ino(inode); if (inode_unhashed(inode)) return; parent = NULL; spin_lock(&root->inode_lock); p = &root->inode_tree.rb_node; while (*p) { parent = *p; entry = rb_entry(parent, struct btrfs_inode, rb_node); if (ino < btrfs_ino(&entry->vfs_inode)) p = &parent->rb_left; else if (ino > btrfs_ino(&entry->vfs_inode)) p = &parent->rb_right; else { WARN_ON(!(entry->vfs_inode.i_state & (I_WILL_FREE | I_FREEING))); rb_replace_node(parent, new, &root->inode_tree); RB_CLEAR_NODE(parent); spin_unlock(&root->inode_lock); return; } } rb_link_node(new, parent, p); rb_insert_color(new, &root->inode_tree); spin_unlock(&root->inode_lock); } static void inode_tree_del(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; int empty = 0; spin_lock(&root->inode_lock); if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) { rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree); RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node); empty = RB_EMPTY_ROOT(&root->inode_tree); } spin_unlock(&root->inode_lock); if (empty && btrfs_root_refs(&root->root_item) == 0) { synchronize_srcu(&root->fs_info->subvol_srcu); spin_lock(&root->inode_lock); empty = RB_EMPTY_ROOT(&root->inode_tree); spin_unlock(&root->inode_lock); if (empty) btrfs_add_dead_root(root); } } void btrfs_invalidate_inodes(struct btrfs_root *root) { struct rb_node *node; struct rb_node *prev; struct btrfs_inode *entry; struct inode *inode; u64 objectid = 0; if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) WARN_ON(btrfs_root_refs(&root->root_item) != 0); spin_lock(&root->inode_lock); again: node = root->inode_tree.rb_node; prev = NULL; while (node) { prev = node; entry = rb_entry(node, struct btrfs_inode, rb_node); if (objectid < btrfs_ino(&entry->vfs_inode)) node = node->rb_left; else if (objectid > btrfs_ino(&entry->vfs_inode)) node = node->rb_right; else break; } if (!node) { while (prev) { entry = rb_entry(prev, struct btrfs_inode, rb_node); if (objectid <= btrfs_ino(&entry->vfs_inode)) { node = prev; break; } prev = rb_next(prev); } } while (node) { entry = rb_entry(node, struct btrfs_inode, rb_node); objectid = btrfs_ino(&entry->vfs_inode) + 1; inode = igrab(&entry->vfs_inode); if (inode) { spin_unlock(&root->inode_lock); if (atomic_read(&inode->i_count) > 1) d_prune_aliases(inode); /* * btrfs_drop_inode will have it removed from * the inode cache when its usage count * hits zero. */ iput(inode); cond_resched(); spin_lock(&root->inode_lock); goto again; } if (cond_resched_lock(&root->inode_lock)) goto again; node = rb_next(node); } spin_unlock(&root->inode_lock); } static int btrfs_init_locked_inode(struct inode *inode, void *p) { struct btrfs_iget_args *args = p; inode->i_ino = args->location->objectid; memcpy(&BTRFS_I(inode)->location, args->location, sizeof(*args->location)); BTRFS_I(inode)->root = args->root; return 0; } static int btrfs_find_actor(struct inode *inode, void *opaque) { struct btrfs_iget_args *args = opaque; return args->location->objectid == BTRFS_I(inode)->location.objectid && args->root == BTRFS_I(inode)->root; } static struct inode *btrfs_iget_locked(struct super_block *s, struct btrfs_key *location, struct btrfs_root *root) { struct inode *inode; struct btrfs_iget_args args; unsigned long hashval = btrfs_inode_hash(location->objectid, root); args.location = location; args.root = root; inode = iget5_locked(s, hashval, btrfs_find_actor, btrfs_init_locked_inode, (void *)&args); return inode; } /* Get an inode object given its location and corresponding root. * Returns in *is_new if the inode was read from disk */ struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location, struct btrfs_root *root, int *new) { struct inode *inode; inode = btrfs_iget_locked(s, location, root); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { btrfs_read_locked_inode(inode); if (!is_bad_inode(inode)) { inode_tree_add(inode); unlock_new_inode(inode); if (new) *new = 1; } else { unlock_new_inode(inode); iput(inode); inode = ERR_PTR(-ESTALE); } } return inode; } static struct inode *new_simple_dir(struct super_block *s, struct btrfs_key *key, struct btrfs_root *root) { struct inode *inode = new_inode(s); if (!inode) return ERR_PTR(-ENOMEM); BTRFS_I(inode)->root = root; memcpy(&BTRFS_I(inode)->location, key, sizeof(*key)); set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags); inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID; inode->i_op = &btrfs_dir_ro_inode_operations; inode->i_fop = &simple_dir_operations; inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO; inode->i_mtime = CURRENT_TIME; inode->i_atime = inode->i_mtime; inode->i_ctime = inode->i_mtime; BTRFS_I(inode)->i_otime = inode->i_mtime; return inode; } struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry) { struct inode *inode; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *sub_root = root; struct btrfs_key location; int index; int ret = 0; if (dentry->d_name.len > BTRFS_NAME_LEN) return ERR_PTR(-ENAMETOOLONG); ret = btrfs_inode_by_name(dir, dentry, &location); if (ret < 0) return ERR_PTR(ret); if (location.objectid == 0) return ERR_PTR(-ENOENT); if (location.type == BTRFS_INODE_ITEM_KEY) { inode = btrfs_iget(dir->i_sb, &location, root, NULL); return inode; } BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY); index = srcu_read_lock(&root->fs_info->subvol_srcu); ret = fixup_tree_root_location(root, dir, dentry, &location, &sub_root); if (ret < 0) { if (ret != -ENOENT) inode = ERR_PTR(ret); else inode = new_simple_dir(dir->i_sb, &location, sub_root); } else { inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL); } srcu_read_unlock(&root->fs_info->subvol_srcu, index); if (!IS_ERR(inode) && root != sub_root) { down_read(&root->fs_info->cleanup_work_sem); if (!(inode->i_sb->s_flags & MS_RDONLY)) ret = btrfs_orphan_cleanup(sub_root); up_read(&root->fs_info->cleanup_work_sem); if (ret) { iput(inode); inode = ERR_PTR(ret); } } return inode; } static int btrfs_dentry_delete(const struct dentry *dentry) { struct btrfs_root *root; struct inode *inode = d_inode(dentry); if (!inode && !IS_ROOT(dentry)) inode = d_inode(dentry->d_parent); if (inode) { root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0) return 1; if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return 1; } return 0; } static void btrfs_dentry_release(struct dentry *dentry) { kfree(dentry->d_fsdata); } static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct inode *inode; inode = btrfs_lookup_dentry(dir, dentry); if (IS_ERR(inode)) { if (PTR_ERR(inode) == -ENOENT) inode = NULL; else return ERR_CAST(inode); } return d_splice_alias(inode, dentry); } unsigned char btrfs_filetype_table[] = { DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK }; static int btrfs_real_readdir(struct file *file, struct dir_context *ctx) { struct inode *inode = file_inode(file); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_item *item; struct btrfs_dir_item *di; struct btrfs_key key; struct btrfs_key found_key; struct btrfs_path *path; struct list_head ins_list; struct list_head del_list; int ret; struct extent_buffer *leaf; int slot; unsigned char d_type; int over = 0; u32 di_cur; u32 di_total; u32 di_len; int key_type = BTRFS_DIR_INDEX_KEY; char tmp_name[32]; char *name_ptr; int name_len; int is_curr = 0; /* ctx->pos points to the current index? */ /* FIXME, use a real flag for deciding about the key type */ if (root->fs_info->tree_root == root) key_type = BTRFS_DIR_ITEM_KEY; if (!dir_emit_dots(file, ctx)) return 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = 1; if (key_type == BTRFS_DIR_INDEX_KEY) { INIT_LIST_HEAD(&ins_list); INIT_LIST_HEAD(&del_list); btrfs_get_delayed_items(inode, &ins_list, &del_list); } key.type = key_type; key.offset = ctx->pos; key.objectid = btrfs_ino(inode); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto err; while (1) { leaf = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) goto err; else if (ret > 0) break; continue; } item = btrfs_item_nr(slot); btrfs_item_key_to_cpu(leaf, &found_key, slot); if (found_key.objectid != key.objectid) break; if (found_key.type != key_type) break; if (found_key.offset < ctx->pos) goto next; if (key_type == BTRFS_DIR_INDEX_KEY && btrfs_should_delete_dir_index(&del_list, found_key.offset)) goto next; ctx->pos = found_key.offset; is_curr = 1; di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item); di_cur = 0; di_total = btrfs_item_size(leaf, item); while (di_cur < di_total) { struct btrfs_key location; if (verify_dir_item(root, leaf, di)) break; name_len = btrfs_dir_name_len(leaf, di); if (name_len <= sizeof(tmp_name)) { name_ptr = tmp_name; } else { name_ptr = kmalloc(name_len, GFP_NOFS); if (!name_ptr) { ret = -ENOMEM; goto err; } } read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1), name_len); d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)]; btrfs_dir_item_key_to_cpu(leaf, di, &location); /* is this a reference to our own snapshot? If so * skip it. * * In contrast to old kernels, we insert the snapshot's * dir item and dir index after it has been created, so * we won't find a reference to our own snapshot. We * still keep the following code for backward * compatibility. */ if (location.type == BTRFS_ROOT_ITEM_KEY && location.objectid == root->root_key.objectid) { over = 0; goto skip; } over = !dir_emit(ctx, name_ptr, name_len, location.objectid, d_type); skip: if (name_ptr != tmp_name) kfree(name_ptr); if (over) goto nopos; di_len = btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di) + sizeof(*di); di_cur += di_len; di = (struct btrfs_dir_item *)((char *)di + di_len); } next: path->slots[0]++; } if (key_type == BTRFS_DIR_INDEX_KEY) { if (is_curr) ctx->pos++; ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list); if (ret) goto nopos; } /* Reached end of directory/root. Bump pos past the last item. */ ctx->pos++; /* * Stop new entries from being returned after we return the last * entry. * * New directory entries are assigned a strictly increasing * offset. This means that new entries created during readdir * are *guaranteed* to be seen in the future by that readdir. * This has broken buggy programs which operate on names as * they're returned by readdir. Until we re-use freed offsets * we have this hack to stop new entries from being returned * under the assumption that they'll never reach this huge * offset. * * This is being careful not to overflow 32bit loff_t unless the * last entry requires it because doing so has broken 32bit apps * in the past. */ if (key_type == BTRFS_DIR_INDEX_KEY) { if (ctx->pos >= INT_MAX) ctx->pos = LLONG_MAX; else ctx->pos = INT_MAX; } nopos: ret = 0; err: if (key_type == BTRFS_DIR_INDEX_KEY) btrfs_put_delayed_items(&ins_list, &del_list); btrfs_free_path(path); return ret; } int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret = 0; bool nolock = false; if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) return 0; if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode)) nolock = true; if (wbc->sync_mode == WB_SYNC_ALL) { if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_commit_transaction(trans, root); } return ret; } /* * This is somewhat expensive, updating the tree every time the * inode changes. But, it is most likely to find the inode in cache. * FIXME, needs more benchmarking...there are no reasons other than performance * to keep or drop this code. */ static int btrfs_dirty_inode(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret; if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) return 0; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_update_inode(trans, root, inode); if (ret && ret == -ENOSPC) { /* whoops, lets try again with the full transaction */ btrfs_end_transaction(trans, root); trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_update_inode(trans, root, inode); } btrfs_end_transaction(trans, root); if (BTRFS_I(inode)->delayed_node) btrfs_balance_delayed_items(root); return ret; } /* * This is a copy of file_update_time. We need this so we can return error on * ENOSPC for updating the inode in the case of file write and mmap writes. */ static int btrfs_update_time(struct inode *inode, struct timespec *now, int flags) { struct btrfs_root *root = BTRFS_I(inode)->root; if (btrfs_root_readonly(root)) return -EROFS; if (flags & S_VERSION) inode_inc_iversion(inode); if (flags & S_CTIME) inode->i_ctime = *now; if (flags & S_MTIME) inode->i_mtime = *now; if (flags & S_ATIME) inode->i_atime = *now; return btrfs_dirty_inode(inode); } /* * find the highest existing sequence number in a directory * and then set the in-memory index_cnt variable to reflect * free sequence numbers */ static int btrfs_set_inode_index_count(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key key, found_key; struct btrfs_path *path; struct extent_buffer *leaf; int ret; key.objectid = btrfs_ino(inode); key.type = BTRFS_DIR_INDEX_KEY; key.offset = (u64)-1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; /* FIXME: we should be able to handle this */ if (ret == 0) goto out; ret = 0; /* * MAGIC NUMBER EXPLANATION: * since we search a directory based on f_pos we have to start at 2 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody * else has to start at 2 */ if (path->slots[0] == 0) { BTRFS_I(inode)->index_cnt = 2; goto out; } path->slots[0]--; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid != btrfs_ino(inode) || found_key.type != BTRFS_DIR_INDEX_KEY) { BTRFS_I(inode)->index_cnt = 2; goto out; } BTRFS_I(inode)->index_cnt = found_key.offset + 1; out: btrfs_free_path(path); return ret; } /* * helper to find a free sequence number in a given directory. This current * code is very simple, later versions will do smarter things in the btree */ int btrfs_set_inode_index(struct inode *dir, u64 *index) { int ret = 0; if (BTRFS_I(dir)->index_cnt == (u64)-1) { ret = btrfs_inode_delayed_dir_index_count(dir); if (ret) { ret = btrfs_set_inode_index_count(dir); if (ret) return ret; } } *index = BTRFS_I(dir)->index_cnt; BTRFS_I(dir)->index_cnt++; return ret; } static int btrfs_insert_inode_locked(struct inode *inode) { struct btrfs_iget_args args; args.location = &BTRFS_I(inode)->location; args.root = BTRFS_I(inode)->root; return insert_inode_locked4(inode, btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root), btrfs_find_actor, &args); } static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, const char *name, int name_len, u64 ref_objectid, u64 objectid, umode_t mode, u64 *index) { struct inode *inode; struct btrfs_inode_item *inode_item; struct btrfs_key *location; struct btrfs_path *path; struct btrfs_inode_ref *ref; struct btrfs_key key[2]; u32 sizes[2]; int nitems = name ? 2 : 1; unsigned long ptr; int ret; path = btrfs_alloc_path(); if (!path) return ERR_PTR(-ENOMEM); inode = new_inode(root->fs_info->sb); if (!inode) { btrfs_free_path(path); return ERR_PTR(-ENOMEM); } /* * O_TMPFILE, set link count to 0, so that after this point, * we fill in an inode item with the correct link count. */ if (!name) set_nlink(inode, 0); /* * we have to initialize this early, so we can reclaim the inode * number if we fail afterwards in this function. */ inode->i_ino = objectid; if (dir && name) { trace_btrfs_inode_request(dir); ret = btrfs_set_inode_index(dir, index); if (ret) { btrfs_free_path(path); iput(inode); return ERR_PTR(ret); } } else if (dir) { *index = 0; } /* * index_cnt is ignored for everything but a dir, * btrfs_get_inode_index_count has an explanation for the magic * number */ BTRFS_I(inode)->index_cnt = 2; BTRFS_I(inode)->dir_index = *index; BTRFS_I(inode)->root = root; BTRFS_I(inode)->generation = trans->transid; inode->i_generation = BTRFS_I(inode)->generation; /* * We could have gotten an inode number from somebody who was fsynced * and then removed in this same transaction, so let's just set full * sync since it will be a full sync anyway and this will blow away the * old info in the log. */ set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); key[0].objectid = objectid; key[0].type = BTRFS_INODE_ITEM_KEY; key[0].offset = 0; sizes[0] = sizeof(struct btrfs_inode_item); if (name) { /* * Start new inodes with an inode_ref. This is slightly more * efficient for small numbers of hard links since they will * be packed into one item. Extended refs will kick in if we * add more hard links than can fit in the ref item. */ key[1].objectid = objectid; key[1].type = BTRFS_INODE_REF_KEY; key[1].offset = ref_objectid; sizes[1] = name_len + sizeof(*ref); } location = &BTRFS_I(inode)->location; location->objectid = objectid; location->offset = 0; location->type = BTRFS_INODE_ITEM_KEY; ret = btrfs_insert_inode_locked(inode); if (ret < 0) goto fail; path->leave_spinning = 1; ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems); if (ret != 0) goto fail_unlock; inode_init_owner(inode, dir, mode); inode_set_bytes(inode, 0); inode->i_mtime = CURRENT_TIME; inode->i_atime = inode->i_mtime; inode->i_ctime = inode->i_mtime; BTRFS_I(inode)->i_otime = inode->i_mtime; inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_inode_item); memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item, sizeof(*inode_item)); fill_inode_item(trans, path->nodes[0], inode_item, inode); if (name) { ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1, struct btrfs_inode_ref); btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len); btrfs_set_inode_ref_index(path->nodes[0], ref, *index); ptr = (unsigned long)(ref + 1); write_extent_buffer(path->nodes[0], name, ptr, name_len); } btrfs_mark_buffer_dirty(path->nodes[0]); btrfs_free_path(path); btrfs_inherit_iflags(inode, dir); if (S_ISREG(mode)) { if (btrfs_test_opt(root, NODATASUM)) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; if (btrfs_test_opt(root, NODATACOW)) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW | BTRFS_INODE_NODATASUM; } inode_tree_add(inode); trace_btrfs_inode_new(inode); btrfs_set_inode_last_trans(trans, inode); btrfs_update_root_times(trans, root); ret = btrfs_inode_inherit_props(trans, inode, dir); if (ret) btrfs_err(root->fs_info, "error inheriting props for ino %llu (root %llu): %d", btrfs_ino(inode), root->root_key.objectid, ret); return inode; fail_unlock: unlock_new_inode(inode); fail: if (dir && name) BTRFS_I(dir)->index_cnt--; btrfs_free_path(path); iput(inode); return ERR_PTR(ret); } static inline u8 btrfs_inode_type(struct inode *inode) { return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT]; } /* * utility function to add 'inode' into 'parent_inode' with * a give name and a given sequence number. * if 'add_backref' is true, also insert a backref from the * inode to the parent directory. */ int btrfs_add_link(struct btrfs_trans_handle *trans, struct inode *parent_inode, struct inode *inode, const char *name, int name_len, int add_backref, u64 index) { int ret = 0; struct btrfs_key key; struct btrfs_root *root = BTRFS_I(parent_inode)->root; u64 ino = btrfs_ino(inode); u64 parent_ino = btrfs_ino(parent_inode); if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key)); } else { key.objectid = ino; key.type = BTRFS_INODE_ITEM_KEY; key.offset = 0; } if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, index, name, name_len); } else if (add_backref) { ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, parent_ino, index); } /* Nothing to clean up yet */ if (ret) return ret; ret = btrfs_insert_dir_item(trans, root, name, name_len, parent_inode, &key, btrfs_inode_type(inode), index); if (ret == -EEXIST || ret == -EOVERFLOW) goto fail_dir_item; else if (ret) { btrfs_abort_transaction(trans, root, ret); return ret; } btrfs_i_size_write(parent_inode, parent_inode->i_size + name_len * 2); inode_inc_iversion(parent_inode); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); return ret; fail_dir_item: if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { u64 local_index; int err; err = btrfs_del_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, &local_index, name, name_len); } else if (add_backref) { u64 local_index; int err; err = btrfs_del_inode_ref(trans, root, name, name_len, ino, parent_ino, &local_index); } return ret; } static int btrfs_add_nondir(struct btrfs_trans_handle *trans, struct inode *dir, struct dentry *dentry, struct inode *inode, int backref, u64 index) { int err = btrfs_add_link(trans, dir, inode, dentry->d_name.name, dentry->d_name.len, backref, index); if (err > 0) err = -EEXIST; return err; } static int btrfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; int err; int drop_inode = 0; u64 objectid; u64 index = 0; if (!new_valid_dev(rdev)) return -EINVAL; /* * 2 for inode item and ref * 2 for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_op = &btrfs_special_inode_operations; init_special_inode(inode, inode->i_mode, rdev); err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_unlock_inode; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) { goto out_unlock_inode; } else { btrfs_update_inode(trans, root, inode); unlock_new_inode(inode); d_instantiate(dentry, inode); } out_unlock: btrfs_end_transaction(trans, root); btrfs_balance_delayed_items(root); btrfs_btree_balance_dirty(root); if (drop_inode) { inode_dec_link_count(inode); iput(inode); } return err; out_unlock_inode: drop_inode = 1; unlock_new_inode(inode); goto out_unlock; } static int btrfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; int drop_inode_on_err = 0; int err; u64 objectid; u64 index = 0; /* * 2 for inode item and ref * 2 for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } drop_inode_on_err = 1; /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; inode->i_mapping->a_ops = &btrfs_aops; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_unlock_inode; err = btrfs_update_inode(trans, root, inode); if (err) goto out_unlock_inode; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) goto out_unlock_inode; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; unlock_new_inode(inode); d_instantiate(dentry, inode); out_unlock: btrfs_end_transaction(trans, root); if (err && drop_inode_on_err) { inode_dec_link_count(inode); iput(inode); } btrfs_balance_delayed_items(root); btrfs_btree_balance_dirty(root); return err; out_unlock_inode: unlock_new_inode(inode); goto out_unlock; } static int btrfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = d_inode(old_dentry); u64 index; int err; int drop_inode = 0; /* do not allow sys_link's with other subvols of the same device */ if (root->objectid != BTRFS_I(inode)->root->objectid) return -EXDEV; if (inode->i_nlink >= BTRFS_LINK_MAX) return -EMLINK; err = btrfs_set_inode_index(dir, &index); if (err) goto fail; /* * 2 items for inode and inode ref * 2 items for dir items * 1 item for parent inode */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto fail; } /* There are several dir indexes for this inode, clear the cache. */ BTRFS_I(inode)->dir_index = 0ULL; inc_nlink(inode); inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; ihold(inode); set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags); err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index); if (err) { drop_inode = 1; } else { struct dentry *parent = dentry->d_parent; err = btrfs_update_inode(trans, root, inode); if (err) goto fail; if (inode->i_nlink == 1) { /* * If new hard link count is 1, it's a file created * with open(2) O_TMPFILE flag. */ err = btrfs_orphan_del(trans, inode); if (err) goto fail; } d_instantiate(dentry, inode); btrfs_log_new_name(trans, inode, NULL, parent); } btrfs_end_transaction(trans, root); btrfs_balance_delayed_items(root); fail: if (drop_inode) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { struct inode *inode = NULL; struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; int err = 0; int drop_on_err = 0; u64 objectid = 0; u64 index = 0; /* * 2 items for inode and ref * 2 items for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_fail; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, S_IFDIR | mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_fail; } drop_on_err = 1; /* these must be set before we unlock the inode */ inode->i_op = &btrfs_dir_inode_operations; inode->i_fop = &btrfs_dir_file_operations; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_fail_inode; btrfs_i_size_write(inode, 0); err = btrfs_update_inode(trans, root, inode); if (err) goto out_fail_inode; err = btrfs_add_link(trans, dir, inode, dentry->d_name.name, dentry->d_name.len, 0, index); if (err) goto out_fail_inode; d_instantiate(dentry, inode); /* * mkdir is special. We're unlocking after we call d_instantiate * to avoid a race with nfsd calling d_instantiate. */ unlock_new_inode(inode); drop_on_err = 0; out_fail: btrfs_end_transaction(trans, root); if (drop_on_err) { inode_dec_link_count(inode); iput(inode); } btrfs_balance_delayed_items(root); btrfs_btree_balance_dirty(root); return err; out_fail_inode: unlock_new_inode(inode); goto out_fail; } /* Find next extent map of a given extent map, caller needs to ensure locks */ static struct extent_map *next_extent_map(struct extent_map *em) { struct rb_node *next; next = rb_next(&em->rb_node); if (!next) return NULL; return container_of(next, struct extent_map, rb_node); } static struct extent_map *prev_extent_map(struct extent_map *em) { struct rb_node *prev; prev = rb_prev(&em->rb_node); if (!prev) return NULL; return container_of(prev, struct extent_map, rb_node); } /* helper for btfs_get_extent. Given an existing extent in the tree, * the existing extent is the nearest extent to map_start, * and an extent that you want to insert, deal with overlap and insert * the best fitted new extent into the tree. */ static int merge_extent_mapping(struct extent_map_tree *em_tree, struct extent_map *existing, struct extent_map *em, u64 map_start) { struct extent_map *prev; struct extent_map *next; u64 start; u64 end; u64 start_diff; BUG_ON(map_start < em->start || map_start >= extent_map_end(em)); if (existing->start > map_start) { next = existing; prev = prev_extent_map(next); } else { prev = existing; next = next_extent_map(prev); } start = prev ? extent_map_end(prev) : em->start; start = max_t(u64, start, em->start); end = next ? next->start : extent_map_end(em); end = min_t(u64, end, extent_map_end(em)); start_diff = start - em->start; em->start = start; em->len = end - start; if (em->block_start < EXTENT_MAP_LAST_BYTE && !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) { em->block_start += start_diff; em->block_len -= start_diff; } return add_extent_mapping(em_tree, em, 0); } static noinline int uncompress_inline(struct btrfs_path *path, struct inode *inode, struct page *page, size_t pg_offset, u64 extent_offset, struct btrfs_file_extent_item *item) { int ret; struct extent_buffer *leaf = path->nodes[0]; char *tmp; size_t max_size; unsigned long inline_size; unsigned long ptr; int compress_type; WARN_ON(pg_offset != 0); compress_type = btrfs_file_extent_compression(leaf, item); max_size = btrfs_file_extent_ram_bytes(leaf, item); inline_size = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0])); tmp = kmalloc(inline_size, GFP_NOFS); if (!tmp) return -ENOMEM; ptr = btrfs_file_extent_inline_start(item); read_extent_buffer(leaf, tmp, ptr, inline_size); max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size); ret = btrfs_decompress(compress_type, tmp, page, extent_offset, inline_size, max_size); kfree(tmp); return ret; } /* * a bit scary, this does extent mapping from logical file offset to the disk. * the ugly parts come from merging extents from the disk with the in-ram * representation. This gets more complex because of the data=ordered code, * where the in-ram extents might be locked pending data=ordered completion. * * This also copies inline extents directly into the page. */ struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page, size_t pg_offset, u64 start, u64 len, int create) { int ret; int err = 0; u64 extent_start = 0; u64 extent_end = 0; u64 objectid = btrfs_ino(inode); u32 found_type; struct btrfs_path *path = NULL; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *item; struct extent_buffer *leaf; struct btrfs_key found_key; struct extent_map *em = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_trans_handle *trans = NULL; const bool new_inline = !page || create; again: read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, start, len); if (em) em->bdev = root->fs_info->fs_devices->latest_bdev; read_unlock(&em_tree->lock); if (em) { if (em->start > start || em->start + em->len <= start) free_extent_map(em); else if (em->block_start == EXTENT_MAP_INLINE && page) free_extent_map(em); else goto out; } em = alloc_extent_map(); if (!em) { err = -ENOMEM; goto out; } em->bdev = root->fs_info->fs_devices->latest_bdev; em->start = EXTENT_MAP_HOLE; em->orig_start = EXTENT_MAP_HOLE; em->len = (u64)-1; em->block_len = (u64)-1; if (!path) { path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out; } /* * Chances are we'll be called again, so go ahead and do * readahead */ path->reada = 1; } ret = btrfs_lookup_file_extent(trans, root, path, objectid, start, trans != NULL); if (ret < 0) { err = ret; goto out; } if (ret != 0) { if (path->slots[0] == 0) goto not_found; path->slots[0]--; } leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); /* are we inside the extent that was found? */ btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = found_key.type; if (found_key.objectid != objectid || found_type != BTRFS_EXTENT_DATA_KEY) { /* * If we backup past the first extent we want to move forward * and see if there is an extent in front of us, otherwise we'll * say there is a hole for our whole search range which can * cause problems. */ extent_end = start; goto next; } found_type = btrfs_file_extent_type(leaf, item); extent_start = found_key.offset; if (found_type == BTRFS_FILE_EXTENT_REG || found_type == BTRFS_FILE_EXTENT_PREALLOC) { extent_end = extent_start + btrfs_file_extent_num_bytes(leaf, item); } else if (found_type == BTRFS_FILE_EXTENT_INLINE) { size_t size; size = btrfs_file_extent_inline_len(leaf, path->slots[0], item); extent_end = ALIGN(extent_start + size, root->sectorsize); } next: if (start >= extent_end) { path->slots[0]++; if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) { err = ret; goto out; } if (ret > 0) goto not_found; leaf = path->nodes[0]; } btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid != objectid || found_key.type != BTRFS_EXTENT_DATA_KEY) goto not_found; if (start + len <= found_key.offset) goto not_found; if (start > found_key.offset) goto next; em->start = start; em->orig_start = start; em->len = found_key.offset - start; goto not_found_em; } btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em); if (found_type == BTRFS_FILE_EXTENT_REG || found_type == BTRFS_FILE_EXTENT_PREALLOC) { goto insert; } else if (found_type == BTRFS_FILE_EXTENT_INLINE) { unsigned long ptr; char *map; size_t size; size_t extent_offset; size_t copy_size; if (new_inline) goto out; size = btrfs_file_extent_inline_len(leaf, path->slots[0], item); extent_offset = page_offset(page) + pg_offset - extent_start; copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset, size - extent_offset); em->start = extent_start + extent_offset; em->len = ALIGN(copy_size, root->sectorsize); em->orig_block_len = em->len; em->orig_start = em->start; ptr = btrfs_file_extent_inline_start(item) + extent_offset; if (create == 0 && !PageUptodate(page)) { if (btrfs_file_extent_compression(leaf, item) != BTRFS_COMPRESS_NONE) { ret = uncompress_inline(path, inode, page, pg_offset, extent_offset, item); if (ret) { err = ret; goto out; } } else { map = kmap(page); read_extent_buffer(leaf, map + pg_offset, ptr, copy_size); if (pg_offset + copy_size < PAGE_CACHE_SIZE) { memset(map + pg_offset + copy_size, 0, PAGE_CACHE_SIZE - pg_offset - copy_size); } kunmap(page); } flush_dcache_page(page); } else if (create && PageUptodate(page)) { BUG(); if (!trans) { kunmap(page); free_extent_map(em); em = NULL; btrfs_release_path(path); trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return ERR_CAST(trans); goto again; } map = kmap(page); write_extent_buffer(leaf, map + pg_offset, ptr, copy_size); kunmap(page); btrfs_mark_buffer_dirty(leaf); } set_extent_uptodate(io_tree, em->start, extent_map_end(em) - 1, NULL, GFP_NOFS); goto insert; } not_found: em->start = start; em->orig_start = start; em->len = len; not_found_em: em->block_start = EXTENT_MAP_HOLE; set_bit(EXTENT_FLAG_VACANCY, &em->flags); insert: btrfs_release_path(path); if (em->start > start || extent_map_end(em) <= start) { btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]", em->start, em->len, start, len); err = -EIO; goto out; } err = 0; write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 0); /* it is possible that someone inserted the extent into the tree * while we had the lock dropped. It is also possible that * an overlapping map exists in the tree */ if (ret == -EEXIST) { struct extent_map *existing; ret = 0; existing = search_extent_mapping(em_tree, start, len); /* * existing will always be non-NULL, since there must be * extent causing the -EEXIST. */ if (start >= extent_map_end(existing) || start <= existing->start) { /* * The existing extent map is the one nearest to * the [start, start + len) range which overlaps */ err = merge_extent_mapping(em_tree, existing, em, start); free_extent_map(existing); if (err) { free_extent_map(em); em = NULL; } } else { free_extent_map(em); em = existing; err = 0; } } write_unlock(&em_tree->lock); out: trace_btrfs_get_extent(root, em); btrfs_free_path(path); if (trans) { ret = btrfs_end_transaction(trans, root); if (!err) err = ret; } if (err) { free_extent_map(em); return ERR_PTR(err); } BUG_ON(!em); /* Error is always set */ return em; } struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page, size_t pg_offset, u64 start, u64 len, int create) { struct extent_map *em; struct extent_map *hole_em = NULL; u64 range_start = start; u64 end; u64 found; u64 found_end; int err = 0; em = btrfs_get_extent(inode, page, pg_offset, start, len, create); if (IS_ERR(em)) return em; if (em) { /* * if our em maps to * - a hole or * - a pre-alloc extent, * there might actually be delalloc bytes behind it. */ if (em->block_start != EXTENT_MAP_HOLE && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) return em; else hole_em = em; } /* check to see if we've wrapped (len == -1 or similar) */ end = start + len; if (end < start) end = (u64)-1; else end -= 1; em = NULL; /* ok, we didn't find anything, lets look for delalloc */ found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start, end, len, EXTENT_DELALLOC, 1); found_end = range_start + found; if (found_end < range_start) found_end = (u64)-1; /* * we didn't find anything useful, return * the original results from get_extent() */ if (range_start > end || found_end <= start) { em = hole_em; hole_em = NULL; goto out; } /* adjust the range_start to make sure it doesn't * go backwards from the start they passed in */ range_start = max(start, range_start); found = found_end - range_start; if (found > 0) { u64 hole_start = start; u64 hole_len = len; em = alloc_extent_map(); if (!em) { err = -ENOMEM; goto out; } /* * when btrfs_get_extent can't find anything it * returns one huge hole * * make sure what it found really fits our range, and * adjust to make sure it is based on the start from * the caller */ if (hole_em) { u64 calc_end = extent_map_end(hole_em); if (calc_end <= start || (hole_em->start > end)) { free_extent_map(hole_em); hole_em = NULL; } else { hole_start = max(hole_em->start, start); hole_len = calc_end - hole_start; } } em->bdev = NULL; if (hole_em && range_start > hole_start) { /* our hole starts before our delalloc, so we * have to return just the parts of the hole * that go until the delalloc starts */ em->len = min(hole_len, range_start - hole_start); em->start = hole_start; em->orig_start = hole_start; /* * don't adjust block start at all, * it is fixed at EXTENT_MAP_HOLE */ em->block_start = hole_em->block_start; em->block_len = hole_len; if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags)) set_bit(EXTENT_FLAG_PREALLOC, &em->flags); } else { em->start = range_start; em->len = found; em->orig_start = range_start; em->block_start = EXTENT_MAP_DELALLOC; em->block_len = found; } } else if (hole_em) { return hole_em; } out: free_extent_map(hole_em); if (err) { free_extent_map(em); return ERR_PTR(err); } return em; } static struct extent_map *btrfs_new_extent_direct(struct inode *inode, u64 start, u64 len) { struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_map *em; struct btrfs_key ins; u64 alloc_hint; int ret; alloc_hint = get_extent_allocation_hint(inode, start, len); ret = btrfs_reserve_extent(root, len, root->sectorsize, 0, alloc_hint, &ins, 1, 1); if (ret) return ERR_PTR(ret); em = create_pinned_em(inode, start, ins.offset, start, ins.objectid, ins.offset, ins.offset, ins.offset, 0); if (IS_ERR(em)) { btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1); return em; } ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid, ins.offset, ins.offset, 0); if (ret) { btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1); free_extent_map(em); return ERR_PTR(ret); } return em; } /* * returns 1 when the nocow is safe, < 1 on error, 0 if the * block must be cow'd */ noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len, u64 *orig_start, u64 *orig_block_len, u64 *ram_bytes) { struct btrfs_trans_handle *trans; struct btrfs_path *path; int ret; struct extent_buffer *leaf; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_file_extent_item *fi; struct btrfs_key key; u64 disk_bytenr; u64 backref_offset; u64 extent_end; u64 num_bytes; int slot; int found_type; bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW); path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), offset, 0); if (ret < 0) goto out; slot = path->slots[0]; if (ret == 1) { if (slot == 0) { /* can't find the item, must cow */ ret = 0; goto out; } slot--; } ret = 0; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY) { /* not our file or wrong item type, must cow */ goto out; } if (key.offset > offset) { /* Wrong offset, must cow */ goto out; } fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); found_type = btrfs_file_extent_type(leaf, fi); if (found_type != BTRFS_FILE_EXTENT_REG && found_type != BTRFS_FILE_EXTENT_PREALLOC) { /* not a regular extent, must cow */ goto out; } if (!nocow && found_type == BTRFS_FILE_EXTENT_REG) goto out; extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi); if (extent_end <= offset) goto out; disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); if (disk_bytenr == 0) goto out; if (btrfs_file_extent_compression(leaf, fi) || btrfs_file_extent_encryption(leaf, fi) || btrfs_file_extent_other_encoding(leaf, fi)) goto out; backref_offset = btrfs_file_extent_offset(leaf, fi); if (orig_start) { *orig_start = key.offset - backref_offset; *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi); *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi); } if (btrfs_extent_readonly(root, disk_bytenr)) goto out; num_bytes = min(offset + *len, extent_end) - offset; if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) { u64 range_end; range_end = round_up(offset + num_bytes, root->sectorsize) - 1; ret = test_range_bit(io_tree, offset, range_end, EXTENT_DELALLOC, 0, NULL); if (ret) { ret = -EAGAIN; goto out; } } btrfs_release_path(path); /* * look for other files referencing this extent, if we * find any we must cow */ trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = 0; goto out; } ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode), key.offset - backref_offset, disk_bytenr); btrfs_end_transaction(trans, root); if (ret) { ret = 0; goto out; } /* * adjust disk_bytenr and num_bytes to cover just the bytes * in this extent we are about to write. If there * are any csums in that range we have to cow in order * to keep the csums correct */ disk_bytenr += backref_offset; disk_bytenr += offset - key.offset; if (csum_exist_in_range(root, disk_bytenr, num_bytes)) goto out; /* * all of the above have passed, it is safe to overwrite this extent * without cow */ *len = num_bytes; ret = 1; out: btrfs_free_path(path); return ret; } bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end) { struct radix_tree_root *root = &inode->i_mapping->page_tree; int found = false; void **pagep = NULL; struct page *page = NULL; int start_idx; int end_idx; start_idx = start >> PAGE_CACHE_SHIFT; /* * end is the last byte in the last page. end == start is legal */ end_idx = end >> PAGE_CACHE_SHIFT; rcu_read_lock(); /* Most of the code in this while loop is lifted from * find_get_page. It's been modified to begin searching from a * page and return just the first page found in that range. If the * found idx is less than or equal to the end idx then we know that * a page exists. If no pages are found or if those pages are * outside of the range then we're fine (yay!) */ while (page == NULL && radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) { page = radix_tree_deref_slot(pagep); if (unlikely(!page)) break; if (radix_tree_exception(page)) { if (radix_tree_deref_retry(page)) { page = NULL; continue; } /* * Otherwise, shmem/tmpfs must be storing a swap entry * here as an exceptional entry: so return it without * attempting to raise page count. */ page = NULL; break; /* TODO: Is this relevant for this use case? */ } if (!page_cache_get_speculative(page)) { page = NULL; continue; } /* * Has the page moved? * This is part of the lockless pagecache protocol. See * include/linux/pagemap.h for details. */ if (unlikely(page != *pagep)) { page_cache_release(page); page = NULL; } } if (page) { if (page->index <= end_idx) found = true; page_cache_release(page); } rcu_read_unlock(); return found; } static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend, struct extent_state **cached_state, int writing) { struct btrfs_ordered_extent *ordered; int ret = 0; while (1) { lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0, cached_state); /* * We're concerned with the entire range that we're going to be * doing DIO to, so we need to make sure theres no ordered * extents in this range. */ ordered = btrfs_lookup_ordered_range(inode, lockstart, lockend - lockstart + 1); /* * We need to make sure there are no buffered pages in this * range either, we could have raced between the invalidate in * generic_file_direct_write and locking the extent. The * invalidate needs to happen so that reads after a write do not * get stale data. */ if (!ordered && (!writing || !btrfs_page_exists_in_range(inode, lockstart, lockend))) break; unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend, cached_state, GFP_NOFS); if (ordered) { btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); } else { /* Screw you mmap */ ret = btrfs_fdatawrite_range(inode, lockstart, lockend); if (ret) break; ret = filemap_fdatawait_range(inode->i_mapping, lockstart, lockend); if (ret) break; /* * If we found a page that couldn't be invalidated just * fall back to buffered. */ ret = invalidate_inode_pages2_range(inode->i_mapping, lockstart >> PAGE_CACHE_SHIFT, lockend >> PAGE_CACHE_SHIFT); if (ret) break; } cond_resched(); } return ret; } static struct extent_map *create_pinned_em(struct inode *inode, u64 start, u64 len, u64 orig_start, u64 block_start, u64 block_len, u64 orig_block_len, u64 ram_bytes, int type) { struct extent_map_tree *em_tree; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; em_tree = &BTRFS_I(inode)->extent_tree; em = alloc_extent_map(); if (!em) return ERR_PTR(-ENOMEM); em->start = start; em->orig_start = orig_start; em->mod_start = start; em->mod_len = len; em->len = len; em->block_len = block_len; em->block_start = block_start; em->bdev = root->fs_info->fs_devices->latest_bdev; em->orig_block_len = orig_block_len; em->ram_bytes = ram_bytes; em->generation = -1; set_bit(EXTENT_FLAG_PINNED, &em->flags); if (type == BTRFS_ORDERED_PREALLOC) set_bit(EXTENT_FLAG_FILLING, &em->flags); do { btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 1); write_unlock(&em_tree->lock); } while (ret == -EEXIST); if (ret) { free_extent_map(em); return ERR_PTR(ret); } return em; } struct btrfs_dio_data { u64 outstanding_extents; u64 reserve; }; static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_state *cached_state = NULL; struct btrfs_dio_data *dio_data = NULL; u64 start = iblock << inode->i_blkbits; u64 lockstart, lockend; u64 len = bh_result->b_size; int unlock_bits = EXTENT_LOCKED; int ret = 0; if (create) unlock_bits |= EXTENT_DIRTY; else len = min_t(u64, len, root->sectorsize); lockstart = start; lockend = start + len - 1; if (current->journal_info) { /* * Need to pull our outstanding extents and set journal_info to NULL so * that anything that needs to check if there's a transction doesn't get * confused. */ dio_data = current->journal_info; current->journal_info = NULL; } /* * If this errors out it's because we couldn't invalidate pagecache for * this range and we need to fallback to buffered. */ if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create)) return -ENOTBLK; em = btrfs_get_extent(inode, NULL, 0, start, len, 0); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } /* * Ok for INLINE and COMPRESSED extents we need to fallback on buffered * io. INLINE is special, and we could probably kludge it in here, but * it's still buffered so for safety lets just fall back to the generic * buffered path. * * For COMPRESSED we _have_ to read the entire extent in so we can * decompress it, so there will be buffering required no matter what we * do, so go ahead and fallback to buffered. * * We return -ENOTBLK because thats what makes DIO go ahead and go back * to buffered IO. Don't blame me, this is the price we pay for using * the generic code. */ if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) || em->block_start == EXTENT_MAP_INLINE) { free_extent_map(em); ret = -ENOTBLK; goto unlock_err; } /* Just a good old fashioned hole, return */ if (!create && (em->block_start == EXTENT_MAP_HOLE || test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) { free_extent_map(em); goto unlock_err; } /* * We don't allocate a new extent in the following cases * * 1) The inode is marked as NODATACOW. In this case we'll just use the * existing extent. * 2) The extent is marked as PREALLOC. We're good to go here and can * just use the extent. * */ if (!create) { len = min(len, em->len - (start - em->start)); lockstart = start + len; goto unlock; } if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) || ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) && em->block_start != EXTENT_MAP_HOLE)) { int type; u64 block_start, orig_start, orig_block_len, ram_bytes; if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) type = BTRFS_ORDERED_PREALLOC; else type = BTRFS_ORDERED_NOCOW; len = min(len, em->len - (start - em->start)); block_start = em->block_start + (start - em->start); if (can_nocow_extent(inode, start, &len, &orig_start, &orig_block_len, &ram_bytes) == 1) { if (type == BTRFS_ORDERED_PREALLOC) { free_extent_map(em); em = create_pinned_em(inode, start, len, orig_start, block_start, len, orig_block_len, ram_bytes, type); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } } ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len, len, type); if (ret) { free_extent_map(em); goto unlock_err; } goto unlock; } } /* * this will cow the extent, reset the len in case we changed * it above */ len = bh_result->b_size; free_extent_map(em); em = btrfs_new_extent_direct(inode, start, len); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } len = min(len, em->len - (start - em->start)); unlock: bh_result->b_blocknr = (em->block_start + (start - em->start)) >> inode->i_blkbits; bh_result->b_size = len; bh_result->b_bdev = em->bdev; set_buffer_mapped(bh_result); if (create) { if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) set_buffer_new(bh_result); /* * Need to update the i_size under the extent lock so buffered * readers will get the updated i_size when we unlock. */ if (start + len > i_size_read(inode)) i_size_write(inode, start + len); /* * If we have an outstanding_extents count still set then we're * within our reservation, otherwise we need to adjust our inode * counter appropriately. */ if (dio_data->outstanding_extents) { (dio_data->outstanding_extents)--; } else { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } btrfs_free_reserved_data_space(inode, len); WARN_ON(dio_data->reserve < len); dio_data->reserve -= len; current->journal_info = dio_data; } /* * In the case of write we need to clear and unlock the entire range, * in the case of read we need to unlock only the end area that we * aren't using if there is any left over space. */ if (lockstart < lockend) { clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, unlock_bits, 1, 0, &cached_state, GFP_NOFS); } else { free_extent_state(cached_state); } free_extent_map(em); return 0; unlock_err: clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, unlock_bits, 1, 0, &cached_state, GFP_NOFS); if (dio_data) current->journal_info = dio_data; return ret; } static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio, int rw, int mirror_num) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret; BUG_ON(rw & REQ_WRITE); bio_get(bio); ret = btrfs_bio_wq_end_io(root->fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR); if (ret) goto err; ret = btrfs_map_bio(root, rw, bio, mirror_num, 0); err: bio_put(bio); return ret; } static int btrfs_check_dio_repairable(struct inode *inode, struct bio *failed_bio, struct io_failure_record *failrec, int failed_mirror) { int num_copies; num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info, failrec->logical, failrec->len); if (num_copies == 1) { /* * we only have a single copy of the data, so don't bother with * all the retry and error correction code that follows. no * matter what the error is, it is very likely to persist. */ pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n", num_copies, failrec->this_mirror, failed_mirror); return 0; } failrec->failed_mirror = failed_mirror; failrec->this_mirror++; if (failrec->this_mirror == failed_mirror) failrec->this_mirror++; if (failrec->this_mirror > num_copies) { pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n", num_copies, failrec->this_mirror, failed_mirror); return 0; } return 1; } static int dio_read_error(struct inode *inode, struct bio *failed_bio, struct page *page, u64 start, u64 end, int failed_mirror, bio_end_io_t *repair_endio, void *repair_arg) { struct io_failure_record *failrec; struct bio *bio; int isector; int read_mode; int ret; BUG_ON(failed_bio->bi_rw & REQ_WRITE); ret = btrfs_get_io_failure_record(inode, start, end, &failrec); if (ret) return ret; ret = btrfs_check_dio_repairable(inode, failed_bio, failrec, failed_mirror); if (!ret) { free_io_failure(inode, failrec); return -EIO; } if (failed_bio->bi_vcnt > 1) read_mode = READ_SYNC | REQ_FAILFAST_DEV; else read_mode = READ_SYNC; isector = start - btrfs_io_bio(failed_bio)->logical; isector >>= inode->i_sb->s_blocksize_bits; bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page, 0, isector, repair_endio, repair_arg); if (!bio) { free_io_failure(inode, failrec); return -EIO; } btrfs_debug(BTRFS_I(inode)->root->fs_info, "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n", read_mode, failrec->this_mirror, failrec->in_validation); ret = submit_dio_repair_bio(inode, bio, read_mode, failrec->this_mirror); if (ret) { free_io_failure(inode, failrec); bio_put(bio); } return ret; } struct btrfs_retry_complete { struct completion done; struct inode *inode; u64 start; int uptodate; }; static void btrfs_retry_endio_nocsum(struct bio *bio) { struct btrfs_retry_complete *done = bio->bi_private; struct bio_vec *bvec; int i; if (bio->bi_error) goto end; done->uptodate = 1; bio_for_each_segment_all(bvec, bio, i) clean_io_failure(done->inode, done->start, bvec->bv_page, 0); end: complete(&done->done); bio_put(bio); } static int __btrfs_correct_data_nocsum(struct inode *inode, struct btrfs_io_bio *io_bio) { struct bio_vec *bvec; struct btrfs_retry_complete done; u64 start; int i; int ret; start = io_bio->logical; done.inode = inode; bio_for_each_segment_all(bvec, &io_bio->bio, i) { try_again: done.uptodate = 0; done.start = start; init_completion(&done.done); ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start, start + bvec->bv_len - 1, io_bio->mirror_num, btrfs_retry_endio_nocsum, &done); if (ret) return ret; wait_for_completion(&done.done); if (!done.uptodate) { /* We might have another mirror, so try again */ goto try_again; } start += bvec->bv_len; } return 0; } static void btrfs_retry_endio(struct bio *bio) { struct btrfs_retry_complete *done = bio->bi_private; struct btrfs_io_bio *io_bio = btrfs_io_bio(bio); struct bio_vec *bvec; int uptodate; int ret; int i; if (bio->bi_error) goto end; uptodate = 1; bio_for_each_segment_all(bvec, bio, i) { ret = __readpage_endio_check(done->inode, io_bio, i, bvec->bv_page, 0, done->start, bvec->bv_len); if (!ret) clean_io_failure(done->inode, done->start, bvec->bv_page, 0); else uptodate = 0; } done->uptodate = uptodate; end: complete(&done->done); bio_put(bio); } static int __btrfs_subio_endio_read(struct inode *inode, struct btrfs_io_bio *io_bio, int err) { struct bio_vec *bvec; struct btrfs_retry_complete done; u64 start; u64 offset = 0; int i; int ret; err = 0; start = io_bio->logical; done.inode = inode; bio_for_each_segment_all(bvec, &io_bio->bio, i) { ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page, 0, start, bvec->bv_len); if (likely(!ret)) goto next; try_again: done.uptodate = 0; done.start = start; init_completion(&done.done); ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start, start + bvec->bv_len - 1, io_bio->mirror_num, btrfs_retry_endio, &done); if (ret) { err = ret; goto next; } wait_for_completion(&done.done); if (!done.uptodate) { /* We might have another mirror, so try again */ goto try_again; } next: offset += bvec->bv_len; start += bvec->bv_len; } return err; } static int btrfs_subio_endio_read(struct inode *inode, struct btrfs_io_bio *io_bio, int err) { bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; if (skip_csum) { if (unlikely(err)) return __btrfs_correct_data_nocsum(inode, io_bio); else return 0; } else { return __btrfs_subio_endio_read(inode, io_bio, err); } } static void btrfs_endio_direct_read(struct bio *bio) { struct btrfs_dio_private *dip = bio->bi_private; struct inode *inode = dip->inode; struct bio *dio_bio; struct btrfs_io_bio *io_bio = btrfs_io_bio(bio); int err = bio->bi_error; if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED) err = btrfs_subio_endio_read(inode, io_bio, err); unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset, dip->logical_offset + dip->bytes - 1); dio_bio = dip->dio_bio; kfree(dip); dio_end_io(dio_bio, bio->bi_error); if (io_bio->end_io) io_bio->end_io(io_bio, err); bio_put(bio); } static void btrfs_endio_direct_write(struct bio *bio) { struct btrfs_dio_private *dip = bio->bi_private; struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ordered_extent *ordered = NULL; u64 ordered_offset = dip->logical_offset; u64 ordered_bytes = dip->bytes; struct bio *dio_bio; int ret; again: ret = btrfs_dec_test_first_ordered_pending(inode, &ordered, &ordered_offset, ordered_bytes, !bio->bi_error); if (!ret) goto out_test; btrfs_init_work(&ordered->work, btrfs_endio_write_helper, finish_ordered_fn, NULL, NULL); btrfs_queue_work(root->fs_info->endio_write_workers, &ordered->work); out_test: /* * our bio might span multiple ordered extents. If we haven't * completed the accounting for the whole dio, go back and try again */ if (ordered_offset < dip->logical_offset + dip->bytes) { ordered_bytes = dip->logical_offset + dip->bytes - ordered_offset; ordered = NULL; goto again; } dio_bio = dip->dio_bio; kfree(dip); dio_end_io(dio_bio, bio->bi_error); bio_put(bio); } static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 offset) { int ret; struct btrfs_root *root = BTRFS_I(inode)->root; ret = btrfs_csum_one_bio(root, inode, bio, offset, 1); BUG_ON(ret); /* -ENOMEM */ return 0; } static void btrfs_end_dio_bio(struct bio *bio) { struct btrfs_dio_private *dip = bio->bi_private; int err = bio->bi_error; if (err) btrfs_warn(BTRFS_I(dip->inode)->root->fs_info, "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d", btrfs_ino(dip->inode), bio->bi_rw, (unsigned long long)bio->bi_iter.bi_sector, bio->bi_iter.bi_size, err); if (dip->subio_endio) err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err); if (err) { dip->errors = 1; /* * before atomic variable goto zero, we must make sure * dip->errors is perceived to be set. */ smp_mb__before_atomic(); } /* if there are more bios still pending for this dio, just exit */ if (!atomic_dec_and_test(&dip->pending_bios)) goto out; if (dip->errors) { bio_io_error(dip->orig_bio); } else { dip->dio_bio->bi_error = 0; bio_endio(dip->orig_bio); } out: bio_put(bio); } static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev, u64 first_sector, gfp_t gfp_flags) { struct bio *bio; bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags); if (bio) bio_associate_current(bio); return bio; } static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root, struct inode *inode, struct btrfs_dio_private *dip, struct bio *bio, u64 file_offset) { struct btrfs_io_bio *io_bio = btrfs_io_bio(bio); struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio); int ret; /* * We load all the csum data we need when we submit * the first bio to reduce the csum tree search and * contention. */ if (dip->logical_offset == file_offset) { ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio, file_offset); if (ret) return ret; } if (bio == dip->orig_bio) return 0; file_offset -= dip->logical_offset; file_offset >>= inode->i_sb->s_blocksize_bits; io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset); return 0; } static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, int rw, u64 file_offset, int skip_sum, int async_submit) { struct btrfs_dio_private *dip = bio->bi_private; int write = rw & REQ_WRITE; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; if (async_submit) async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers); bio_get(bio); if (!write) { ret = btrfs_bio_wq_end_io(root->fs_info, bio, BTRFS_WQ_ENDIO_DATA); if (ret) goto err; } if (skip_sum) goto map; if (write && async_submit) { ret = btrfs_wq_submit_bio(root->fs_info, inode, rw, bio, 0, 0, file_offset, __btrfs_submit_bio_start_direct_io, __btrfs_submit_bio_done); goto err; } else if (write) { /* * If we aren't doing async submit, calculate the csum of the * bio now. */ ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1); if (ret) goto err; } else { ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio, file_offset); if (ret) goto err; } map: ret = btrfs_map_bio(root, rw, bio, 0, async_submit); err: bio_put(bio); return ret; } static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip, int skip_sum) { struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct bio *bio; struct bio *orig_bio = dip->orig_bio; struct bio_vec *bvec = orig_bio->bi_io_vec; u64 start_sector = orig_bio->bi_iter.bi_sector; u64 file_offset = dip->logical_offset; u64 submit_len = 0; u64 map_length; int nr_pages = 0; int ret; int async_submit = 0; map_length = orig_bio->bi_iter.bi_size; ret = btrfs_map_block(root->fs_info, rw, start_sector << 9, &map_length, NULL, 0); if (ret) return -EIO; if (map_length >= orig_bio->bi_iter.bi_size) { bio = orig_bio; dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED; goto submit; } /* async crcs make it difficult to collect full stripe writes. */ if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK) async_submit = 0; else async_submit = 1; bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS); if (!bio) return -ENOMEM; bio->bi_private = dip; bio->bi_end_io = btrfs_end_dio_bio; btrfs_io_bio(bio)->logical = file_offset; atomic_inc(&dip->pending_bios); while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) { if (map_length < submit_len + bvec->bv_len || bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset) < bvec->bv_len) { /* * inc the count before we submit the bio so * we know the end IO handler won't happen before * we inc the count. Otherwise, the dip might get freed * before we're done setting it up */ atomic_inc(&dip->pending_bios); ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum, async_submit); if (ret) { bio_put(bio); atomic_dec(&dip->pending_bios); goto out_err; } start_sector += submit_len >> 9; file_offset += submit_len; submit_len = 0; nr_pages = 0; bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS); if (!bio) goto out_err; bio->bi_private = dip; bio->bi_end_io = btrfs_end_dio_bio; btrfs_io_bio(bio)->logical = file_offset; map_length = orig_bio->bi_iter.bi_size; ret = btrfs_map_block(root->fs_info, rw, start_sector << 9, &map_length, NULL, 0); if (ret) { bio_put(bio); goto out_err; } } else { submit_len += bvec->bv_len; nr_pages++; bvec++; } } submit: ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum, async_submit); if (!ret) return 0; bio_put(bio); out_err: dip->errors = 1; /* * before atomic variable goto zero, we must * make sure dip->errors is perceived to be set. */ smp_mb__before_atomic(); if (atomic_dec_and_test(&dip->pending_bios)) bio_io_error(dip->orig_bio); /* bio_end_io() will handle error, so we needn't return it */ return 0; } static void btrfs_submit_direct(int rw, struct bio *dio_bio, struct inode *inode, loff_t file_offset) { struct btrfs_dio_private *dip = NULL; struct bio *io_bio = NULL; struct btrfs_io_bio *btrfs_bio; int skip_sum; int write = rw & REQ_WRITE; int ret = 0; skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS); if (!io_bio) { ret = -ENOMEM; goto free_ordered; } dip = kzalloc(sizeof(*dip), GFP_NOFS); if (!dip) { ret = -ENOMEM; goto free_ordered; } dip->private = dio_bio->bi_private; dip->inode = inode; dip->logical_offset = file_offset; dip->bytes = dio_bio->bi_iter.bi_size; dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9; io_bio->bi_private = dip; dip->orig_bio = io_bio; dip->dio_bio = dio_bio; atomic_set(&dip->pending_bios, 0); btrfs_bio = btrfs_io_bio(io_bio); btrfs_bio->logical = file_offset; if (write) { io_bio->bi_end_io = btrfs_endio_direct_write; } else { io_bio->bi_end_io = btrfs_endio_direct_read; dip->subio_endio = btrfs_subio_endio_read; } ret = btrfs_submit_direct_hook(rw, dip, skip_sum); if (!ret) return; if (btrfs_bio->end_io) btrfs_bio->end_io(btrfs_bio, ret); free_ordered: /* * If we arrived here it means either we failed to submit the dip * or we either failed to clone the dio_bio or failed to allocate the * dip. If we cloned the dio_bio and allocated the dip, we can just * call bio_endio against our io_bio so that we get proper resource * cleanup if we fail to submit the dip, otherwise, we must do the * same as btrfs_endio_direct_[write|read] because we can't call these * callbacks - they require an allocated dip and a clone of dio_bio. */ if (io_bio && dip) { io_bio->bi_error = -EIO; bio_endio(io_bio); /* * The end io callbacks free our dip, do the final put on io_bio * and all the cleanup and final put for dio_bio (through * dio_end_io()). */ dip = NULL; io_bio = NULL; } else { if (write) { struct btrfs_ordered_extent *ordered; ordered = btrfs_lookup_ordered_extent(inode, file_offset); set_bit(BTRFS_ORDERED_IOERR, &ordered->flags); /* * Decrements our ref on the ordered extent and removes * the ordered extent from the inode's ordered tree, * doing all the proper resource cleanup such as for the * reserved space and waking up any waiters for this * ordered extent (through btrfs_remove_ordered_extent). */ btrfs_finish_ordered_io(ordered); } else { unlock_extent(&BTRFS_I(inode)->io_tree, file_offset, file_offset + dio_bio->bi_iter.bi_size - 1); } dio_bio->bi_error = -EIO; /* * Releases and cleans up our dio_bio, no need to bio_put() * nor bio_endio()/bio_io_error() against dio_bio. */ dio_end_io(dio_bio, ret); } if (io_bio) bio_put(io_bio); kfree(dip); } static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb, const struct iov_iter *iter, loff_t offset) { int seg; int i; unsigned blocksize_mask = root->sectorsize - 1; ssize_t retval = -EINVAL; if (offset & blocksize_mask) goto out; if (iov_iter_alignment(iter) & blocksize_mask) goto out; /* If this is a write we don't need to check anymore */ if (iov_iter_rw(iter) == WRITE) return 0; /* * Check to make sure we don't have duplicate iov_base's in this * iovec, if so return EINVAL, otherwise we'll get csum errors * when reading back. */ for (seg = 0; seg < iter->nr_segs; seg++) { for (i = seg + 1; i < iter->nr_segs; i++) { if (iter->iov[seg].iov_base == iter->iov[i].iov_base) goto out; } } retval = 0; out: return retval; } static ssize_t btrfs_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; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_dio_data dio_data = { 0 }; size_t count = 0; int flags = 0; bool wakeup = true; bool relock = false; ssize_t ret; if (check_direct_IO(BTRFS_I(inode)->root, iocb, iter, offset)) return 0; inode_dio_begin(inode); smp_mb__after_atomic(); /* * The generic stuff only does filemap_write_and_wait_range, which * isn't enough if we've written compressed pages to this area, so * we need to flush the dirty pages again to make absolutely sure * that any outstanding dirty pages are on disk. */ count = iov_iter_count(iter); if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &BTRFS_I(inode)->runtime_flags)) filemap_fdatawrite_range(inode->i_mapping, offset, offset + count - 1); if (iov_iter_rw(iter) == WRITE) { /* * If the write DIO is beyond the EOF, we need update * the isize, but it is protected by i_mutex. So we can * not unlock the i_mutex at this case. */ if (offset + count <= inode->i_size) { mutex_unlock(&inode->i_mutex); relock = true; } ret = btrfs_delalloc_reserve_space(inode, count); if (ret) goto out; dio_data.outstanding_extents = div64_u64(count + BTRFS_MAX_EXTENT_SIZE - 1, BTRFS_MAX_EXTENT_SIZE); /* * We need to know how many extents we reserved so that we can * do the accounting properly if we go over the number we * originally calculated. Abuse current->journal_info for this. */ dio_data.reserve = round_up(count, root->sectorsize); current->journal_info = &dio_data; } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK, &BTRFS_I(inode)->runtime_flags)) { inode_dio_end(inode); flags = DIO_LOCKING | DIO_SKIP_HOLES; wakeup = false; } ret = __blockdev_direct_IO(iocb, inode, BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev, iter, offset, btrfs_get_blocks_direct, NULL, btrfs_submit_direct, flags); if (iov_iter_rw(iter) == WRITE) { current->journal_info = NULL; if (ret < 0 && ret != -EIOCBQUEUED) { if (dio_data.reserve) btrfs_delalloc_release_space(inode, dio_data.reserve); } else if (ret >= 0 && (size_t)ret < count) btrfs_delalloc_release_space(inode, count - (size_t)ret); } out: if (wakeup) inode_dio_end(inode); if (relock) mutex_lock(&inode->i_mutex); return ret; } #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC) static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len) { int ret; ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS); if (ret) return ret; return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap); } int btrfs_readpage(struct file *file, struct page *page) { struct extent_io_tree *tree; tree = &BTRFS_I(page->mapping->host)->io_tree; return extent_read_full_page(tree, page, btrfs_get_extent, 0); } static int btrfs_writepage(struct page *page, struct writeback_control *wbc) { struct extent_io_tree *tree; if (current->flags & PF_MEMALLOC) { redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } tree = &BTRFS_I(page->mapping->host)->io_tree; return extent_write_full_page(tree, page, btrfs_get_extent, wbc); } static int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc) { struct extent_io_tree *tree; tree = &BTRFS_I(mapping->host)->io_tree; return extent_writepages(tree, mapping, btrfs_get_extent, wbc); } static int btrfs_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { struct extent_io_tree *tree; tree = &BTRFS_I(mapping->host)->io_tree; return extent_readpages(tree, mapping, pages, nr_pages, btrfs_get_extent); } static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags) { struct extent_io_tree *tree; struct extent_map_tree *map; int ret; tree = &BTRFS_I(page->mapping->host)->io_tree; map = &BTRFS_I(page->mapping->host)->extent_tree; ret = try_release_extent_mapping(map, tree, page, gfp_flags); if (ret == 1) { ClearPagePrivate(page); set_page_private(page, 0); page_cache_release(page); } return ret; } static int btrfs_releasepage(struct page *page, gfp_t gfp_flags) { if (PageWriteback(page) || PageDirty(page)) return 0; return __btrfs_releasepage(page, gfp_flags & GFP_NOFS); } static void btrfs_invalidatepage(struct page *page, unsigned int offset, unsigned int length) { struct inode *inode = page->mapping->host; struct extent_io_tree *tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; u64 page_start = page_offset(page); u64 page_end = page_start + PAGE_CACHE_SIZE - 1; int inode_evicting = inode->i_state & I_FREEING; /* * we have the page locked, so new writeback can't start, * and the dirty bit won't be cleared while we are here. * * Wait for IO on this page so that we can safely clear * the PagePrivate2 bit and do ordered accounting */ wait_on_page_writeback(page); tree = &BTRFS_I(inode)->io_tree; if (offset) { btrfs_releasepage(page, GFP_NOFS); return; } if (!inode_evicting) lock_extent_bits(tree, page_start, page_end, 0, &cached_state); ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { /* * IO on this page will never be started, so we need * to account for any ordered extents now */ if (!inode_evicting) clear_extent_bit(tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_LOCKED | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS); /* * whoever cleared the private bit is responsible * for the finish_ordered_io */ if (TestClearPagePrivate2(page)) { struct btrfs_ordered_inode_tree *tree; u64 new_len; tree = &BTRFS_I(inode)->ordered_tree; spin_lock_irq(&tree->lock); set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags); new_len = page_start - ordered->file_offset; if (new_len < ordered->truncated_len) ordered->truncated_len = new_len; spin_unlock_irq(&tree->lock); if (btrfs_dec_test_ordered_pending(inode, &ordered, page_start, PAGE_CACHE_SIZE, 1)) btrfs_finish_ordered_io(ordered); } btrfs_put_ordered_extent(ordered); if (!inode_evicting) { cached_state = NULL; lock_extent_bits(tree, page_start, page_end, 0, &cached_state); } } if (!inode_evicting) { clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, &cached_state, GFP_NOFS); __btrfs_releasepage(page, GFP_NOFS); } ClearPageChecked(page); if (PagePrivate(page)) { ClearPagePrivate(page); set_page_private(page, 0); page_cache_release(page); } } /* * btrfs_page_mkwrite() is not allowed to change the file size as it gets * called from a page fault handler when a page is first dirtied. Hence we must * be careful to check for EOF conditions here. We set the page up correctly * for a written page which means we get ENOSPC checking when writing into * holes and correct delalloc and unwritten extent mapping on filesystems that * support these features. * * We are not allowed to take the i_mutex here so we have to play games to * protect against truncate races as the page could now be beyond EOF. Because * vmtruncate() writes the inode size before removing pages, once we have the * page lock we can determine safely if the page is beyond EOF. If it is not * beyond EOF, then the page is guaranteed safe against truncation until we * unlock the page. */ int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; struct inode *inode = file_inode(vma->vm_file); struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; char *kaddr; unsigned long zero_start; loff_t size; int ret; int reserved = 0; u64 page_start; u64 page_end; sb_start_pagefault(inode->i_sb); ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (!ret) { ret = file_update_time(vma->vm_file); reserved = 1; } if (ret) { if (ret == -ENOMEM) ret = VM_FAULT_OOM; else /* -ENOSPC, -EIO, etc */ ret = VM_FAULT_SIGBUS; if (reserved) goto out; goto out_noreserve; } ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */ again: lock_page(page); size = i_size_read(inode); page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; if ((page->mapping != inode->i_mapping) || (page_start >= size)) { /* page got truncated out from underneath us */ goto out_unlock; } wait_on_page_writeback(page); lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state); set_page_extent_mapped(page); /* * we can't set the delalloc bits if there are pending ordered * extents. Drop our locks and wait for them to finish */ ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } /* * XXX - page_mkwrite gets called every time the page is dirtied, even * if it was already dirty, so for space accounting reasons we need to * clear any delalloc bits for the range we are fixing to save. There * is probably a better way to do this, but for now keep consistent with * prepare_pages in the normal write path. */ clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); ret = btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); if (ret) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); ret = VM_FAULT_SIGBUS; goto out_unlock; } ret = 0; /* page is wholly or partially inside EOF */ if (page_start + PAGE_CACHE_SIZE > size) zero_start = size & ~PAGE_CACHE_MASK; else zero_start = PAGE_CACHE_SIZE; if (zero_start != PAGE_CACHE_SIZE) { kaddr = kmap(page); memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start); flush_dcache_page(page); kunmap(page); } ClearPageChecked(page); set_page_dirty(page); SetPageUptodate(page); BTRFS_I(inode)->last_trans = root->fs_info->generation; BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid; BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit; unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_unlock: if (!ret) { sb_end_pagefault(inode->i_sb); return VM_FAULT_LOCKED; } unlock_page(page); out: btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); out_noreserve: sb_end_pagefault(inode->i_sb); return ret; } static int btrfs_truncate(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *rsv; int ret = 0; int err = 0; struct btrfs_trans_handle *trans; u64 mask = root->sectorsize - 1; u64 min_size = btrfs_calc_trunc_metadata_size(root, 1); ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1); if (ret) return ret; /* * Yes ladies and gentelment, this is indeed ugly. The fact is we have * 3 things going on here * * 1) We need to reserve space for our orphan item and the space to * delete our orphan item. Lord knows we don't want to have a dangling * orphan item because we didn't reserve space to remove it. * * 2) We need to reserve space to update our inode. * * 3) We need to have something to cache all the space that is going to * be free'd up by the truncate operation, but also have some slack * space reserved in case it uses space during the truncate (thank you * very much snapshotting). * * And we need these to all be seperate. The fact is we can use alot of * space doing the truncate, and we have no earthly idea how much space * we will use, so we need the truncate reservation to be seperate so it * doesn't end up using space reserved for updating the inode or * removing the orphan item. We also need to be able to stop the * transaction and start a new one, which means we need to be able to * update the inode several times, and we have no idea of knowing how * many times that will be, so we can't just reserve 1 item for the * entirety of the opration, so that has to be done seperately as well. * Then there is the orphan item, which does indeed need to be held on * to for the whole operation, and we need nobody to touch this reserved * space except the orphan code. * * So that leaves us with * * 1) root->orphan_block_rsv - for the orphan deletion. * 2) rsv - for the truncate reservation, which we will steal from the * transaction reservation. * 3) fs_info->trans_block_rsv - this will have 1 items worth left for * updating the inode. */ rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!rsv) return -ENOMEM; rsv->size = min_size; rsv->failfast = 1; /* * 1 for the truncate slack space * 1 for updating the inode. */ trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto out; } /* Migrate the slack space for the truncate to our reserve */ ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv, min_size); BUG_ON(ret); /* * So if we truncate and then write and fsync we normally would just * write the extents that changed, which is a problem if we need to * first truncate that entire inode. So set this flag so we write out * all of the extents in the inode to the sync log so we're completely * safe. */ set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); trans->block_rsv = rsv; while (1) { ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size, BTRFS_EXTENT_DATA_KEY); if (ret != -ENOSPC && ret != -EAGAIN) { err = ret; break; } trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); if (ret) { err = ret; break; } btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { ret = err = PTR_ERR(trans); trans = NULL; break; } ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv, min_size); BUG_ON(ret); /* shouldn't happen */ trans->block_rsv = rsv; } if (ret == 0 && inode->i_nlink > 0) { trans->block_rsv = root->orphan_block_rsv; ret = btrfs_orphan_del(trans, inode); if (ret) err = ret; } if (trans) { trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); if (ret && !err) err = ret; ret = btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); } out: btrfs_free_block_rsv(root, rsv); if (ret && !err) err = ret; return err; } /* * create a new subvolume directory/inode (helper for the ioctl). */ int btrfs_create_subvol_root(struct btrfs_trans_handle *trans, struct btrfs_root *new_root, struct btrfs_root *parent_root, u64 new_dirid) { struct inode *inode; int err; u64 index = 0; inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid, new_dirid, S_IFDIR | (~current_umask() & S_IRWXUGO), &index); if (IS_ERR(inode)) return PTR_ERR(inode); inode->i_op = &btrfs_dir_inode_operations; inode->i_fop = &btrfs_dir_file_operations; set_nlink(inode, 1); btrfs_i_size_write(inode, 0); unlock_new_inode(inode); err = btrfs_subvol_inherit_props(trans, new_root, parent_root); if (err) btrfs_err(new_root->fs_info, "error inheriting subvolume %llu properties: %d", new_root->root_key.objectid, err); err = btrfs_update_inode(trans, new_root, inode); iput(inode); return err; } struct inode *btrfs_alloc_inode(struct super_block *sb) { struct btrfs_inode *ei; struct inode *inode; ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS); if (!ei) return NULL; ei->root = NULL; ei->generation = 0; ei->last_trans = 0; ei->last_sub_trans = 0; ei->logged_trans = 0; ei->delalloc_bytes = 0; ei->defrag_bytes = 0; ei->disk_i_size = 0; ei->flags = 0; ei->csum_bytes = 0; ei->index_cnt = (u64)-1; ei->dir_index = 0; ei->last_unlink_trans = 0; ei->last_log_commit = 0; spin_lock_init(&ei->lock); ei->outstanding_extents = 0; ei->reserved_extents = 0; ei->runtime_flags = 0; ei->force_compress = BTRFS_COMPRESS_NONE; ei->delayed_node = NULL; ei->i_otime.tv_sec = 0; ei->i_otime.tv_nsec = 0; inode = &ei->vfs_inode; extent_map_tree_init(&ei->extent_tree); extent_io_tree_init(&ei->io_tree, &inode->i_data); extent_io_tree_init(&ei->io_failure_tree, &inode->i_data); ei->io_tree.track_uptodate = 1; ei->io_failure_tree.track_uptodate = 1; atomic_set(&ei->sync_writers, 0); mutex_init(&ei->log_mutex); mutex_init(&ei->delalloc_mutex); btrfs_ordered_inode_tree_init(&ei->ordered_tree); INIT_LIST_HEAD(&ei->delalloc_inodes); RB_CLEAR_NODE(&ei->rb_node); return inode; } #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS void btrfs_test_destroy_inode(struct inode *inode) { btrfs_drop_extent_cache(inode, 0, (u64)-1, 0); kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode)); } #endif static void btrfs_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode)); } void btrfs_destroy_inode(struct inode *inode) { struct btrfs_ordered_extent *ordered; struct btrfs_root *root = BTRFS_I(inode)->root; WARN_ON(!hlist_empty(&inode->i_dentry)); WARN_ON(inode->i_data.nrpages); WARN_ON(BTRFS_I(inode)->outstanding_extents); WARN_ON(BTRFS_I(inode)->reserved_extents); WARN_ON(BTRFS_I(inode)->delalloc_bytes); WARN_ON(BTRFS_I(inode)->csum_bytes); WARN_ON(BTRFS_I(inode)->defrag_bytes); /* * This can happen where we create an inode, but somebody else also * created the same inode and we need to destroy the one we already * created. */ if (!root) goto free; if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { btrfs_info(root->fs_info, "inode %llu still on the orphan list", btrfs_ino(inode)); atomic_dec(&root->orphan_inodes); } while (1) { ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1); if (!ordered) break; else { btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup", ordered->file_offset, ordered->len); btrfs_remove_ordered_extent(inode, ordered); btrfs_put_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); } } inode_tree_del(inode); btrfs_drop_extent_cache(inode, 0, (u64)-1, 0); free: call_rcu(&inode->i_rcu, btrfs_i_callback); } int btrfs_drop_inode(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; if (root == NULL) return 1; /* the snap/subvol tree is on deleting */ if (btrfs_root_refs(&root->root_item) == 0) return 1; else return generic_drop_inode(inode); } static void init_once(void *foo) { struct btrfs_inode *ei = (struct btrfs_inode *) foo; inode_init_once(&ei->vfs_inode); } void btrfs_destroy_cachep(void) { /* * Make sure all delayed rcu free inodes are flushed before we * destroy cache. */ rcu_barrier(); if (btrfs_inode_cachep) kmem_cache_destroy(btrfs_inode_cachep); if (btrfs_trans_handle_cachep) kmem_cache_destroy(btrfs_trans_handle_cachep); if (btrfs_transaction_cachep) kmem_cache_destroy(btrfs_transaction_cachep); if (btrfs_path_cachep) kmem_cache_destroy(btrfs_path_cachep); if (btrfs_free_space_cachep) kmem_cache_destroy(btrfs_free_space_cachep); if (btrfs_delalloc_work_cachep) kmem_cache_destroy(btrfs_delalloc_work_cachep); } int btrfs_init_cachep(void) { btrfs_inode_cachep = kmem_cache_create("btrfs_inode", sizeof(struct btrfs_inode), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once); if (!btrfs_inode_cachep) goto fail; btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle", sizeof(struct btrfs_trans_handle), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_trans_handle_cachep) goto fail; btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction", sizeof(struct btrfs_transaction), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_transaction_cachep) goto fail; btrfs_path_cachep = kmem_cache_create("btrfs_path", sizeof(struct btrfs_path), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_path_cachep) goto fail; btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space", sizeof(struct btrfs_free_space), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_free_space_cachep) goto fail; btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work", sizeof(struct btrfs_delalloc_work), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_delalloc_work_cachep) goto fail; return 0; fail: btrfs_destroy_cachep(); return -ENOMEM; } static int btrfs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { u64 delalloc_bytes; struct inode *inode = d_inode(dentry); u32 blocksize = inode->i_sb->s_blocksize; generic_fillattr(inode, stat); stat->dev = BTRFS_I(inode)->root->anon_dev; stat->blksize = PAGE_CACHE_SIZE; spin_lock(&BTRFS_I(inode)->lock); delalloc_bytes = BTRFS_I(inode)->delalloc_bytes; spin_unlock(&BTRFS_I(inode)->lock); stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) + ALIGN(delalloc_bytes, blocksize)) >> 9; return 0; } static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(old_dir)->root; struct btrfs_root *dest = BTRFS_I(new_dir)->root; struct inode *new_inode = d_inode(new_dentry); struct inode *old_inode = d_inode(old_dentry); struct timespec ctime = CURRENT_TIME; u64 index = 0; u64 root_objectid; int ret; u64 old_ino = btrfs_ino(old_inode); if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return -EPERM; /* we only allow rename subvolume link between subvolumes */ if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) return -EXDEV; if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID || (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID)) return -ENOTEMPTY; if (S_ISDIR(old_inode->i_mode) && new_inode && new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; /* check for collisions, even if the name isn't there */ ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, new_dentry->d_name.name, new_dentry->d_name.len); if (ret) { if (ret == -EEXIST) { /* we shouldn't get * eexist without a new_inode */ if (WARN_ON(!new_inode)) { return ret; } } else { /* maybe -EOVERFLOW */ return ret; } } ret = 0; /* * we're using rename to replace one file with another. Start IO on it * now so we don't add too much work to the end of the transaction */ if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size) filemap_flush(old_inode->i_mapping); /* close the racy window with snapshot create/destroy ioctl */ if (old_ino == BTRFS_FIRST_FREE_OBJECTID) down_read(&root->fs_info->subvol_sem); /* * We want to reserve the absolute worst case amount of items. So if * both inodes are subvols and we need to unlink them then that would * require 4 item modifications, but if they are both normal inodes it * would require 5 item modifications, so we'll assume their normal * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items * should cover the worst case number of items we'll modify. */ trans = btrfs_start_transaction(root, 11); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_notrans; } if (dest != root) btrfs_record_root_in_trans(trans, dest); ret = btrfs_set_inode_index(new_dir, &index); if (ret) goto out_fail; BTRFS_I(old_inode)->dir_index = 0ULL; if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { /* force full log commit if subvolume involved. */ btrfs_set_log_full_commit(root->fs_info, trans); } else { ret = btrfs_insert_inode_ref(trans, dest, new_dentry->d_name.name, new_dentry->d_name.len, old_ino, btrfs_ino(new_dir), index); if (ret) goto out_fail; /* * this is an ugly little race, but the rename is required * to make sure that if we crash, the inode is either at the * old name or the new one. pinning the log transaction lets * us make sure we don't allow a log commit to come in after * we unlink the name but before we add the new name back in. */ btrfs_pin_log_trans(root); } inode_inc_iversion(old_dir); inode_inc_iversion(new_dir); inode_inc_iversion(old_inode); old_dir->i_ctime = old_dir->i_mtime = ctime; new_dir->i_ctime = new_dir->i_mtime = ctime; old_inode->i_ctime = ctime; if (old_dentry->d_parent != new_dentry->d_parent) btrfs_record_unlink_dir(trans, old_dir, old_inode, 1); if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { root_objectid = BTRFS_I(old_inode)->root->root_key.objectid; ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid, old_dentry->d_name.name, old_dentry->d_name.len); } else { ret = __btrfs_unlink_inode(trans, root, old_dir, d_inode(old_dentry), old_dentry->d_name.name, old_dentry->d_name.len); if (!ret) ret = btrfs_update_inode(trans, root, old_inode); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (new_inode) { inode_inc_iversion(new_inode); new_inode->i_ctime = CURRENT_TIME; if (unlikely(btrfs_ino(new_inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { root_objectid = BTRFS_I(new_inode)->location.objectid; ret = btrfs_unlink_subvol(trans, dest, new_dir, root_objectid, new_dentry->d_name.name, new_dentry->d_name.len); BUG_ON(new_inode->i_nlink == 0); } else { ret = btrfs_unlink_inode(trans, dest, new_dir, d_inode(new_dentry), new_dentry->d_name.name, new_dentry->d_name.len); } if (!ret && new_inode->i_nlink == 0) ret = btrfs_orphan_add(trans, d_inode(new_dentry)); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } } ret = btrfs_add_link(trans, new_dir, old_inode, new_dentry->d_name.name, new_dentry->d_name.len, 0, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (old_inode->i_nlink == 1) BTRFS_I(old_inode)->dir_index = index; if (old_ino != BTRFS_FIRST_FREE_OBJECTID) { struct dentry *parent = new_dentry->d_parent; btrfs_log_new_name(trans, old_inode, old_dir, parent); btrfs_end_log_trans(root); } out_fail: btrfs_end_transaction(trans, root); out_notrans: if (old_ino == BTRFS_FIRST_FREE_OBJECTID) up_read(&root->fs_info->subvol_sem); return ret; } static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags) { if (flags & ~RENAME_NOREPLACE) return -EINVAL; return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry); } static void btrfs_run_delalloc_work(struct btrfs_work *work) { struct btrfs_delalloc_work *delalloc_work; struct inode *inode; delalloc_work = container_of(work, struct btrfs_delalloc_work, work); inode = delalloc_work->inode; if (delalloc_work->wait) { btrfs_wait_ordered_range(inode, 0, (u64)-1); } else { filemap_flush(inode->i_mapping); if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &BTRFS_I(inode)->runtime_flags)) filemap_flush(inode->i_mapping); } if (delalloc_work->delay_iput) btrfs_add_delayed_iput(inode); else iput(inode); complete(&delalloc_work->completion); } struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode, int wait, int delay_iput) { struct btrfs_delalloc_work *work; work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS); if (!work) return NULL; init_completion(&work->completion); INIT_LIST_HEAD(&work->list); work->inode = inode; work->wait = wait; work->delay_iput = delay_iput; WARN_ON_ONCE(!inode); btrfs_init_work(&work->work, btrfs_flush_delalloc_helper, btrfs_run_delalloc_work, NULL, NULL); return work; } void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work) { wait_for_completion(&work->completion); kmem_cache_free(btrfs_delalloc_work_cachep, work); } /* * some fairly slow code that needs optimization. This walks the list * of all the inodes with pending delalloc and forces them to disk. */ static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput, int nr) { struct btrfs_inode *binode; struct inode *inode; struct btrfs_delalloc_work *work, *next; struct list_head works; struct list_head splice; int ret = 0; INIT_LIST_HEAD(&works); INIT_LIST_HEAD(&splice); mutex_lock(&root->delalloc_mutex); spin_lock(&root->delalloc_lock); list_splice_init(&root->delalloc_inodes, &splice); while (!list_empty(&splice)) { binode = list_entry(splice.next, struct btrfs_inode, delalloc_inodes); list_move_tail(&binode->delalloc_inodes, &root->delalloc_inodes); inode = igrab(&binode->vfs_inode); if (!inode) { cond_resched_lock(&root->delalloc_lock); continue; } spin_unlock(&root->delalloc_lock); work = btrfs_alloc_delalloc_work(inode, 0, delay_iput); if (!work) { if (delay_iput) btrfs_add_delayed_iput(inode); else iput(inode); ret = -ENOMEM; goto out; } list_add_tail(&work->list, &works); btrfs_queue_work(root->fs_info->flush_workers, &work->work); ret++; if (nr != -1 && ret >= nr) goto out; cond_resched(); spin_lock(&root->delalloc_lock); } spin_unlock(&root->delalloc_lock); out: list_for_each_entry_safe(work, next, &works, list) { list_del_init(&work->list); btrfs_wait_and_free_delalloc_work(work); } if (!list_empty_careful(&splice)) { spin_lock(&root->delalloc_lock); list_splice_tail(&splice, &root->delalloc_inodes); spin_unlock(&root->delalloc_lock); } mutex_unlock(&root->delalloc_mutex); return ret; } int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput) { int ret; if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) return -EROFS; ret = __start_delalloc_inodes(root, delay_iput, -1); if (ret > 0) ret = 0; /* * the filemap_flush will queue IO into the worker threads, but * we have to make sure the IO is actually started and that * ordered extents get created before we return */ atomic_inc(&root->fs_info->async_submit_draining); while (atomic_read(&root->fs_info->nr_async_submits) || atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->nr_async_submits) == 0 && atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } atomic_dec(&root->fs_info->async_submit_draining); return ret; } int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput, int nr) { struct btrfs_root *root; struct list_head splice; int ret; if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) return -EROFS; INIT_LIST_HEAD(&splice); mutex_lock(&fs_info->delalloc_root_mutex); spin_lock(&fs_info->delalloc_root_lock); list_splice_init(&fs_info->delalloc_roots, &splice); while (!list_empty(&splice) && nr) { root = list_first_entry(&splice, struct btrfs_root, delalloc_root); root = btrfs_grab_fs_root(root); BUG_ON(!root); list_move_tail(&root->delalloc_root, &fs_info->delalloc_roots); spin_unlock(&fs_info->delalloc_root_lock); ret = __start_delalloc_inodes(root, delay_iput, nr); btrfs_put_fs_root(root); if (ret < 0) goto out; if (nr != -1) { nr -= ret; WARN_ON(nr < 0); } spin_lock(&fs_info->delalloc_root_lock); } spin_unlock(&fs_info->delalloc_root_lock); ret = 0; atomic_inc(&fs_info->async_submit_draining); while (atomic_read(&fs_info->nr_async_submits) || atomic_read(&fs_info->async_delalloc_pages)) { wait_event(fs_info->async_submit_wait, (atomic_read(&fs_info->nr_async_submits) == 0 && atomic_read(&fs_info->async_delalloc_pages) == 0)); } atomic_dec(&fs_info->async_submit_draining); out: if (!list_empty_careful(&splice)) { spin_lock(&fs_info->delalloc_root_lock); list_splice_tail(&splice, &fs_info->delalloc_roots); spin_unlock(&fs_info->delalloc_root_lock); } mutex_unlock(&fs_info->delalloc_root_mutex); return ret; } static int btrfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_path *path; struct btrfs_key key; struct inode *inode = NULL; int err; int drop_inode = 0; u64 objectid; u64 index = 0; int name_len; int datasize; unsigned long ptr; struct btrfs_file_extent_item *ei; struct extent_buffer *leaf; name_len = strlen(symname); if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root)) return -ENAMETOOLONG; /* * 2 items for inode item and ref * 2 items for dir items * 1 item for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, S_IFLNK|S_IRWXUGO, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; inode->i_mapping->a_ops = &btrfs_aops; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_unlock_inode; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) goto out_unlock_inode; path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out_unlock_inode; } key.objectid = btrfs_ino(inode); key.offset = 0; key.type = BTRFS_EXTENT_DATA_KEY; datasize = btrfs_file_extent_calc_inline_size(name_len); err = btrfs_insert_empty_item(trans, root, path, &key, datasize); if (err) { btrfs_free_path(path); goto out_unlock_inode; } leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, ei, trans->transid); btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); btrfs_set_file_extent_encryption(leaf, ei, 0); btrfs_set_file_extent_compression(leaf, ei, 0); btrfs_set_file_extent_other_encoding(leaf, ei, 0); btrfs_set_file_extent_ram_bytes(leaf, ei, name_len); ptr = btrfs_file_extent_inline_start(ei); write_extent_buffer(leaf, symname, ptr, name_len); btrfs_mark_buffer_dirty(leaf); btrfs_free_path(path); inode->i_op = &btrfs_symlink_inode_operations; inode->i_mapping->a_ops = &btrfs_symlink_aops; inode_set_bytes(inode, name_len); btrfs_i_size_write(inode, name_len); err = btrfs_update_inode(trans, root, inode); if (err) { drop_inode = 1; goto out_unlock_inode; } unlock_new_inode(inode); d_instantiate(dentry, inode); out_unlock: btrfs_end_transaction(trans, root); if (drop_inode) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; out_unlock_inode: drop_inode = 1; unlock_new_inode(inode); goto out_unlock; } static int __btrfs_prealloc_file_range(struct inode *inode, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint, struct btrfs_trans_handle *trans) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key ins; u64 cur_offset = start; u64 i_size; u64 cur_bytes; int ret = 0; bool own_trans = true; if (trans) own_trans = false; while (num_bytes > 0) { if (own_trans) { trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); break; } } cur_bytes = min(num_bytes, 256ULL * 1024 * 1024); cur_bytes = max(cur_bytes, min_size); ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0, *alloc_hint, &ins, 1, 0); if (ret) { if (own_trans) btrfs_end_transaction(trans, root); break; } ret = insert_reserved_file_extent(trans, inode, cur_offset, ins.objectid, ins.offset, ins.offset, ins.offset, 0, 0, 0, BTRFS_FILE_EXTENT_PREALLOC); if (ret) { btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 0); btrfs_abort_transaction(trans, root, ret); if (own_trans) btrfs_end_transaction(trans, root); break; } btrfs_drop_extent_cache(inode, cur_offset, cur_offset + ins.offset -1, 0); em = alloc_extent_map(); if (!em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); goto next; } em->start = cur_offset; em->orig_start = cur_offset; em->len = ins.offset; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->ram_bytes = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PREALLOC, &em->flags); em->generation = trans->transid; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 1); write_unlock(&em_tree->lock); if (ret != -EEXIST) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + ins.offset - 1, 0); } free_extent_map(em); next: num_bytes -= ins.offset; cur_offset += ins.offset; *alloc_hint = ins.objectid + ins.offset; inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC; if (!(mode & FALLOC_FL_KEEP_SIZE) && (actual_len > inode->i_size) && (cur_offset > inode->i_size)) { if (cur_offset > actual_len) i_size = actual_len; else i_size = cur_offset; i_size_write(inode, i_size); btrfs_ordered_update_i_size(inode, i_size, NULL); } ret = btrfs_update_inode(trans, root, inode); if (ret) { btrfs_abort_transaction(trans, root, ret); if (own_trans) btrfs_end_transaction(trans, root); break; } if (own_trans) btrfs_end_transaction(trans, root); } return ret; } int btrfs_prealloc_file_range(struct inode *inode, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint) { return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, min_size, actual_len, alloc_hint, NULL); } int btrfs_prealloc_file_range_trans(struct inode *inode, struct btrfs_trans_handle *trans, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint) { return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, min_size, actual_len, alloc_hint, trans); } static int btrfs_set_page_dirty(struct page *page) { return __set_page_dirty_nobuffers(page); } static int btrfs_permission(struct inode *inode, int mask) { struct btrfs_root *root = BTRFS_I(inode)->root; umode_t mode = inode->i_mode; if (mask & MAY_WRITE && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) { if (btrfs_root_readonly(root)) return -EROFS; if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) return -EACCES; } return generic_permission(inode, mask); } static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; u64 objectid; u64 index; int ret = 0; /* * 5 units required for adding orphan entry */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_find_free_ino(root, &objectid); if (ret) goto out; inode = btrfs_new_inode(trans, root, dir, NULL, 0, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { ret = PTR_ERR(inode); inode = NULL; goto out; } inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; inode->i_mapping->a_ops = &btrfs_aops; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; ret = btrfs_init_inode_security(trans, inode, dir, NULL); if (ret) goto out_inode; ret = btrfs_update_inode(trans, root, inode); if (ret) goto out_inode; ret = btrfs_orphan_add(trans, inode); if (ret) goto out_inode; /* * We set number of links to 0 in btrfs_new_inode(), and here we set * it to 1 because d_tmpfile() will issue a warning if the count is 0, * through: * * d_tmpfile() -> inode_dec_link_count() -> drop_nlink() */ set_nlink(inode, 1); unlock_new_inode(inode); d_tmpfile(dentry, inode); mark_inode_dirty(inode); out: btrfs_end_transaction(trans, root); if (ret) iput(inode); btrfs_balance_delayed_items(root); btrfs_btree_balance_dirty(root); return ret; out_inode: unlock_new_inode(inode); goto out; } /* Inspired by filemap_check_errors() */ int btrfs_inode_check_errors(struct inode *inode) { int ret = 0; if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) && test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags)) ret = -ENOSPC; if (test_bit(AS_EIO, &inode->i_mapping->flags) && test_and_clear_bit(AS_EIO, &inode->i_mapping->flags)) ret = -EIO; return ret; } static const struct inode_operations btrfs_dir_inode_operations = { .getattr = btrfs_getattr, .lookup = btrfs_lookup, .create = btrfs_create, .unlink = btrfs_unlink, .link = btrfs_link, .mkdir = btrfs_mkdir, .rmdir = btrfs_rmdir, .rename2 = btrfs_rename2, .symlink = btrfs_symlink, .setattr = btrfs_setattr, .mknod = btrfs_mknod, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .permission = btrfs_permission, .get_acl = btrfs_get_acl, .set_acl = btrfs_set_acl, .update_time = btrfs_update_time, .tmpfile = btrfs_tmpfile, }; static const struct inode_operations btrfs_dir_ro_inode_operations = { .lookup = btrfs_lookup, .permission = btrfs_permission, .get_acl = btrfs_get_acl, .set_acl = btrfs_set_acl, .update_time = btrfs_update_time, }; static const struct file_operations btrfs_dir_file_operations = { .llseek = generic_file_llseek, .read = generic_read_dir, .iterate = btrfs_real_readdir, .unlocked_ioctl = btrfs_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = btrfs_ioctl, #endif .release = btrfs_release_file, .fsync = btrfs_sync_file, }; static struct extent_io_ops btrfs_extent_io_ops = { .fill_delalloc = run_delalloc_range, .submit_bio_hook = btrfs_submit_bio_hook, .merge_bio_hook = btrfs_merge_bio_hook, .readpage_end_io_hook = btrfs_readpage_end_io_hook, .writepage_end_io_hook = btrfs_writepage_end_io_hook, .writepage_start_hook = btrfs_writepage_start_hook, .set_bit_hook = btrfs_set_bit_hook, .clear_bit_hook = btrfs_clear_bit_hook, .merge_extent_hook = btrfs_merge_extent_hook, .split_extent_hook = btrfs_split_extent_hook, }; /* * btrfs doesn't support the bmap operation because swapfiles * use bmap to make a mapping of extents in the file. They assume * these extents won't change over the life of the file and they * use the bmap result to do IO directly to the drive. * * the btrfs bmap call would return logical addresses that aren't * suitable for IO and they also will change frequently as COW * operations happen. So, swapfile + btrfs == corruption. * * For now we're avoiding this by dropping bmap. */ static const struct address_space_operations btrfs_aops = { .readpage = btrfs_readpage, .writepage = btrfs_writepage, .writepages = btrfs_writepages, .readpages = btrfs_readpages, .direct_IO = btrfs_direct_IO, .invalidatepage = btrfs_invalidatepage, .releasepage = btrfs_releasepage, .set_page_dirty = btrfs_set_page_dirty, .error_remove_page = generic_error_remove_page, }; static const struct address_space_operations btrfs_symlink_aops = { .readpage = btrfs_readpage, .writepage = btrfs_writepage, .invalidatepage = btrfs_invalidatepage, .releasepage = btrfs_releasepage, }; static const struct inode_operations btrfs_file_inode_operations = { .getattr = btrfs_getattr, .setattr = btrfs_setattr, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .permission = btrfs_permission, .fiemap = btrfs_fiemap, .get_acl = btrfs_get_acl, .set_acl = btrfs_set_acl, .update_time = btrfs_update_time, }; static const struct inode_operations btrfs_special_inode_operations = { .getattr = btrfs_getattr, .setattr = btrfs_setattr, .permission = btrfs_permission, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .get_acl = btrfs_get_acl, .set_acl = btrfs_set_acl, .update_time = btrfs_update_time, }; static const struct inode_operations btrfs_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, .getattr = btrfs_getattr, .setattr = btrfs_setattr, .permission = btrfs_permission, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .update_time = btrfs_update_time, }; const struct dentry_operations btrfs_dentry_operations = { .d_delete = btrfs_dentry_delete, .d_release = btrfs_dentry_release, };
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1781_0
crossvul-cpp_data_bad_2737_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick 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 ImageMagick. % % % % 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 % % ImageMagick Studio 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 ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* 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-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/distort.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/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/resource_.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned long ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #if defined(MAGICKCORE_WINDOWS_SUPPORT) "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal, double MaxVal,ExceptionInfo *exception) { double f; int x; register Quantum *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q)); if (f + GetPixelRed(image,q) > QuantumRange) SetPixelRed(image,QuantumRange,q); else SetPixelRed(image,GetPixelRed(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); } else { SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelBlue(image,q),q); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q)); if (f+GetPixelBlue(image,q) > QuantumRange) SetPixelBlue(image,QuantumRange,q); else SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelRed(image,0,q); SetPixelGreen(image,0,q); } else { SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelRed(image,q),q); } } p++; q+=GetPixelChannels(image); } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal, double MaxVal,ExceptionInfo *exception) { double f; int x; register Quantum *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (Quantum *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q)); if (f+GetPixelRed(image,q) > QuantumRange) SetPixelRed(image,QuantumRange,q); else SetPixelRed(image,GetPixelRed(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); } else { SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelBlue(image,q),q); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q)); if (f + GetPixelBlue(image,q) > QuantumRange) SetPixelBlue(image,QuantumRange,q); else SetPixelBlue(image,GetPixelBlue(image,q)+ (int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelRed(image,0,q); } else { SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelRed(image,q),q); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(const Image *image,Quantum *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q); SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q); SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *CacheBlock, *DecompressBlock; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; int zip_status; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *)); if(CacheBlock==NULL) return NULL; DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(DecompressBlock==NULL) { RelinquishMagickMemory(CacheBlock); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; zip_status = inflateInit(&zip_info); if (zip_status != Z_OK) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "UnableToUncompressImage","`%s'",clone_info->filename); (void) fclose(mat_file); RelinquishUniqueFileResource(clone_info->filename); return NULL; } /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock); zip_info.next_in = (Bytef *) CacheBlock; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) DecompressBlock; zip_status = inflate(&zip_info,Z_NO_FLUSH); if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file); (void) extent; if(zip_status == Z_STREAM_END) goto DblBreak; } if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: RelinquishUniqueFileResource(clone_info->filename); return NULL; } return image2; } #endif static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotate_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; (void) SeekBlob(image,0,SEEK_SET); while (EOFBlob(image) != MagickFalse) { /* Object parser loop. */ ldblk=ReadBlobLSBLong(image); if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf != 0) && (HDR.imagf != 1)) break; if (HDR.nameLen > 0xFFFF) return((Image *) NULL); for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; SetImageColorspace(image,GRAYColorspace,exception); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); return(image); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return((Image *) NULL); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return((Image *) NULL); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(image,q,(int) image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception); else InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception); } quantum_info=DestroyQuantumInfo(quantum_info); rotate_image=RotateImage(image,90.0,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X 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 ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); quantum_info=DestroyQuantumInfo(quantum_info); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); END_OF_READING: clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT image format to % the list of supported formats. The attributes 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 RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("MAT","MAT","MATLAB level 5 image format"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->flags^=CoderBlobSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % MagickBooleanType WriteMATImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { ssize_t y; unsigned z; register const Quantum *p; unsigned int status; int logging; size_t DataSize; char padding; char MATLAB_HDR[0x80]; time_t current_time; struct tm local_time; unsigned char *pixels; int is_gray; MagickOffsetType scene; QuantumInfo *quantum_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); (void) logging; assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace,exception); is_gray = SetImageGray(image,exception); z = is_gray ? 0 : 3; /* Store MAT header. */ DataSize = image->rows /*Y*/ * image->columns /*X*/; if(!is_gray) DataSize *= 3 /*Z*/; padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image, miMATRIX); (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56)); (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */ (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */ (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */ (void) WriteBlobLSBLong(image, 0); (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */ (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */ if(!is_gray) { (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image, 0); } (void) WriteBlobLSBShort(image, 1); /* 0xB0 */ (void) WriteBlobLSBShort(image, 1); /* 0xB2 */ (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */ /* Store image data. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetQuantumPixels(quantum_info); do { for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } while(z-- >= 2); while(padding-->0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2737_0
crossvul-cpp_data_bad_1765_0
/* * vivid-osd.c - osd support for testing overlays. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. * * This program is free software; you may redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * 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/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/font.h> #include <linux/mutex.h> #include <linux/videodev2.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/fb.h> #include <media/videobuf2-vmalloc.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-fh.h> #include <media/v4l2-event.h> #include <media/v4l2-common.h> #include "vivid-core.h" #include "vivid-osd.h" #define MAX_OSD_WIDTH 720 #define MAX_OSD_HEIGHT 576 /* * Order: white, yellow, cyan, green, magenta, red, blue, black, * and same again with the alpha bit set (if any) */ static const u16 rgb555[16] = { 0x7fff, 0x7fe0, 0x03ff, 0x03e0, 0x7c1f, 0x7c00, 0x001f, 0x0000, 0xffff, 0xffe0, 0x83ff, 0x83e0, 0xfc1f, 0xfc00, 0x801f, 0x8000 }; static const u16 rgb565[16] = { 0xffff, 0xffe0, 0x07ff, 0x07e0, 0xf81f, 0xf800, 0x001f, 0x0000, 0xffff, 0xffe0, 0x07ff, 0x07e0, 0xf81f, 0xf800, 0x001f, 0x0000 }; void vivid_clear_fb(struct vivid_dev *dev) { void *p = dev->video_vbase; const u16 *rgb = rgb555; unsigned x, y; if (dev->fb_defined.green.length == 6) rgb = rgb565; for (y = 0; y < dev->display_height; y++) { u16 *d = p; for (x = 0; x < dev->display_width; x++) d[x] = rgb[(y / 16 + x / 16) % 16]; p += dev->display_byte_stride; } } /* --------------------------------------------------------------------- */ static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg) { struct vivid_dev *dev = (struct vivid_dev *)info->par; switch (cmd) { case FBIOGET_VBLANK: { struct fb_vblank vblank; vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT | FB_VBLANK_HAVE_VSYNC; vblank.count = 0; vblank.vcount = 0; vblank.hcount = 0; if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank))) return -EFAULT; return 0; } default: dprintk(dev, 1, "Unknown ioctl %08x\n", cmd); return -EINVAL; } return 0; } /* Framebuffer device handling */ static int vivid_fb_set_var(struct vivid_dev *dev, struct fb_var_screeninfo *var) { dprintk(dev, 1, "vivid_fb_set_var\n"); if (var->bits_per_pixel != 16) { dprintk(dev, 1, "vivid_fb_set_var - Invalid bpp\n"); return -EINVAL; } dev->display_byte_stride = var->xres * dev->bytes_per_pixel; return 0; } static int vivid_fb_get_fix(struct vivid_dev *dev, struct fb_fix_screeninfo *fix) { dprintk(dev, 1, "vivid_fb_get_fix\n"); memset(fix, 0, sizeof(struct fb_fix_screeninfo)); strlcpy(fix->id, "vioverlay fb", sizeof(fix->id)); fix->smem_start = dev->video_pbase; fix->smem_len = dev->video_buffer_size; fix->type = FB_TYPE_PACKED_PIXELS; fix->visual = FB_VISUAL_TRUECOLOR; fix->xpanstep = 1; fix->ypanstep = 1; fix->ywrapstep = 0; fix->line_length = dev->display_byte_stride; fix->accel = FB_ACCEL_NONE; return 0; } /* Check the requested display mode, returning -EINVAL if we can't handle it. */ static int _vivid_fb_check_var(struct fb_var_screeninfo *var, struct vivid_dev *dev) { dprintk(dev, 1, "vivid_fb_check_var\n"); var->bits_per_pixel = 16; if (var->green.length == 5) { var->red.offset = 10; var->red.length = 5; var->green.offset = 5; var->green.length = 5; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 15; var->transp.length = 1; } else { var->red.offset = 11; var->red.length = 5; var->green.offset = 5; var->green.length = 6; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; } var->xoffset = var->yoffset = 0; var->left_margin = var->upper_margin = 0; var->nonstd = 0; var->vmode &= ~FB_VMODE_MASK; var->vmode = FB_VMODE_NONINTERLACED; /* Dummy values */ var->hsync_len = 24; var->vsync_len = 2; var->pixclock = 84316; var->right_margin = 776; var->lower_margin = 591; return 0; } static int vivid_fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { struct vivid_dev *dev = (struct vivid_dev *) info->par; dprintk(dev, 1, "vivid_fb_check_var\n"); return _vivid_fb_check_var(var, dev); } static int vivid_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { return 0; } static int vivid_fb_set_par(struct fb_info *info) { int rc = 0; struct vivid_dev *dev = (struct vivid_dev *) info->par; dprintk(dev, 1, "vivid_fb_set_par\n"); rc = vivid_fb_set_var(dev, &info->var); vivid_fb_get_fix(dev, &info->fix); return rc; } static int vivid_fb_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, struct fb_info *info) { u32 color, *palette; if (regno >= info->cmap.len) return -EINVAL; color = ((transp & 0xFF00) << 16) | ((red & 0xFF00) << 8) | (green & 0xFF00) | ((blue & 0xFF00) >> 8); if (regno >= 16) return -EINVAL; palette = info->pseudo_palette; if (info->var.bits_per_pixel == 16) { switch (info->var.green.length) { case 6: color = (red & 0xf800) | ((green & 0xfc00) >> 5) | ((blue & 0xf800) >> 11); break; case 5: color = ((red & 0xf800) >> 1) | ((green & 0xf800) >> 6) | ((blue & 0xf800) >> 11) | (transp ? 0x8000 : 0); break; } } palette[regno] = color; return 0; } /* We don't really support blanking. All this does is enable or disable the OSD. */ static int vivid_fb_blank(int blank_mode, struct fb_info *info) { struct vivid_dev *dev = (struct vivid_dev *)info->par; dprintk(dev, 1, "Set blanking mode : %d\n", blank_mode); switch (blank_mode) { case FB_BLANK_UNBLANK: break; case FB_BLANK_NORMAL: case FB_BLANK_HSYNC_SUSPEND: case FB_BLANK_VSYNC_SUSPEND: case FB_BLANK_POWERDOWN: break; } return 0; } static struct fb_ops vivid_fb_ops = { .owner = THIS_MODULE, .fb_check_var = vivid_fb_check_var, .fb_set_par = vivid_fb_set_par, .fb_setcolreg = vivid_fb_setcolreg, .fb_fillrect = cfb_fillrect, .fb_copyarea = cfb_copyarea, .fb_imageblit = cfb_imageblit, .fb_cursor = NULL, .fb_ioctl = vivid_fb_ioctl, .fb_pan_display = vivid_fb_pan_display, .fb_blank = vivid_fb_blank, }; /* Initialization */ /* Setup our initial video mode */ static int vivid_fb_init_vidmode(struct vivid_dev *dev) { struct v4l2_rect start_window; /* Color mode */ dev->bits_per_pixel = 16; dev->bytes_per_pixel = dev->bits_per_pixel / 8; start_window.width = MAX_OSD_WIDTH; start_window.left = 0; dev->display_byte_stride = start_window.width * dev->bytes_per_pixel; /* Vertical size & position */ start_window.height = MAX_OSD_HEIGHT; start_window.top = 0; dev->display_width = start_window.width; dev->display_height = start_window.height; /* Generate a valid fb_var_screeninfo */ dev->fb_defined.xres = dev->display_width; dev->fb_defined.yres = dev->display_height; dev->fb_defined.xres_virtual = dev->display_width; dev->fb_defined.yres_virtual = dev->display_height; dev->fb_defined.bits_per_pixel = dev->bits_per_pixel; dev->fb_defined.vmode = FB_VMODE_NONINTERLACED; dev->fb_defined.left_margin = start_window.left + 1; dev->fb_defined.upper_margin = start_window.top + 1; dev->fb_defined.accel_flags = FB_ACCEL_NONE; dev->fb_defined.nonstd = 0; /* set default to 1:5:5:5 */ dev->fb_defined.green.length = 5; /* We've filled in the most data, let the usual mode check routine fill in the rest. */ _vivid_fb_check_var(&dev->fb_defined, dev); /* Generate valid fb_fix_screeninfo */ vivid_fb_get_fix(dev, &dev->fb_fix); /* Generate valid fb_info */ dev->fb_info.node = -1; dev->fb_info.flags = FBINFO_FLAG_DEFAULT; dev->fb_info.fbops = &vivid_fb_ops; dev->fb_info.par = dev; dev->fb_info.var = dev->fb_defined; dev->fb_info.fix = dev->fb_fix; dev->fb_info.screen_base = (u8 __iomem *)dev->video_vbase; dev->fb_info.fbops = &vivid_fb_ops; /* Supply some monitor specs. Bogus values will do for now */ dev->fb_info.monspecs.hfmin = 8000; dev->fb_info.monspecs.hfmax = 70000; dev->fb_info.monspecs.vfmin = 10; dev->fb_info.monspecs.vfmax = 100; /* Allocate color map */ if (fb_alloc_cmap(&dev->fb_info.cmap, 256, 1)) { pr_err("abort, unable to alloc cmap\n"); return -ENOMEM; } /* Allocate the pseudo palette */ dev->fb_info.pseudo_palette = kmalloc_array(16, sizeof(u32), GFP_KERNEL); return dev->fb_info.pseudo_palette ? 0 : -ENOMEM; } /* Release any memory we've grabbed */ void vivid_fb_release_buffers(struct vivid_dev *dev) { if (dev->video_vbase == NULL) return; /* Release cmap */ if (dev->fb_info.cmap.len) fb_dealloc_cmap(&dev->fb_info.cmap); /* Release pseudo palette */ kfree(dev->fb_info.pseudo_palette); kfree((void *)dev->video_vbase); } /* Initialize the specified card */ int vivid_fb_init(struct vivid_dev *dev) { int ret; dev->video_buffer_size = MAX_OSD_HEIGHT * MAX_OSD_WIDTH * 2; dev->video_vbase = kzalloc(dev->video_buffer_size, GFP_KERNEL | GFP_DMA32); if (dev->video_vbase == NULL) return -ENOMEM; dev->video_pbase = virt_to_phys(dev->video_vbase); pr_info("Framebuffer at 0x%lx, mapped to 0x%p, size %dk\n", dev->video_pbase, dev->video_vbase, dev->video_buffer_size / 1024); /* Set the startup video mode information */ ret = vivid_fb_init_vidmode(dev); if (ret) { vivid_fb_release_buffers(dev); return ret; } vivid_clear_fb(dev); /* Register the framebuffer */ if (register_framebuffer(&dev->fb_info) < 0) { vivid_fb_release_buffers(dev); return -EINVAL; } /* Set the card to the requested mode */ vivid_fb_set_par(&dev->fb_info); return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1765_0
crossvul-cpp_data_bad_866_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-200/c/bad_866_3
crossvul-cpp_data_bad_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; } rds_info_copy(iter, &minfo, sizeof(minfo)); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5099_0
crossvul-cpp_data_bad_3832_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; memset(&uf, 0, sizeof(uf)); 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_3832_0
crossvul-cpp_data_bad_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 Status2; 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 (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) { Status = AE_OK; /* Clean up */ 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); return_ACPI_STATUS (Status); } else if (ACPI_FAILURE (Status)) { /* First error is most important */ (void) AcpiPsCompleteThisOp (WalkState, Op); return_ACPI_STATUS (Status); } } Status2 = AcpiPsCompleteThisOp (WalkState, Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } AcpiPsPopScope (&(WalkState->ParserState), &Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (Op); return_ACPI_STATUS (Status); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2751_0
crossvul-cpp_data_bad_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" } }; 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/bad_3568_7
crossvul-cpp_data_bad_2750_0
/******************************************************************************* * * Module Name: dsutils - Dispatcher utilities * ******************************************************************************/ /****************************************************************************** * * 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 "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acdebug.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsutils") /******************************************************************************* * * FUNCTION: AcpiDsClearImplicitReturn * * PARAMETERS: WalkState - Current State * * RETURN: None. * * DESCRIPTION: Clear and remove a reference on an implicit return value. Used * to delete "stale" return values (if enabled, the return value * from every operator is saved at least momentarily, in case the * parent method exits.) * ******************************************************************************/ void AcpiDsClearImplicitReturn ( ACPI_WALK_STATE *WalkState) { ACPI_FUNCTION_NAME (DsClearImplicitReturn); /* * Slack must be enabled for this feature */ if (!AcpiGbl_EnableInterpreterSlack) { return; } if (WalkState->ImplicitReturnObj) { /* * Delete any "stale" implicit return. However, in * complex statements, the implicit return value can be * bubbled up several levels. */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Removing reference on stale implicit return obj %p\n", WalkState->ImplicitReturnObj)); AcpiUtRemoveReference (WalkState->ImplicitReturnObj); WalkState->ImplicitReturnObj = NULL; } } #ifndef ACPI_NO_METHOD_EXECUTION /******************************************************************************* * * FUNCTION: AcpiDsDoImplicitReturn * * PARAMETERS: ReturnDesc - The return value * WalkState - Current State * AddReference - True if a reference should be added to the * return object * * RETURN: TRUE if implicit return enabled, FALSE otherwise * * DESCRIPTION: Implements the optional "implicit return". We save the result * of every ASL operator and control method invocation in case the * parent method exit. Before storing a new return value, we * delete the previous return value. * ******************************************************************************/ BOOLEAN AcpiDsDoImplicitReturn ( ACPI_OPERAND_OBJECT *ReturnDesc, ACPI_WALK_STATE *WalkState, BOOLEAN AddReference) { ACPI_FUNCTION_NAME (DsDoImplicitReturn); /* * Slack must be enabled for this feature, and we must * have a valid return object */ if ((!AcpiGbl_EnableInterpreterSlack) || (!ReturnDesc)) { return (FALSE); } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result %p will be implicitly returned; Prev=%p\n", ReturnDesc, WalkState->ImplicitReturnObj)); /* * Delete any "stale" implicit return value first. However, in * complex statements, the implicit return value can be * bubbled up several levels, so we don't clear the value if it * is the same as the ReturnDesc. */ if (WalkState->ImplicitReturnObj) { if (WalkState->ImplicitReturnObj == ReturnDesc) { return (TRUE); } AcpiDsClearImplicitReturn (WalkState); } /* Save the implicit return value, add a reference if requested */ WalkState->ImplicitReturnObj = ReturnDesc; if (AddReference) { AcpiUtAddReference (ReturnDesc); } return (TRUE); } /******************************************************************************* * * FUNCTION: AcpiDsIsResultUsed * * PARAMETERS: Op - Current Op * WalkState - Current State * * RETURN: TRUE if result is used, FALSE otherwise * * DESCRIPTION: Check if a result object will be used by the parent * ******************************************************************************/ BOOLEAN AcpiDsIsResultUsed ( ACPI_PARSE_OBJECT *Op, ACPI_WALK_STATE *WalkState) { const ACPI_OPCODE_INFO *ParentInfo; ACPI_FUNCTION_TRACE_PTR (DsIsResultUsed, Op); /* Must have both an Op and a Result Object */ if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_UINT8 (TRUE); } /* * We know that this operator is not a * Return() operator (would not come here.) The following code is the * optional support for a so-called "implicit return". Some AML code * assumes that the last value of the method is "implicitly" returned * to the caller. Just save the last result as the return value. * NOTE: this is optional because the ASL language does not actually * support this behavior. */ (void) AcpiDsDoImplicitReturn (WalkState->ResultObj, WalkState, TRUE); /* * Now determine if the parent will use the result * * If there is no parent, or the parent is a ScopeOp, we are executing * at the method level. An executing method typically has no parent, * since each method is parsed separately. A method invoked externally * via ExecuteControlMethod has a ScopeOp as the parent. */ if ((!Op->Common.Parent) || (Op->Common.Parent->Common.AmlOpcode == AML_SCOPE_OP)) { /* No parent, the return value cannot possibly be used */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "At Method level, result of [%s] not used\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode))); return_UINT8 (FALSE); } /* Get info on the parent. The RootOp is AML_SCOPE */ ParentInfo = AcpiPsGetOpcodeInfo (Op->Common.Parent->Common.AmlOpcode); if (ParentInfo->Class == AML_CLASS_UNKNOWN) { ACPI_ERROR ((AE_INFO, "Unknown parent opcode Op=%p", Op)); return_UINT8 (FALSE); } /* * Decide what to do with the result based on the parent. If * the parent opcode will not use the result, delete the object. * Otherwise leave it as is, it will be deleted when it is used * as an operand later. */ switch (ParentInfo->Class) { case AML_CLASS_CONTROL: switch (Op->Common.Parent->Common.AmlOpcode) { case AML_RETURN_OP: /* Never delete the return value associated with a return opcode */ goto ResultUsed; case AML_IF_OP: case AML_WHILE_OP: /* * If we are executing the predicate AND this is the predicate op, * we will use the return value */ if ((WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING) && (WalkState->ControlState->Control.PredicateOp == Op)) { goto ResultUsed; } break; default: /* Ignore other control opcodes */ break; } /* The general control opcode returns no result */ goto ResultNotUsed; case AML_CLASS_CREATE: /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; case AML_CLASS_NAMED_OBJECT: if ((Op->Common.Parent->Common.AmlOpcode == AML_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_DATA_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BUFFER_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_INT_EVAL_SUBTREE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BANK_FIELD_OP)) { /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; } goto ResultNotUsed; default: /* * In all other cases. the parent will actually use the return * object, so keep it. */ goto ResultUsed; } ResultUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (TRUE); ResultNotUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] not used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (FALSE); } /******************************************************************************* * * FUNCTION: AcpiDsDeleteResultIfNotUsed * * PARAMETERS: Op - Current parse Op * ResultObj - Result of the operation * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Used after interpretation of an opcode. If there is an internal * result descriptor, check if the parent opcode will actually use * this result. If not, delete the result now so that it will * not become orphaned. * ******************************************************************************/ void AcpiDsDeleteResultIfNotUsed ( ACPI_PARSE_OBJECT *Op, ACPI_OPERAND_OBJECT *ResultObj, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsDeleteResultIfNotUsed, ResultObj); if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_VOID; } if (!ResultObj) { return_VOID; } if (!AcpiDsIsResultUsed (Op, WalkState)) { /* Must pop the result stack (ObjDesc should be equal to ResultObj) */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_SUCCESS (Status)) { AcpiUtRemoveReference (ResultObj); } } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsResolveOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: Status * * DESCRIPTION: Resolve all operands to their values. Used to prepare * arguments to a control method invocation (a call from one * method to another.) * ******************************************************************************/ ACPI_STATUS AcpiDsResolveOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (DsResolveOperands, WalkState); /* * Attempt to resolve each of the valid operands * Method arguments are passed by reference, not by value. This means * that the actual objects are passed, not copies of the objects. */ for (i = 0; i < WalkState->NumOperands; i++) { Status = AcpiExResolveToValue (&WalkState->Operands[i], WalkState); if (ACPI_FAILURE (Status)) { break; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsClearOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: None * * DESCRIPTION: Clear all operands on the current walk state operand stack. * ******************************************************************************/ void AcpiDsClearOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsClearOperands, WalkState); /* Remove a reference on each operand on the stack */ for (i = 0; i < WalkState->NumOperands; i++) { /* * Remove a reference to all operands, including both * "Arguments" and "Targets". */ AcpiUtRemoveReference (WalkState->Operands[i]); WalkState->Operands[i] = NULL; } WalkState->NumOperands = 0; return_VOID; } #endif /******************************************************************************* * * FUNCTION: AcpiDsCreateOperand * * PARAMETERS: WalkState - Current walk state * Arg - Parse object for the argument * ArgIndex - Which argument (zero based) * * RETURN: Status * * DESCRIPTION: Translate a parse tree object that is an argument to an AML * opcode to the equivalent interpreter object. This may include * looking up a name or entering a new name into the internal * namespace. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperand ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Arg, UINT32 ArgIndex) { ACPI_STATUS Status = AE_OK; char *NameString; UINT32 NameLength; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PARSE_OBJECT *ParentOp; UINT16 Opcode; ACPI_INTERPRETER_MODE InterpreterMode; const ACPI_OPCODE_INFO *OpInfo; ACPI_FUNCTION_TRACE_PTR (DsCreateOperand, Arg); /* A valid name must be looked up in the namespace */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && (Arg->Common.Value.String) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Getting a name: Arg=%p\n", Arg)); /* Get the entire name string from the AML stream */ Status = AcpiExGetNameString (ACPI_TYPE_ANY, Arg->Common.Value.Buffer, &NameString, &NameLength); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* All prefixes have been handled, and the name is in NameString */ /* * Special handling for BufferField declarations. This is a deferred * opcode that unfortunately defines the field name as the last * parameter instead of the first. We get here when we are performing * the deferred execution, so the actual name of the field is already * in the namespace. We don't want to attempt to look it up again * because we may be executing in a different scope than where the * actual opcode exists. */ if ((WalkState->DeferredNode) && (WalkState->DeferredNode->Type == ACPI_TYPE_BUFFER_FIELD) && (ArgIndex == (UINT32) ((WalkState->Opcode == AML_CREATE_FIELD_OP) ? 3 : 2))) { ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, WalkState->DeferredNode); Status = AE_OK; } else /* All other opcodes */ { /* * Differentiate between a namespace "create" operation * versus a "lookup" operation (IMODE_LOAD_PASS2 vs. * IMODE_EXECUTE) in order to support the creation of * namespace objects during the execution of control methods. */ ParentOp = Arg->Common.Parent; OpInfo = AcpiPsGetOpcodeInfo (ParentOp->Common.AmlOpcode); if ((OpInfo->Flags & AML_NSNODE) && (ParentOp->Common.AmlOpcode != AML_INT_METHODCALL_OP) && (ParentOp->Common.AmlOpcode != AML_REGION_OP) && (ParentOp->Common.AmlOpcode != AML_INT_NAMEPATH_OP)) { /* Enter name into namespace if not found */ InterpreterMode = ACPI_IMODE_LOAD_PASS2; } else { /* Return a failure if name not found */ InterpreterMode = ACPI_IMODE_EXECUTE; } Status = AcpiNsLookup (WalkState->ScopeInfo, NameString, ACPI_TYPE_ANY, InterpreterMode, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, WalkState, ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, &ObjDesc)); /* * The only case where we pass through (ignore) a NOT_FOUND * error is for the CondRefOf opcode. */ if (Status == AE_NOT_FOUND) { if (ParentOp->Common.AmlOpcode == AML_CONDITIONAL_REF_OF_OP) { /* * For the Conditional Reference op, it's OK if * the name is not found; We just need a way to * indicate this to the interpreter, set the * object to the root */ ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, AcpiGbl_RootNode); Status = AE_OK; } else if (ParentOp->Common.AmlOpcode == AML_EXTERNAL_OP) { /* * This opcode should never appear here. It is used only * by AML disassemblers and is surrounded by an If(0) * by the ASL compiler. * * Therefore, if we see it here, it is a serious error. */ Status = AE_AML_BAD_OPCODE; } else { /* * We just plain didn't find it -- which is a * very serious error at this point */ Status = AE_AML_NAME_NOT_FOUND; } } if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (NameString, Status); } } /* Free the namestring created above */ ACPI_FREE (NameString); /* Check status from the lookup */ if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Put the resulting object onto the current object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } else { /* Check for null name case */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * If the name is null, this means that this is an * optional result parameter that was not specified * in the original ASL. Create a Zero Constant for a * placeholder. (Store to a constant is a Noop.) */ Opcode = AML_ZERO_OP; /* Has no arguments! */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Null namepath: Arg=%p\n", Arg)); } else { Opcode = Arg->Common.AmlOpcode; } /* Get the object type of the argument */ OpInfo = AcpiPsGetOpcodeInfo (Opcode); if (OpInfo->ObjectType == ACPI_TYPE_INVALID) { return_ACPI_STATUS (AE_NOT_IMPLEMENTED); } if ((OpInfo->Flags & AML_HAS_RETVAL) || (Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * Use value that was already previously returned * by the evaluation of this argument */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { /* * Only error is underflow, and this indicates * a missing or null operand! */ ACPI_EXCEPTION ((AE_INFO, Status, "Missing or null operand")); return_ACPI_STATUS (Status); } } else { /* Create an ACPI_INTERNAL_OBJECT for the argument */ ObjDesc = AcpiUtCreateInternalObject (OpInfo->ObjectType); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize the new object */ Status = AcpiDsInitObjectFromOp ( WalkState, Arg, Opcode, &ObjDesc); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (Status); } } /* Put the operand object on the object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsCreateOperands * * PARAMETERS: WalkState - Current state * FirstArg - First argument of a parser argument tree * * RETURN: Status * * DESCRIPTION: Convert an operator's arguments from a parse tree format to * namespace objects and place those argument object on the object * stack in preparation for evaluation by the interpreter. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ AcpiDsObjStackPopAndDelete (ArgCount, WalkState); ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); } /***************************************************************************** * * FUNCTION: AcpiDsEvaluateNamePath * * PARAMETERS: WalkState - Current state of the parse tree walk, * the opcode of current operation should be * AML_INT_NAMEPATH_OP * * RETURN: Status * * DESCRIPTION: Translate the -NamePath- parse tree object to the equivalent * interpreter object, convert it to value, if needed, duplicate * it, if needed, and push it onto the current result stack. * ****************************************************************************/ ACPI_STATUS AcpiDsEvaluateNamePath ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op = WalkState->Op; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_OPERAND_OBJECT *NewObjDesc; UINT8 Type; ACPI_FUNCTION_TRACE_PTR (DsEvaluateNamePath, WalkState); if (!Op->Common.Parent) { /* This happens after certain exception processing */ goto Exit; } if ((Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_REF_OF_OP)) { /* TBD: Should we specify this feature as a bit of OpInfo->Flags of these opcodes? */ goto Exit; } Status = AcpiDsCreateOperand (WalkState, Op, 0); if (ACPI_FAILURE (Status)) { goto Exit; } if (Op->Common.Flags & ACPI_PARSEOP_TARGET) { NewObjDesc = *Operand; goto PushResult; } Type = (*Operand)->Common.Type; Status = AcpiExResolveToValue (Operand, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } if (Type == ACPI_TYPE_INTEGER) { /* It was incremented by AcpiExResolveToValue */ AcpiUtRemoveReference (*Operand); Status = AcpiUtCopyIobjectToIobject ( *Operand, &NewObjDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } } else { /* * The object either was anew created or is * a Namespace node - don't decrement it. */ NewObjDesc = *Operand; } /* Cleanup for name-path operand */ Status = AcpiDsObjStackPop (1, WalkState); if (ACPI_FAILURE (Status)) { WalkState->ResultObj = NewObjDesc; goto Exit; } PushResult: WalkState->ResultObj = NewObjDesc; Status = AcpiDsResultPush (WalkState->ResultObj, WalkState); if (ACPI_SUCCESS (Status)) { /* Force to take it from stack */ Op->Common.Flags |= ACPI_PARSEOP_IN_STACK; } Exit: return_ACPI_STATUS (Status); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2750_0
crossvul-cpp_data_good_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); } } 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); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); } 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); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); 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/good_1674_0
crossvul-cpp_data_good_5694_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 (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) * Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk) * Copyright (C) Terry Dawson VK2KTJ (terry@animats.net) * Copyright (C) Tomi Manninen OH2BNS (oh2bns@sral.fi) */ #include <linux/capability.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.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/spinlock.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/stat.h> #include <net/net_namespace.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/skbuff.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/fcntl.h> #include <linux/termios.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/notifier.h> #include <net/rose.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <net/tcp_states.h> #include <net/ip.h> #include <net/arp.h> static int rose_ndevs = 10; int sysctl_rose_restart_request_timeout = ROSE_DEFAULT_T0; int sysctl_rose_call_request_timeout = ROSE_DEFAULT_T1; int sysctl_rose_reset_request_timeout = ROSE_DEFAULT_T2; int sysctl_rose_clear_request_timeout = ROSE_DEFAULT_T3; int sysctl_rose_no_activity_timeout = ROSE_DEFAULT_IDLE; int sysctl_rose_ack_hold_back_timeout = ROSE_DEFAULT_HB; int sysctl_rose_routing_control = ROSE_DEFAULT_ROUTING; int sysctl_rose_link_fail_timeout = ROSE_DEFAULT_FAIL_TIMEOUT; int sysctl_rose_maximum_vcs = ROSE_DEFAULT_MAXVC; int sysctl_rose_window_size = ROSE_DEFAULT_WINDOW_SIZE; static HLIST_HEAD(rose_list); static DEFINE_SPINLOCK(rose_list_lock); static const struct proto_ops rose_proto_ops; ax25_address rose_callsign; /* * ROSE network devices are virtual network devices encapsulating ROSE * 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 rose_netdev_xmit_lock_key; static struct lock_class_key rose_netdev_addr_lock_key; static void rose_set_lockdep_one(struct net_device *dev, struct netdev_queue *txq, void *_unused) { lockdep_set_class(&txq->_xmit_lock, &rose_netdev_xmit_lock_key); } static void rose_set_lockdep_key(struct net_device *dev) { lockdep_set_class(&dev->addr_list_lock, &rose_netdev_addr_lock_key); netdev_for_each_tx_queue(dev, rose_set_lockdep_one, NULL); } /* * Convert a ROSE address into text. */ char *rose2asc(char *buf, const rose_address *addr) { if (addr->rose_addr[0] == 0x00 && addr->rose_addr[1] == 0x00 && addr->rose_addr[2] == 0x00 && addr->rose_addr[3] == 0x00 && addr->rose_addr[4] == 0x00) { strcpy(buf, "*"); } else { sprintf(buf, "%02X%02X%02X%02X%02X", addr->rose_addr[0] & 0xFF, addr->rose_addr[1] & 0xFF, addr->rose_addr[2] & 0xFF, addr->rose_addr[3] & 0xFF, addr->rose_addr[4] & 0xFF); } return buf; } /* * Compare two ROSE addresses, 0 == equal. */ int rosecmp(rose_address *addr1, rose_address *addr2) { int i; for (i = 0; i < 5; i++) if (addr1->rose_addr[i] != addr2->rose_addr[i]) return 1; return 0; } /* * Compare two ROSE addresses for only mask digits, 0 == equal. */ int rosecmpm(rose_address *addr1, rose_address *addr2, unsigned short mask) { unsigned int i, j; if (mask > 10) return 1; for (i = 0; i < mask; i++) { j = i / 2; if ((i % 2) != 0) { if ((addr1->rose_addr[j] & 0x0F) != (addr2->rose_addr[j] & 0x0F)) return 1; } else { if ((addr1->rose_addr[j] & 0xF0) != (addr2->rose_addr[j] & 0xF0)) return 1; } } return 0; } /* * Socket removal during an interrupt is now safe. */ static void rose_remove_socket(struct sock *sk) { spin_lock_bh(&rose_list_lock); sk_del_node_init(sk); spin_unlock_bh(&rose_list_lock); } /* * Kill all bound sockets on a broken link layer connection to a * particular neighbour. */ void rose_kill_by_neigh(struct rose_neigh *neigh) { struct sock *s; spin_lock_bh(&rose_list_lock); sk_for_each(s, &rose_list) { struct rose_sock *rose = rose_sk(s); if (rose->neighbour == neigh) { rose_disconnect(s, ENETUNREACH, ROSE_OUT_OF_ORDER, 0); rose->neighbour->use--; rose->neighbour = NULL; } } spin_unlock_bh(&rose_list_lock); } /* * Kill all bound sockets on a dropped device. */ static void rose_kill_by_device(struct net_device *dev) { struct sock *s; spin_lock_bh(&rose_list_lock); sk_for_each(s, &rose_list) { struct rose_sock *rose = rose_sk(s); if (rose->device == dev) { rose_disconnect(s, ENETUNREACH, ROSE_OUT_OF_ORDER, 0); rose->neighbour->use--; rose->device = NULL; } } spin_unlock_bh(&rose_list_lock); } /* * Handle device status changes. */ static int rose_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; switch (dev->type) { case ARPHRD_ROSE: rose_kill_by_device(dev); break; case ARPHRD_AX25: rose_link_device_down(dev); rose_rt_device_down(dev); break; } return NOTIFY_DONE; } /* * Add a socket to the bound sockets list. */ static void rose_insert_socket(struct sock *sk) { spin_lock_bh(&rose_list_lock); sk_add_node(sk, &rose_list); spin_unlock_bh(&rose_list_lock); } /* * Find a socket that wants to accept the Call Request we just * received. */ static struct sock *rose_find_listener(rose_address *addr, ax25_address *call) { struct sock *s; spin_lock_bh(&rose_list_lock); sk_for_each(s, &rose_list) { struct rose_sock *rose = rose_sk(s); if (!rosecmp(&rose->source_addr, addr) && !ax25cmp(&rose->source_call, call) && !rose->source_ndigis && s->sk_state == TCP_LISTEN) goto found; } sk_for_each(s, &rose_list) { struct rose_sock *rose = rose_sk(s); if (!rosecmp(&rose->source_addr, addr) && !ax25cmp(&rose->source_call, &null_ax25_address) && s->sk_state == TCP_LISTEN) goto found; } s = NULL; found: spin_unlock_bh(&rose_list_lock); return s; } /* * Find a connected ROSE socket given my LCI and device. */ struct sock *rose_find_socket(unsigned int lci, struct rose_neigh *neigh) { struct sock *s; spin_lock_bh(&rose_list_lock); sk_for_each(s, &rose_list) { struct rose_sock *rose = rose_sk(s); if (rose->lci == lci && rose->neighbour == neigh) goto found; } s = NULL; found: spin_unlock_bh(&rose_list_lock); return s; } /* * Find a unique LCI for a given device. */ unsigned int rose_new_lci(struct rose_neigh *neigh) { int lci; if (neigh->dce_mode) { for (lci = 1; lci <= sysctl_rose_maximum_vcs; lci++) if (rose_find_socket(lci, neigh) == NULL && rose_route_free_lci(lci, neigh) == NULL) return lci; } else { for (lci = sysctl_rose_maximum_vcs; lci > 0; lci--) if (rose_find_socket(lci, neigh) == NULL && rose_route_free_lci(lci, neigh) == NULL) return lci; } return 0; } /* * Deferred destroy. */ void rose_destroy_socket(struct sock *); /* * Handler for deferred kills. */ static void rose_destroy_timer(unsigned long data) { rose_destroy_socket((struct sock *)data); } /* * 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 rose_destroy_socket(struct sock *sk) { struct sk_buff *skb; rose_remove_socket(sk); rose_stop_heartbeat(sk); rose_stop_idletimer(sk); rose_stop_timer(sk); rose_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); rose_start_heartbeat(skb->sk); rose_sk(skb->sk)->state = ROSE_STATE_0; } kfree_skb(skb); } if (sk_has_allocations(sk)) { /* Defer: outstanding buffers */ setup_timer(&sk->sk_timer, rose_destroy_timer, (unsigned long)sk); sk->sk_timer.expires = jiffies + 10 * HZ; add_timer(&sk->sk_timer); } else sock_put(sk); } /* * Handling for system calls applied via the various interfaces to a * ROSE socket object. */ static int rose_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); int opt; if (level != SOL_ROSE) return -ENOPROTOOPT; if (optlen < sizeof(int)) return -EINVAL; if (get_user(opt, (int __user *)optval)) return -EFAULT; switch (optname) { case ROSE_DEFER: rose->defer = opt ? 1 : 0; return 0; case ROSE_T1: if (opt < 1) return -EINVAL; rose->t1 = opt * HZ; return 0; case ROSE_T2: if (opt < 1) return -EINVAL; rose->t2 = opt * HZ; return 0; case ROSE_T3: if (opt < 1) return -EINVAL; rose->t3 = opt * HZ; return 0; case ROSE_HOLDBACK: if (opt < 1) return -EINVAL; rose->hb = opt * HZ; return 0; case ROSE_IDLE: if (opt < 0) return -EINVAL; rose->idle = opt * 60 * HZ; return 0; case ROSE_QBITINCL: rose->qbitincl = opt ? 1 : 0; return 0; default: return -ENOPROTOOPT; } } static int rose_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); int val = 0; int len; if (level != SOL_ROSE) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; switch (optname) { case ROSE_DEFER: val = rose->defer; break; case ROSE_T1: val = rose->t1 / HZ; break; case ROSE_T2: val = rose->t2 / HZ; break; case ROSE_T3: val = rose->t3 / HZ; break; case ROSE_HOLDBACK: val = rose->hb / HZ; break; case ROSE_IDLE: val = rose->idle / (60 * HZ); break; case ROSE_QBITINCL: val = rose->qbitincl; 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 rose_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; if (sk->sk_state != TCP_LISTEN) { struct rose_sock *rose = rose_sk(sk); rose->dest_ndigis = 0; memset(&rose->dest_addr, 0, ROSE_ADDR_LEN); memset(&rose->dest_call, 0, AX25_ADDR_LEN); memset(rose->dest_digis, 0, AX25_ADDR_LEN * ROSE_MAX_DIGIS); sk->sk_max_ack_backlog = backlog; sk->sk_state = TCP_LISTEN; return 0; } return -EOPNOTSUPP; } static struct proto rose_proto = { .name = "ROSE", .owner = THIS_MODULE, .obj_size = sizeof(struct rose_sock), }; static int rose_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct rose_sock *rose; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; if (sock->type != SOCK_SEQPACKET || protocol != 0) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_ROSE, GFP_ATOMIC, &rose_proto); if (sk == NULL) return -ENOMEM; rose = rose_sk(sk); sock_init_data(sock, sk); skb_queue_head_init(&rose->ack_queue); #ifdef M_BIT skb_queue_head_init(&rose->frag_queue); rose->fraglen = 0; #endif sock->ops = &rose_proto_ops; sk->sk_protocol = protocol; init_timer(&rose->timer); init_timer(&rose->idletimer); rose->t1 = msecs_to_jiffies(sysctl_rose_call_request_timeout); rose->t2 = msecs_to_jiffies(sysctl_rose_reset_request_timeout); rose->t3 = msecs_to_jiffies(sysctl_rose_clear_request_timeout); rose->hb = msecs_to_jiffies(sysctl_rose_ack_hold_back_timeout); rose->idle = msecs_to_jiffies(sysctl_rose_no_activity_timeout); rose->state = ROSE_STATE_0; return 0; } static struct sock *rose_make_new(struct sock *osk) { struct sock *sk; struct rose_sock *rose, *orose; if (osk->sk_type != SOCK_SEQPACKET) return NULL; sk = sk_alloc(sock_net(osk), PF_ROSE, GFP_ATOMIC, &rose_proto); if (sk == NULL) return NULL; rose = rose_sk(sk); sock_init_data(NULL, sk); skb_queue_head_init(&rose->ack_queue); #ifdef M_BIT skb_queue_head_init(&rose->frag_queue); rose->fraglen = 0; #endif 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); init_timer(&rose->timer); init_timer(&rose->idletimer); orose = rose_sk(osk); rose->t1 = orose->t1; rose->t2 = orose->t2; rose->t3 = orose->t3; rose->hb = orose->hb; rose->idle = orose->idle; rose->defer = orose->defer; rose->device = orose->device; rose->qbitincl = orose->qbitincl; return sk; } static int rose_release(struct socket *sock) { struct sock *sk = sock->sk; struct rose_sock *rose; if (sk == NULL) return 0; sock_hold(sk); sock_orphan(sk); lock_sock(sk); rose = rose_sk(sk); switch (rose->state) { case ROSE_STATE_0: release_sock(sk); rose_disconnect(sk, 0, -1, -1); lock_sock(sk); rose_destroy_socket(sk); break; case ROSE_STATE_2: rose->neighbour->use--; release_sock(sk); rose_disconnect(sk, 0, -1, -1); lock_sock(sk); rose_destroy_socket(sk); break; case ROSE_STATE_1: case ROSE_STATE_3: case ROSE_STATE_4: case ROSE_STATE_5: rose_clear_queues(sk); rose_stop_idletimer(sk); rose_write_internal(sk, ROSE_CLEAR_REQUEST); rose_start_t3timer(sk); rose->state = ROSE_STATE_2; sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DEAD); sock_set_flag(sk, SOCK_DESTROY); break; default: break; } sock->sk = NULL; release_sock(sk); sock_put(sk); return 0; } static int rose_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *addr = (struct sockaddr_rose *)uaddr; struct net_device *dev; ax25_address *source; ax25_uid_assoc *user; int n; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr_len != sizeof(struct sockaddr_rose) && addr_len != sizeof(struct full_sockaddr_rose)) return -EINVAL; if (addr->srose_family != AF_ROSE) return -EINVAL; if (addr_len == sizeof(struct sockaddr_rose) && addr->srose_ndigis > 1) return -EINVAL; if ((unsigned int) addr->srose_ndigis > ROSE_MAX_DIGIS) return -EINVAL; if ((dev = rose_dev_get(&addr->srose_addr)) == NULL) return -EADDRNOTAVAIL; source = &addr->srose_call; user = ax25_findbyuid(current_euid()); if (user) { rose->source_call = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_BIND_SERVICE)) return -EACCES; rose->source_call = *source; } rose->source_addr = addr->srose_addr; rose->device = dev; rose->source_ndigis = addr->srose_ndigis; if (addr_len == sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_addr = (struct full_sockaddr_rose *)uaddr; for (n = 0 ; n < addr->srose_ndigis ; n++) rose->source_digis[n] = full_addr->srose_digis[n]; } else { if (rose->source_ndigis == 1) { rose->source_digis[0] = addr->srose_digi; } } rose_insert_socket(sk); sock_reset_flag(sk, SOCK_ZAPPED); return 0; } static int rose_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *addr = (struct sockaddr_rose *)uaddr; unsigned char cause, diagnostic; struct net_device *dev; ax25_uid_assoc *user; int n, err = 0; if (addr_len != sizeof(struct sockaddr_rose) && addr_len != sizeof(struct full_sockaddr_rose)) return -EINVAL; if (addr->srose_family != AF_ROSE) return -EINVAL; if (addr_len == sizeof(struct sockaddr_rose) && addr->srose_ndigis > 1) return -EINVAL; if ((unsigned int) addr->srose_ndigis > ROSE_MAX_DIGIS) return -EINVAL; /* Source + Destination digis should not exceed ROSE_MAX_DIGIS */ if ((rose->source_ndigis + addr->srose_ndigis) > ROSE_MAX_DIGIS) return -EINVAL; lock_sock(sk); if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) { /* Connect completed during a ERESTARTSYS event */ sock->state = SS_CONNECTED; goto out_release; } 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) { /* No reconnect on a seqpacket socket */ err = -EISCONN; goto out_release; } sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; rose->neighbour = rose_get_neigh(&addr->srose_addr, &cause, &diagnostic, 0); if (!rose->neighbour) { err = -ENETUNREACH; goto out_release; } rose->lci = rose_new_lci(rose->neighbour); if (!rose->lci) { err = -ENETUNREACH; 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 = rose_dev_first()) == NULL) { err = -ENETUNREACH; goto out_release; } user = ax25_findbyuid(current_euid()); if (!user) { err = -EINVAL; goto out_release; } memcpy(&rose->source_addr, dev->dev_addr, ROSE_ADDR_LEN); rose->source_call = user->call; rose->device = dev; ax25_uid_put(user); rose_insert_socket(sk); /* Finish the bind */ } rose->dest_addr = addr->srose_addr; rose->dest_call = addr->srose_call; rose->rand = ((long)rose & 0xFFFF) + rose->lci; rose->dest_ndigis = addr->srose_ndigis; if (addr_len == sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_addr = (struct full_sockaddr_rose *)uaddr; for (n = 0 ; n < addr->srose_ndigis ; n++) rose->dest_digis[n] = full_addr->srose_digis[n]; } else { if (rose->dest_ndigis == 1) { rose->dest_digis[0] = addr->srose_digi; } } /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; rose->state = ROSE_STATE_1; rose->neighbour->use++; rose_write_internal(sk, ROSE_CALL_REQUEST); rose_start_heartbeat(sk); rose_start_t1timer(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 rose_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 */ skb->sk = NULL; kfree_skb(skb); sk->sk_ack_backlog--; out_release: release_sock(sk); return err; } static int rose_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_rose *srose = (struct full_sockaddr_rose *)uaddr; struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); int n; memset(srose, 0, sizeof(*srose)); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; for (n = 0; n < rose->dest_ndigis; n++) srose->srose_digis[n] = rose->dest_digis[n]; } else { srose->srose_family = AF_ROSE; srose->srose_addr = rose->source_addr; srose->srose_call = rose->source_call; srose->srose_ndigis = rose->source_ndigis; for (n = 0; n < rose->source_ndigis; n++) srose->srose_digis[n] = rose->source_digis[n]; } *uaddr_len = sizeof(struct full_sockaddr_rose); return 0; } int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the rose frame start */ memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); if (!rose_parse_facilities(skb->data + ROSE_CALL_REQ_FACILITIES_OFF, skb->len - ROSE_CALL_REQ_FACILITIES_OFF, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); /* * We can't accept the Call Request. */ if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; } static int rose_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *usrose = (struct sockaddr_rose *)msg->msg_name; int err; struct full_sockaddr_rose srose; struct sk_buff *skb; unsigned char *asmptr; int n, size, qbit = 0; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT)) return -EINVAL; if (sock_flag(sk, SOCK_ZAPPED)) return -EADDRNOTAVAIL; if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); return -EPIPE; } if (rose->neighbour == NULL || rose->device == NULL) return -ENETUNREACH; if (usrose != NULL) { if (msg->msg_namelen != sizeof(struct sockaddr_rose) && msg->msg_namelen != sizeof(struct full_sockaddr_rose)) return -EINVAL; memset(&srose, 0, sizeof(struct full_sockaddr_rose)); memcpy(&srose, usrose, msg->msg_namelen); if (rosecmp(&rose->dest_addr, &srose.srose_addr) != 0 || ax25cmp(&rose->dest_call, &srose.srose_call) != 0) return -EISCONN; if (srose.srose_ndigis != rose->dest_ndigis) return -EISCONN; if (srose.srose_ndigis == rose->dest_ndigis) { for (n = 0 ; n < srose.srose_ndigis ; n++) if (ax25cmp(&rose->dest_digis[n], &srose.srose_digis[n])) return -EISCONN; } if (srose.srose_family != AF_ROSE) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; srose.srose_family = AF_ROSE; srose.srose_addr = rose->dest_addr; srose.srose_call = rose->dest_call; srose.srose_ndigis = rose->dest_ndigis; for (n = 0 ; n < rose->dest_ndigis ; n++) srose.srose_digis[n] = rose->dest_digis[n]; } /* Build a packet */ /* Sanity check the packet size */ if (len > 65535) return -EMSGSIZE; size = len + AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN; if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL) return err; skb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN); /* * Put the data on the end */ skb_reset_transport_header(skb); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); return err; } /* * If the Q BIT Include socket option is in force, the first * byte of the user data is the logical value of the Q Bit. */ if (rose->qbitincl) { qbit = skb->data[0]; skb_pull(skb, 1); } /* * Push down the ROSE header */ asmptr = skb_push(skb, ROSE_MIN_LEN); /* Build a ROSE Network header */ asmptr[0] = ((rose->lci >> 8) & 0x0F) | ROSE_GFI; asmptr[1] = (rose->lci >> 0) & 0xFF; asmptr[2] = ROSE_DATA; if (qbit) asmptr[0] |= ROSE_Q_BIT; if (sk->sk_state != TCP_ESTABLISHED) { kfree_skb(skb); return -ENOTCONN; } #ifdef M_BIT #define ROSE_PACLEN (256-ROSE_MIN_LEN) if (skb->len - ROSE_MIN_LEN > ROSE_PACLEN) { unsigned char header[ROSE_MIN_LEN]; struct sk_buff *skbn; int frontlen; int lg; /* Save a copy of the Header */ skb_copy_from_linear_data(skb, header, ROSE_MIN_LEN); skb_pull(skb, ROSE_MIN_LEN); frontlen = skb_headroom(skb); while (skb->len > 0) { if ((skbn = sock_alloc_send_skb(sk, frontlen + ROSE_PACLEN, 0, &err)) == NULL) { kfree_skb(skb); return err; } skbn->sk = sk; skbn->free = 1; skbn->arp = 1; skb_reserve(skbn, frontlen); lg = (ROSE_PACLEN > skb->len) ? skb->len : ROSE_PACLEN; /* Copy the user data */ skb_copy_from_linear_data(skb, skb_put(skbn, lg), lg); skb_pull(skb, lg); /* Duplicate the Header */ skb_push(skbn, ROSE_MIN_LEN); skb_copy_to_linear_data(skbn, header, ROSE_MIN_LEN); if (skb->len > 0) skbn->data[2] |= M_BIT; skb_queue_tail(&sk->sk_write_queue, skbn); /* Throw it on the queue */ } skb->free = 1; kfree_skb(skb); } else { skb_queue_tail(&sk->sk_write_queue, skb); /* Throw it on the queue */ } #else skb_queue_tail(&sk->sk_write_queue, skb); /* Shove it onto the queue */ #endif rose_kick(sk); return len; } static int rose_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name; size_t copied; unsigned char *asmptr; struct sk_buff *skb; int n, er, qbit; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) return er; qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT; skb_pull(skb, ROSE_MIN_LEN); if (rose->qbitincl) { asmptr = skb_push(skb, 1); *asmptr = qbit; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (srose != NULL) { memset(srose, 0, msg->msg_namelen); srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name; for (n = 0 ; n < rose->dest_ndigis ; n++) full_srose->srose_digis[n] = rose->dest_digis[n]; msg->msg_namelen = sizeof(struct full_sockaddr_rose); } else { if (rose->dest_ndigis >= 1) { srose->srose_ndigis = 1; srose->srose_digi = rose->dest_digis[0]; } msg->msg_namelen = sizeof(struct sockaddr_rose); } } skb_free_datagram(sk, skb); return copied; } static int rose_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); void __user *argp = (void __user *)arg; switch (cmd) { case TIOCOUTQ: { long amount; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; return put_user(amount, (unsigned int __user *) argp); } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; /* 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; return put_user(amount, (unsigned int __user *) argp); } case SIOCGSTAMP: return sock_get_timestamp(sk, (struct timeval __user *) argp); case SIOCGSTAMPNS: return sock_get_timestampns(sk, (struct timespec __user *) argp); 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 SIOCRSCLRRT: if (!capable(CAP_NET_ADMIN)) return -EPERM; return rose_rt_ioctl(cmd, argp); case SIOCRSGCAUSE: { struct rose_cause_struct rose_cause; rose_cause.cause = rose->cause; rose_cause.diagnostic = rose->diagnostic; return copy_to_user(argp, &rose_cause, sizeof(struct rose_cause_struct)) ? -EFAULT : 0; } case SIOCRSSCAUSE: { struct rose_cause_struct rose_cause; if (copy_from_user(&rose_cause, argp, sizeof(struct rose_cause_struct))) return -EFAULT; rose->cause = rose_cause.cause; rose->diagnostic = rose_cause.diagnostic; return 0; } case SIOCRSSL2CALL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (ax25cmp(&rose_callsign, &null_ax25_address) != 0) ax25_listen_release(&rose_callsign, NULL); if (copy_from_user(&rose_callsign, argp, sizeof(ax25_address))) return -EFAULT; if (ax25cmp(&rose_callsign, &null_ax25_address) != 0) return ax25_listen_register(&rose_callsign, NULL); return 0; case SIOCRSGL2CALL: return copy_to_user(argp, &rose_callsign, sizeof(ax25_address)) ? -EFAULT : 0; case SIOCRSACCEPT: if (rose->state == ROSE_STATE_5) { rose_write_internal(sk, ROSE_CALL_ACCEPTED); rose_start_idletimer(sk); rose->condition = 0x00; rose->vs = 0; rose->va = 0; rose->vr = 0; rose->vl = 0; rose->state = ROSE_STATE_3; } return 0; default: return -ENOIOCTLCMD; } return 0; } #ifdef CONFIG_PROC_FS static void *rose_info_start(struct seq_file *seq, loff_t *pos) __acquires(rose_list_lock) { spin_lock_bh(&rose_list_lock); return seq_hlist_start_head(&rose_list, *pos); } static void *rose_info_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_hlist_next(v, &rose_list, pos); } static void rose_info_stop(struct seq_file *seq, void *v) __releases(rose_list_lock) { spin_unlock_bh(&rose_list_lock); } static int rose_info_show(struct seq_file *seq, void *v) { char buf[11], rsbuf[11]; if (v == SEQ_START_TOKEN) seq_puts(seq, "dest_addr dest_call src_addr src_call dev lci neigh st vs vr va t t1 t2 t3 hb idle Snd-Q Rcv-Q inode\n"); else { struct sock *s = sk_entry(v); struct rose_sock *rose = rose_sk(s); const char *devname, *callsign; const struct net_device *dev = rose->device; if (!dev) devname = "???"; else devname = dev->name; seq_printf(seq, "%-10s %-9s ", rose2asc(rsbuf, &rose->dest_addr), ax2asc(buf, &rose->dest_call)); if (ax25cmp(&rose->source_call, &null_ax25_address) == 0) callsign = "??????-?"; else callsign = ax2asc(buf, &rose->source_call); seq_printf(seq, "%-10s %-9s %-5s %3.3X %05d %d %d %d %d %3lu %3lu %3lu %3lu %3lu %3lu/%03lu %5d %5d %ld\n", rose2asc(rsbuf, &rose->source_addr), callsign, devname, rose->lci & 0x0FFF, (rose->neighbour) ? rose->neighbour->number : 0, rose->state, rose->vs, rose->vr, rose->va, ax25_display_timer(&rose->timer) / HZ, rose->t1 / HZ, rose->t2 / HZ, rose->t3 / HZ, rose->hb / HZ, ax25_display_timer(&rose->idletimer) / (60 * HZ), rose->idle / (60 * HZ), sk_wmem_alloc_get(s), sk_rmem_alloc_get(s), s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L); } return 0; } static const struct seq_operations rose_info_seqops = { .start = rose_info_start, .next = rose_info_next, .stop = rose_info_stop, .show = rose_info_show, }; static int rose_info_open(struct inode *inode, struct file *file) { return seq_open(file, &rose_info_seqops); } static const struct file_operations rose_info_fops = { .owner = THIS_MODULE, .open = rose_info_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* CONFIG_PROC_FS */ static const struct net_proto_family rose_family_ops = { .family = PF_ROSE, .create = rose_create, .owner = THIS_MODULE, }; static const struct proto_ops rose_proto_ops = { .family = PF_ROSE, .owner = THIS_MODULE, .release = rose_release, .bind = rose_bind, .connect = rose_connect, .socketpair = sock_no_socketpair, .accept = rose_accept, .getname = rose_getname, .poll = datagram_poll, .ioctl = rose_ioctl, .listen = rose_listen, .shutdown = sock_no_shutdown, .setsockopt = rose_setsockopt, .getsockopt = rose_getsockopt, .sendmsg = rose_sendmsg, .recvmsg = rose_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static struct notifier_block rose_dev_notifier = { .notifier_call = rose_device_event, }; static struct net_device **dev_rose; static struct ax25_protocol rose_pid = { .pid = AX25_P_ROSE, .func = rose_route_frame }; static struct ax25_linkfail rose_linkfail_notifier = { .func = rose_link_failed }; static int __init rose_proto_init(void) { int i; int rc; if (rose_ndevs > 0x7FFFFFFF/sizeof(struct net_device *)) { printk(KERN_ERR "ROSE: rose_proto_init - rose_ndevs parameter to large\n"); rc = -EINVAL; goto out; } rc = proto_register(&rose_proto, 0); if (rc != 0) goto out; rose_callsign = null_ax25_address; dev_rose = kzalloc(rose_ndevs * sizeof(struct net_device *), GFP_KERNEL); if (dev_rose == NULL) { printk(KERN_ERR "ROSE: rose_proto_init - unable to allocate device structure\n"); rc = -ENOMEM; goto out_proto_unregister; } for (i = 0; i < rose_ndevs; i++) { struct net_device *dev; char name[IFNAMSIZ]; sprintf(name, "rose%d", i); dev = alloc_netdev(0, name, rose_setup); if (!dev) { printk(KERN_ERR "ROSE: rose_proto_init - unable to allocate memory\n"); rc = -ENOMEM; goto fail; } rc = register_netdev(dev); if (rc) { printk(KERN_ERR "ROSE: netdevice registration failed\n"); free_netdev(dev); goto fail; } rose_set_lockdep_key(dev); dev_rose[i] = dev; } sock_register(&rose_family_ops); register_netdevice_notifier(&rose_dev_notifier); ax25_register_pid(&rose_pid); ax25_linkfail_register(&rose_linkfail_notifier); #ifdef CONFIG_SYSCTL rose_register_sysctl(); #endif rose_loopback_init(); rose_add_loopback_neigh(); proc_create("rose", S_IRUGO, init_net.proc_net, &rose_info_fops); proc_create("rose_neigh", S_IRUGO, init_net.proc_net, &rose_neigh_fops); proc_create("rose_nodes", S_IRUGO, init_net.proc_net, &rose_nodes_fops); proc_create("rose_routes", S_IRUGO, init_net.proc_net, &rose_routes_fops); out: return rc; fail: while (--i >= 0) { unregister_netdev(dev_rose[i]); free_netdev(dev_rose[i]); } kfree(dev_rose); out_proto_unregister: proto_unregister(&rose_proto); goto out; } module_init(rose_proto_init); module_param(rose_ndevs, int, 0); MODULE_PARM_DESC(rose_ndevs, "number of ROSE devices"); MODULE_AUTHOR("Jonathan Naylor G4KLX <g4klx@g4klx.demon.co.uk>"); MODULE_DESCRIPTION("The amateur radio ROSE network layer protocol"); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_ROSE); static void __exit rose_exit(void) { int i; remove_proc_entry("rose", init_net.proc_net); remove_proc_entry("rose_neigh", init_net.proc_net); remove_proc_entry("rose_nodes", init_net.proc_net); remove_proc_entry("rose_routes", init_net.proc_net); rose_loopback_clear(); rose_rt_free(); ax25_protocol_release(AX25_P_ROSE); ax25_linkfail_release(&rose_linkfail_notifier); if (ax25cmp(&rose_callsign, &null_ax25_address) != 0) ax25_listen_release(&rose_callsign, NULL); #ifdef CONFIG_SYSCTL rose_unregister_sysctl(); #endif unregister_netdevice_notifier(&rose_dev_notifier); sock_unregister(PF_ROSE); for (i = 0; i < rose_ndevs; i++) { struct net_device *dev = dev_rose[i]; if (dev) { unregister_netdev(dev); free_netdev(dev); } } kfree(dev_rose); proto_unregister(&rose_proto); } module_exit(rose_exit);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5694_0
crossvul-cpp_data_good_3696_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 "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; } 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); 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) { 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; } return 0; } int rds_recvmsg(struct kiocb *iocb, 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; struct sockaddr_in *sin; 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); msg->msg_namelen = 0; if (msg_flags & MSG_OOB) goto out; while (1) { /* 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)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); 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); 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)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; 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; } rds_info_copy(iter, &minfo, sizeof(minfo)); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3696_0
crossvul-cpp_data_good_1829_3
/***********************************************************************/ /* */ /* OCaml */ /* */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* */ /* Copyright 1996 Institut National de Recherche en Informatique et */ /* en Automatique. All rights reserved. This file is distributed */ /* under the terms of the GNU Library General Public License, with */ /* the special exception on linking described in file ../LICENSE. */ /* */ /***********************************************************************/ /* Structured input, compact format */ /* The interface of this file is "caml/intext.h" */ #include <string.h> #include <stdio.h> #include "caml/alloc.h" #include "caml/callback.h" #include "caml/custom.h" #include "caml/fail.h" #include "caml/gc.h" #include "caml/intext.h" #include "caml/io.h" #include "caml/md5.h" #include "caml/memory.h" #include "caml/mlvalues.h" #include "caml/misc.h" #include "caml/reverse.h" static unsigned char * intern_src; /* Reading pointer in block holding input data. */ static unsigned char * intern_input; /* Pointer to beginning of block holding input data. Meaningful only if intern_input_malloced = 1. */ static int intern_input_malloced; /* 1 if intern_input was allocated by caml_stat_alloc() and needs caml_stat_free() on error, 0 otherwise. */ static header_t * intern_dest; /* Writing pointer in destination block */ static char * intern_extra_block; /* If non-NULL, point to new heap chunk allocated with caml_alloc_for_heap. */ static asize_t obj_counter; /* Count how many objects seen so far */ static value * intern_obj_table; /* The pointers to objects already seen */ static unsigned int intern_color; /* Color to assign to newly created headers */ static header_t intern_header; /* Original header of the destination block. Meaningful only if intern_extra_block is NULL. */ static value intern_block; /* Point to the heap block allocated as destination block. Meaningful only if intern_extra_block is NULL. */ static char * intern_resolve_code_pointer(unsigned char digest[16], asize_t offset); CAMLnoreturn_start static void intern_bad_code_pointer(unsigned char digest[16]) CAMLnoreturn_end; static void intern_free_stack(void); #define Sign_extend_shift ((sizeof(intnat) - 1) * 8) #define Sign_extend(x) (((intnat)(x) << Sign_extend_shift) >> Sign_extend_shift) #define read8u() (*intern_src++) #define read8s() Sign_extend(*intern_src++) #define read16u() \ (intern_src += 2, \ (intern_src[-2] << 8) + intern_src[-1]) #define read16s() \ (intern_src += 2, \ (Sign_extend(intern_src[-2]) << 8) + intern_src[-1]) #define read32u() \ (intern_src += 4, \ ((uintnat)(intern_src[-4]) << 24) + (intern_src[-3] << 16) + \ (intern_src[-2] << 8) + intern_src[-1]) #define read32s() \ (intern_src += 4, \ (Sign_extend(intern_src[-4]) << 24) + (intern_src[-3] << 16) + \ (intern_src[-2] << 8) + intern_src[-1]) #ifdef ARCH_SIXTYFOUR static intnat read64s(void) { intnat res; int i; res = 0; for (i = 0; i < 8; i++) res = (res << 8) + intern_src[i]; intern_src += 8; return res; } #endif #define readblock(dest,len) \ (memmove((dest), intern_src, (len)), intern_src += (len)) static void intern_cleanup(void) { if (intern_input_malloced) caml_stat_free(intern_input); if (intern_obj_table != NULL) caml_stat_free(intern_obj_table); if (intern_extra_block != NULL) { /* free newly allocated heap chunk */ caml_free_for_heap(intern_extra_block); } else if (intern_block != 0) { /* restore original header for heap block, otherwise GC is confused */ Hd_val(intern_block) = intern_header; } /* free the recursion stack */ intern_free_stack(); } static void readfloat(double * dest, unsigned int code) { if (sizeof(double) != 8) { intern_cleanup(); caml_invalid_argument("input_value: non-standard floats"); } readblock((char *) dest, 8); /* Fix up endianness, if needed */ #if ARCH_FLOAT_ENDIANNESS == 0x76543210 /* Host is big-endian; fix up if data read is little-endian */ if (code != CODE_DOUBLE_BIG) Reverse_64(dest, dest); #elif ARCH_FLOAT_ENDIANNESS == 0x01234567 /* Host is little-endian; fix up if data read is big-endian */ if (code != CODE_DOUBLE_LITTLE) Reverse_64(dest, dest); #else /* Host is neither big nor little; permute as appropriate */ if (code == CODE_DOUBLE_LITTLE) Permute_64(dest, ARCH_FLOAT_ENDIANNESS, dest, 0x01234567) else Permute_64(dest, ARCH_FLOAT_ENDIANNESS, dest, 0x76543210); #endif } /* [len] is a number of floats */ static void readfloats(double * dest, mlsize_t len, unsigned int code) { mlsize_t i; if (sizeof(double) != 8) { intern_cleanup(); caml_invalid_argument("input_value: non-standard floats"); } readblock((char *) dest, len * 8); /* Fix up endianness, if needed */ #if ARCH_FLOAT_ENDIANNESS == 0x76543210 /* Host is big-endian; fix up if data read is little-endian */ if (code != CODE_DOUBLE_ARRAY8_BIG && code != CODE_DOUBLE_ARRAY32_BIG) { for (i = 0; i < len; i++) Reverse_64(dest + i, dest + i); } #elif ARCH_FLOAT_ENDIANNESS == 0x01234567 /* Host is little-endian; fix up if data read is big-endian */ if (code != CODE_DOUBLE_ARRAY8_LITTLE && code != CODE_DOUBLE_ARRAY32_LITTLE) { for (i = 0; i < len; i++) Reverse_64(dest + i, dest + i); } #else /* Host is neither big nor little; permute as appropriate */ if (code == CODE_DOUBLE_ARRAY8_LITTLE || code == CODE_DOUBLE_ARRAY32_LITTLE) { for (i = 0; i < len; i++) Permute_64(dest + i, ARCH_FLOAT_ENDIANNESS, dest + i, 0x01234567); } else { for (i = 0; i < len; i++) Permute_64(dest + i, ARCH_FLOAT_ENDIANNESS, dest + i, 0x76543210); } #endif } /* Item on the stack with defined operation */ struct intern_item { value * dest; intnat arg; enum { OReadItems, /* read arg items and store them in dest[0], dest[1], ... */ OFreshOID, /* generate a fresh OID and store it in *dest */ OShift /* offset *dest by arg */ } op; }; /* FIXME: This is duplicated in two other places, with the only difference of the type of elements stored in the stack. Possible solution in C would be to instantiate stack these function via. C preprocessor macro. */ #define INTERN_STACK_INIT_SIZE 256 #define INTERN_STACK_MAX_SIZE (1024*1024*100) static struct intern_item intern_stack_init[INTERN_STACK_INIT_SIZE]; static struct intern_item * intern_stack = intern_stack_init; static struct intern_item * intern_stack_limit = intern_stack_init + INTERN_STACK_INIT_SIZE; /* Free the recursion stack if needed */ static void intern_free_stack(void) { if (intern_stack != intern_stack_init) { free(intern_stack); /* Reinitialize the globals for next time around */ intern_stack = intern_stack_init; intern_stack_limit = intern_stack + INTERN_STACK_INIT_SIZE; } } /* Same, then raise Out_of_memory */ static void intern_stack_overflow(void) { caml_gc_message (0x04, "Stack overflow in un-marshaling value\n", 0); intern_free_stack(); caml_raise_out_of_memory(); } static struct intern_item * intern_resize_stack(struct intern_item * sp) { asize_t newsize = 2 * (intern_stack_limit - intern_stack); asize_t sp_offset = sp - intern_stack; struct intern_item * newstack; if (newsize >= INTERN_STACK_MAX_SIZE) intern_stack_overflow(); if (intern_stack == intern_stack_init) { newstack = malloc(sizeof(struct intern_item) * newsize); if (newstack == NULL) intern_stack_overflow(); memcpy(newstack, intern_stack_init, sizeof(struct intern_item) * INTERN_STACK_INIT_SIZE); } else { newstack = realloc(intern_stack, sizeof(struct intern_item) * newsize); if (newstack == NULL) intern_stack_overflow(); } intern_stack = newstack; intern_stack_limit = newstack + newsize; return newstack + sp_offset; } /* Convenience macros for requesting operation on the stack */ #define PushItem() \ do { \ sp++; \ if (sp >= intern_stack_limit) sp = intern_resize_stack(sp); \ } while(0) #define ReadItems(_dest,_n) \ do { \ if (_n > 0) { \ PushItem(); \ sp->op = OReadItems; \ sp->dest = _dest; \ sp->arg = _n; \ } \ } while(0) static void intern_rec(value *dest) { unsigned int code; tag_t tag; mlsize_t size, len, ofs_ind; value v; asize_t ofs; header_t header; unsigned char digest[16]; struct custom_operations * ops; char * codeptr; struct intern_item * sp; sp = intern_stack; /* Initially let's try to read the first object from the stream */ ReadItems(dest, 1); /* The un-marshaler loop, the recursion is unrolled */ while(sp != intern_stack) { /* Interpret next item on the stack */ dest = sp->dest; switch (sp->op) { case OFreshOID: /* Refresh the object ID */ /* but do not do it for predefined exception slots */ if (Long_val(Field((value)dest, 1)) >= 0) caml_set_oo_id((value)dest); /* Pop item and iterate */ sp--; break; case OShift: /* Shift value by an offset */ *dest += sp->arg; /* Pop item and iterate */ sp--; break; case OReadItems: /* Pop item */ sp->dest++; if (--(sp->arg) == 0) sp--; /* Read a value and set v to this value */ code = read8u(); if (code >= PREFIX_SMALL_INT) { if (code >= PREFIX_SMALL_BLOCK) { /* Small block */ tag = code & 0xF; size = (code >> 4) & 0x7; read_block: if (size == 0) { v = Atom(tag); } else { v = Val_hp(intern_dest); if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v; *intern_dest = Make_header(size, tag, intern_color); intern_dest += 1 + size; /* For objects, we need to freshen the oid */ if (tag == Object_tag) { Assert(size >= 2); /* Request to read rest of the elements of the block */ ReadItems(&Field(v, 2), size - 2); /* Request freshing OID */ PushItem(); sp->op = OFreshOID; sp->dest = (value*) v; sp->arg = 1; /* Finally read first two block elements: method table and old OID */ ReadItems(&Field(v, 0), 2); } else /* If it's not an object then read the contents of the block */ ReadItems(&Field(v, 0), size); } } else { /* Small integer */ v = Val_int(code & 0x3F); } } else { if (code >= PREFIX_SMALL_STRING) { /* Small string */ len = (code & 0x1F); read_string: size = (len + sizeof(value)) / sizeof(value); v = Val_hp(intern_dest); if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v; *intern_dest = Make_header(size, String_tag, intern_color); intern_dest += 1 + size; Field(v, size - 1) = 0; ofs_ind = Bsize_wsize(size) - 1; Byte(v, ofs_ind) = ofs_ind - len; readblock(String_val(v), len); } else { switch(code) { case CODE_INT8: v = Val_long(read8s()); break; case CODE_INT16: v = Val_long(read16s()); break; case CODE_INT32: v = Val_long(read32s()); break; case CODE_INT64: #ifdef ARCH_SIXTYFOUR v = Val_long(read64s()); break; #else intern_cleanup(); caml_failwith("input_value: integer too large"); break; #endif case CODE_SHARED8: ofs = read8u(); read_shared: Assert (ofs > 0); Assert (ofs <= obj_counter); Assert (intern_obj_table != NULL); v = intern_obj_table[obj_counter - ofs]; break; case CODE_SHARED16: ofs = read16u(); goto read_shared; case CODE_SHARED32: ofs = read32u(); goto read_shared; case CODE_BLOCK32: header = (header_t) read32u(); tag = Tag_hd(header); size = Wosize_hd(header); goto read_block; case CODE_BLOCK64: #ifdef ARCH_SIXTYFOUR header = (header_t) read64s(); tag = Tag_hd(header); size = Wosize_hd(header); goto read_block; #else intern_cleanup(); caml_failwith("input_value: data block too large"); break; #endif case CODE_STRING8: len = read8u(); goto read_string; case CODE_STRING32: len = read32u(); goto read_string; case CODE_DOUBLE_LITTLE: case CODE_DOUBLE_BIG: v = Val_hp(intern_dest); if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v; *intern_dest = Make_header(Double_wosize, Double_tag, intern_color); intern_dest += 1 + Double_wosize; readfloat((double *) v, code); break; case CODE_DOUBLE_ARRAY8_LITTLE: case CODE_DOUBLE_ARRAY8_BIG: len = read8u(); read_double_array: size = len * Double_wosize; v = Val_hp(intern_dest); if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v; *intern_dest = Make_header(size, Double_array_tag, intern_color); intern_dest += 1 + size; readfloats((double *) v, len, code); break; case CODE_DOUBLE_ARRAY32_LITTLE: case CODE_DOUBLE_ARRAY32_BIG: len = read32u(); goto read_double_array; case CODE_CODEPOINTER: ofs = read32u(); readblock(digest, 16); codeptr = intern_resolve_code_pointer(digest, ofs); if (codeptr != NULL) { v = (value) codeptr; } else { value * function_placeholder = caml_named_value ("Debugger.function_placeholder"); if (function_placeholder != NULL) { v = *function_placeholder; } else { intern_cleanup(); intern_bad_code_pointer(digest); } } break; case CODE_INFIXPOINTER: ofs = read32u(); /* Read a value to *dest, then offset *dest by ofs */ PushItem(); sp->dest = dest; sp->op = OShift; sp->arg = ofs; ReadItems(dest, 1); continue; /* with next iteration of main loop, skipping *dest = v */ case CODE_CUSTOM: ops = caml_find_custom_operations((char *) intern_src); if (ops == NULL) { intern_cleanup(); caml_failwith("input_value: unknown custom block identifier"); } while (*intern_src++ != 0) /*nothing*/; /*skip identifier*/ size = ops->deserialize((void *) (intern_dest + 2)); size = 1 + (size + sizeof(value) - 1) / sizeof(value); v = Val_hp(intern_dest); if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v; *intern_dest = Make_header(size, Custom_tag, intern_color); Custom_ops_val(v) = ops; if (ops->finalize != NULL && Is_young(v)) { /* Remembered that the block has a finalizer */ if (caml_finalize_table.ptr >= caml_finalize_table.limit){ CAMLassert (caml_finalize_table.ptr == caml_finalize_table.limit); caml_realloc_ref_table (&caml_finalize_table); } *caml_finalize_table.ptr++ = (value *)v; } intern_dest += 1 + size; break; default: intern_cleanup(); caml_failwith("input_value: ill-formed message"); } } } /* end of case OReadItems */ *dest = v; break; default: Assert(0); } } /* We are done. Cleanup the stack and leave the function */ intern_free_stack(); } static void intern_alloc(mlsize_t whsize, mlsize_t num_objects) { mlsize_t wosize; if (whsize == 0) { intern_obj_table = NULL; intern_extra_block = NULL; intern_block = 0; return; } wosize = Wosize_whsize(whsize); if (wosize > Max_wosize) { /* Round desired size up to next page */ asize_t request = ((Bsize_wsize(whsize) + Page_size - 1) >> Page_log) << Page_log; intern_extra_block = caml_alloc_for_heap(request); if (intern_extra_block == NULL) caml_raise_out_of_memory(); intern_color = caml_allocation_color(intern_extra_block); intern_dest = (header_t *) intern_extra_block; } else { /* this is a specialised version of caml_alloc from alloc.c */ if (wosize == 0){ intern_block = Atom (String_tag); }else if (wosize <= Max_young_wosize){ intern_block = caml_alloc_small (wosize, String_tag); }else{ intern_block = caml_alloc_shr (wosize, String_tag); /* do not do the urgent_gc check here because it might darken intern_block into gray and break the Assert 3 lines down */ } intern_header = Hd_val(intern_block); intern_color = Color_hd(intern_header); Assert (intern_color == Caml_white || intern_color == Caml_black); intern_dest = (header_t *) Hp_val(intern_block); intern_extra_block = NULL; } obj_counter = 0; if (num_objects > 0) intern_obj_table = (value *) caml_stat_alloc(num_objects * sizeof(value)); else intern_obj_table = NULL; } static void intern_add_to_heap(mlsize_t whsize) { /* Add new heap chunk to heap if needed */ if (intern_extra_block != NULL) { /* If heap chunk not filled totally, build free block at end */ asize_t request = ((Bsize_wsize(whsize) + Page_size - 1) >> Page_log) << Page_log; header_t * end_extra_block = (header_t *) intern_extra_block + Wsize_bsize(request); Assert(intern_dest <= end_extra_block); if (intern_dest < end_extra_block){ caml_make_free_blocks ((value *) intern_dest, end_extra_block - intern_dest, 0, Caml_white); } caml_allocated_words += Wsize_bsize ((char *) intern_dest - intern_extra_block); caml_add_to_heap(intern_extra_block); } } value caml_input_val(struct channel *chan) { uint32_t magic; mlsize_t block_len, num_objects, whsize; char * block; value res; if (! caml_channel_binary_mode(chan)) caml_failwith("input_value: not a binary channel"); magic = caml_getword(chan); if (magic != Intext_magic_number) caml_failwith("input_value: bad object"); block_len = caml_getword(chan); num_objects = caml_getword(chan); #ifdef ARCH_SIXTYFOUR caml_getword(chan); /* skip size_32 */ whsize = caml_getword(chan); #else whsize = caml_getword(chan); caml_getword(chan); /* skip size_64 */ #endif /* Read block from channel */ block = caml_stat_alloc(block_len); /* During [caml_really_getblock], concurrent [caml_input_val] operations can take place (via signal handlers or context switching in systhreads), and [intern_input] may change. So, wait until [caml_really_getblock] is over before using [intern_input] and the other global vars. */ if (caml_really_getblock(chan, block, block_len) == 0) { caml_stat_free(block); caml_failwith("input_value: truncated object"); } intern_input = (unsigned char *) block; intern_input_malloced = 1; intern_src = intern_input; intern_alloc(whsize, num_objects); /* Fill it in */ intern_rec(&res); intern_add_to_heap(whsize); /* Free everything */ caml_stat_free(intern_input); if (intern_obj_table != NULL) caml_stat_free(intern_obj_table); return caml_check_urgent_gc(res); } CAMLprim value caml_input_value(value vchan) { CAMLparam1 (vchan); struct channel * chan = Channel(vchan); CAMLlocal1 (res); Lock(chan); res = caml_input_val(chan); Unlock(chan); CAMLreturn (res); } CAMLexport value caml_input_val_from_string(value str, intnat ofs) { CAMLparam1 (str); mlsize_t num_objects, whsize; CAMLlocal1 (obj); intern_src = &Byte_u(str, ofs + 2*4); intern_input_malloced = 0; num_objects = read32u(); #ifdef ARCH_SIXTYFOUR intern_src += 4; /* skip size_32 */ whsize = read32u(); #else whsize = read32u(); intern_src += 4; /* skip size_64 */ #endif /* Allocate result */ intern_alloc(whsize, num_objects); intern_src = &Byte_u(str, ofs + 5*4); /* If a GC occurred */ /* Fill it in */ intern_rec(&obj); intern_add_to_heap(whsize); /* Free everything */ if (intern_obj_table != NULL) caml_stat_free(intern_obj_table); CAMLreturn (caml_check_urgent_gc(obj)); } CAMLprim value caml_input_value_from_string(value str, value ofs) { return caml_input_val_from_string(str, Long_val(ofs)); } static value input_val_from_block(void) { mlsize_t num_objects, whsize; value obj; num_objects = read32u(); #ifdef ARCH_SIXTYFOUR intern_src += 4; /* skip size_32 */ whsize = read32u(); #else whsize = read32u(); intern_src += 4; /* skip size_64 */ #endif /* Allocate result */ intern_alloc(whsize, num_objects); /* Fill it in */ intern_rec(&obj); intern_add_to_heap(whsize); /* Free internal data structures */ if (intern_obj_table != NULL) caml_stat_free(intern_obj_table); return caml_check_urgent_gc(obj); } CAMLexport value caml_input_value_from_malloc(char * data, intnat ofs) { uint32_t magic; value obj; intern_input = (unsigned char *) data; intern_src = intern_input + ofs; intern_input_malloced = 1; magic = read32u(); if (magic != Intext_magic_number) caml_failwith("input_value_from_malloc: bad object"); intern_src += 4; /* Skip block_len */ obj = input_val_from_block(); /* Free the input */ caml_stat_free(intern_input); return obj; } /* [len] is a number of bytes */ CAMLexport value caml_input_value_from_block(char * data, intnat len) { uint32_t magic; mlsize_t block_len; value obj; intern_input = (unsigned char *) data; intern_src = intern_input; intern_input_malloced = 0; magic = read32u(); if (magic != Intext_magic_number) caml_failwith("input_value_from_block: bad object"); block_len = read32u(); if (5*4 + block_len > len) caml_failwith("input_value_from_block: bad block length"); obj = input_val_from_block(); return obj; } /* [ofs] is a [value] that represents a number of bytes result is a [value] that represents a number of bytes */ CAMLprim value caml_marshal_data_size(value buff, value ofs) { uint32_t magic; mlsize_t block_len; intern_src = &Byte_u(buff, Long_val(ofs)); intern_input_malloced = 0; magic = read32u(); if (magic != Intext_magic_number){ caml_failwith("Marshal.data_size: bad object"); } block_len = read32u(); return Val_long(block_len); } /* Resolution of code pointers */ static char * intern_resolve_code_pointer(unsigned char digest[16], asize_t offset) { int i; for (i = caml_code_fragments_table.size - 1; i >= 0; i--) { struct code_fragment * cf = caml_code_fragments_table.contents[i]; if (! cf->digest_computed) { caml_md5_block(cf->digest, cf->code_start, cf->code_end - cf->code_start); cf->digest_computed = 1; } if (memcmp(digest, cf->digest, 16) == 0) { if (cf->code_start + offset < cf->code_end) return cf->code_start + offset; else return NULL; } } return NULL; } static void intern_bad_code_pointer(unsigned char digest[16]) { char msg[256]; snprintf(msg, sizeof(msg), "input_value: unknown code module " "%02X%02X%02X%02X%02X%02X%02X%02X" "%02X%02X%02X%02X%02X%02X%02X%02X", digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); caml_failwith(msg); } /* Functions for writing user-defined marshallers */ CAMLexport int caml_deserialize_uint_1(void) { return read8u(); } CAMLexport int caml_deserialize_sint_1(void) { return read8s(); } CAMLexport int caml_deserialize_uint_2(void) { return read16u(); } CAMLexport int caml_deserialize_sint_2(void) { return read16s(); } CAMLexport uint32_t caml_deserialize_uint_4(void) { return read32u(); } CAMLexport int32_t caml_deserialize_sint_4(void) { return read32s(); } CAMLexport uint64_t caml_deserialize_uint_8(void) { uint64_t i; caml_deserialize_block_8(&i, 1); return i; } CAMLexport int64_t caml_deserialize_sint_8(void) { int64_t i; caml_deserialize_block_8(&i, 1); return i; } CAMLexport float caml_deserialize_float_4(void) { float f; caml_deserialize_block_4(&f, 1); return f; } CAMLexport double caml_deserialize_float_8(void) { double f; caml_deserialize_block_float_8(&f, 1); return f; } CAMLexport void caml_deserialize_block_1(void * data, intnat len) { memmove(data, intern_src, len); intern_src += len; } CAMLexport void caml_deserialize_block_2(void * data, intnat len) { #ifndef ARCH_BIG_ENDIAN unsigned char * p, * q; for (p = intern_src, q = data; len > 0; len--, p += 2, q += 2) Reverse_16(q, p); intern_src = p; #else memmove(data, intern_src, len * 2); intern_src += len * 2; #endif } CAMLexport void caml_deserialize_block_4(void * data, intnat len) { #ifndef ARCH_BIG_ENDIAN unsigned char * p, * q; for (p = intern_src, q = data; len > 0; len--, p += 4, q += 4) Reverse_32(q, p); intern_src = p; #else memmove(data, intern_src, len * 4); intern_src += len * 4; #endif } CAMLexport void caml_deserialize_block_8(void * data, intnat len) { #ifndef ARCH_BIG_ENDIAN unsigned char * p, * q; for (p = intern_src, q = data; len > 0; len--, p += 8, q += 8) Reverse_64(q, p); intern_src = p; #else memmove(data, intern_src, len * 8); intern_src += len * 8; #endif } CAMLexport void caml_deserialize_block_float_8(void * data, intnat len) { #if ARCH_FLOAT_ENDIANNESS == 0x01234567 memmove(data, intern_src, len * 8); intern_src += len * 8; #elif ARCH_FLOAT_ENDIANNESS == 0x76543210 unsigned char * p, * q; for (p = intern_src, q = data; len > 0; len--, p += 8, q += 8) Reverse_64(q, p); intern_src = p; #else unsigned char * p, * q; for (p = intern_src, q = data; len > 0; len--, p += 8, q += 8) Permute_64(q, ARCH_FLOAT_ENDIANNESS, p, 0x01234567); intern_src = p; #endif } CAMLexport void caml_deserialize_error(char * msg) { intern_cleanup(); caml_failwith(msg); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_1829_3
crossvul-cpp_data_good_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) { /* do not disclose physical addresses: attack vector */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; 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/good_4747_0
crossvul-cpp_data_bad_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; 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 (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/bad_1790_0
crossvul-cpp_data_bad_3830_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 (!capable(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 = 0; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); memset(uaddr, 0, *uaddrlen); 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_3830_0
crossvul-cpp_data_good_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, .flags = GENL_ADMIN_PERM, }; 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/good_3473_0
crossvul-cpp_data_bad_759_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. * * 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 <asm/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/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/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #include <linux/kmemleak.h> #endif #include <net/secure_seq.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_min_valid_pmtu __read_mostly = IPV4_MIN_MTU; /* * 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 struct dst_ops ipv4_dst_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .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, }; #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 = { .owner = THIS_MODULE, .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 = { .owner = THIS_MODULE, .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; } static int rt_acct_proc_open(struct inode *inode, struct file *file) { return single_open(file, rt_acct_proc_show, NULL); } static const struct file_operations rt_acct_proc_fops = { .owner = THIS_MODULE, .open = rt_acct_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", S_IRUGO, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", S_IRUGO, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create("rt_acct", 0, net->proc_net, &rt_acct_proc_fops); 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); } #define IP_IDENTS_SZ 2048u struct ip_ident_bucket { atomic_t id; u32 stamp32; }; static struct ip_ident_bucket *ip_idents __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) { struct ip_ident_bucket *bucket = ip_idents + hash % IP_IDENTS_SZ; u32 old = ACCESS_ONCE(bucket->stamp32); u32 now = (u32)jiffies; u32 delta = 0; if (old != now && cmpxchg(&bucket->stamp32, old, now) == old) delta = prandom_u32_max(now - old); return atomic_add_return(segs + delta, &bucket->id) - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(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, ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(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); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { 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(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); 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 inline void rt_free(struct rtable *rt) { call_rcu(&rt->dst.rcu_head, dst_rcu_free); } 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); rt_free(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); rt_free(rt); } } 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->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, 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 = kzalloc(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_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_expires = 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, NULL, &new_gw); if (!IS_ERR(n)) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, 0); } 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; 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(&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; 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); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 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 in_device *in_dev = __in_dev_get_rcu(skb->dev); struct rtable *rt = skb_rtable(skb); struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; /* 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_BH(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: IP_INC_STATS_BH(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_BH(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 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; struct fib_result res; if (dst_metric_locked(dst, RTAX_MTU)) return; if (dst->dev->mtu < mtu) return; if (mtu < ip_rt_min_pmtu) mtu = ip_rt_min_pmtu; if (rt->rt_pmtu == mtu && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, 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, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; if (!mark) mark = IP4_REPLY_MARK(net, skb->mark); __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); 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(&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; 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(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && odst->ops->check(odst, 0) == NULL) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) rt->dst.path, &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, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); 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; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(sock_net(sk), &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 by dst_free(). */ 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 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 flowi4 fl4; struct iphdr *iph; iph = ip_hdr(skb); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = iph->daddr; fl4.saddr = iph->saddr; fl4.flowi4_tos = RT_TOS(iph->tos); fl4.flowi4_oif = rt->dst.dev->ifindex; fl4.flowi4_iif = skb->dev->ifindex; fl4.flowi4_mark = skb->mark; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res) == 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 advmss = dst_metric_raw(dst, RTAX_ADVMSS); if (advmss == 0) { advmss = max_t(unsigned int, dst->dev->mtu - 40, ip_rt_min_advmss); if (advmss > 65535 - 40) advmss = 65535 - 40; } return advmss; } 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 = dst->dev->mtu; if (unlikely(dst_metric_locked(dst, RTAX_MTU))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } return min_t(unsigned int, mtu, IP_MAX_MTU); } 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) return fnhe; } return NULL; } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr) { 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_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (!(rt->dst.flags & DST_NOCACHE)) { rcu_assign_pointer(*porig, rt); if (orig) rt_free(orig); 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; prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) rt_free(orig); } else ret = false; return ret; } static DEFINE_SPINLOCK(rt_uncached_lock); static LIST_HEAD(rt_uncached_list); static void rt_add_uncached_list(struct rtable *rt) { spin_lock_bh(&rt_uncached_lock); list_add_tail(&rt->rt_uncached, &rt_uncached_list); spin_unlock_bh(&rt_uncached_lock); } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *) dst; if (!list_empty(&rt->rt_uncached)) { spin_lock_bh(&rt_uncached_lock); list_del(&rt->rt_uncached); spin_unlock_bh(&rt_uncached_lock); } } void rt_flush_dev(struct net_device *dev) { if (!list_empty(&rt_uncached_list)) { struct net *net = dev_net(dev); struct rtable *rt; spin_lock_bh(&rt_uncached_lock); list_for_each_entry(rt, &rt_uncached_list, 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(&rt_uncached_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) { 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; } dst_init_metrics(&rt->dst, fi->fib_metrics, true); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr); else if (!(rt->dst.flags & DST_NOCACHE)) 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. */ rt->dst.flags |= DST_NOCACHE; 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 } static struct rtable *rt_dst_alloc(struct net_device *dev, bool nopolicy, bool noxfrm, bool will_cache) { return dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : (DST_HOST | DST_NOCACHE)) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 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 rtable *rth; struct in_device *in_dev = __in_dev_get_rcu(dev); u32 itag = 0; int err; /* Primary sanity checks. */ if (in_dev == NULL) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) goto e_inval; if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(saddr)) goto e_inval; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr)) goto e_inval; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto e_err; } rth = rt_dst_alloc(dev_net(dev)->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) goto e_nobufs; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_genid = rt_genid_ipv4(dev_net(dev)); rth->rt_flags = RTCF_MULTICAST; rth->rt_type = RTN_MULTICAST; rth->rt_is_input= 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); if (our) { rth->dst.input= ip_local_deliver; rth->rt_flags |= RTCF_LOCAL; } #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; e_nobufs: return -ENOBUFS; e_inval: return -EINVAL; e_err: return err; } 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, true); } } #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; unsigned int flags = 0; 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 == NULL) { 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 != NULL) 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, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev)); rth->rt_flags = flags; rth->rt_type = res->type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rth->dst.output = ip_output; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag); skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, const struct flowi4 *fl4, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) fib_select_multipath(res); #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 flowi4 fl4; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; int err = -EINVAL; struct net *net = dev_net(dev); 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. */ if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res.fi = 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.daddr = daddr; fl4.saddr = saddr; err = fib_lookup(net, &fl4, &res); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res.type == RTN_BROADCAST) 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_keep_err; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res.type != RTN_UNICAST) goto martian_destination; err = ip_mkroute_input(skb, &res, &fl4, in_dev, daddr, saddr, tos); 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_keep_err; } 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(net->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.input= ip_local_deliver; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_genid = rt_genid_ipv4(net); rth->rt_flags = flags|RTCF_LOCAL; rth->rt_type = res.type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); 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) { if (unlikely(!rt_cache_route(&FIB_RES_NH(res), rth))) { rth->dst.flags |= DST_NOCACHE; 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; 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: err = -EINVAL; martian_source_keep_err: 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) { int res; tos &= IPTOS_RT_MASK; rcu_read_lock(); /* 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); if (in_dev) { int our = ip_check_mc_rcu(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 ) { int res = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); rcu_read_unlock(); return res; } } rcu_read_unlock(); return -EINVAL; } res = ip_route_input_slow(skb, daddr, saddr, tos, dev); rcu_read_unlock(); return res; } EXPORT_SYMBOL(ip_route_input_noref); /* 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)) 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. */ fi = NULL; } fnhe = NULL; do_cache &= fi != NULL; if (do_cache) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); 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(&rth->dst); return rth; } } add: rth = rt_dst_alloc(dev_out, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->dst.output = ip_output; rth->rt_genid = rt_genid_ipv4(dev_net(dev_out)); rth->rt_flags = flags; rth->rt_type = type; rth->rt_is_input = 0; rth->rt_iif = orig_oif ? : 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(out_slow_tot); if (flags & RTCF_LOCAL) rth->dst.input = ip_local_deliver; 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); return rth; } /* * Major route resolver routine. */ struct rtable *__ip_route_output_key(struct net *net, struct flowi4 *fl4) { struct net_device *dev_out = NULL; __u8 tos = RT_FL_TOS(fl4); unsigned int flags = 0; struct fib_result res; struct rtable *rth; int orig_oif; res.tclassid = 0; res.fi = NULL; res.table = NULL; orig_oif = fl4->flowi4_oif; 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(); 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 == NULL) 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 == NULL) 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)) { 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; } if (fib_lookup(net, fl4, &res)) { res.fi = NULL; res.table = NULL; if (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(-ENETUNREACH); 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; } dev_out = net->loopback_dev; fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res.fi->fib_nhs > 1 && fl4->flowi4_oif == 0) fib_select_multipath(&res); else #endif if (!res.prefixlen && res.table->tb_num_default > 1 && res.type == RTN_UNICAST && !fl4->flowi4_oif) fib_select_default(&res); if (!fl4->saddr) fl4->saddr = FIB_RES_PREFSRC(net, res); 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: rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(__ip_route_output_key); 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, .protocol = cpu_to_be16(ETH_P_IP), .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_NONE, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard_sk; new->dev = ort->dst.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_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_free(new); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, 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); static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (nlh == NULL) 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 = RT_TABLE_MAIN; if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) 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_be32(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_be32(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_be32(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_be32(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 (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; 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, nowait, portid); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (skb == NULL) { err = -ENOBUFS; goto errout; } /* 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); /* Bugfix: need to give ip_route_input enough of an IP header to not gag. */ ip_hdr(skb)->protocol = IPPROTO_ICMP; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); src = tb[RTA_SRC] ? nla_get_be32(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_be32(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; memset(&fl4, 0, sizeof(fl4)); 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; if (iif) { struct net_device *dev; dev = __dev_get_by_index(net, iif); if (dev == NULL) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; local_bh_disable(); err = ip_route_input(skb, dst, src, rtm->rtm_tos, dev); local_bh_enable(); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key(net, &fl4); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); } if (err) goto errout_free; skb_dst_set(skb, &rt->dst); if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; err = rt_fill_info(net, dst, src, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0); if (err <= 0) goto errout_free; err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: kfree_skb(skb); goto errout; } 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_timeout __read_mostly = RT_GC_TIMEOUT; 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 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 == NULL) 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 == NULL) 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); get_random_bytes(&net->ipv4.dev_addr_genid, sizeof(net->ipv4.dev_addr_genid)); 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 rc = 0; ip_idents = kmalloc(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)); #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, NULL); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return rc; } #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_759_0
crossvul-cpp_data_good_2750_0
/******************************************************************************* * * Module Name: dsutils - Dispatcher utilities * ******************************************************************************/ /****************************************************************************** * * 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 "acdispat.h" #include "acinterp.h" #include "acnamesp.h" #include "acdebug.h" #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsutils") /******************************************************************************* * * FUNCTION: AcpiDsClearImplicitReturn * * PARAMETERS: WalkState - Current State * * RETURN: None. * * DESCRIPTION: Clear and remove a reference on an implicit return value. Used * to delete "stale" return values (if enabled, the return value * from every operator is saved at least momentarily, in case the * parent method exits.) * ******************************************************************************/ void AcpiDsClearImplicitReturn ( ACPI_WALK_STATE *WalkState) { ACPI_FUNCTION_NAME (DsClearImplicitReturn); /* * Slack must be enabled for this feature */ if (!AcpiGbl_EnableInterpreterSlack) { return; } if (WalkState->ImplicitReturnObj) { /* * Delete any "stale" implicit return. However, in * complex statements, the implicit return value can be * bubbled up several levels. */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Removing reference on stale implicit return obj %p\n", WalkState->ImplicitReturnObj)); AcpiUtRemoveReference (WalkState->ImplicitReturnObj); WalkState->ImplicitReturnObj = NULL; } } #ifndef ACPI_NO_METHOD_EXECUTION /******************************************************************************* * * FUNCTION: AcpiDsDoImplicitReturn * * PARAMETERS: ReturnDesc - The return value * WalkState - Current State * AddReference - True if a reference should be added to the * return object * * RETURN: TRUE if implicit return enabled, FALSE otherwise * * DESCRIPTION: Implements the optional "implicit return". We save the result * of every ASL operator and control method invocation in case the * parent method exit. Before storing a new return value, we * delete the previous return value. * ******************************************************************************/ BOOLEAN AcpiDsDoImplicitReturn ( ACPI_OPERAND_OBJECT *ReturnDesc, ACPI_WALK_STATE *WalkState, BOOLEAN AddReference) { ACPI_FUNCTION_NAME (DsDoImplicitReturn); /* * Slack must be enabled for this feature, and we must * have a valid return object */ if ((!AcpiGbl_EnableInterpreterSlack) || (!ReturnDesc)) { return (FALSE); } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result %p will be implicitly returned; Prev=%p\n", ReturnDesc, WalkState->ImplicitReturnObj)); /* * Delete any "stale" implicit return value first. However, in * complex statements, the implicit return value can be * bubbled up several levels, so we don't clear the value if it * is the same as the ReturnDesc. */ if (WalkState->ImplicitReturnObj) { if (WalkState->ImplicitReturnObj == ReturnDesc) { return (TRUE); } AcpiDsClearImplicitReturn (WalkState); } /* Save the implicit return value, add a reference if requested */ WalkState->ImplicitReturnObj = ReturnDesc; if (AddReference) { AcpiUtAddReference (ReturnDesc); } return (TRUE); } /******************************************************************************* * * FUNCTION: AcpiDsIsResultUsed * * PARAMETERS: Op - Current Op * WalkState - Current State * * RETURN: TRUE if result is used, FALSE otherwise * * DESCRIPTION: Check if a result object will be used by the parent * ******************************************************************************/ BOOLEAN AcpiDsIsResultUsed ( ACPI_PARSE_OBJECT *Op, ACPI_WALK_STATE *WalkState) { const ACPI_OPCODE_INFO *ParentInfo; ACPI_FUNCTION_TRACE_PTR (DsIsResultUsed, Op); /* Must have both an Op and a Result Object */ if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_UINT8 (TRUE); } /* * We know that this operator is not a * Return() operator (would not come here.) The following code is the * optional support for a so-called "implicit return". Some AML code * assumes that the last value of the method is "implicitly" returned * to the caller. Just save the last result as the return value. * NOTE: this is optional because the ASL language does not actually * support this behavior. */ (void) AcpiDsDoImplicitReturn (WalkState->ResultObj, WalkState, TRUE); /* * Now determine if the parent will use the result * * If there is no parent, or the parent is a ScopeOp, we are executing * at the method level. An executing method typically has no parent, * since each method is parsed separately. A method invoked externally * via ExecuteControlMethod has a ScopeOp as the parent. */ if ((!Op->Common.Parent) || (Op->Common.Parent->Common.AmlOpcode == AML_SCOPE_OP)) { /* No parent, the return value cannot possibly be used */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "At Method level, result of [%s] not used\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode))); return_UINT8 (FALSE); } /* Get info on the parent. The RootOp is AML_SCOPE */ ParentInfo = AcpiPsGetOpcodeInfo (Op->Common.Parent->Common.AmlOpcode); if (ParentInfo->Class == AML_CLASS_UNKNOWN) { ACPI_ERROR ((AE_INFO, "Unknown parent opcode Op=%p", Op)); return_UINT8 (FALSE); } /* * Decide what to do with the result based on the parent. If * the parent opcode will not use the result, delete the object. * Otherwise leave it as is, it will be deleted when it is used * as an operand later. */ switch (ParentInfo->Class) { case AML_CLASS_CONTROL: switch (Op->Common.Parent->Common.AmlOpcode) { case AML_RETURN_OP: /* Never delete the return value associated with a return opcode */ goto ResultUsed; case AML_IF_OP: case AML_WHILE_OP: /* * If we are executing the predicate AND this is the predicate op, * we will use the return value */ if ((WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING) && (WalkState->ControlState->Control.PredicateOp == Op)) { goto ResultUsed; } break; default: /* Ignore other control opcodes */ break; } /* The general control opcode returns no result */ goto ResultNotUsed; case AML_CLASS_CREATE: /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; case AML_CLASS_NAMED_OBJECT: if ((Op->Common.Parent->Common.AmlOpcode == AML_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_DATA_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BUFFER_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_INT_EVAL_SUBTREE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BANK_FIELD_OP)) { /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; } goto ResultNotUsed; default: /* * In all other cases. the parent will actually use the return * object, so keep it. */ goto ResultUsed; } ResultUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (TRUE); ResultNotUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] not used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (FALSE); } /******************************************************************************* * * FUNCTION: AcpiDsDeleteResultIfNotUsed * * PARAMETERS: Op - Current parse Op * ResultObj - Result of the operation * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Used after interpretation of an opcode. If there is an internal * result descriptor, check if the parent opcode will actually use * this result. If not, delete the result now so that it will * not become orphaned. * ******************************************************************************/ void AcpiDsDeleteResultIfNotUsed ( ACPI_PARSE_OBJECT *Op, ACPI_OPERAND_OBJECT *ResultObj, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsDeleteResultIfNotUsed, ResultObj); if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_VOID; } if (!ResultObj) { return_VOID; } if (!AcpiDsIsResultUsed (Op, WalkState)) { /* Must pop the result stack (ObjDesc should be equal to ResultObj) */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_SUCCESS (Status)) { AcpiUtRemoveReference (ResultObj); } } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsResolveOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: Status * * DESCRIPTION: Resolve all operands to their values. Used to prepare * arguments to a control method invocation (a call from one * method to another.) * ******************************************************************************/ ACPI_STATUS AcpiDsResolveOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (DsResolveOperands, WalkState); /* * Attempt to resolve each of the valid operands * Method arguments are passed by reference, not by value. This means * that the actual objects are passed, not copies of the objects. */ for (i = 0; i < WalkState->NumOperands; i++) { Status = AcpiExResolveToValue (&WalkState->Operands[i], WalkState); if (ACPI_FAILURE (Status)) { break; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsClearOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: None * * DESCRIPTION: Clear all operands on the current walk state operand stack. * ******************************************************************************/ void AcpiDsClearOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsClearOperands, WalkState); /* Remove a reference on each operand on the stack */ for (i = 0; i < WalkState->NumOperands; i++) { /* * Remove a reference to all operands, including both * "Arguments" and "Targets". */ AcpiUtRemoveReference (WalkState->Operands[i]); WalkState->Operands[i] = NULL; } WalkState->NumOperands = 0; return_VOID; } #endif /******************************************************************************* * * FUNCTION: AcpiDsCreateOperand * * PARAMETERS: WalkState - Current walk state * Arg - Parse object for the argument * ArgIndex - Which argument (zero based) * * RETURN: Status * * DESCRIPTION: Translate a parse tree object that is an argument to an AML * opcode to the equivalent interpreter object. This may include * looking up a name or entering a new name into the internal * namespace. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperand ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Arg, UINT32 ArgIndex) { ACPI_STATUS Status = AE_OK; char *NameString; UINT32 NameLength; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PARSE_OBJECT *ParentOp; UINT16 Opcode; ACPI_INTERPRETER_MODE InterpreterMode; const ACPI_OPCODE_INFO *OpInfo; ACPI_FUNCTION_TRACE_PTR (DsCreateOperand, Arg); /* A valid name must be looked up in the namespace */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && (Arg->Common.Value.String) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Getting a name: Arg=%p\n", Arg)); /* Get the entire name string from the AML stream */ Status = AcpiExGetNameString (ACPI_TYPE_ANY, Arg->Common.Value.Buffer, &NameString, &NameLength); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* All prefixes have been handled, and the name is in NameString */ /* * Special handling for BufferField declarations. This is a deferred * opcode that unfortunately defines the field name as the last * parameter instead of the first. We get here when we are performing * the deferred execution, so the actual name of the field is already * in the namespace. We don't want to attempt to look it up again * because we may be executing in a different scope than where the * actual opcode exists. */ if ((WalkState->DeferredNode) && (WalkState->DeferredNode->Type == ACPI_TYPE_BUFFER_FIELD) && (ArgIndex == (UINT32) ((WalkState->Opcode == AML_CREATE_FIELD_OP) ? 3 : 2))) { ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, WalkState->DeferredNode); Status = AE_OK; } else /* All other opcodes */ { /* * Differentiate between a namespace "create" operation * versus a "lookup" operation (IMODE_LOAD_PASS2 vs. * IMODE_EXECUTE) in order to support the creation of * namespace objects during the execution of control methods. */ ParentOp = Arg->Common.Parent; OpInfo = AcpiPsGetOpcodeInfo (ParentOp->Common.AmlOpcode); if ((OpInfo->Flags & AML_NSNODE) && (ParentOp->Common.AmlOpcode != AML_INT_METHODCALL_OP) && (ParentOp->Common.AmlOpcode != AML_REGION_OP) && (ParentOp->Common.AmlOpcode != AML_INT_NAMEPATH_OP)) { /* Enter name into namespace if not found */ InterpreterMode = ACPI_IMODE_LOAD_PASS2; } else { /* Return a failure if name not found */ InterpreterMode = ACPI_IMODE_EXECUTE; } Status = AcpiNsLookup (WalkState->ScopeInfo, NameString, ACPI_TYPE_ANY, InterpreterMode, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, WalkState, ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, &ObjDesc)); /* * The only case where we pass through (ignore) a NOT_FOUND * error is for the CondRefOf opcode. */ if (Status == AE_NOT_FOUND) { if (ParentOp->Common.AmlOpcode == AML_CONDITIONAL_REF_OF_OP) { /* * For the Conditional Reference op, it's OK if * the name is not found; We just need a way to * indicate this to the interpreter, set the * object to the root */ ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, AcpiGbl_RootNode); Status = AE_OK; } else if (ParentOp->Common.AmlOpcode == AML_EXTERNAL_OP) { /* * This opcode should never appear here. It is used only * by AML disassemblers and is surrounded by an If(0) * by the ASL compiler. * * Therefore, if we see it here, it is a serious error. */ Status = AE_AML_BAD_OPCODE; } else { /* * We just plain didn't find it -- which is a * very serious error at this point */ Status = AE_AML_NAME_NOT_FOUND; } } if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (NameString, Status); } } /* Free the namestring created above */ ACPI_FREE (NameString); /* Check status from the lookup */ if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Put the resulting object onto the current object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } else { /* Check for null name case */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * If the name is null, this means that this is an * optional result parameter that was not specified * in the original ASL. Create a Zero Constant for a * placeholder. (Store to a constant is a Noop.) */ Opcode = AML_ZERO_OP; /* Has no arguments! */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Null namepath: Arg=%p\n", Arg)); } else { Opcode = Arg->Common.AmlOpcode; } /* Get the object type of the argument */ OpInfo = AcpiPsGetOpcodeInfo (Opcode); if (OpInfo->ObjectType == ACPI_TYPE_INVALID) { return_ACPI_STATUS (AE_NOT_IMPLEMENTED); } if ((OpInfo->Flags & AML_HAS_RETVAL) || (Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * Use value that was already previously returned * by the evaluation of this argument */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { /* * Only error is underflow, and this indicates * a missing or null operand! */ ACPI_EXCEPTION ((AE_INFO, Status, "Missing or null operand")); return_ACPI_STATUS (Status); } } else { /* Create an ACPI_INTERNAL_OBJECT for the argument */ ObjDesc = AcpiUtCreateInternalObject (OpInfo->ObjectType); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize the new object */ Status = AcpiDsInitObjectFromOp ( WalkState, Arg, Opcode, &ObjDesc); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (Status); } } /* Put the operand object on the object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsCreateOperands * * PARAMETERS: WalkState - Current state * FirstArg - First argument of a parser argument tree * * RETURN: Status * * DESCRIPTION: Convert an operator's arguments from a parse tree format to * namespace objects and place those argument object on the object * stack in preparation for evaluation by the interpreter. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 PrevNumOperands = WalkState->NumOperands; UINT32 NewNumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ NewNumOperands = Index; Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ WalkState->NumOperands = i; AcpiDsObjStackPopAndDelete (NewNumOperands, WalkState); /* Restore operand count */ WalkState->NumOperands = PrevNumOperands; ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); } /***************************************************************************** * * FUNCTION: AcpiDsEvaluateNamePath * * PARAMETERS: WalkState - Current state of the parse tree walk, * the opcode of current operation should be * AML_INT_NAMEPATH_OP * * RETURN: Status * * DESCRIPTION: Translate the -NamePath- parse tree object to the equivalent * interpreter object, convert it to value, if needed, duplicate * it, if needed, and push it onto the current result stack. * ****************************************************************************/ ACPI_STATUS AcpiDsEvaluateNamePath ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op = WalkState->Op; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_OPERAND_OBJECT *NewObjDesc; UINT8 Type; ACPI_FUNCTION_TRACE_PTR (DsEvaluateNamePath, WalkState); if (!Op->Common.Parent) { /* This happens after certain exception processing */ goto Exit; } if ((Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_REF_OF_OP)) { /* TBD: Should we specify this feature as a bit of OpInfo->Flags of these opcodes? */ goto Exit; } Status = AcpiDsCreateOperand (WalkState, Op, 0); if (ACPI_FAILURE (Status)) { goto Exit; } if (Op->Common.Flags & ACPI_PARSEOP_TARGET) { NewObjDesc = *Operand; goto PushResult; } Type = (*Operand)->Common.Type; Status = AcpiExResolveToValue (Operand, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } if (Type == ACPI_TYPE_INTEGER) { /* It was incremented by AcpiExResolveToValue */ AcpiUtRemoveReference (*Operand); Status = AcpiUtCopyIobjectToIobject ( *Operand, &NewObjDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } } else { /* * The object either was anew created or is * a Namespace node - don't decrement it. */ NewObjDesc = *Operand; } /* Cleanup for name-path operand */ Status = AcpiDsObjStackPop (1, WalkState); if (ACPI_FAILURE (Status)) { WalkState->ResultObj = NewObjDesc; goto Exit; } PushResult: WalkState->ResultObj = NewObjDesc; Status = AcpiDsResultPush (WalkState->ResultObj, WalkState); if (ACPI_SUCCESS (Status)) { /* Force to take it from stack */ Op->Common.Flags |= ACPI_PARSEOP_IN_STACK; } Exit: return_ACPI_STATUS (Status); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2750_0
crossvul-cpp_data_bad_5683_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 address family and sockets. */ #include <linux/module.h> #include <asm/ioctls.h> #include <net/bluetooth/bluetooth.h> #include <linux/proc_fs.h> #define VERSION "2.16" /* Bluetooth sockets */ #define BT_MAX_PROTO 8 static const struct net_proto_family *bt_proto[BT_MAX_PROTO]; static DEFINE_RWLOCK(bt_proto_lock); static struct lock_class_key bt_lock_key[BT_MAX_PROTO]; static const char *const bt_key_strings[BT_MAX_PROTO] = { "sk_lock-AF_BLUETOOTH-BTPROTO_L2CAP", "sk_lock-AF_BLUETOOTH-BTPROTO_HCI", "sk_lock-AF_BLUETOOTH-BTPROTO_SCO", "sk_lock-AF_BLUETOOTH-BTPROTO_RFCOMM", "sk_lock-AF_BLUETOOTH-BTPROTO_BNEP", "sk_lock-AF_BLUETOOTH-BTPROTO_CMTP", "sk_lock-AF_BLUETOOTH-BTPROTO_HIDP", "sk_lock-AF_BLUETOOTH-BTPROTO_AVDTP", }; static struct lock_class_key bt_slock_key[BT_MAX_PROTO]; static const char *const bt_slock_key_strings[BT_MAX_PROTO] = { "slock-AF_BLUETOOTH-BTPROTO_L2CAP", "slock-AF_BLUETOOTH-BTPROTO_HCI", "slock-AF_BLUETOOTH-BTPROTO_SCO", "slock-AF_BLUETOOTH-BTPROTO_RFCOMM", "slock-AF_BLUETOOTH-BTPROTO_BNEP", "slock-AF_BLUETOOTH-BTPROTO_CMTP", "slock-AF_BLUETOOTH-BTPROTO_HIDP", "slock-AF_BLUETOOTH-BTPROTO_AVDTP", }; void bt_sock_reclassify_lock(struct sock *sk, int proto) { BUG_ON(!sk); BUG_ON(sock_owned_by_user(sk)); sock_lock_init_class_and_name(sk, bt_slock_key_strings[proto], &bt_slock_key[proto], bt_key_strings[proto], &bt_lock_key[proto]); } EXPORT_SYMBOL(bt_sock_reclassify_lock); int bt_sock_register(int proto, const struct net_proto_family *ops) { int err = 0; if (proto < 0 || proto >= BT_MAX_PROTO) return -EINVAL; write_lock(&bt_proto_lock); if (bt_proto[proto]) err = -EEXIST; else bt_proto[proto] = ops; write_unlock(&bt_proto_lock); return err; } EXPORT_SYMBOL(bt_sock_register); int bt_sock_unregister(int proto) { int err = 0; if (proto < 0 || proto >= BT_MAX_PROTO) return -EINVAL; write_lock(&bt_proto_lock); if (!bt_proto[proto]) err = -ENOENT; else bt_proto[proto] = NULL; write_unlock(&bt_proto_lock); return err; } EXPORT_SYMBOL(bt_sock_unregister); static int bt_sock_create(struct net *net, struct socket *sock, int proto, int kern) { int err; if (net != &init_net) return -EAFNOSUPPORT; if (proto < 0 || proto >= BT_MAX_PROTO) return -EINVAL; if (!bt_proto[proto]) request_module("bt-proto-%d", proto); err = -EPROTONOSUPPORT; read_lock(&bt_proto_lock); if (bt_proto[proto] && try_module_get(bt_proto[proto]->owner)) { err = bt_proto[proto]->create(net, sock, proto, kern); if (!err) bt_sock_reclassify_lock(sock->sk, proto); module_put(bt_proto[proto]->owner); } read_unlock(&bt_proto_lock); return err; } void bt_sock_link(struct bt_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_add_node(sk, &l->head); write_unlock(&l->lock); } EXPORT_SYMBOL(bt_sock_link); void bt_sock_unlink(struct bt_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_del_node_init(sk); write_unlock(&l->lock); } EXPORT_SYMBOL(bt_sock_unlink); void bt_accept_enqueue(struct sock *parent, struct sock *sk) { BT_DBG("parent %p, sk %p", parent, sk); sock_hold(sk); list_add_tail(&bt_sk(sk)->accept_q, &bt_sk(parent)->accept_q); bt_sk(sk)->parent = parent; parent->sk_ack_backlog++; } EXPORT_SYMBOL(bt_accept_enqueue); void bt_accept_unlink(struct sock *sk) { BT_DBG("sk %p state %d", sk, sk->sk_state); list_del_init(&bt_sk(sk)->accept_q); bt_sk(sk)->parent->sk_ack_backlog--; bt_sk(sk)->parent = NULL; sock_put(sk); } EXPORT_SYMBOL(bt_accept_unlink); struct sock *bt_accept_dequeue(struct sock *parent, struct socket *newsock) { struct list_head *p, *n; struct sock *sk; BT_DBG("parent %p", parent); list_for_each_safe(p, n, &bt_sk(parent)->accept_q) { sk = (struct sock *) list_entry(p, struct bt_sock, accept_q); lock_sock(sk); /* FIXME: Is this check still needed */ if (sk->sk_state == BT_CLOSED) { release_sock(sk); bt_accept_unlink(sk); continue; } if (sk->sk_state == BT_CONNECTED || !newsock || test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) { bt_accept_unlink(sk); if (newsock) sock_graft(sk, newsock); release_sock(sk); return sk; } release_sock(sk); } return NULL; } EXPORT_SYMBOL(bt_accept_dequeue); int bt_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; size_t copied; int err; BT_DBG("sock %p sk %p len %zu", sock, sk, len); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; 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); if (err == 0) sock_recv_ts_and_drops(msg, sk, skb); skb_free_datagram(sk, skb); return err ? : copied; } EXPORT_SYMBOL(bt_sock_recvmsg); static long bt_sock_data_wait(struct sock *sk, long timeo) { DECLARE_WAITQUEUE(wait, current); add_wait_queue(sk_sleep(sk), &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (!skb_queue_empty(&sk->sk_receive_queue)) break; if (sk->sk_err || (sk->sk_shutdown & RCV_SHUTDOWN)) break; if (signal_pending(current) || !timeo) break; set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); return timeo; } int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int err = 0; size_t target, copied = 0; long timeo; if (flags & MSG_OOB) return -EOPNOTSUPP; msg->msg_namelen = 0; BT_DBG("sk %p size %zu", sk, size); lock_sock(sk); target = sock_rcvlowat(sk, flags & MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); do { struct sk_buff *skb; int chunk; skb = skb_dequeue(&sk->sk_receive_queue); if (!skb) { if (copied >= target) break; err = sock_error(sk); if (err) break; if (sk->sk_shutdown & RCV_SHUTDOWN) break; err = -EAGAIN; if (!timeo) break; timeo = bt_sock_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } continue; } chunk = min_t(unsigned int, skb->len, size); if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (!copied) copied = -EFAULT; break; } copied += chunk; size -= chunk; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { int skb_len = skb_headlen(skb); if (chunk <= skb_len) { __skb_pull(skb, chunk); } else { struct sk_buff *frag; __skb_pull(skb, skb_len); chunk -= skb_len; skb_walk_frags(skb, frag) { if (chunk <= frag->len) { /* Pulling partial data */ skb->len -= chunk; skb->data_len -= chunk; __skb_pull(frag, chunk); break; } else if (frag->len) { /* Pulling all frag data */ chunk -= frag->len; skb->len -= frag->len; skb->data_len -= frag->len; __skb_pull(frag, frag->len); } } } if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); out: release_sock(sk); return copied ? : err; } EXPORT_SYMBOL(bt_sock_stream_recvmsg); static inline unsigned int bt_accept_poll(struct sock *parent) { struct list_head *p, *n; struct sock *sk; list_for_each_safe(p, n, &bt_sk(parent)->accept_q) { sk = (struct sock *) list_entry(p, struct bt_sock, accept_q); if (sk->sk_state == BT_CONNECTED || (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags) && sk->sk_state == BT_CONNECT2)) return POLLIN | POLLRDNORM; } return 0; } unsigned int bt_sock_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask = 0; BT_DBG("sock %p, sk %p", sock, sk); poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == BT_LISTEN) return bt_accept_poll(sk); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; if (sk->sk_state == BT_CLOSED) mask |= POLLHUP; if (sk->sk_state == BT_CONNECT || sk->sk_state == BT_CONNECT2 || sk->sk_state == BT_CONFIG) return mask; if (!test_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags) && sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); return mask; } EXPORT_SYMBOL(bt_sock_poll); int bt_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; struct sk_buff *skb; long amount; int err; BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg); switch (cmd) { case TIOCOUTQ: if (sk->sk_state == BT_LISTEN) return -EINVAL; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; err = put_user(amount, (int __user *) arg); break; case TIOCINQ: if (sk->sk_state == BT_LISTEN) return -EINVAL; lock_sock(sk); skb = skb_peek(&sk->sk_receive_queue); amount = skb ? skb->len : 0; release_sock(sk); err = put_user(amount, (int __user *) arg); break; case SIOCGSTAMP: err = sock_get_timestamp(sk, (struct timeval __user *) arg); break; case SIOCGSTAMPNS: err = sock_get_timestampns(sk, (struct timespec __user *) arg); break; default: err = -ENOIOCTLCMD; break; } return err; } EXPORT_SYMBOL(bt_sock_ioctl); int bt_sock_wait_state(struct sock *sk, int state, unsigned long timeo) { DECLARE_WAITQUEUE(wait, current); int err = 0; BT_DBG("sk %p", sk); add_wait_queue(sk_sleep(sk), &wait); set_current_state(TASK_INTERRUPTIBLE); while (sk->sk_state != state) { if (!timeo) { err = -EINPROGRESS; 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_INTERRUPTIBLE); err = sock_error(sk); if (err) break; } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); return err; } EXPORT_SYMBOL(bt_sock_wait_state); #ifdef CONFIG_PROC_FS struct bt_seq_state { struct bt_sock_list *l; }; static void *bt_seq_start(struct seq_file *seq, loff_t *pos) __acquires(seq->private->l->lock) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; read_lock(&l->lock); return seq_hlist_start_head(&l->head, *pos); } static void *bt_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; return seq_hlist_next(v, &l->head, pos); } static void bt_seq_stop(struct seq_file *seq, void *v) __releases(seq->private->l->lock) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; read_unlock(&l->lock); } static int bt_seq_show(struct seq_file *seq, void *v) { struct bt_seq_state *s = seq->private; struct bt_sock_list *l = s->l; if (v == SEQ_START_TOKEN) { seq_puts(seq ,"sk RefCnt Rmem Wmem User Inode Src Dst Parent"); if (l->custom_seq_show) { seq_putc(seq, ' '); l->custom_seq_show(seq, v); } seq_putc(seq, '\n'); } else { struct sock *sk = sk_entry(v); struct bt_sock *bt = bt_sk(sk); seq_printf(seq, "%pK %-6d %-6u %-6u %-6u %-6lu %pMR %pMR %-6lu", sk, atomic_read(&sk->sk_refcnt), sk_rmem_alloc_get(sk), sk_wmem_alloc_get(sk), from_kuid(seq_user_ns(seq), sock_i_uid(sk)), sock_i_ino(sk), &bt->src, &bt->dst, bt->parent? sock_i_ino(bt->parent): 0LU); if (l->custom_seq_show) { seq_putc(seq, ' '); l->custom_seq_show(seq, v); } seq_putc(seq, '\n'); } return 0; } static struct seq_operations bt_seq_ops = { .start = bt_seq_start, .next = bt_seq_next, .stop = bt_seq_stop, .show = bt_seq_show, }; static int bt_seq_open(struct inode *inode, struct file *file) { struct bt_sock_list *sk_list; struct bt_seq_state *s; sk_list = PDE(inode)->data; s = __seq_open_private(file, &bt_seq_ops, sizeof(struct bt_seq_state)); if (!s) return -ENOMEM; s->l = sk_list; return 0; } int bt_procfs_init(struct module* module, struct net *net, const char *name, struct bt_sock_list* sk_list, int (* seq_show)(struct seq_file *, void *)) { struct proc_dir_entry * pde; sk_list->custom_seq_show = seq_show; sk_list->fops.owner = module; sk_list->fops.open = bt_seq_open; sk_list->fops.read = seq_read; sk_list->fops.llseek = seq_lseek; sk_list->fops.release = seq_release_private; pde = proc_create(name, 0, net->proc_net, &sk_list->fops); if (!pde) return -ENOMEM; pde->data = sk_list; return 0; } void bt_procfs_cleanup(struct net *net, const char *name) { remove_proc_entry(name, net->proc_net); } #else int bt_procfs_init(struct module* module, struct net *net, const char *name, struct bt_sock_list* sk_list, int (* seq_show)(struct seq_file *, void *)) { return 0; } void bt_procfs_cleanup(struct net *net, const char *name) { } #endif EXPORT_SYMBOL(bt_procfs_init); EXPORT_SYMBOL(bt_procfs_cleanup); static struct net_proto_family bt_sock_family_ops = { .owner = THIS_MODULE, .family = PF_BLUETOOTH, .create = bt_sock_create, }; static int __init bt_init(void) { int err; BT_INFO("Core ver %s", VERSION); err = bt_sysfs_init(); if (err < 0) return err; err = sock_register(&bt_sock_family_ops); if (err < 0) { bt_sysfs_cleanup(); return err; } BT_INFO("HCI device and connection manager initialized"); err = hci_sock_init(); if (err < 0) goto error; err = l2cap_init(); if (err < 0) goto sock_err; err = sco_init(); if (err < 0) { l2cap_exit(); goto sock_err; } return 0; sock_err: hci_sock_cleanup(); error: sock_unregister(PF_BLUETOOTH); bt_sysfs_cleanup(); return err; } static void __exit bt_exit(void) { sco_exit(); l2cap_exit(); hci_sock_cleanup(); sock_unregister(PF_BLUETOOTH); bt_sysfs_cleanup(); } subsys_initcall(bt_init); module_exit(bt_exit); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Bluetooth Core ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_BLUETOOTH);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5683_0
crossvul-cpp_data_good_5687_0
/********************************************************************* * * Filename: af_irda.c * Version: 0.9 * Description: IrDA sockets implementation * Status: Stable * Author: Dag Brattli <dagb@cs.uit.no> * Created at: Sun May 31 10:12:43 1998 * Modified at: Sat Dec 25 21:10:23 1999 * Modified by: Dag Brattli <dag@brattli.net> * Sources: af_netroom.c, af_ax25.c, af_rose.c, af_x25.c etc. * * Copyright (c) 1999 Dag Brattli <dagb@cs.uit.no> * Copyright (c) 1999-2003 Jean Tourrilhes <jt@hpl.hp.com> * 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; 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 * * Linux-IrDA now supports four different types of IrDA sockets: * * o SOCK_STREAM: TinyTP connections with SAR disabled. The * max SDU size is 0 for conn. of this type * o SOCK_SEQPACKET: TinyTP connections with SAR enabled. TTP may * fragment the messages, but will preserve * the message boundaries * o SOCK_DGRAM: IRDAPROTO_UNITDATA: TinyTP connections with Unitdata * (unreliable) transfers * IRDAPROTO_ULTRA: Connectionless and unreliable data * ********************************************************************/ #include <linux/capability.h> #include <linux/module.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/net.h> #include <linux/irda.h> #include <linux/poll.h> #include <asm/ioctls.h> /* TIOCOUTQ, TIOCINQ */ #include <asm/uaccess.h> #include <net/sock.h> #include <net/tcp_states.h> #include <net/irda/af_irda.h> static int irda_create(struct net *net, struct socket *sock, int protocol, int kern); static const struct proto_ops irda_stream_ops; static const struct proto_ops irda_seqpacket_ops; static const struct proto_ops irda_dgram_ops; #ifdef CONFIG_IRDA_ULTRA static const struct proto_ops irda_ultra_ops; #define ULTRA_MAX_DATA 382 #endif /* CONFIG_IRDA_ULTRA */ #define IRDA_MAX_HEADER (TTP_MAX_HEADER) /* * Function irda_data_indication (instance, sap, skb) * * Received some data from TinyTP. Just queue it on the receive queue * */ static int irda_data_indication(void *instance, void *sap, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; int err; IRDA_DEBUG(3, "%s()\n", __func__); self = instance; sk = instance; err = sock_queue_rcv_skb(sk, skb); if (err) { IRDA_DEBUG(1, "%s(), error: no more mem!\n", __func__); self->rx_flow = FLOW_STOP; /* When we return error, TTP will need to requeue the skb */ return err; } return 0; } /* * Function irda_disconnect_indication (instance, sap, reason, skb) * * Connection has been closed. Check reason to find out why * */ static void irda_disconnect_indication(void *instance, void *sap, LM_REASON reason, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; self = instance; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); /* Don't care about it, but let's not leak it */ if(skb) dev_kfree_skb(skb); sk = instance; if (sk == NULL) { IRDA_DEBUG(0, "%s(%p) : BUG : sk is NULL\n", __func__, self); return; } /* Prevent race conditions with irda_release() and irda_shutdown() */ bh_lock_sock(sk); if (!sock_flag(sk, SOCK_DEAD) && sk->sk_state != TCP_CLOSE) { sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); /* Close our TSAP. * If we leave it open, IrLMP put it back into the list of * unconnected LSAPs. The problem is that any incoming request * can then be matched to this socket (and it will be, because * it is at the head of the list). This would prevent any * listening socket waiting on the same TSAP to get those * requests. Some apps forget to close sockets, or hang to it * a bit too long, so we may stay in this dead state long * enough to be noticed... * Note : all socket function do check sk->sk_state, so we are * safe... * Jean II */ if (self->tsap) { irttp_close_tsap(self->tsap); self->tsap = NULL; } } bh_unlock_sock(sk); /* Note : once we are there, there is not much you want to do * with the socket anymore, apart from closing it. * For example, bind() and connect() won't reset sk->sk_err, * sk->sk_shutdown and sk->sk_flags to valid values... * Jean II */ } /* * Function irda_connect_confirm (instance, sap, qos, max_sdu_size, skb) * * Connections has been confirmed by the remote device * */ static void irda_connect_confirm(void *instance, void *sap, struct qos_info *qos, __u32 max_sdu_size, __u8 max_header_size, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; self = instance; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); sk = instance; if (sk == NULL) { dev_kfree_skb(skb); return; } dev_kfree_skb(skb); // Should be ??? skb_queue_tail(&sk->sk_receive_queue, skb); /* How much header space do we need to reserve */ self->max_header_size = max_header_size; /* IrTTP max SDU size in transmit direction */ self->max_sdu_size_tx = max_sdu_size; /* Find out what the largest chunk of data that we can transmit is */ switch (sk->sk_type) { case SOCK_STREAM: if (max_sdu_size != 0) { IRDA_ERROR("%s: max_sdu_size must be 0\n", __func__); return; } self->max_data_size = irttp_get_max_seg_size(self->tsap); break; case SOCK_SEQPACKET: if (max_sdu_size == 0) { IRDA_ERROR("%s: max_sdu_size cannot be 0\n", __func__); return; } self->max_data_size = max_sdu_size; break; default: self->max_data_size = irttp_get_max_seg_size(self->tsap); } IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__, self->max_data_size); memcpy(&self->qos_tx, qos, sizeof(struct qos_info)); /* We are now connected! */ sk->sk_state = TCP_ESTABLISHED; sk->sk_state_change(sk); } /* * Function irda_connect_indication(instance, sap, qos, max_sdu_size, userdata) * * Incoming connection * */ static void irda_connect_indication(void *instance, void *sap, struct qos_info *qos, __u32 max_sdu_size, __u8 max_header_size, struct sk_buff *skb) { struct irda_sock *self; struct sock *sk; self = instance; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); sk = instance; if (sk == NULL) { dev_kfree_skb(skb); return; } /* How much header space do we need to reserve */ self->max_header_size = max_header_size; /* IrTTP max SDU size in transmit direction */ self->max_sdu_size_tx = max_sdu_size; /* Find out what the largest chunk of data that we can transmit is */ switch (sk->sk_type) { case SOCK_STREAM: if (max_sdu_size != 0) { IRDA_ERROR("%s: max_sdu_size must be 0\n", __func__); kfree_skb(skb); return; } self->max_data_size = irttp_get_max_seg_size(self->tsap); break; case SOCK_SEQPACKET: if (max_sdu_size == 0) { IRDA_ERROR("%s: max_sdu_size cannot be 0\n", __func__); kfree_skb(skb); return; } self->max_data_size = max_sdu_size; break; default: self->max_data_size = irttp_get_max_seg_size(self->tsap); } IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__, self->max_data_size); memcpy(&self->qos_tx, qos, sizeof(struct qos_info)); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_state_change(sk); } /* * Function irda_connect_response (handle) * * Accept incoming connection * */ static void irda_connect_response(struct irda_sock *self) { struct sk_buff *skb; IRDA_DEBUG(2, "%s()\n", __func__); skb = alloc_skb(TTP_MAX_HEADER + TTP_SAR_HEADER, GFP_ATOMIC); if (skb == NULL) { IRDA_DEBUG(0, "%s() Unable to allocate sk_buff!\n", __func__); return; } /* Reserve space for MUX_CONTROL and LAP header */ skb_reserve(skb, IRDA_MAX_HEADER); irttp_connect_response(self->tsap, self->max_sdu_size_rx, skb); } /* * Function irda_flow_indication (instance, sap, flow) * * Used by TinyTP to tell us if it can accept more data or not * */ static void irda_flow_indication(void *instance, void *sap, LOCAL_FLOW flow) { struct irda_sock *self; struct sock *sk; IRDA_DEBUG(2, "%s()\n", __func__); self = instance; sk = instance; BUG_ON(sk == NULL); switch (flow) { case FLOW_STOP: IRDA_DEBUG(1, "%s(), IrTTP wants us to slow down\n", __func__); self->tx_flow = flow; break; case FLOW_START: self->tx_flow = flow; IRDA_DEBUG(1, "%s(), IrTTP wants us to start again\n", __func__); wake_up_interruptible(sk_sleep(sk)); break; default: IRDA_DEBUG(0, "%s(), Unknown flow command!\n", __func__); /* Unknown flow command, better stop */ self->tx_flow = flow; break; } } /* * Function irda_getvalue_confirm (obj_id, value, priv) * * Got answer from remote LM-IAS, just pass object to requester... * * Note : duplicate from above, but we need our own version that * doesn't touch the dtsap_sel and save the full value structure... */ static void irda_getvalue_confirm(int result, __u16 obj_id, struct ias_value *value, void *priv) { struct irda_sock *self; self = priv; if (!self) { IRDA_WARNING("%s: lost myself!\n", __func__); return; } IRDA_DEBUG(2, "%s(%p)\n", __func__, self); /* We probably don't need to make any more queries */ iriap_close(self->iriap); self->iriap = NULL; /* Check if request succeeded */ if (result != IAS_SUCCESS) { IRDA_DEBUG(1, "%s(), IAS query failed! (%d)\n", __func__, result); self->errno = result; /* We really need it later */ /* Wake up any processes waiting for result */ wake_up_interruptible(&self->query_wait); return; } /* Pass the object to the caller (so the caller must delete it) */ self->ias_result = value; self->errno = 0; /* Wake up any processes waiting for result */ wake_up_interruptible(&self->query_wait); } /* * Function irda_selective_discovery_indication (discovery) * * Got a selective discovery indication from IrLMP. * * IrLMP is telling us that this node is new and matching our hint bit * filter. Wake up any process waiting for answer... */ static void irda_selective_discovery_indication(discinfo_t *discovery, DISCOVERY_MODE mode, void *priv) { struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); self = priv; if (!self) { IRDA_WARNING("%s: lost myself!\n", __func__); return; } /* Pass parameter to the caller */ self->cachedaddr = discovery->daddr; /* Wake up process if its waiting for device to be discovered */ wake_up_interruptible(&self->query_wait); } /* * Function irda_discovery_timeout (priv) * * Timeout in the selective discovery process * * We were waiting for a node to be discovered, but nothing has come up * so far. Wake up the user and tell him that we failed... */ static void irda_discovery_timeout(u_long priv) { struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); self = (struct irda_sock *) priv; BUG_ON(self == NULL); /* Nothing for the caller */ self->cachelog = NULL; self->cachedaddr = 0; self->errno = -ETIME; /* Wake up process if its still waiting... */ wake_up_interruptible(&self->query_wait); } /* * Function irda_open_tsap (self) * * Open local Transport Service Access Point (TSAP) * */ static int irda_open_tsap(struct irda_sock *self, __u8 tsap_sel, char *name) { notify_t notify; if (self->tsap) { IRDA_DEBUG(0, "%s: busy!\n", __func__); return -EBUSY; } /* Initialize callbacks to be used by the IrDA stack */ irda_notify_init(&notify); notify.connect_confirm = irda_connect_confirm; notify.connect_indication = irda_connect_indication; notify.disconnect_indication = irda_disconnect_indication; notify.data_indication = irda_data_indication; notify.udata_indication = irda_data_indication; notify.flow_indication = irda_flow_indication; notify.instance = self; strncpy(notify.name, name, NOTIFY_MAX_NAME); self->tsap = irttp_open_tsap(tsap_sel, DEFAULT_INITIAL_CREDIT, &notify); if (self->tsap == NULL) { IRDA_DEBUG(0, "%s(), Unable to allocate TSAP!\n", __func__); return -ENOMEM; } /* Remember which TSAP selector we actually got */ self->stsap_sel = self->tsap->stsap_sel; return 0; } /* * Function irda_open_lsap (self) * * Open local Link Service Access Point (LSAP). Used for opening Ultra * sockets */ #ifdef CONFIG_IRDA_ULTRA static int irda_open_lsap(struct irda_sock *self, int pid) { notify_t notify; if (self->lsap) { IRDA_WARNING("%s(), busy!\n", __func__); return -EBUSY; } /* Initialize callbacks to be used by the IrDA stack */ irda_notify_init(&notify); notify.udata_indication = irda_data_indication; notify.instance = self; strncpy(notify.name, "Ultra", NOTIFY_MAX_NAME); self->lsap = irlmp_open_lsap(LSAP_CONNLESS, &notify, pid); if (self->lsap == NULL) { IRDA_DEBUG( 0, "%s(), Unable to allocate LSAP!\n", __func__); return -ENOMEM; } return 0; } #endif /* CONFIG_IRDA_ULTRA */ /* * Function irda_find_lsap_sel (self, name) * * Try to lookup LSAP selector in remote LM-IAS * * Basically, we start a IAP query, and then go to sleep. When the query * return, irda_getvalue_confirm will wake us up, and we can examine the * result of the query... * Note that in some case, the query fail even before we go to sleep, * creating some races... */ static int irda_find_lsap_sel(struct irda_sock *self, char *name) { IRDA_DEBUG(2, "%s(%p, %s)\n", __func__, self, name); if (self->iriap) { IRDA_WARNING("%s(): busy with a previous query\n", __func__); return -EBUSY; } self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self, irda_getvalue_confirm); if(self->iriap == NULL) return -ENOMEM; /* Treat unexpected wakeup as disconnect */ self->errno = -EHOSTUNREACH; /* Query remote LM-IAS */ iriap_getvaluebyclass_request(self->iriap, self->saddr, self->daddr, name, "IrDA:TinyTP:LsapSel"); /* Wait for answer, if not yet finished (or failed) */ if (wait_event_interruptible(self->query_wait, (self->iriap==NULL))) /* Treat signals as disconnect */ return -EHOSTUNREACH; /* Check what happened */ if (self->errno) { /* Requested object/attribute doesn't exist */ if((self->errno == IAS_CLASS_UNKNOWN) || (self->errno == IAS_ATTRIB_UNKNOWN)) return -EADDRNOTAVAIL; else return -EHOSTUNREACH; } /* Get the remote TSAP selector */ switch (self->ias_result->type) { case IAS_INTEGER: IRDA_DEBUG(4, "%s() int=%d\n", __func__, self->ias_result->t.integer); if (self->ias_result->t.integer != -1) self->dtsap_sel = self->ias_result->t.integer; else self->dtsap_sel = 0; break; default: self->dtsap_sel = 0; IRDA_DEBUG(0, "%s(), bad type!\n", __func__); break; } if (self->ias_result) irias_delete_value(self->ias_result); if (self->dtsap_sel) return 0; return -EADDRNOTAVAIL; } /* * Function irda_discover_daddr_and_lsap_sel (self, name) * * This try to find a device with the requested service. * * It basically look into the discovery log. For each address in the list, * it queries the LM-IAS of the device to find if this device offer * the requested service. * If there is more than one node supporting the service, we complain * to the user (it should move devices around). * The, we set both the destination address and the lsap selector to point * on the service on the unique device we have found. * * Note : this function fails if there is more than one device in range, * because IrLMP doesn't disconnect the LAP when the last LSAP is closed. * Moreover, we would need to wait the LAP disconnection... */ static int irda_discover_daddr_and_lsap_sel(struct irda_sock *self, char *name) { discinfo_t *discoveries; /* Copy of the discovery log */ int number; /* Number of nodes in the log */ int i; int err = -ENETUNREACH; __u32 daddr = DEV_ADDR_ANY; /* Address we found the service on */ __u8 dtsap_sel = 0x0; /* TSAP associated with it */ IRDA_DEBUG(2, "%s(), name=%s\n", __func__, name); /* Ask lmp for the current discovery log * Note : we have to use irlmp_get_discoveries(), as opposed * to play with the cachelog directly, because while we are * making our ias query, le log might change... */ discoveries = irlmp_get_discoveries(&number, self->mask.word, self->nslots); /* Check if the we got some results */ if (discoveries == NULL) return -ENETUNREACH; /* No nodes discovered */ /* * Now, check all discovered devices (if any), and connect * client only about the services that the client is * interested in... */ for(i = 0; i < number; i++) { /* Try the address in the log */ self->daddr = discoveries[i].daddr; self->saddr = 0x0; IRDA_DEBUG(1, "%s(), trying daddr = %08x\n", __func__, self->daddr); /* Query remote LM-IAS for this service */ err = irda_find_lsap_sel(self, name); switch (err) { case 0: /* We found the requested service */ if(daddr != DEV_ADDR_ANY) { IRDA_DEBUG(1, "%s(), discovered service ''%s'' in two different devices !!!\n", __func__, name); self->daddr = DEV_ADDR_ANY; kfree(discoveries); return -ENOTUNIQ; } /* First time we found that one, save it ! */ daddr = self->daddr; dtsap_sel = self->dtsap_sel; break; case -EADDRNOTAVAIL: /* Requested service simply doesn't exist on this node */ break; default: /* Something bad did happen :-( */ IRDA_DEBUG(0, "%s(), unexpected IAS query failure\n", __func__); self->daddr = DEV_ADDR_ANY; kfree(discoveries); return -EHOSTUNREACH; break; } } /* Cleanup our copy of the discovery log */ kfree(discoveries); /* Check out what we found */ if(daddr == DEV_ADDR_ANY) { IRDA_DEBUG(1, "%s(), cannot discover service ''%s'' in any device !!!\n", __func__, name); self->daddr = DEV_ADDR_ANY; return -EADDRNOTAVAIL; } /* Revert back to discovered device & service */ self->daddr = daddr; self->saddr = 0x0; self->dtsap_sel = dtsap_sel; IRDA_DEBUG(1, "%s(), discovered requested service ''%s'' at address %08x\n", __func__, name, self->daddr); return 0; } /* * Function irda_getname (sock, uaddr, uaddr_len, peer) * * Return the our own, or peers socket address (sockaddr_irda) * */ static int irda_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_irda saddr; struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); memset(&saddr, 0, sizeof(saddr)); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->dtsap_sel; saddr.sir_addr = self->daddr; } else { saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->stsap_sel; saddr.sir_addr = self->saddr; } IRDA_DEBUG(1, "%s(), tsap_sel = %#x\n", __func__, saddr.sir_lsap_sel); IRDA_DEBUG(1, "%s(), addr = %08x\n", __func__, saddr.sir_addr); /* uaddr_len come to us uninitialised */ *uaddr_len = sizeof (struct sockaddr_irda); memcpy(uaddr, &saddr, *uaddr_len); return 0; } /* * Function irda_listen (sock, backlog) * * Just move to the listen state * */ static int irda_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = -EOPNOTSUPP; IRDA_DEBUG(2, "%s()\n", __func__); lock_sock(sk); if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) && (sk->sk_type != SOCK_DGRAM)) goto out; if (sk->sk_state != TCP_LISTEN) { sk->sk_max_ack_backlog = backlog; sk->sk_state = TCP_LISTEN; err = 0; } out: release_sock(sk); return err; } /* * Function irda_bind (sock, uaddr, addr_len) * * Used by servers to register their well known TSAP * */ static int irda_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr; struct irda_sock *self = irda_sk(sk); int err; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); if (addr_len != sizeof(struct sockaddr_irda)) return -EINVAL; lock_sock(sk); #ifdef CONFIG_IRDA_ULTRA /* Special care for Ultra sockets */ if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA)) { self->pid = addr->sir_lsap_sel; err = -EOPNOTSUPP; if (self->pid & 0x80) { IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__); goto out; } err = irda_open_lsap(self, self->pid); if (err < 0) goto out; /* Pretend we are connected */ sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; err = 0; goto out; } #endif /* CONFIG_IRDA_ULTRA */ self->ias_obj = irias_new_object(addr->sir_name, jiffies); err = -ENOMEM; if (self->ias_obj == NULL) goto out; err = irda_open_tsap(self, addr->sir_lsap_sel, addr->sir_name); if (err < 0) { irias_delete_object(self->ias_obj); self->ias_obj = NULL; goto out; } /* Register with LM-IAS */ irias_add_integer_attrib(self->ias_obj, "IrDA:TinyTP:LsapSel", self->stsap_sel, IAS_KERNEL_ATTR); irias_insert_object(self->ias_obj); err = 0; out: release_sock(sk); return err; } /* * Function irda_accept (sock, newsock, flags) * * Wait for incoming connection * */ static int irda_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct irda_sock *new, *self = irda_sk(sk); struct sock *newsk; struct sk_buff *skb; int err; IRDA_DEBUG(2, "%s()\n", __func__); err = irda_create(sock_net(sk), newsock, sk->sk_protocol, 0); if (err) return err; err = -EINVAL; lock_sock(sk); if (sock->state != SS_UNCONNECTED) goto out; if ((sk = sock->sk) == NULL) goto out; err = -EOPNOTSUPP; if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) && (sk->sk_type != SOCK_DGRAM)) goto out; err = -EINVAL; if (sk->sk_state != TCP_LISTEN) goto out; /* * The read queue this time is holding sockets ready to use * hooked into the SABM we saved */ /* * We can perform the accept only if there is incoming data * on the listening socket. * So, we will block the caller until we receive any data. * If the caller was waiting on select() or poll() before * calling us, the data is waiting for us ;-) * Jean II */ while (1) { skb = skb_dequeue(&sk->sk_receive_queue); if (skb) break; /* Non blocking operation */ err = -EWOULDBLOCK; if (flags & O_NONBLOCK) goto out; err = wait_event_interruptible(*(sk_sleep(sk)), skb_peek(&sk->sk_receive_queue)); if (err) goto out; } newsk = newsock->sk; err = -EIO; if (newsk == NULL) goto out; newsk->sk_state = TCP_ESTABLISHED; new = irda_sk(newsk); /* Now attach up the new socket */ new->tsap = irttp_dup(self->tsap, new); err = -EPERM; /* value does not seem to make sense. -arnd */ if (!new->tsap) { IRDA_DEBUG(0, "%s(), dup failed!\n", __func__); kfree_skb(skb); goto out; } new->stsap_sel = new->tsap->stsap_sel; new->dtsap_sel = new->tsap->dtsap_sel; new->saddr = irttp_get_saddr(new->tsap); new->daddr = irttp_get_daddr(new->tsap); new->max_sdu_size_tx = self->max_sdu_size_tx; new->max_sdu_size_rx = self->max_sdu_size_rx; new->max_data_size = self->max_data_size; new->max_header_size = self->max_header_size; memcpy(&new->qos_tx, &self->qos_tx, sizeof(struct qos_info)); /* Clean up the original one to keep it in listen state */ irttp_listen(self->tsap); kfree_skb(skb); sk->sk_ack_backlog--; newsock->state = SS_CONNECTED; irda_connect_response(new); err = 0; out: release_sock(sk); return err; } /* * Function irda_connect (sock, uaddr, addr_len, flags) * * Connect to a IrDA device * * The main difference with a "standard" connect is that with IrDA we need * to resolve the service name into a TSAP selector (in TCP, port number * doesn't have to be resolved). * Because of this service name resolution, we can offer "auto-connect", * where we connect to a service without specifying a destination address. * * Note : by consulting "errno", the user space caller may learn the cause * of the failure. Most of them are visible in the function, others may come * from subroutines called and are listed here : * o EBUSY : already processing a connect * o EHOSTUNREACH : bad addr->sir_addr argument * o EADDRNOTAVAIL : bad addr->sir_name argument * o ENOTUNIQ : more than one node has addr->sir_name (auto-connect) * o ENETUNREACH : no node found on the network (auto-connect) */ static int irda_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr; struct irda_sock *self = irda_sk(sk); int err; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); lock_sock(sk); /* Don't allow connect for Ultra sockets */ err = -ESOCKTNOSUPPORT; if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA)) goto out; if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) { sock->state = SS_CONNECTED; err = 0; goto out; /* Connect completed during a ERESTARTSYS event */ } if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) { sock->state = SS_UNCONNECTED; err = -ECONNREFUSED; goto out; } err = -EISCONN; /* No reconnect on a seqpacket socket */ if (sk->sk_state == TCP_ESTABLISHED) goto out; sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; err = -EINVAL; if (addr_len != sizeof(struct sockaddr_irda)) goto out; /* Check if user supplied any destination device address */ if ((!addr->sir_addr) || (addr->sir_addr == DEV_ADDR_ANY)) { /* Try to find one suitable */ err = irda_discover_daddr_and_lsap_sel(self, addr->sir_name); if (err) { IRDA_DEBUG(0, "%s(), auto-connect failed!\n", __func__); goto out; } } else { /* Use the one provided by the user */ self->daddr = addr->sir_addr; IRDA_DEBUG(1, "%s(), daddr = %08x\n", __func__, self->daddr); /* If we don't have a valid service name, we assume the * user want to connect on a specific LSAP. Prevent * the use of invalid LSAPs (IrLMP 1.1 p10). Jean II */ if((addr->sir_name[0] != '\0') || (addr->sir_lsap_sel >= 0x70)) { /* Query remote LM-IAS using service name */ err = irda_find_lsap_sel(self, addr->sir_name); if (err) { IRDA_DEBUG(0, "%s(), connect failed!\n", __func__); goto out; } } else { /* Directly connect to the remote LSAP * specified by the sir_lsap field. * Please use with caution, in IrDA LSAPs are * dynamic and there is no "well-known" LSAP. */ self->dtsap_sel = addr->sir_lsap_sel; } } /* Check if we have opened a local TSAP */ if (!self->tsap) irda_open_tsap(self, LSAP_ANY, addr->sir_name); /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; /* Connect to remote device */ err = irttp_connect_request(self->tsap, self->dtsap_sel, self->saddr, self->daddr, NULL, self->max_sdu_size_rx, NULL); if (err) { IRDA_DEBUG(0, "%s(), connect failed!\n", __func__); goto out; } /* Now the loop */ err = -EINPROGRESS; if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) goto out; err = -ERESTARTSYS; if (wait_event_interruptible(*(sk_sleep(sk)), (sk->sk_state != TCP_SYN_SENT))) goto out; if (sk->sk_state != TCP_ESTABLISHED) { sock->state = SS_UNCONNECTED; if (sk->sk_prot->disconnect(sk, flags)) sock->state = SS_DISCONNECTING; err = sock_error(sk); if (!err) err = -ECONNRESET; goto out; } sock->state = SS_CONNECTED; /* At this point, IrLMP has assigned our source address */ self->saddr = irttp_get_saddr(self->tsap); err = 0; out: release_sock(sk); return err; } static struct proto irda_proto = { .name = "IRDA", .owner = THIS_MODULE, .obj_size = sizeof(struct irda_sock), }; /* * Function irda_create (sock, protocol) * * Create IrDA socket * */ static int irda_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct irda_sock *self; IRDA_DEBUG(2, "%s()\n", __func__); if (net != &init_net) return -EAFNOSUPPORT; /* Check for valid socket type */ switch (sock->type) { case SOCK_STREAM: /* For TTP connections with SAR disabled */ case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */ case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */ break; default: return -ESOCKTNOSUPPORT; } /* Allocate networking socket */ sk = sk_alloc(net, PF_IRDA, GFP_ATOMIC, &irda_proto); if (sk == NULL) return -ENOMEM; self = irda_sk(sk); IRDA_DEBUG(2, "%s() : self is %p\n", __func__, self); init_waitqueue_head(&self->query_wait); switch (sock->type) { case SOCK_STREAM: sock->ops = &irda_stream_ops; self->max_sdu_size_rx = TTP_SAR_DISABLE; break; case SOCK_SEQPACKET: sock->ops = &irda_seqpacket_ops; self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; case SOCK_DGRAM: switch (protocol) { #ifdef CONFIG_IRDA_ULTRA case IRDAPROTO_ULTRA: sock->ops = &irda_ultra_ops; /* Initialise now, because we may send on unbound * sockets. Jean II */ self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER; self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER; break; #endif /* CONFIG_IRDA_ULTRA */ case IRDAPROTO_UNITDATA: sock->ops = &irda_dgram_ops; /* We let Unitdata conn. be like seqpack conn. */ self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } /* Initialise networking socket struct */ sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */ sk->sk_family = PF_IRDA; sk->sk_protocol = protocol; /* Register as a client with IrLMP */ self->ckey = irlmp_register_client(0, NULL, NULL, NULL); self->mask.word = 0xffff; self->rx_flow = self->tx_flow = FLOW_START; self->nslots = DISCOVERY_DEFAULT_SLOTS; self->daddr = DEV_ADDR_ANY; /* Until we get connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ return 0; } /* * Function irda_destroy_socket (self) * * Destroy socket * */ static void irda_destroy_socket(struct irda_sock *self) { IRDA_DEBUG(2, "%s(%p)\n", __func__, self); /* Unregister with IrLMP */ irlmp_unregister_client(self->ckey); irlmp_unregister_service(self->skey); /* Unregister with LM-IAS */ if (self->ias_obj) { irias_delete_object(self->ias_obj); self->ias_obj = NULL; } if (self->iriap) { iriap_close(self->iriap); self->iriap = NULL; } if (self->tsap) { irttp_disconnect_request(self->tsap, NULL, P_NORMAL); irttp_close_tsap(self->tsap); self->tsap = NULL; } #ifdef CONFIG_IRDA_ULTRA if (self->lsap) { irlmp_close_lsap(self->lsap); self->lsap = NULL; } #endif /* CONFIG_IRDA_ULTRA */ } /* * Function irda_release (sock) */ static int irda_release(struct socket *sock) { struct sock *sk = sock->sk; IRDA_DEBUG(2, "%s()\n", __func__); if (sk == NULL) return 0; lock_sock(sk); sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); /* Destroy IrDA socket */ irda_destroy_socket(irda_sk(sk)); sock_orphan(sk); sock->sk = NULL; release_sock(sk); /* Purge queues (see sock_init_data()) */ skb_queue_purge(&sk->sk_receive_queue); /* Destroy networking socket if we are the last reference on it, * i.e. if(sk->sk_refcnt == 0) -> sk_free(sk) */ sock_put(sk); /* Notes on socket locking and deallocation... - Jean II * In theory we should put pairs of sock_hold() / sock_put() to * prevent the socket to be destroyed whenever there is an * outstanding request or outstanding incoming packet or event. * * 1) This may include IAS request, both in connect and getsockopt. * Unfortunately, the situation is a bit more messy than it looks, * because we close iriap and kfree(self) above. * * 2) This may include selective discovery in getsockopt. * Same stuff as above, irlmp registration and self are gone. * * Probably 1 and 2 may not matter, because it's all triggered * by a process and the socket layer already prevent the * socket to go away while a process is holding it, through * sockfd_put() and fput()... * * 3) This may include deferred TSAP closure. In particular, * we may receive a late irda_disconnect_indication() * Fortunately, (tsap_cb *)->close_pend should protect us * from that. * * I did some testing on SMP, and it looks solid. And the socket * memory leak is now gone... - Jean II */ return 0; } /* * Function irda_sendmsg (iocb, sock, msg, len) * * Send message down to TinyTP. This function is used for both STREAM and * SEQPACK services. This is possible since it forces the client to * fragment the message if necessary */ static int irda_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct irda_sock *self; struct sk_buff *skb; int err = -EPIPE; IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len); /* Note : socket.c set MSG_EOR on SEQPACKET sockets */ if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_EOR | MSG_CMSG_COMPAT | MSG_NOSIGNAL)) { return -EINVAL; } lock_sock(sk); if (sk->sk_shutdown & SEND_SHUTDOWN) goto out_err; if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } self = irda_sk(sk); /* Check if IrTTP is wants us to slow down */ if (wait_event_interruptible(*(sk_sleep(sk)), (self->tx_flow != FLOW_STOP || sk->sk_state != TCP_ESTABLISHED))) { err = -ERESTARTSYS; goto out; } /* Check if we are still connected */ if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Check that we don't send out too big frames */ if (len > self->max_data_size) { IRDA_DEBUG(2, "%s(), Chopping frame from %zd to %d bytes!\n", __func__, len, self->max_data_size); len = self->max_data_size; } skb = sock_alloc_send_skb(sk, len + self->max_header_size + 16, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) goto out_err; skb_reserve(skb, self->max_header_size + 16); skb_reset_transport_header(skb); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); goto out_err; } /* * Just send the message to TinyTP, and let it deal with possible * errors. No need to duplicate all that here */ err = irttp_data_request(self->tsap, skb); if (err) { IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err); goto out_err; } release_sock(sk); /* Tell client how much data we actually sent */ return len; out_err: err = sk_stream_error(sk, msg->msg_flags, err); out: release_sock(sk); return err; } /* * Function irda_recvmsg_dgram (iocb, sock, msg, size, flags) * * Try to receive message and copy it to user. The frame is discarded * after being read, regardless of how much the user actually read */ static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct sk_buff *skb; size_t copied; int err; IRDA_DEBUG(4, "%s()\n", __func__); msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) return err; skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n", __func__, copied, size); copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); skb_free_datagram(sk, skb); /* * Check if we have previously stopped IrTTP and we know * have more free space in our rx_queue. If so tell IrTTP * to start delivering frames again before our rx_queue gets * empty */ if (self->rx_flow == FLOW_STOP) { if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) { IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__); self->rx_flow = FLOW_START; irttp_flow_request(self->tsap, FLOW_START); } } return copied; } /* * Function irda_recvmsg_stream (iocb, sock, msg, size, flags) */ static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); int noblock = flags & MSG_DONTWAIT; size_t copied = 0; int target, err; long timeo; IRDA_DEBUG(3, "%s()\n", __func__); if ((err = sock_error(sk)) < 0) return err; if (sock->flags & __SO_ACCEPTCON) return -EINVAL; err =-EOPNOTSUPP; if (flags & MSG_OOB) return -EOPNOTSUPP; err = 0; target = sock_rcvlowat(sk, flags & MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, noblock); msg->msg_namelen = 0; do { int chunk; struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue); if (skb == NULL) { DEFINE_WAIT(wait); err = 0; if (copied >= target) break; prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) ; else if (sk->sk_shutdown & RCV_SHUTDOWN) ; else if (noblock) err = -EAGAIN; else if (signal_pending(current)) err = sock_intr_errno(timeo); else if (sk->sk_state != TCP_ESTABLISHED) err = -ENOTCONN; else if (skb_peek(&sk->sk_receive_queue) == NULL) /* Wait process until data arrives */ schedule(); finish_wait(sk_sleep(sk), &wait); if (err) return err; if (sk->sk_shutdown & RCV_SHUTDOWN) break; continue; } chunk = min_t(unsigned int, skb->len, size); if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { skb_pull(skb, chunk); /* put the skb back if we didn't use it up.. */ if (skb->len) { IRDA_DEBUG(1, "%s(), back on q!\n", __func__); skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { IRDA_DEBUG(0, "%s() questionable!?\n", __func__); /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); /* * Check if we have previously stopped IrTTP and we know * have more free space in our rx_queue. If so tell IrTTP * to start delivering frames again before our rx_queue gets * empty */ if (self->rx_flow == FLOW_STOP) { if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) { IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__); self->rx_flow = FLOW_START; irttp_flow_request(self->tsap, FLOW_START); } } return copied; } /* * Function irda_sendmsg_dgram (iocb, sock, msg, len) * * Send message down to TinyTP for the unreliable sequenced * packet service... * */ static int irda_sendmsg_dgram(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct irda_sock *self; struct sk_buff *skb; int err; IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len); if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); err = -EPIPE; goto out; } err = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; self = irda_sk(sk); /* * Check that we don't send out too big frames. This is an unreliable * service, so we have no fragmentation and no coalescence */ if (len > self->max_data_size) { IRDA_DEBUG(0, "%s(), Warning to much data! " "Chopping frame from %zd to %d bytes!\n", __func__, len, self->max_data_size); len = self->max_data_size; } skb = sock_alloc_send_skb(sk, len + self->max_header_size, msg->msg_flags & MSG_DONTWAIT, &err); err = -ENOBUFS; if (!skb) goto out; skb_reserve(skb, self->max_header_size); skb_reset_transport_header(skb); IRDA_DEBUG(4, "%s(), appending user data\n", __func__); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); goto out; } /* * Just send the message to TinyTP, and let it deal with possible * errors. No need to duplicate all that here */ err = irttp_udata_request(self->tsap, skb); if (err) { IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err); goto out; } release_sock(sk); return len; out: release_sock(sk); return err; } /* * Function irda_sendmsg_ultra (iocb, sock, msg, len) * * Send message down to IrLMP for the unreliable Ultra * packet service... */ #ifdef CONFIG_IRDA_ULTRA static int irda_sendmsg_ultra(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct irda_sock *self; __u8 pid = 0; int bound = 0; struct sk_buff *skb; int err; IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len); err = -EINVAL; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); goto out; } self = irda_sk(sk); /* Check if an address was specified with sendto. Jean II */ if (msg->msg_name) { struct sockaddr_irda *addr = (struct sockaddr_irda *) msg->msg_name; err = -EINVAL; /* Check address, extract pid. Jean II */ if (msg->msg_namelen < sizeof(*addr)) goto out; if (addr->sir_family != AF_IRDA) goto out; pid = addr->sir_lsap_sel; if (pid & 0x80) { IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__); err = -EOPNOTSUPP; goto out; } } else { /* Check that the socket is properly bound to an Ultra * port. Jean II */ if ((self->lsap == NULL) || (sk->sk_state != TCP_ESTABLISHED)) { IRDA_DEBUG(0, "%s(), socket not bound to Ultra PID.\n", __func__); err = -ENOTCONN; goto out; } /* Use PID from socket */ bound = 1; } /* * Check that we don't send out too big frames. This is an unreliable * service, so we have no fragmentation and no coalescence */ if (len > self->max_data_size) { IRDA_DEBUG(0, "%s(), Warning to much data! " "Chopping frame from %zd to %d bytes!\n", __func__, len, self->max_data_size); len = self->max_data_size; } skb = sock_alloc_send_skb(sk, len + self->max_header_size, msg->msg_flags & MSG_DONTWAIT, &err); err = -ENOBUFS; if (!skb) goto out; skb_reserve(skb, self->max_header_size); skb_reset_transport_header(skb); IRDA_DEBUG(4, "%s(), appending user data\n", __func__); skb_put(skb, len); err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); if (err) { kfree_skb(skb); goto out; } err = irlmp_connless_data_request((bound ? self->lsap : NULL), skb, pid); if (err) IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err); out: release_sock(sk); return err ? : len; } #endif /* CONFIG_IRDA_ULTRA */ /* * Function irda_shutdown (sk, how) */ static int irda_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); IRDA_DEBUG(1, "%s(%p)\n", __func__, self); lock_sock(sk); sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); if (self->iriap) { iriap_close(self->iriap); self->iriap = NULL; } if (self->tsap) { irttp_disconnect_request(self->tsap, NULL, P_NORMAL); irttp_close_tsap(self->tsap); self->tsap = NULL; } /* A few cleanup so the socket look as good as new... */ self->rx_flow = self->tx_flow = FLOW_START; /* needed ??? */ self->daddr = DEV_ADDR_ANY; /* Until we get re-connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ release_sock(sk); return 0; } /* * Function irda_poll (file, sock, wait) */ static unsigned int irda_poll(struct file * file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); unsigned int mask; IRDA_DEBUG(4, "%s()\n", __func__); poll_wait(file, sk_sleep(sk), wait); mask = 0; /* Exceptional events? */ if (sk->sk_err) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) { IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__); mask |= POLLHUP; } /* Readable? */ if (!skb_queue_empty(&sk->sk_receive_queue)) { IRDA_DEBUG(4, "Socket is readable\n"); mask |= POLLIN | POLLRDNORM; } /* Connection-based need to check for termination and startup */ switch (sk->sk_type) { case SOCK_STREAM: if (sk->sk_state == TCP_CLOSE) { IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__); mask |= POLLHUP; } if (sk->sk_state == TCP_ESTABLISHED) { if ((self->tx_flow == FLOW_START) && sock_writeable(sk)) { mask |= POLLOUT | POLLWRNORM | POLLWRBAND; } } break; case SOCK_SEQPACKET: if ((self->tx_flow == FLOW_START) && sock_writeable(sk)) { mask |= POLLOUT | POLLWRNORM | POLLWRBAND; } break; case SOCK_DGRAM: if (sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; break; default: break; } return mask; } /* * Function irda_ioctl (sock, cmd, arg) */ static int irda_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; int err; IRDA_DEBUG(4, "%s(), cmd=%#x\n", __func__, cmd); err = -EINVAL; switch (cmd) { case TIOCOUTQ: { long amount; amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; err = put_user(amount, (unsigned int __user *)arg); break; } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; /* 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; err = put_user(amount, (unsigned int __user *)arg); break; } case SIOCGSTAMP: if (sk != NULL) err = sock_get_timestamp(sk, (struct timeval __user *)arg); break; case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFMETRIC: case SIOCSIFMETRIC: break; default: IRDA_DEBUG(1, "%s(), doing device ioctl!\n", __func__); err = -ENOIOCTLCMD; } return err; } #ifdef CONFIG_COMPAT /* * Function irda_ioctl (sock, cmd, arg) */ static int irda_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { /* * All IRDA's ioctl are standard ones. */ return -ENOIOCTLCMD; } #endif /* * Function irda_setsockopt (sock, level, optname, optval, optlen) * * Set some options for the socket * */ static int irda_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct irda_ias_set *ias_opt; struct ias_object *ias_obj; struct ias_attrib * ias_attr; /* Attribute in IAS object */ int opt, free_ias = 0, err = 0; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); if (level != SOL_IRLMP) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case IRLMP_IAS_SET: /* The user want to add an attribute to an existing IAS object * (in the IAS database) or to create a new object with this * attribute. * We first query IAS to know if the object exist, and then * create the right attribute... */ if (optlen != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, optlen)) { kfree(ias_opt); err = -EFAULT; goto out; } /* Find the object we target. * If the user gives us an empty string, we use the object * associated with this socket. This will workaround * duplicated class name - Jean II */ if(ias_opt->irda_class_name[0] == '\0') { if(self->ias_obj == NULL) { kfree(ias_opt); err = -EINVAL; goto out; } ias_obj = self->ias_obj; } else ias_obj = irias_find_object(ias_opt->irda_class_name); /* Only ROOT can mess with the global IAS database. * Users can only add attributes to the object associated * with the socket they own - Jean II */ if((!capable(CAP_NET_ADMIN)) && ((ias_obj == NULL) || (ias_obj != self->ias_obj))) { kfree(ias_opt); err = -EPERM; goto out; } /* If the object doesn't exist, create it */ if(ias_obj == (struct ias_object *) NULL) { /* Create a new object */ ias_obj = irias_new_object(ias_opt->irda_class_name, jiffies); if (ias_obj == NULL) { kfree(ias_opt); err = -ENOMEM; goto out; } free_ias = 1; } /* Do we have the attribute already ? */ if(irias_find_attrib(ias_obj, ias_opt->irda_attrib_name)) { kfree(ias_opt); if (free_ias) { kfree(ias_obj->name); kfree(ias_obj); } err = -EINVAL; goto out; } /* Look at the type */ switch(ias_opt->irda_attrib_type) { case IAS_INTEGER: /* Add an integer attribute */ irias_add_integer_attrib( ias_obj, ias_opt->irda_attrib_name, ias_opt->attribute.irda_attrib_int, IAS_USER_ATTR); break; case IAS_OCT_SEQ: /* Check length */ if(ias_opt->attribute.irda_attrib_octet_seq.len > IAS_MAX_OCTET_STRING) { kfree(ias_opt); if (free_ias) { kfree(ias_obj->name); kfree(ias_obj); } err = -EINVAL; goto out; } /* Add an octet sequence attribute */ irias_add_octseq_attrib( ias_obj, ias_opt->irda_attrib_name, ias_opt->attribute.irda_attrib_octet_seq.octet_seq, ias_opt->attribute.irda_attrib_octet_seq.len, IAS_USER_ATTR); break; case IAS_STRING: /* Should check charset & co */ /* Check length */ /* The length is encoded in a __u8, and * IAS_MAX_STRING == 256, so there is no way * userspace can pass us a string too large. * Jean II */ /* NULL terminate the string (avoid troubles) */ ias_opt->attribute.irda_attrib_string.string[ias_opt->attribute.irda_attrib_string.len] = '\0'; /* Add a string attribute */ irias_add_string_attrib( ias_obj, ias_opt->irda_attrib_name, ias_opt->attribute.irda_attrib_string.string, IAS_USER_ATTR); break; default : kfree(ias_opt); if (free_ias) { kfree(ias_obj->name); kfree(ias_obj); } err = -EINVAL; goto out; } irias_insert_object(ias_obj); kfree(ias_opt); break; case IRLMP_IAS_DEL: /* The user want to delete an object from our local IAS * database. We just need to query the IAS, check is the * object is not owned by the kernel and delete it. */ if (optlen != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, optlen)) { kfree(ias_opt); err = -EFAULT; goto out; } /* Find the object we target. * If the user gives us an empty string, we use the object * associated with this socket. This will workaround * duplicated class name - Jean II */ if(ias_opt->irda_class_name[0] == '\0') ias_obj = self->ias_obj; else ias_obj = irias_find_object(ias_opt->irda_class_name); if(ias_obj == (struct ias_object *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Only ROOT can mess with the global IAS database. * Users can only del attributes from the object associated * with the socket they own - Jean II */ if((!capable(CAP_NET_ADMIN)) && ((ias_obj == NULL) || (ias_obj != self->ias_obj))) { kfree(ias_opt); err = -EPERM; goto out; } /* Find the attribute (in the object) we target */ ias_attr = irias_find_attrib(ias_obj, ias_opt->irda_attrib_name); if(ias_attr == (struct ias_attrib *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Check is the user space own the object */ if(ias_attr->value->owner != IAS_USER_ATTR) { IRDA_DEBUG(1, "%s(), attempting to delete a kernel attribute\n", __func__); kfree(ias_opt); err = -EPERM; goto out; } /* Remove the attribute (and maybe the object) */ irias_delete_attrib(ias_obj, ias_attr, 1); kfree(ias_opt); break; case IRLMP_MAX_SDU_SIZE: if (optlen < sizeof(int)) { err = -EINVAL; goto out; } if (get_user(opt, (int __user *)optval)) { err = -EFAULT; goto out; } /* Only possible for a seqpacket service (TTP with SAR) */ if (sk->sk_type != SOCK_SEQPACKET) { IRDA_DEBUG(2, "%s(), setting max_sdu_size = %d\n", __func__, opt); self->max_sdu_size_rx = opt; } else { IRDA_WARNING("%s: not allowed to set MAXSDUSIZE for this socket type!\n", __func__); err = -ENOPROTOOPT; goto out; } break; case IRLMP_HINTS_SET: if (optlen < sizeof(int)) { err = -EINVAL; goto out; } /* The input is really a (__u8 hints[2]), easier as an int */ if (get_user(opt, (int __user *)optval)) { err = -EFAULT; goto out; } /* Unregister any old registration */ if (self->skey) irlmp_unregister_service(self->skey); self->skey = irlmp_register_service((__u16) opt); break; case IRLMP_HINT_MASK_SET: /* As opposed to the previous case which set the hint bits * that we advertise, this one set the filter we use when * making a discovery (nodes which don't match any hint * bit in the mask are not reported). */ if (optlen < sizeof(int)) { err = -EINVAL; goto out; } /* The input is really a (__u8 hints[2]), easier as an int */ if (get_user(opt, (int __user *)optval)) { err = -EFAULT; goto out; } /* Set the new hint mask */ self->mask.word = (__u16) opt; /* Mask out extension bits */ self->mask.word &= 0x7f7f; /* Check if no bits */ if(!self->mask.word) self->mask.word = 0xFFFF; break; default: err = -ENOPROTOOPT; break; } out: release_sock(sk); return err; } /* * Function irda_extract_ias_value(ias_opt, ias_value) * * Translate internal IAS value structure to the user space representation * * The external representation of IAS values, as we exchange them with * user space program is quite different from the internal representation, * as stored in the IAS database (because we need a flat structure for * crossing kernel boundary). * This function transform the former in the latter. We also check * that the value type is valid. */ static int irda_extract_ias_value(struct irda_ias_set *ias_opt, struct ias_value *ias_value) { /* Look at the type */ switch (ias_value->type) { case IAS_INTEGER: /* Copy the integer */ ias_opt->attribute.irda_attrib_int = ias_value->t.integer; break; case IAS_OCT_SEQ: /* Set length */ ias_opt->attribute.irda_attrib_octet_seq.len = ias_value->len; /* Copy over */ memcpy(ias_opt->attribute.irda_attrib_octet_seq.octet_seq, ias_value->t.oct_seq, ias_value->len); break; case IAS_STRING: /* Set length */ ias_opt->attribute.irda_attrib_string.len = ias_value->len; ias_opt->attribute.irda_attrib_string.charset = ias_value->charset; /* Copy over */ memcpy(ias_opt->attribute.irda_attrib_string.string, ias_value->t.string, ias_value->len); /* NULL terminate the string (avoid troubles) */ ias_opt->attribute.irda_attrib_string.string[ias_value->len] = '\0'; break; case IAS_MISSING: default : return -EINVAL; } /* Copy type over */ ias_opt->irda_attrib_type = ias_value->type; return 0; } /* * Function irda_getsockopt (sock, level, optname, optval, optlen) */ static int irda_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct irda_device_list list; struct irda_device_info *discoveries; struct irda_ias_set * ias_opt; /* IAS get/query params */ struct ias_object * ias_obj; /* Object in IAS */ struct ias_attrib * ias_attr; /* Attribute in IAS object */ int daddr = DEV_ADDR_ANY; /* Dest address for IAS queries */ int val = 0; int len = 0; int err = 0; int offset, total; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); if (level != SOL_IRLMP) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if(len < 0) return -EINVAL; lock_sock(sk); switch (optname) { case IRLMP_ENUMDEVICES: /* Offset to first device entry */ offset = sizeof(struct irda_device_list) - sizeof(struct irda_device_info); if (len < offset) { err = -EINVAL; goto out; } /* Ask lmp for the current discovery log */ discoveries = irlmp_get_discoveries(&list.len, self->mask.word, self->nslots); /* Check if the we got some results */ if (discoveries == NULL) { err = -EAGAIN; goto out; /* Didn't find any devices */ } /* Write total list length back to client */ if (copy_to_user(optval, &list, offset)) err = -EFAULT; /* Copy the list itself - watch for overflow */ if (list.len > 2048) { err = -EINVAL; goto bed; } total = offset + (list.len * sizeof(struct irda_device_info)); if (total > len) total = len; if (copy_to_user(optval+offset, discoveries, total - offset)) err = -EFAULT; /* Write total number of bytes used back to client */ if (put_user(total, optlen)) err = -EFAULT; bed: /* Free up our buffer */ kfree(discoveries); break; case IRLMP_MAX_SDU_SIZE: val = self->max_data_size; len = sizeof(int); if (put_user(len, optlen)) { err = -EFAULT; goto out; } if (copy_to_user(optval, &val, len)) { err = -EFAULT; goto out; } break; case IRLMP_IAS_GET: /* The user want an object from our local IAS database. * We just need to query the IAS and return the value * that we found */ /* Check that the user has allocated the right space for us */ if (len != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, len)) { kfree(ias_opt); err = -EFAULT; goto out; } /* Find the object we target. * If the user gives us an empty string, we use the object * associated with this socket. This will workaround * duplicated class name - Jean II */ if(ias_opt->irda_class_name[0] == '\0') ias_obj = self->ias_obj; else ias_obj = irias_find_object(ias_opt->irda_class_name); if(ias_obj == (struct ias_object *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Find the attribute (in the object) we target */ ias_attr = irias_find_attrib(ias_obj, ias_opt->irda_attrib_name); if(ias_attr == (struct ias_attrib *) NULL) { kfree(ias_opt); err = -EINVAL; goto out; } /* Translate from internal to user structure */ err = irda_extract_ias_value(ias_opt, ias_attr->value); if(err) { kfree(ias_opt); goto out; } /* Copy reply to the user */ if (copy_to_user(optval, ias_opt, sizeof(struct irda_ias_set))) { kfree(ias_opt); err = -EFAULT; goto out; } /* Note : don't need to put optlen, we checked it */ kfree(ias_opt); break; case IRLMP_IAS_QUERY: /* The user want an object from a remote IAS database. * We need to use IAP to query the remote database and * then wait for the answer to come back. */ /* Check that the user has allocated the right space for us */ if (len != sizeof(struct irda_ias_set)) { err = -EINVAL; goto out; } ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC); if (ias_opt == NULL) { err = -ENOMEM; goto out; } /* Copy query to the driver. */ if (copy_from_user(ias_opt, optval, len)) { kfree(ias_opt); err = -EFAULT; goto out; } /* At this point, there are two cases... * 1) the socket is connected - that's the easy case, we * just query the device we are connected to... * 2) the socket is not connected - the user doesn't want * to connect and/or may not have a valid service name * (so can't create a fake connection). In this case, * we assume that the user pass us a valid destination * address in the requesting structure... */ if(self->daddr != DEV_ADDR_ANY) { /* We are connected - reuse known daddr */ daddr = self->daddr; } else { /* We are not connected, we must specify a valid * destination address */ daddr = ias_opt->daddr; if((!daddr) || (daddr == DEV_ADDR_ANY)) { kfree(ias_opt); err = -EINVAL; goto out; } } /* Check that we can proceed with IAP */ if (self->iriap) { IRDA_WARNING("%s: busy with a previous query\n", __func__); kfree(ias_opt); err = -EBUSY; goto out; } self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self, irda_getvalue_confirm); if (self->iriap == NULL) { kfree(ias_opt); err = -ENOMEM; goto out; } /* Treat unexpected wakeup as disconnect */ self->errno = -EHOSTUNREACH; /* Query remote LM-IAS */ iriap_getvaluebyclass_request(self->iriap, self->saddr, daddr, ias_opt->irda_class_name, ias_opt->irda_attrib_name); /* Wait for answer, if not yet finished (or failed) */ if (wait_event_interruptible(self->query_wait, (self->iriap == NULL))) { /* pending request uses copy of ias_opt-content * we can free it regardless! */ kfree(ias_opt); /* Treat signals as disconnect */ err = -EHOSTUNREACH; goto out; } /* Check what happened */ if (self->errno) { kfree(ias_opt); /* Requested object/attribute doesn't exist */ if((self->errno == IAS_CLASS_UNKNOWN) || (self->errno == IAS_ATTRIB_UNKNOWN)) err = -EADDRNOTAVAIL; else err = -EHOSTUNREACH; goto out; } /* Translate from internal to user structure */ err = irda_extract_ias_value(ias_opt, self->ias_result); if (self->ias_result) irias_delete_value(self->ias_result); if (err) { kfree(ias_opt); goto out; } /* Copy reply to the user */ if (copy_to_user(optval, ias_opt, sizeof(struct irda_ias_set))) { kfree(ias_opt); err = -EFAULT; goto out; } /* Note : don't need to put optlen, we checked it */ kfree(ias_opt); break; case IRLMP_WAITDEVICE: /* This function is just another way of seeing life ;-) * IRLMP_ENUMDEVICES assumes that you have a static network, * and that you just want to pick one of the devices present. * On the other hand, in here we assume that no device is * present and that at some point in the future a device will * come into range. When this device arrive, we just wake * up the caller, so that he has time to connect to it before * the device goes away... * Note : once the node has been discovered for more than a * few second, it won't trigger this function, unless it * goes away and come back changes its hint bits (so we * might call it IRLMP_WAITNEWDEVICE). */ /* Check that the user is passing us an int */ if (len != sizeof(int)) { err = -EINVAL; goto out; } /* Get timeout in ms (max time we block the caller) */ if (get_user(val, (int __user *)optval)) { err = -EFAULT; goto out; } /* Tell IrLMP we want to be notified */ irlmp_update_client(self->ckey, self->mask.word, irda_selective_discovery_indication, NULL, (void *) self); /* Do some discovery (and also return cached results) */ irlmp_discovery_request(self->nslots); /* Wait until a node is discovered */ if (!self->cachedaddr) { IRDA_DEBUG(1, "%s(), nothing discovered yet, going to sleep...\n", __func__); /* Set watchdog timer to expire in <val> ms. */ self->errno = 0; setup_timer(&self->watchdog, irda_discovery_timeout, (unsigned long)self); mod_timer(&self->watchdog, jiffies + msecs_to_jiffies(val)); /* Wait for IR-LMP to call us back */ __wait_event_interruptible(self->query_wait, (self->cachedaddr != 0 || self->errno == -ETIME), err); /* If watchdog is still activated, kill it! */ del_timer(&(self->watchdog)); IRDA_DEBUG(1, "%s(), ...waking up !\n", __func__); if (err != 0) goto out; } else IRDA_DEBUG(1, "%s(), found immediately !\n", __func__); /* Tell IrLMP that we have been notified */ irlmp_update_client(self->ckey, self->mask.word, NULL, NULL, NULL); /* Check if the we got some results */ if (!self->cachedaddr) { err = -EAGAIN; /* Didn't find any devices */ goto out; } daddr = self->cachedaddr; /* Cleanup */ self->cachedaddr = 0; /* We return the daddr of the device that trigger the * wakeup. As irlmp pass us only the new devices, we * are sure that it's not an old device. * If the user want more details, he should query * the whole discovery log and pick one device... */ if (put_user(daddr, (int __user *)optval)) { err = -EFAULT; goto out; } break; default: err = -ENOPROTOOPT; } out: release_sock(sk); return err; } static const struct net_proto_family irda_family_ops = { .family = PF_IRDA, .create = irda_create, .owner = THIS_MODULE, }; static const struct proto_ops irda_stream_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = irda_connect, .socketpair = sock_no_socketpair, .accept = irda_accept, .getname = irda_getname, .poll = irda_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = irda_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg, .recvmsg = irda_recvmsg_stream, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const struct proto_ops irda_seqpacket_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = irda_connect, .socketpair = sock_no_socketpair, .accept = irda_accept, .getname = irda_getname, .poll = datagram_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = irda_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg, .recvmsg = irda_recvmsg_dgram, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const struct proto_ops irda_dgram_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = irda_connect, .socketpair = sock_no_socketpair, .accept = irda_accept, .getname = irda_getname, .poll = datagram_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = irda_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg_dgram, .recvmsg = irda_recvmsg_dgram, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; #ifdef CONFIG_IRDA_ULTRA static const struct proto_ops irda_ultra_ops = { .family = PF_IRDA, .owner = THIS_MODULE, .release = irda_release, .bind = irda_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = irda_getname, .poll = datagram_poll, .ioctl = irda_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = irda_compat_ioctl, #endif .listen = sock_no_listen, .shutdown = irda_shutdown, .setsockopt = irda_setsockopt, .getsockopt = irda_getsockopt, .sendmsg = irda_sendmsg_ultra, .recvmsg = irda_recvmsg_dgram, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; #endif /* CONFIG_IRDA_ULTRA */ /* * Function irsock_init (pro) * * Initialize IrDA protocol * */ int __init irsock_init(void) { int rc = proto_register(&irda_proto, 0); if (rc == 0) rc = sock_register(&irda_family_ops); return rc; } /* * Function irsock_cleanup (void) * * Remove IrDA protocol * */ void irsock_cleanup(void) { sock_unregister(PF_IRDA); proto_unregister(&irda_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_5687_0
crossvul-cpp_data_good_759_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. * * 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 <asm/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/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/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #include <linux/kmemleak.h> #endif #include <net/secure_seq.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_min_valid_pmtu __read_mostly = IPV4_MIN_MTU; /* * 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 struct dst_ops ipv4_dst_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .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, }; #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 = { .owner = THIS_MODULE, .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 = { .owner = THIS_MODULE, .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; } static int rt_acct_proc_open(struct inode *inode, struct file *file) { return single_open(file, rt_acct_proc_show, NULL); } static const struct file_operations rt_acct_proc_fops = { .owner = THIS_MODULE, .open = rt_acct_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", S_IRUGO, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", S_IRUGO, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create("rt_acct", 0, net->proc_net, &rt_acct_proc_fops); 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); } #define IP_IDENTS_SZ 2048u struct ip_ident_bucket { atomic_t id; u32 stamp32; }; static struct ip_ident_bucket *ip_idents __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) { struct ip_ident_bucket *bucket = ip_idents + hash % IP_IDENTS_SZ; u32 old = ACCESS_ONCE(bucket->stamp32); u32 now = (u32)jiffies; u32 delta = 0; if (old != now && cmpxchg(&bucket->stamp32, old, now) == old) delta = prandom_u32_max(now - old); return atomic_add_return(segs + delta, &bucket->id) - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(struct iphdr *iph, int segs) { static u32 ip_idents_hashrnd __read_mostly; static u32 ip_idents_hashrnd_extra __read_mostly; u32 hash, id; net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); net_get_random_once(&ip_idents_hashrnd_extra, sizeof(ip_idents_hashrnd_extra)); hash = jhash_3words((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol ^ ip_idents_hashrnd_extra, ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(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); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { 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(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); 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 inline void rt_free(struct rtable *rt) { call_rcu(&rt->dst.rcu_head, dst_rcu_free); } 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); rt_free(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); rt_free(rt); } } 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->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, 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 = kzalloc(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_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_expires = 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, NULL, &new_gw); if (!IS_ERR(n)) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, 0); } 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; 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(&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; 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); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 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 in_device *in_dev = __in_dev_get_rcu(skb->dev); struct rtable *rt = skb_rtable(skb); struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; /* 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_BH(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: IP_INC_STATS_BH(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_BH(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 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; struct fib_result res; if (dst_metric_locked(dst, RTAX_MTU)) return; if (dst->dev->mtu < mtu) return; if (mtu < ip_rt_min_pmtu) mtu = ip_rt_min_pmtu; if (rt->rt_pmtu == mtu && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, 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, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; if (!mark) mark = IP4_REPLY_MARK(net, skb->mark); __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); 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(&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; 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(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && odst->ops->check(odst, 0) == NULL) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) rt->dst.path, &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, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); 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; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(sock_net(sk), &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 by dst_free(). */ 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 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 flowi4 fl4; struct iphdr *iph; iph = ip_hdr(skb); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = iph->daddr; fl4.saddr = iph->saddr; fl4.flowi4_tos = RT_TOS(iph->tos); fl4.flowi4_oif = rt->dst.dev->ifindex; fl4.flowi4_iif = skb->dev->ifindex; fl4.flowi4_mark = skb->mark; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res) == 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 advmss = dst_metric_raw(dst, RTAX_ADVMSS); if (advmss == 0) { advmss = max_t(unsigned int, dst->dev->mtu - 40, ip_rt_min_advmss); if (advmss > 65535 - 40) advmss = 65535 - 40; } return advmss; } 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 = dst->dev->mtu; if (unlikely(dst_metric_locked(dst, RTAX_MTU))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } return min_t(unsigned int, mtu, IP_MAX_MTU); } 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) return fnhe; } return NULL; } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr) { 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_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (!(rt->dst.flags & DST_NOCACHE)) { rcu_assign_pointer(*porig, rt); if (orig) rt_free(orig); 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; prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) rt_free(orig); } else ret = false; return ret; } static DEFINE_SPINLOCK(rt_uncached_lock); static LIST_HEAD(rt_uncached_list); static void rt_add_uncached_list(struct rtable *rt) { spin_lock_bh(&rt_uncached_lock); list_add_tail(&rt->rt_uncached, &rt_uncached_list); spin_unlock_bh(&rt_uncached_lock); } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *) dst; if (!list_empty(&rt->rt_uncached)) { spin_lock_bh(&rt_uncached_lock); list_del(&rt->rt_uncached); spin_unlock_bh(&rt_uncached_lock); } } void rt_flush_dev(struct net_device *dev) { if (!list_empty(&rt_uncached_list)) { struct net *net = dev_net(dev); struct rtable *rt; spin_lock_bh(&rt_uncached_lock); list_for_each_entry(rt, &rt_uncached_list, 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(&rt_uncached_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) { 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; } dst_init_metrics(&rt->dst, fi->fib_metrics, true); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr); else if (!(rt->dst.flags & DST_NOCACHE)) 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. */ rt->dst.flags |= DST_NOCACHE; 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 } static struct rtable *rt_dst_alloc(struct net_device *dev, bool nopolicy, bool noxfrm, bool will_cache) { return dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : (DST_HOST | DST_NOCACHE)) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 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 rtable *rth; struct in_device *in_dev = __in_dev_get_rcu(dev); u32 itag = 0; int err; /* Primary sanity checks. */ if (in_dev == NULL) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) goto e_inval; if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(saddr)) goto e_inval; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr)) goto e_inval; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto e_err; } rth = rt_dst_alloc(dev_net(dev)->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) goto e_nobufs; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_genid = rt_genid_ipv4(dev_net(dev)); rth->rt_flags = RTCF_MULTICAST; rth->rt_type = RTN_MULTICAST; rth->rt_is_input= 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); if (our) { rth->dst.input= ip_local_deliver; rth->rt_flags |= RTCF_LOCAL; } #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; e_nobufs: return -ENOBUFS; e_inval: return -EINVAL; e_err: return err; } 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, true); } } #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; unsigned int flags = 0; 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 == NULL) { 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 != NULL) 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, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev)); rth->rt_flags = flags; rth->rt_type = res->type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rth->dst.output = ip_output; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag); skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, const struct flowi4 *fl4, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) fib_select_multipath(res); #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 flowi4 fl4; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; int err = -EINVAL; struct net *net = dev_net(dev); 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. */ if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res.fi = 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.daddr = daddr; fl4.saddr = saddr; err = fib_lookup(net, &fl4, &res); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res.type == RTN_BROADCAST) 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_keep_err; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res.type != RTN_UNICAST) goto martian_destination; err = ip_mkroute_input(skb, &res, &fl4, in_dev, daddr, saddr, tos); 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_keep_err; } 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(net->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.input= ip_local_deliver; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_genid = rt_genid_ipv4(net); rth->rt_flags = flags|RTCF_LOCAL; rth->rt_type = res.type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); 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) { if (unlikely(!rt_cache_route(&FIB_RES_NH(res), rth))) { rth->dst.flags |= DST_NOCACHE; 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; 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: err = -EINVAL; martian_source_keep_err: 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) { int res; tos &= IPTOS_RT_MASK; rcu_read_lock(); /* 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); if (in_dev) { int our = ip_check_mc_rcu(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 ) { int res = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); rcu_read_unlock(); return res; } } rcu_read_unlock(); return -EINVAL; } res = ip_route_input_slow(skb, daddr, saddr, tos, dev); rcu_read_unlock(); return res; } EXPORT_SYMBOL(ip_route_input_noref); /* 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)) 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. */ fi = NULL; } fnhe = NULL; do_cache &= fi != NULL; if (do_cache) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); 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(&rth->dst); return rth; } } add: rth = rt_dst_alloc(dev_out, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->dst.output = ip_output; rth->rt_genid = rt_genid_ipv4(dev_net(dev_out)); rth->rt_flags = flags; rth->rt_type = type; rth->rt_is_input = 0; rth->rt_iif = orig_oif ? : 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(out_slow_tot); if (flags & RTCF_LOCAL) rth->dst.input = ip_local_deliver; 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); return rth; } /* * Major route resolver routine. */ struct rtable *__ip_route_output_key(struct net *net, struct flowi4 *fl4) { struct net_device *dev_out = NULL; __u8 tos = RT_FL_TOS(fl4); unsigned int flags = 0; struct fib_result res; struct rtable *rth; int orig_oif; res.tclassid = 0; res.fi = NULL; res.table = NULL; orig_oif = fl4->flowi4_oif; 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(); 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 == NULL) 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 == NULL) 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)) { 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; } if (fib_lookup(net, fl4, &res)) { res.fi = NULL; res.table = NULL; if (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(-ENETUNREACH); 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; } dev_out = net->loopback_dev; fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res.fi->fib_nhs > 1 && fl4->flowi4_oif == 0) fib_select_multipath(&res); else #endif if (!res.prefixlen && res.table->tb_num_default > 1 && res.type == RTN_UNICAST && !fl4->flowi4_oif) fib_select_default(&res); if (!fl4->saddr) fl4->saddr = FIB_RES_PREFSRC(net, res); 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: rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(__ip_route_output_key); 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, .protocol = cpu_to_be16(ETH_P_IP), .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_NONE, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard_sk; new->dev = ort->dst.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_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_free(new); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, 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); static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (nlh == NULL) 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 = RT_TABLE_MAIN; if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) 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_be32(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_be32(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_be32(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_be32(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 (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; 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, nowait, portid); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (skb == NULL) { err = -ENOBUFS; goto errout; } /* 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); /* Bugfix: need to give ip_route_input enough of an IP header to not gag. */ ip_hdr(skb)->protocol = IPPROTO_ICMP; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); src = tb[RTA_SRC] ? nla_get_be32(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_be32(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; memset(&fl4, 0, sizeof(fl4)); 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; if (iif) { struct net_device *dev; dev = __dev_get_by_index(net, iif); if (dev == NULL) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; local_bh_disable(); err = ip_route_input(skb, dst, src, rtm->rtm_tos, dev); local_bh_enable(); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key(net, &fl4); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); } if (err) goto errout_free; skb_dst_set(skb, &rt->dst); if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; err = rt_fill_info(net, dst, src, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0); if (err <= 0) goto errout_free; err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: kfree_skb(skb); goto errout; } 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_timeout __read_mostly = RT_GC_TIMEOUT; 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 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 == NULL) 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 == NULL) 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); get_random_bytes(&net->ipv4.dev_addr_genid, sizeof(net->ipv4.dev_addr_genid)); 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 rc = 0; ip_idents = kmalloc(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)); #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, NULL); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return rc; } #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_759_0
crossvul-cpp_data_good_5760_0
#include "sb_pci_mp.h" #include <linux/module.h> #include <linux/parport.h> extern struct parport *parport_pc_probe_port(unsigned long base_lo, unsigned long base_hi, int irq, int dma, struct device *dev, int irqflags); static struct mp_device_t mp_devs[MAX_MP_DEV]; static int mp_nrpcibrds = sizeof(mp_pciboards)/sizeof(mppcibrd_t); static int NR_BOARD=0; static int NR_PORTS=0; static struct mp_port multi_ports[MAX_MP_PORT]; static struct irq_info irq_lists[NR_IRQS]; static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset); static _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value); static _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset); static int sb1054_get_register(struct sb_uart_port *port, int page, int reg); static int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value); static void SendATCommand(struct mp_port *mtpt); static int set_deep_fifo(struct sb_uart_port *port, int status); static int get_deep_fifo(struct sb_uart_port *port); static int get_device_type(int arg); static int set_auto_rts(struct sb_uart_port *port, int status); static void mp_stop(struct tty_struct *tty); static void __mp_start(struct tty_struct *tty); static void mp_start(struct tty_struct *tty); static void mp_tasklet_action(unsigned long data); static inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear); static int mp_startup(struct sb_uart_state *state, int init_hw); static void mp_shutdown(struct sb_uart_state *state); static void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios); static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c); static int mp_put_char(struct tty_struct *tty, unsigned char ch); static void mp_put_chars(struct tty_struct *tty); static int mp_write(struct tty_struct *tty, const unsigned char *buf, int count); static int mp_write_room(struct tty_struct *tty); static int mp_chars_in_buffer(struct tty_struct *tty); static void mp_flush_buffer(struct tty_struct *tty); static void mp_send_xchar(struct tty_struct *tty, char ch); static void mp_throttle(struct tty_struct *tty); static void mp_unthrottle(struct tty_struct *tty); static int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo); static int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo); static int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value); static int mp_tiocmget(struct tty_struct *tty); static int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear); static int mp_break_ctl(struct tty_struct *tty, int break_state); static int mp_do_autoconfig(struct sb_uart_state *state); static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg); static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt); static int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg); static void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios); static void mp_close(struct tty_struct *tty, struct file *filp); static void mp_wait_until_sent(struct tty_struct *tty, int timeout); static void mp_hangup(struct tty_struct *tty); static void mp_update_termios(struct sb_uart_state *state); static int mp_block_til_ready(struct file *filp, struct sb_uart_state *state); static struct sb_uart_state *uart_get(struct uart_driver *drv, int line); static int mp_open(struct tty_struct *tty, struct file *filp); static const char *mp_type(struct sb_uart_port *port); static void mp_change_pm(struct sb_uart_state *state, int pm_state); static inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port); static void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port); static void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state); static int mp_register_driver(struct uart_driver *drv); static void mp_unregister_driver(struct uart_driver *drv); static int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port); static int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port); static void autoconfig(struct mp_port *mtpt, unsigned int probeflags); static void autoconfig_irq(struct mp_port *mtpt); static void multi_stop_tx(struct sb_uart_port *port); static void multi_start_tx(struct sb_uart_port *port); static void multi_stop_rx(struct sb_uart_port *port); static void multi_enable_ms(struct sb_uart_port *port); static _INLINE_ void receive_chars(struct mp_port *mtpt, int *status ); static _INLINE_ void transmit_chars(struct mp_port *mtpt); static _INLINE_ void check_modem_status(struct mp_port *mtpt); static inline void multi_handle_port(struct mp_port *mtpt); static irqreturn_t multi_interrupt(int irq, void *dev_id); static void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt); static int serial_link_irq_chain(struct mp_port *mtpt); static void serial_unlink_irq_chain(struct mp_port *mtpt); static void multi_timeout(unsigned long data); static unsigned int multi_tx_empty(struct sb_uart_port *port); static unsigned int multi_get_mctrl(struct sb_uart_port *port); static void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl); static void multi_break_ctl(struct sb_uart_port *port, int break_state); static int multi_startup(struct sb_uart_port *port); static void multi_shutdown(struct sb_uart_port *port); static unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud); static void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old); static void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate); static void multi_release_std_resource(struct mp_port *mtpt); static void multi_release_port(struct sb_uart_port *port); static int multi_request_port(struct sb_uart_port *port); static void multi_config_port(struct sb_uart_port *port, int flags); static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser); static const char *multi_type(struct sb_uart_port *port); static void __init multi_init_ports(void); static void __init multi_register_ports(struct uart_driver *drv); static int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd); static int deep[256]; static int deep_count; static int fcr_arr[256]; static int fcr_count; static int ttr[256]; static int ttr_count; static int rtr[256]; static int rtr_count; module_param_array(deep,int,&deep_count,0); module_param_array(fcr_arr,int,&fcr_count,0); module_param_array(ttr,int,&ttr_count,0); module_param_array(rtr,int,&rtr_count,0); static _INLINE_ unsigned int serial_in(struct mp_port *mtpt, int offset) { return inb(mtpt->port.iobase + offset); } static _INLINE_ void serial_out(struct mp_port *mtpt, int offset, int value) { outb(value, mtpt->port.iobase + offset); } static _INLINE_ unsigned int read_option_register(struct mp_port *mtpt, int offset) { return inb(mtpt->option_base_addr + offset); } static int sb1053a_get_interface(struct mp_port *mtpt, int port_num) { unsigned long option_base_addr = mtpt->option_base_addr; unsigned int interface = 0; switch (port_num) { case 0: case 1: /* set GPO[1:0] = 00 */ outb(0x00, option_base_addr + MP_OPTR_GPODR); break; case 2: case 3: /* set GPO[1:0] = 01 */ outb(0x01, option_base_addr + MP_OPTR_GPODR); break; case 4: case 5: /* set GPO[1:0] = 10 */ outb(0x02, option_base_addr + MP_OPTR_GPODR); break; default: break; } port_num &= 0x1; /* get interface */ interface = inb(option_base_addr + MP_OPTR_IIR0 + port_num); /* set GPO[1:0] = 11 */ outb(0x03, option_base_addr + MP_OPTR_GPODR); return (interface); } static int sb1054_get_register(struct sb_uart_port *port, int page, int reg) { int ret = 0; unsigned int lcr = 0; unsigned int mcr = 0; unsigned int tmp = 0; if( page <= 0) { printk(" page 0 can not use this fuction\n"); return -1; } switch(page) { case 1: lcr = SB105X_GET_LCR(port); tmp = lcr | SB105X_LCR_DLAB; SB105X_PUT_LCR(port, tmp); tmp = SB105X_GET_LCR(port); ret = SB105X_GET_REG(port,reg); SB105X_PUT_LCR(port,lcr); break; case 2: mcr = SB105X_GET_MCR(port); tmp = mcr | SB105X_MCR_P2S; SB105X_PUT_MCR(port,tmp); ret = SB105X_GET_REG(port,reg); SB105X_PUT_MCR(port,mcr); break; case 3: lcr = SB105X_GET_LCR(port); tmp = lcr | SB105X_LCR_BF; SB105X_PUT_LCR(port,tmp); SB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P3KEY); ret = SB105X_GET_REG(port,reg); SB105X_PUT_LCR(port,lcr); break; case 4: lcr = SB105X_GET_LCR(port); tmp = lcr | SB105X_LCR_BF; SB105X_PUT_LCR(port,tmp); SB105X_PUT_REG(port,SB105X_PSR,SB105X_PSR_P4KEY); ret = SB105X_GET_REG(port,reg); SB105X_PUT_LCR(port,lcr); break; default: printk(" error invalid page number \n"); return -1; } return ret; } static int sb1054_set_register(struct sb_uart_port *port, int page, int reg, int value) { int lcr = 0; int mcr = 0; int ret = 0; if( page <= 0) { printk(" page 0 can not use this fuction\n"); return -1; } switch(page) { case 1: lcr = SB105X_GET_LCR(port); SB105X_PUT_LCR(port, lcr | SB105X_LCR_DLAB); SB105X_PUT_REG(port,reg,value); SB105X_PUT_LCR(port, lcr); ret = 1; break; case 2: mcr = SB105X_GET_MCR(port); SB105X_PUT_MCR(port, mcr | SB105X_MCR_P2S); SB105X_PUT_REG(port,reg,value); SB105X_PUT_MCR(port, mcr); ret = 1; break; case 3: lcr = SB105X_GET_LCR(port); SB105X_PUT_LCR(port, lcr | SB105X_LCR_BF); SB105X_PUT_PSR(port, SB105X_PSR_P3KEY); SB105X_PUT_REG(port,reg,value); SB105X_PUT_LCR(port, lcr); ret = 1; break; case 4: lcr = SB105X_GET_LCR(port); SB105X_PUT_LCR(port, lcr | SB105X_LCR_BF); SB105X_PUT_PSR(port, SB105X_PSR_P4KEY); SB105X_PUT_REG(port,reg,value); SB105X_PUT_LCR(port, lcr); ret = 1; break; default: printk(" error invalid page number \n"); return -1; } return ret; } static int set_multidrop_mode(struct sb_uart_port *port, unsigned int mode) { int mdr = SB105XA_MDR_NPS; if (mode & MDMODE_ENABLE) { mdr |= SB105XA_MDR_MDE; } if (1) //(mode & MDMODE_AUTO) { int efr = 0; mdr |= SB105XA_MDR_AME; efr = sb1054_get_register(port, PAGE_3, SB105X_EFR); efr |= SB105X_EFR_SCD; sb1054_set_register(port, PAGE_3, SB105X_EFR, efr); } sb1054_set_register(port, PAGE_1, SB105XA_MDR, mdr); port->mdmode &= ~0x6; port->mdmode |= mode; printk("[%d] multidrop init: %x\n", port->line, port->mdmode); return 0; } static int get_multidrop_addr(struct sb_uart_port *port) { return sb1054_get_register(port, PAGE_3, SB105X_XOFF2); } static int set_multidrop_addr(struct sb_uart_port *port, unsigned int addr) { sb1054_set_register(port, PAGE_3, SB105X_XOFF2, addr); return 0; } static void SendATCommand(struct mp_port *mtpt) { // a t cr lf unsigned char ch[] = {0x61,0x74,0x0d,0x0a,0x0}; unsigned char lineControl; unsigned char i=0; unsigned char Divisor = 0xc; lineControl = serial_inp(mtpt,UART_LCR); serial_outp(mtpt,UART_LCR,(lineControl | UART_LCR_DLAB)); serial_outp(mtpt,UART_DLL,(Divisor & 0xff)); serial_outp(mtpt,UART_DLM,(Divisor & 0xff00)>>8); //baudrate is 4800 serial_outp(mtpt,UART_LCR,lineControl); serial_outp(mtpt,UART_LCR,0x03); // N-8-1 serial_outp(mtpt,UART_FCR,7); serial_outp(mtpt,UART_MCR,0x3); while(ch[i]){ while((serial_inp(mtpt,UART_LSR) & 0x60) !=0x60){ ; } serial_outp(mtpt,0,ch[i++]); } }// end of SendATCommand() static int set_deep_fifo(struct sb_uart_port *port, int status) { int afr_status = 0; afr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR); if(status == ENABLE) { afr_status |= SB105X_AFR_AFEN; } else { afr_status &= ~SB105X_AFR_AFEN; } sb1054_set_register(port,PAGE_4,SB105X_AFR,afr_status); sb1054_set_register(port,PAGE_4,SB105X_TTR,ttr[port->line]); sb1054_set_register(port,PAGE_4,SB105X_RTR,rtr[port->line]); afr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR); return afr_status; } static int get_device_type(int arg) { int ret; ret = inb(mp_devs[arg].option_reg_addr+MP_OPTR_DIR0); ret = (ret & 0xf0) >> 4; switch (ret) { case DIR_UART_16C550: return PORT_16C55X; case DIR_UART_16C1050: return PORT_16C105X; case DIR_UART_16C1050A: /* if (mtpt->port.line < 2) { return PORT_16C105XA; } else { if (mtpt->device->device_id & 0x50) { return PORT_16C55X; } else { return PORT_16C105X; } }*/ return PORT_16C105XA; default: return PORT_UNKNOWN; } } static int get_deep_fifo(struct sb_uart_port *port) { int afr_status = 0; afr_status = sb1054_get_register(port, PAGE_4, SB105X_AFR); return afr_status; } static int set_auto_rts(struct sb_uart_port *port, int status) { int atr_status = 0; #if 0 int efr_status = 0; efr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR); if(status == ENABLE) efr_status |= SB105X_EFR_ARTS; else efr_status &= ~SB105X_EFR_ARTS; sb1054_set_register(port,PAGE_3,SB105X_EFR,efr_status); efr_status = sb1054_get_register(port, PAGE_3, SB105X_EFR); #endif //ATR atr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR); switch(status) { case RS422PTP: atr_status = (SB105X_ATR_TPS) | (SB105X_ATR_A80); break; case RS422MD: atr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80); break; case RS485NE: atr_status = (SB105X_ATR_RCMS) | (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80); break; case RS485ECHO: atr_status = (SB105X_ATR_TPS) | (SB105X_ATR_TCMS) | (SB105X_ATR_A80); break; } sb1054_set_register(port,PAGE_3,SB105X_ATR,atr_status); atr_status = sb1054_get_register(port, PAGE_3, SB105X_ATR); return atr_status; } static void mp_stop(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; unsigned long flags; spin_lock_irqsave(&port->lock, flags); port->ops->stop_tx(port); spin_unlock_irqrestore(&port->lock, flags); } static void __mp_start(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; if (!uart_circ_empty(&state->info->xmit) && state->info->xmit.buf && !tty->stopped && !tty->hw_stopped) port->ops->start_tx(port); } static void mp_start(struct tty_struct *tty) { __mp_start(tty); } static void mp_tasklet_action(unsigned long data) { struct sb_uart_state *state = (struct sb_uart_state *)data; struct tty_struct *tty; printk("tasklet is called!\n"); tty = state->info->tty; tty_wakeup(tty); } static inline void mp_update_mctrl(struct sb_uart_port *port, unsigned int set, unsigned int clear) { unsigned int old; old = port->mctrl; port->mctrl = (old & ~clear) | set; if (old != port->mctrl) port->ops->set_mctrl(port, port->mctrl); } #define uart_set_mctrl(port,set) mp_update_mctrl(port,set,0) #define uart_clear_mctrl(port,clear) mp_update_mctrl(port,0,clear) static int mp_startup(struct sb_uart_state *state, int init_hw) { struct sb_uart_info *info = state->info; struct sb_uart_port *port = state->port; unsigned long page; int retval = 0; if (info->flags & UIF_INITIALIZED) return 0; if (info->tty) set_bit(TTY_IO_ERROR, &info->tty->flags); if (port->type == PORT_UNKNOWN) return 0; if (!info->xmit.buf) { page = get_zeroed_page(GFP_KERNEL); if (!page) return -ENOMEM; info->xmit.buf = (unsigned char *) page; uart_circ_clear(&info->xmit); } retval = port->ops->startup(port); if (retval == 0) { if (init_hw) { mp_change_speed(state, NULL); if (info->tty->termios.c_cflag & CBAUD) uart_set_mctrl(port, TIOCM_RTS | TIOCM_DTR); } info->flags |= UIF_INITIALIZED; clear_bit(TTY_IO_ERROR, &info->tty->flags); } if (retval && capable(CAP_SYS_ADMIN)) retval = 0; return retval; } static void mp_shutdown(struct sb_uart_state *state) { struct sb_uart_info *info = state->info; struct sb_uart_port *port = state->port; if (info->tty) set_bit(TTY_IO_ERROR, &info->tty->flags); if (info->flags & UIF_INITIALIZED) { info->flags &= ~UIF_INITIALIZED; if (!info->tty || (info->tty->termios.c_cflag & HUPCL)) uart_clear_mctrl(port, TIOCM_DTR | TIOCM_RTS); wake_up_interruptible(&info->delta_msr_wait); port->ops->shutdown(port); synchronize_irq(port->irq); } tasklet_kill(&info->tlet); if (info->xmit.buf) { free_page((unsigned long)info->xmit.buf); info->xmit.buf = NULL; } } static void mp_change_speed(struct sb_uart_state *state, struct MP_TERMIOS *old_termios) { struct tty_struct *tty = state->info->tty; struct sb_uart_port *port = state->port; if (!tty || port->type == PORT_UNKNOWN) return; if (tty->termios.c_cflag & CRTSCTS) state->info->flags |= UIF_CTS_FLOW; else state->info->flags &= ~UIF_CTS_FLOW; if (tty->termios.c_cflag & CLOCAL) state->info->flags &= ~UIF_CHECK_CD; else state->info->flags |= UIF_CHECK_CD; port->ops->set_termios(port, &tty->termios, old_termios); } static inline int __mp_put_char(struct sb_uart_port *port, struct circ_buf *circ, unsigned char c) { unsigned long flags; int ret = 0; if (!circ->buf) return 0; spin_lock_irqsave(&port->lock, flags); if (uart_circ_chars_free(circ) != 0) { circ->buf[circ->head] = c; circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1); ret = 1; } spin_unlock_irqrestore(&port->lock, flags); return ret; } static int mp_put_char(struct tty_struct *tty, unsigned char ch) { struct sb_uart_state *state = tty->driver_data; return __mp_put_char(state->port, &state->info->xmit, ch); } static void mp_put_chars(struct tty_struct *tty) { mp_start(tty); } static int mp_write(struct tty_struct *tty, const unsigned char *buf, int count) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port; struct circ_buf *circ; int c, ret = 0; if (!state || !state->info) { return -EL3HLT; } port = state->port; circ = &state->info->xmit; if (!circ->buf) return 0; while (1) { c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE); if (count < c) c = count; if (c <= 0) break; memcpy(circ->buf + circ->head, buf, c); circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1); buf += c; count -= c; ret += c; } mp_start(tty); return ret; } static int mp_write_room(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; return uart_circ_chars_free(&state->info->xmit); } static int mp_chars_in_buffer(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; return uart_circ_chars_pending(&state->info->xmit); } static void mp_flush_buffer(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port; unsigned long flags; if (!state || !state->info) { return; } port = state->port; spin_lock_irqsave(&port->lock, flags); uart_circ_clear(&state->info->xmit); spin_unlock_irqrestore(&port->lock, flags); wake_up_interruptible(&tty->write_wait); tty_wakeup(tty); } static void mp_send_xchar(struct tty_struct *tty, char ch) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; unsigned long flags; if (port->ops->send_xchar) port->ops->send_xchar(port, ch); else { port->x_char = ch; if (ch) { spin_lock_irqsave(&port->lock, flags); port->ops->start_tx(port); spin_unlock_irqrestore(&port->lock, flags); } } } static void mp_throttle(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; if (I_IXOFF(tty)) mp_send_xchar(tty, STOP_CHAR(tty)); if (tty->termios.c_cflag & CRTSCTS) uart_clear_mctrl(state->port, TIOCM_RTS); } static void mp_unthrottle(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; if (I_IXOFF(tty)) { if (port->x_char) port->x_char = 0; else mp_send_xchar(tty, START_CHAR(tty)); } if (tty->termios.c_cflag & CRTSCTS) uart_set_mctrl(port, TIOCM_RTS); } static int mp_get_info(struct sb_uart_state *state, struct serial_struct *retinfo) { struct sb_uart_port *port = state->port; struct serial_struct tmp; memset(&tmp, 0, sizeof(tmp)); tmp.type = port->type; tmp.line = port->line; tmp.port = port->iobase; if (HIGH_BITS_OFFSET) tmp.port_high = (long) port->iobase >> HIGH_BITS_OFFSET; tmp.irq = port->irq; tmp.flags = port->flags; tmp.xmit_fifo_size = port->fifosize; tmp.baud_base = port->uartclk / 16; tmp.close_delay = state->close_delay; tmp.closing_wait = state->closing_wait == USF_CLOSING_WAIT_NONE ? ASYNC_CLOSING_WAIT_NONE : state->closing_wait; tmp.custom_divisor = port->custom_divisor; tmp.hub6 = port->hub6; tmp.io_type = port->iotype; tmp.iomem_reg_shift = port->regshift; tmp.iomem_base = (void *)port->mapbase; if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) return -EFAULT; return 0; } static int mp_set_info(struct sb_uart_state *state, struct serial_struct *newinfo) { struct serial_struct new_serial; struct sb_uart_port *port = state->port; unsigned long new_port; unsigned int change_irq, change_port, closing_wait; unsigned int old_custom_divisor; unsigned int old_flags, new_flags; int retval = 0; if (copy_from_user(&new_serial, newinfo, sizeof(new_serial))) return -EFAULT; new_port = new_serial.port; if (HIGH_BITS_OFFSET) new_port += (unsigned long) new_serial.port_high << HIGH_BITS_OFFSET; new_serial.irq = irq_canonicalize(new_serial.irq); closing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ? USF_CLOSING_WAIT_NONE : new_serial.closing_wait; MP_STATE_LOCK(state); change_irq = new_serial.irq != port->irq; change_port = new_port != port->iobase || (unsigned long)new_serial.iomem_base != port->mapbase || new_serial.hub6 != port->hub6 || new_serial.io_type != port->iotype || new_serial.iomem_reg_shift != port->regshift || new_serial.type != port->type; old_flags = port->flags; new_flags = new_serial.flags; old_custom_divisor = port->custom_divisor; if (!capable(CAP_SYS_ADMIN)) { retval = -EPERM; if (change_irq || change_port || (new_serial.baud_base != port->uartclk / 16) || (new_serial.close_delay != state->close_delay) || (closing_wait != state->closing_wait) || (new_serial.xmit_fifo_size != port->fifosize) || (((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0)) goto exit; port->flags = ((port->flags & ~UPF_USR_MASK) | (new_flags & UPF_USR_MASK)); port->custom_divisor = new_serial.custom_divisor; goto check_and_exit; } if (port->ops->verify_port) retval = port->ops->verify_port(port, &new_serial); if ((new_serial.irq >= NR_IRQS) || (new_serial.irq < 0) || (new_serial.baud_base < 9600)) retval = -EINVAL; if (retval) goto exit; if (change_port || change_irq) { retval = -EBUSY; if (uart_users(state) > 1) goto exit; mp_shutdown(state); } if (change_port) { unsigned long old_iobase, old_mapbase; unsigned int old_type, old_iotype, old_hub6, old_shift; old_iobase = port->iobase; old_mapbase = port->mapbase; old_type = port->type; old_hub6 = port->hub6; old_iotype = port->iotype; old_shift = port->regshift; if (old_type != PORT_UNKNOWN) port->ops->release_port(port); port->iobase = new_port; port->type = new_serial.type; port->hub6 = new_serial.hub6; port->iotype = new_serial.io_type; port->regshift = new_serial.iomem_reg_shift; port->mapbase = (unsigned long)new_serial.iomem_base; if (port->type != PORT_UNKNOWN) { retval = port->ops->request_port(port); } else { retval = 0; } if (retval && old_type != PORT_UNKNOWN) { port->iobase = old_iobase; port->type = old_type; port->hub6 = old_hub6; port->iotype = old_iotype; port->regshift = old_shift; port->mapbase = old_mapbase; retval = port->ops->request_port(port); if (retval) port->type = PORT_UNKNOWN; retval = -EBUSY; } } port->irq = new_serial.irq; port->uartclk = new_serial.baud_base * 16; port->flags = (port->flags & ~UPF_CHANGE_MASK) | (new_flags & UPF_CHANGE_MASK); port->custom_divisor = new_serial.custom_divisor; state->close_delay = new_serial.close_delay; state->closing_wait = closing_wait; port->fifosize = new_serial.xmit_fifo_size; if (state->info->tty) state->info->tty->low_latency = (port->flags & UPF_LOW_LATENCY) ? 1 : 0; check_and_exit: retval = 0; if (port->type == PORT_UNKNOWN) goto exit; if (state->info->flags & UIF_INITIALIZED) { if (((old_flags ^ port->flags) & UPF_SPD_MASK) || old_custom_divisor != port->custom_divisor) { if (port->flags & UPF_SPD_MASK) { printk(KERN_NOTICE "%s sets custom speed on ttyMP%d. This " "is deprecated.\n", current->comm, port->line); } mp_change_speed(state, NULL); } } else retval = mp_startup(state, 1); exit: MP_STATE_UNLOCK(state); return retval; } static int mp_get_lsr_info(struct sb_uart_state *state, unsigned int *value) { struct sb_uart_port *port = state->port; unsigned int result; result = port->ops->tx_empty(port); if (port->x_char || ((uart_circ_chars_pending(&state->info->xmit) > 0) && !state->info->tty->stopped && !state->info->tty->hw_stopped)) result &= ~TIOCSER_TEMT; return put_user(result, value); } static int mp_tiocmget(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; int result = -EIO; MP_STATE_LOCK(state); if (!(tty->flags & (1 << TTY_IO_ERROR))) { result = port->mctrl; spin_lock_irq(&port->lock); result |= port->ops->get_mctrl(port); spin_unlock_irq(&port->lock); } MP_STATE_UNLOCK(state); return result; } static int mp_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; int ret = -EIO; MP_STATE_LOCK(state); if (!(tty->flags & (1 << TTY_IO_ERROR))) { mp_update_mctrl(port, set, clear); ret = 0; } MP_STATE_UNLOCK(state); return ret; } static int mp_break_ctl(struct tty_struct *tty, int break_state) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; MP_STATE_LOCK(state); if (port->type != PORT_UNKNOWN) port->ops->break_ctl(port, break_state); MP_STATE_UNLOCK(state); return 0; } static int mp_do_autoconfig(struct sb_uart_state *state) { struct sb_uart_port *port = state->port; int flags, ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (mutex_lock_interruptible(&state->mutex)) return -ERESTARTSYS; ret = -EBUSY; if (uart_users(state) == 1) { mp_shutdown(state); if (port->type != PORT_UNKNOWN) port->ops->release_port(port); flags = UART_CONFIG_TYPE; if (port->flags & UPF_AUTO_IRQ) flags |= UART_CONFIG_IRQ; port->ops->config_port(port, flags); ret = mp_startup(state, 1); } MP_STATE_UNLOCK(state); return ret; } static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg) { struct sb_uart_port *port = state->port; DECLARE_WAITQUEUE(wait, current); struct sb_uart_icount cprev, cnow; int ret; spin_lock_irq(&port->lock); memcpy(&cprev, &port->icount, sizeof(struct sb_uart_icount)); port->ops->enable_ms(port); spin_unlock_irq(&port->lock); add_wait_queue(&state->info->delta_msr_wait, &wait); for (;;) { spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); set_current_state(TASK_INTERRUPTIBLE); if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) || ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) || ((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) || ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) { ret = 0; break; } schedule(); if (signal_pending(current)) { ret = -ERESTARTSYS; break; } cprev = cnow; } current->state = TASK_RUNNING; remove_wait_queue(&state->info->delta_msr_wait, &wait); return ret; } static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount = {}; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; } static int mp_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct sb_uart_state *state = tty->driver_data; struct mp_port *info = (struct mp_port *)state->port; int ret = -ENOIOCTLCMD; switch (cmd) { case TIOCSMULTIDROP: /* set multi-drop mode enable or disable, and default operation mode is H/W mode */ if (info->port.type == PORT_16C105XA) { //arg &= ~0x6; //state->port->mdmode = 0; return set_multidrop_mode((struct sb_uart_port *)info, (unsigned int)arg); } ret = -ENOTSUPP; break; case GETDEEPFIFO: ret = get_deep_fifo(state->port); return ret; case SETDEEPFIFO: ret = set_deep_fifo(state->port,arg); deep[state->port->line] = arg; return ret; case SETTTR: if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){ ret = sb1054_set_register(state->port,PAGE_4,SB105X_TTR,arg); ttr[state->port->line] = arg; } return ret; case SETRTR: if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){ ret = sb1054_set_register(state->port,PAGE_4,SB105X_RTR,arg); rtr[state->port->line] = arg; } return ret; case GETTTR: if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){ ret = sb1054_get_register(state->port,PAGE_4,SB105X_TTR); } return ret; case GETRTR: if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){ ret = sb1054_get_register(state->port,PAGE_4,SB105X_RTR); } return ret; case SETFCR: if (info->port.type == PORT_16C105X || info->port.type == PORT_16C105XA){ ret = sb1054_set_register(state->port,PAGE_1,SB105X_FCR,arg); } else{ serial_out(info,2,arg); } return ret; case TIOCSMDADDR: /* set multi-drop address */ if (info->port.type == PORT_16C105XA) { state->port->mdmode |= MDMODE_ADDR; return set_multidrop_addr((struct sb_uart_port *)info, (unsigned int)arg); } ret = -ENOTSUPP; break; case TIOCGMDADDR: /* set multi-drop address */ if ((info->port.type == PORT_16C105XA) && (state->port->mdmode & MDMODE_ADDR)) { return get_multidrop_addr((struct sb_uart_port *)info); } ret = -ENOTSUPP; break; case TIOCSENDADDR: /* send address in multi-drop mode */ if ((info->port.type == PORT_16C105XA) && (state->port->mdmode & (MDMODE_ENABLE))) { if (mp_chars_in_buffer(tty) > 0) { tty_wait_until_sent(tty, 0); } //while ((serial_in(info, UART_LSR) & 0x60) != 0x60); //while (sb1054_get_register(state->port, PAGE_2, SB105X_TFCR) != 0); while ((serial_in(info, UART_LSR) & 0x60) != 0x60); serial_out(info, UART_SCR, (int)arg); } break; case TIOCGSERIAL: ret = mp_get_info(state, (struct serial_struct *)arg); break; case TIOCSSERIAL: ret = mp_set_info(state, (struct serial_struct *)arg); break; case TIOCSERCONFIG: ret = mp_do_autoconfig(state); break; case TIOCSERGWILD: /* obsolete */ case TIOCSERSWILD: /* obsolete */ ret = 0; break; /* for Multiport */ case TIOCGNUMOFPORT: /* Get number of ports */ return NR_PORTS; case TIOCGGETDEVID: return mp_devs[arg].device_id; case TIOCGGETREV: return mp_devs[arg].revision; case TIOCGGETNRPORTS: return mp_devs[arg].nr_ports; case TIOCGGETBDNO: return NR_BOARD; case TIOCGGETINTERFACE: if (mp_devs[arg].revision == 0xc0) { /* for SB16C1053APCI */ return (sb1053a_get_interface(info, info->port.line)); } else { return (inb(mp_devs[arg].option_reg_addr+MP_OPTR_IIR0+(state->port->line/8))); } case TIOCGGETPORTTYPE: ret = get_device_type(arg);; return ret; case TIOCSMULTIECHO: /* set to multi-drop mode(RS422) or echo mode(RS485)*/ outb( ( inb(info->interface_config_addr) & ~0x03 ) | 0x01 , info->interface_config_addr); return 0; case TIOCSPTPNOECHO: /* set to multi-drop mode(RS422) or echo mode(RS485) */ outb( ( inb(info->interface_config_addr) & ~0x03 ) , info->interface_config_addr); return 0; } if (ret != -ENOIOCTLCMD) goto out; if (tty->flags & (1 << TTY_IO_ERROR)) { ret = -EIO; goto out; } switch (cmd) { case TIOCMIWAIT: ret = mp_wait_modem_status(state, arg); break; case TIOCGICOUNT: ret = mp_get_count(state, (struct serial_icounter_struct *)arg); break; } if (ret != -ENOIOCTLCMD) goto out; MP_STATE_LOCK(state); switch (cmd) { case TIOCSERGETLSR: /* Get line status register */ ret = mp_get_lsr_info(state, (unsigned int *)arg); break; default: { struct sb_uart_port *port = state->port; if (port->ops->ioctl) ret = port->ops->ioctl(port, cmd, arg); break; } } MP_STATE_UNLOCK(state); out: return ret; } static void mp_set_termios(struct tty_struct *tty, struct MP_TERMIOS *old_termios) { struct sb_uart_state *state = tty->driver_data; unsigned long flags; unsigned int cflag = tty->termios.c_cflag; #define RELEVANT_IFLAG(iflag) ((iflag) & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK)) if ((cflag ^ old_termios->c_cflag) == 0 && RELEVANT_IFLAG(tty->termios.c_iflag ^ old_termios->c_iflag) == 0) return; mp_change_speed(state, old_termios); if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD)) uart_clear_mctrl(state->port, TIOCM_RTS | TIOCM_DTR); if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) { unsigned int mask = TIOCM_DTR; if (!(cflag & CRTSCTS) || !test_bit(TTY_THROTTLED, &tty->flags)) mask |= TIOCM_RTS; uart_set_mctrl(state->port, mask); } if ((old_termios->c_cflag & CRTSCTS) && !(cflag & CRTSCTS)) { spin_lock_irqsave(&state->port->lock, flags); tty->hw_stopped = 0; __mp_start(tty); spin_unlock_irqrestore(&state->port->lock, flags); } if (!(old_termios->c_cflag & CRTSCTS) && (cflag & CRTSCTS)) { spin_lock_irqsave(&state->port->lock, flags); if (!(state->port->ops->get_mctrl(state->port) & TIOCM_CTS)) { tty->hw_stopped = 1; state->port->ops->stop_tx(state->port); } spin_unlock_irqrestore(&state->port->lock, flags); } } static void mp_close(struct tty_struct *tty, struct file *filp) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port; printk("mp_close!\n"); if (!state || !state->port) return; port = state->port; printk("close1 %d\n", __LINE__); MP_STATE_LOCK(state); printk("close2 %d\n", __LINE__); if (tty_hung_up_p(filp)) goto done; printk("close3 %d\n", __LINE__); if ((tty->count == 1) && (state->count != 1)) { printk("mp_close: bad serial port count; tty->count is 1, " "state->count is %d\n", state->count); state->count = 1; } printk("close4 %d\n", __LINE__); if (--state->count < 0) { printk("rs_close: bad serial port count for ttyMP%d: %d\n", port->line, state->count); state->count = 0; } if (state->count) goto done; tty->closing = 1; printk("close5 %d\n", __LINE__); if (state->closing_wait != USF_CLOSING_WAIT_NONE) tty_wait_until_sent(tty, state->closing_wait); printk("close6 %d\n", __LINE__); if (state->info->flags & UIF_INITIALIZED) { unsigned long flags; spin_lock_irqsave(&port->lock, flags); port->ops->stop_rx(port); spin_unlock_irqrestore(&port->lock, flags); mp_wait_until_sent(tty, port->timeout); } printk("close7 %d\n", __LINE__); mp_shutdown(state); printk("close8 %d\n", __LINE__); mp_flush_buffer(tty); tty_ldisc_flush(tty); tty->closing = 0; state->info->tty = NULL; if (state->info->blocked_open) { if (state->close_delay) { set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(state->close_delay); } } else { mp_change_pm(state, 3); } printk("close8 %d\n", __LINE__); state->info->flags &= ~UIF_NORMAL_ACTIVE; wake_up_interruptible(&state->info->open_wait); done: printk("close done\n"); MP_STATE_UNLOCK(state); module_put(THIS_MODULE); } static void mp_wait_until_sent(struct tty_struct *tty, int timeout) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; unsigned long char_time, expire; if (port->type == PORT_UNKNOWN || port->fifosize == 0) return; char_time = (port->timeout - HZ/50) / port->fifosize; char_time = char_time / 5; if (char_time == 0) char_time = 1; if (timeout && timeout < char_time) char_time = timeout; if (timeout == 0 || timeout > 2 * port->timeout) timeout = 2 * port->timeout; expire = jiffies + timeout; while (!port->ops->tx_empty(port)) { set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(char_time); if (signal_pending(current)) break; if (time_after(jiffies, expire)) break; } set_current_state(TASK_RUNNING); /* might not be needed */ } static void mp_hangup(struct tty_struct *tty) { struct sb_uart_state *state = tty->driver_data; MP_STATE_LOCK(state); if (state->info && state->info->flags & UIF_NORMAL_ACTIVE) { mp_flush_buffer(tty); mp_shutdown(state); state->count = 0; state->info->flags &= ~UIF_NORMAL_ACTIVE; state->info->tty = NULL; wake_up_interruptible(&state->info->open_wait); wake_up_interruptible(&state->info->delta_msr_wait); } MP_STATE_UNLOCK(state); } static void mp_update_termios(struct sb_uart_state *state) { struct tty_struct *tty = state->info->tty; struct sb_uart_port *port = state->port; if (!(tty->flags & (1 << TTY_IO_ERROR))) { mp_change_speed(state, NULL); if (tty->termios.c_cflag & CBAUD) uart_set_mctrl(port, TIOCM_DTR | TIOCM_RTS); } } static int mp_block_til_ready(struct file *filp, struct sb_uart_state *state) { DECLARE_WAITQUEUE(wait, current); struct sb_uart_info *info = state->info; struct sb_uart_port *port = state->port; unsigned int mctrl; info->blocked_open++; state->count--; add_wait_queue(&info->open_wait, &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (tty_hung_up_p(filp) || info->tty == NULL) break; if (!(info->flags & UIF_INITIALIZED)) break; if ((filp->f_flags & O_NONBLOCK) || (info->tty->termios.c_cflag & CLOCAL) || (info->tty->flags & (1 << TTY_IO_ERROR))) { break; } if (info->tty->termios.c_cflag & CBAUD) uart_set_mctrl(port, TIOCM_DTR); spin_lock_irq(&port->lock); port->ops->enable_ms(port); mctrl = port->ops->get_mctrl(port); spin_unlock_irq(&port->lock); if (mctrl & TIOCM_CAR) break; MP_STATE_UNLOCK(state); schedule(); MP_STATE_LOCK(state); if (signal_pending(current)) break; } set_current_state(TASK_RUNNING); remove_wait_queue(&info->open_wait, &wait); state->count++; info->blocked_open--; if (signal_pending(current)) return -ERESTARTSYS; if (!info->tty || tty_hung_up_p(filp)) return -EAGAIN; return 0; } static struct sb_uart_state *uart_get(struct uart_driver *drv, int line) { struct sb_uart_state *state; MP_MUTEX_LOCK(mp_mutex); state = drv->state + line; if (mutex_lock_interruptible(&state->mutex)) { state = ERR_PTR(-ERESTARTSYS); goto out; } state->count++; if (!state->port) { state->count--; MP_STATE_UNLOCK(state); state = ERR_PTR(-ENXIO); goto out; } if (!state->info) { state->info = kmalloc(sizeof(struct sb_uart_info), GFP_KERNEL); if (state->info) { memset(state->info, 0, sizeof(struct sb_uart_info)); init_waitqueue_head(&state->info->open_wait); init_waitqueue_head(&state->info->delta_msr_wait); state->port->info = state->info; tasklet_init(&state->info->tlet, mp_tasklet_action, (unsigned long)state); } else { state->count--; MP_STATE_UNLOCK(state); state = ERR_PTR(-ENOMEM); } } out: MP_MUTEX_UNLOCK(mp_mutex); return state; } static int mp_open(struct tty_struct *tty, struct file *filp) { struct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state; struct sb_uart_state *state; int retval; int line = tty->index; struct mp_port *mtpt; retval = -ENODEV; if (line >= tty->driver->num) goto fail; state = uart_get(drv, line); if (IS_ERR(state)) { retval = PTR_ERR(state); goto fail; } mtpt = (struct mp_port *)state->port; tty->driver_data = state; tty->low_latency = (state->port->flags & UPF_LOW_LATENCY) ? 1 : 0; tty->alt_speed = 0; state->info->tty = tty; if (tty_hung_up_p(filp)) { retval = -EAGAIN; state->count--; MP_STATE_UNLOCK(state); goto fail; } if (state->count == 1) mp_change_pm(state, 0); retval = mp_startup(state, 0); if (retval == 0) retval = mp_block_til_ready(filp, state); MP_STATE_UNLOCK(state); if (retval == 0 && !(state->info->flags & UIF_NORMAL_ACTIVE)) { state->info->flags |= UIF_NORMAL_ACTIVE; mp_update_termios(state); } uart_clear_mctrl(state->port, TIOCM_RTS); try_module_get(THIS_MODULE); fail: return retval; } static const char *mp_type(struct sb_uart_port *port) { const char *str = NULL; if (port->ops->type) str = port->ops->type(port); if (!str) str = "unknown"; return str; } static void mp_change_pm(struct sb_uart_state *state, int pm_state) { struct sb_uart_port *port = state->port; if (port->ops->pm) port->ops->pm(port, pm_state, state->pm_state); state->pm_state = pm_state; } static inline void mp_report_port(struct uart_driver *drv, struct sb_uart_port *port) { char address[64]; switch (port->iotype) { case UPIO_PORT: snprintf(address, sizeof(address),"I/O 0x%x", port->iobase); break; case UPIO_HUB6: snprintf(address, sizeof(address),"I/O 0x%x offset 0x%x", port->iobase, port->hub6); break; case UPIO_MEM: snprintf(address, sizeof(address),"MMIO 0x%lx", port->mapbase); break; default: snprintf(address, sizeof(address),"*unknown*" ); strlcpy(address, "*unknown*", sizeof(address)); break; } printk( "%s%d at %s (irq = %d) is a %s\n", drv->dev_name, port->line, address, port->irq, mp_type(port)); } static void mp_configure_port(struct uart_driver *drv, struct sb_uart_state *state, struct sb_uart_port *port) { unsigned int flags; if (!port->iobase && !port->mapbase && !port->membase) { DPRINTK("%s error \n",__FUNCTION__); return; } flags = UART_CONFIG_TYPE; if (port->flags & UPF_AUTO_IRQ) flags |= UART_CONFIG_IRQ; if (port->flags & UPF_BOOT_AUTOCONF) { port->type = PORT_UNKNOWN; port->ops->config_port(port, flags); } if (port->type != PORT_UNKNOWN) { unsigned long flags; mp_report_port(drv, port); spin_lock_irqsave(&port->lock, flags); port->ops->set_mctrl(port, 0); spin_unlock_irqrestore(&port->lock, flags); mp_change_pm(state, 3); } } static void mp_unconfigure_port(struct uart_driver *drv, struct sb_uart_state *state) { struct sb_uart_port *port = state->port; struct sb_uart_info *info = state->info; if (info && info->tty) tty_hangup(info->tty); MP_STATE_LOCK(state); state->info = NULL; if (port->type != PORT_UNKNOWN) port->ops->release_port(port); port->type = PORT_UNKNOWN; if (info) { tasklet_kill(&info->tlet); kfree(info); } MP_STATE_UNLOCK(state); } static struct tty_operations mp_ops = { .open = mp_open, .close = mp_close, .write = mp_write, .put_char = mp_put_char, .flush_chars = mp_put_chars, .write_room = mp_write_room, .chars_in_buffer= mp_chars_in_buffer, .flush_buffer = mp_flush_buffer, .ioctl = mp_ioctl, .throttle = mp_throttle, .unthrottle = mp_unthrottle, .send_xchar = mp_send_xchar, .set_termios = mp_set_termios, .stop = mp_stop, .start = mp_start, .hangup = mp_hangup, .break_ctl = mp_break_ctl, .wait_until_sent= mp_wait_until_sent, #ifdef CONFIG_PROC_FS .proc_fops = NULL, #endif .tiocmget = mp_tiocmget, .tiocmset = mp_tiocmset, }; static int mp_register_driver(struct uart_driver *drv) { struct tty_driver *normal = NULL; int i, retval; drv->state = kmalloc(sizeof(struct sb_uart_state) * drv->nr, GFP_KERNEL); retval = -ENOMEM; if (!drv->state) { printk("SB PCI Error: Kernel memory allocation error!\n"); goto out; } memset(drv->state, 0, sizeof(struct sb_uart_state) * drv->nr); normal = alloc_tty_driver(drv->nr); if (!normal) { printk("SB PCI Error: tty allocation error!\n"); goto out; } drv->tty_driver = normal; normal->owner = drv->owner; normal->magic = TTY_DRIVER_MAGIC; normal->driver_name = drv->driver_name; normal->name = drv->dev_name; normal->major = drv->major; normal->minor_start = drv->minor; normal->num = MAX_MP_PORT ; normal->type = TTY_DRIVER_TYPE_SERIAL; normal->subtype = SERIAL_TYPE_NORMAL; normal->init_termios = tty_std_termios; normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL; normal->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV; normal->driver_state = drv; tty_set_operations(normal, &mp_ops); for (i = 0; i < drv->nr; i++) { struct sb_uart_state *state = drv->state + i; state->close_delay = 500; state->closing_wait = 30000; mutex_init(&state->mutex); } retval = tty_register_driver(normal); out: if (retval < 0) { printk("Register tty driver Fail!\n"); put_tty_driver(normal); kfree(drv->state); } return retval; } void mp_unregister_driver(struct uart_driver *drv) { struct tty_driver *normal = NULL; normal = drv->tty_driver; if (!normal) { return; } tty_unregister_driver(normal); put_tty_driver(normal); drv->tty_driver = NULL; if (drv->state) { kfree(drv->state); } } static int mp_add_one_port(struct uart_driver *drv, struct sb_uart_port *port) { struct sb_uart_state *state; int ret = 0; if (port->line >= drv->nr) return -EINVAL; state = drv->state + port->line; MP_MUTEX_LOCK(mp_mutex); if (state->port) { ret = -EINVAL; goto out; } state->port = port; spin_lock_init(&port->lock); port->cons = drv->cons; port->info = state->info; mp_configure_port(drv, state, port); tty_register_device(drv->tty_driver, port->line, port->dev); out: MP_MUTEX_UNLOCK(mp_mutex); return ret; } static int mp_remove_one_port(struct uart_driver *drv, struct sb_uart_port *port) { struct sb_uart_state *state = drv->state + port->line; if (state->port != port) printk(KERN_ALERT "Removing wrong port: %p != %p\n", state->port, port); MP_MUTEX_LOCK(mp_mutex); tty_unregister_device(drv->tty_driver, port->line); mp_unconfigure_port(drv, state); state->port = NULL; MP_MUTEX_UNLOCK(mp_mutex); return 0; } static void autoconfig(struct mp_port *mtpt, unsigned int probeflags) { unsigned char status1, scratch, scratch2, scratch3; unsigned char save_lcr, save_mcr; unsigned long flags; unsigned char u_type; unsigned char b_ret = 0; if (!mtpt->port.iobase && !mtpt->port.mapbase && !mtpt->port.membase) return; DEBUG_AUTOCONF("ttyMP%d: autoconf (0x%04x, 0x%p): ", mtpt->port.line, mtpt->port.iobase, mtpt->port.membase); spin_lock_irqsave(&mtpt->port.lock, flags); if (!(mtpt->port.flags & UPF_BUGGY_UART)) { scratch = serial_inp(mtpt, UART_IER); serial_outp(mtpt, UART_IER, 0); #ifdef __i386__ outb(0xff, 0x080); #endif scratch2 = serial_inp(mtpt, UART_IER) & 0x0f; serial_outp(mtpt, UART_IER, 0x0F); #ifdef __i386__ outb(0, 0x080); #endif scratch3 = serial_inp(mtpt, UART_IER) & 0x0F; serial_outp(mtpt, UART_IER, scratch); if (scratch2 != 0 || scratch3 != 0x0F) { DEBUG_AUTOCONF("IER test failed (%02x, %02x) ", scratch2, scratch3); goto out; } } save_mcr = serial_in(mtpt, UART_MCR); save_lcr = serial_in(mtpt, UART_LCR); if (!(mtpt->port.flags & UPF_SKIP_TEST)) { serial_outp(mtpt, UART_MCR, UART_MCR_LOOP | 0x0A); status1 = serial_inp(mtpt, UART_MSR) & 0xF0; serial_outp(mtpt, UART_MCR, save_mcr); if (status1 != 0x90) { DEBUG_AUTOCONF("LOOP test failed (%02x) ", status1); goto out; } } serial_outp(mtpt, UART_LCR, 0xBF); serial_outp(mtpt, UART_EFR, 0); serial_outp(mtpt, UART_LCR, 0); serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO); scratch = serial_in(mtpt, UART_IIR) >> 6; DEBUG_AUTOCONF("iir=%d ", scratch); if(mtpt->device->nr_ports >= 8) b_ret = read_option_register(mtpt,(MP_OPTR_DIR0 + ((mtpt->port.line)/8))); else b_ret = read_option_register(mtpt,MP_OPTR_DIR0); u_type = (b_ret & 0xf0) >> 4; if(mtpt->port.type == PORT_UNKNOWN ) { switch (u_type) { case DIR_UART_16C550: mtpt->port.type = PORT_16C55X; break; case DIR_UART_16C1050: mtpt->port.type = PORT_16C105X; break; case DIR_UART_16C1050A: if (mtpt->port.line < 2) { mtpt->port.type = PORT_16C105XA; } else { if (mtpt->device->device_id & 0x50) { mtpt->port.type = PORT_16C55X; } else { mtpt->port.type = PORT_16C105X; } } break; default: mtpt->port.type = PORT_UNKNOWN; break; } } if(mtpt->port.type == PORT_UNKNOWN ) { printk("unknow2\n"); switch (scratch) { case 0: case 1: mtpt->port.type = PORT_UNKNOWN; break; case 2: case 3: mtpt->port.type = PORT_16C55X; break; } } serial_outp(mtpt, UART_LCR, save_lcr); mtpt->port.fifosize = uart_config[mtpt->port.type].dfl_xmit_fifo_size; mtpt->capabilities = uart_config[mtpt->port.type].flags; if (mtpt->port.type == PORT_UNKNOWN) goto out; serial_outp(mtpt, UART_MCR, save_mcr); serial_outp(mtpt, UART_FCR, (UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT)); serial_outp(mtpt, UART_FCR, 0); (void)serial_in(mtpt, UART_RX); serial_outp(mtpt, UART_IER, 0); out: spin_unlock_irqrestore(&mtpt->port.lock, flags); DEBUG_AUTOCONF("type=%s\n", uart_config[mtpt->port.type].name); } static void autoconfig_irq(struct mp_port *mtpt) { unsigned char save_mcr, save_ier; unsigned long irqs; int irq; /* forget possible initially masked and pending IRQ */ probe_irq_off(probe_irq_on()); save_mcr = serial_inp(mtpt, UART_MCR); save_ier = serial_inp(mtpt, UART_IER); serial_outp(mtpt, UART_MCR, UART_MCR_OUT1 | UART_MCR_OUT2); irqs = probe_irq_on(); serial_outp(mtpt, UART_MCR, 0); serial_outp(mtpt, UART_MCR, UART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2); serial_outp(mtpt, UART_IER, 0x0f); /* enable all intrs */ (void)serial_inp(mtpt, UART_LSR); (void)serial_inp(mtpt, UART_RX); (void)serial_inp(mtpt, UART_IIR); (void)serial_inp(mtpt, UART_MSR); serial_outp(mtpt, UART_TX, 0xFF); irq = probe_irq_off(irqs); serial_outp(mtpt, UART_MCR, save_mcr); serial_outp(mtpt, UART_IER, save_ier); mtpt->port.irq = (irq > 0) ? irq : 0; } static void multi_stop_tx(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; if (mtpt->ier & UART_IER_THRI) { mtpt->ier &= ~UART_IER_THRI; serial_out(mtpt, UART_IER, mtpt->ier); } tasklet_schedule(&port->info->tlet); } static void multi_start_tx(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; if (!(mtpt->ier & UART_IER_THRI)) { mtpt->ier |= UART_IER_THRI; serial_out(mtpt, UART_IER, mtpt->ier); } } static void multi_stop_rx(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; mtpt->ier &= ~UART_IER_RLSI; mtpt->port.read_status_mask &= ~UART_LSR_DR; serial_out(mtpt, UART_IER, mtpt->ier); } static void multi_enable_ms(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; mtpt->ier |= UART_IER_MSI; serial_out(mtpt, UART_IER, mtpt->ier); } static _INLINE_ void receive_chars(struct mp_port *mtpt, int *status ) { struct tty_struct *tty = mtpt->port.info->tty; unsigned char lsr = *status; int max_count = 256; unsigned char ch; char flag; //lsr &= mtpt->port.read_status_mask; do { if ((lsr & UART_LSR_PE) && (mtpt->port.mdmode & MDMODE_ENABLE)) { ch = serial_inp(mtpt, UART_RX); } else if (lsr & UART_LSR_SPECIAL) { flag = 0; ch = serial_inp(mtpt, UART_RX); if (lsr & UART_LSR_BI) { mtpt->port.icount.brk++; flag = TTY_BREAK; if (sb_uart_handle_break(&mtpt->port)) goto ignore_char; } if (lsr & UART_LSR_PE) { mtpt->port.icount.parity++; flag = TTY_PARITY; } if (lsr & UART_LSR_FE) { mtpt->port.icount.frame++; flag = TTY_FRAME; } if (lsr & UART_LSR_OE) { mtpt->port.icount.overrun++; flag = TTY_OVERRUN; } tty_insert_flip_char(tty, ch, flag); } else { ch = serial_inp(mtpt, UART_RX); tty_insert_flip_char(tty, ch, 0); } ignore_char: lsr = serial_inp(mtpt, UART_LSR); } while ((lsr & UART_LSR_DR) && (max_count-- > 0)); tty_flip_buffer_push(tty); } static _INLINE_ void transmit_chars(struct mp_port *mtpt) { struct circ_buf *xmit = &mtpt->port.info->xmit; int count; if (mtpt->port.x_char) { serial_outp(mtpt, UART_TX, mtpt->port.x_char); mtpt->port.icount.tx++; mtpt->port.x_char = 0; return; } if (uart_circ_empty(xmit) || uart_tx_stopped(&mtpt->port)) { multi_stop_tx(&mtpt->port); return; } count = uart_circ_chars_pending(xmit); if(count > mtpt->port.fifosize) { count = mtpt->port.fifosize; } printk("[%d] mdmode: %x\n", mtpt->port.line, mtpt->port.mdmode); do { #if 0 /* check multi-drop mode */ if ((mtpt->port.mdmode & (MDMODE_ENABLE | MDMODE_ADDR)) == (MDMODE_ENABLE | MDMODE_ADDR)) { printk("send address\n"); /* send multi-drop address */ serial_out(mtpt, UART_SCR, xmit->buf[xmit->tail]); } else #endif { serial_out(mtpt, UART_TX, xmit->buf[xmit->tail]); } xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1); mtpt->port.icount.tx++; } while (--count > 0); } static _INLINE_ void check_modem_status(struct mp_port *mtpt) { int status; status = serial_in(mtpt, UART_MSR); if ((status & UART_MSR_ANY_DELTA) == 0) return; if (status & UART_MSR_TERI) mtpt->port.icount.rng++; if (status & UART_MSR_DDSR) mtpt->port.icount.dsr++; if (status & UART_MSR_DDCD) sb_uart_handle_dcd_change(&mtpt->port, status & UART_MSR_DCD); if (status & UART_MSR_DCTS) sb_uart_handle_cts_change(&mtpt->port, status & UART_MSR_CTS); wake_up_interruptible(&mtpt->port.info->delta_msr_wait); } static inline void multi_handle_port(struct mp_port *mtpt) { unsigned int status = serial_inp(mtpt, UART_LSR); //printk("lsr: %x\n", status); if ((status & UART_LSR_DR) || (status & UART_LSR_SPECIAL)) receive_chars(mtpt, &status); check_modem_status(mtpt); if (status & UART_LSR_THRE) { if ((mtpt->port.type == PORT_16C105X) || (mtpt->port.type == PORT_16C105XA)) transmit_chars(mtpt); else { if (mtpt->interface >= RS485NE) uart_set_mctrl(&mtpt->port, TIOCM_RTS); transmit_chars(mtpt); if (mtpt->interface >= RS485NE) { while((status=serial_in(mtpt,UART_LSR) &0x60)!=0x60); uart_clear_mctrl(&mtpt->port, TIOCM_RTS); } } } } static irqreturn_t multi_interrupt(int irq, void *dev_id) { struct irq_info *iinfo = dev_id; struct list_head *lhead, *end = NULL; int pass_counter = 0; spin_lock(&iinfo->lock); lhead = iinfo->head; do { struct mp_port *mtpt; unsigned int iir; mtpt = list_entry(lhead, struct mp_port, list); iir = serial_in(mtpt, UART_IIR); printk("interrupt! port %d, iir 0x%x\n", mtpt->port.line, iir); //wlee if (!(iir & UART_IIR_NO_INT)) { printk("interrupt handle\n"); spin_lock(&mtpt->port.lock); multi_handle_port(mtpt); spin_unlock(&mtpt->port.lock); end = NULL; } else if (end == NULL) end = lhead; lhead = lhead->next; if (lhead == iinfo->head && pass_counter++ > PASS_LIMIT) { printk(KERN_ERR "multi: too much work for " "irq%d\n", irq); printk( "multi: too much work for " "irq%d\n", irq); break; } } while (lhead != end); spin_unlock(&iinfo->lock); return IRQ_HANDLED; } static void serial_do_unlink(struct irq_info *i, struct mp_port *mtpt) { spin_lock_irq(&i->lock); if (!list_empty(i->head)) { if (i->head == &mtpt->list) i->head = i->head->next; list_del(&mtpt->list); } else { i->head = NULL; } spin_unlock_irq(&i->lock); } static int serial_link_irq_chain(struct mp_port *mtpt) { struct irq_info *i = irq_lists + mtpt->port.irq; int ret, irq_flags = mtpt->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED : 0; spin_lock_irq(&i->lock); if (i->head) { list_add(&mtpt->list, i->head); spin_unlock_irq(&i->lock); ret = 0; } else { INIT_LIST_HEAD(&mtpt->list); i->head = &mtpt->list; spin_unlock_irq(&i->lock); ret = request_irq(mtpt->port.irq, multi_interrupt, irq_flags, "serial", i); if (ret < 0) serial_do_unlink(i, mtpt); } return ret; } static void serial_unlink_irq_chain(struct mp_port *mtpt) { struct irq_info *i = irq_lists + mtpt->port.irq; if (list_empty(i->head)) { free_irq(mtpt->port.irq, i); } serial_do_unlink(i, mtpt); } static void multi_timeout(unsigned long data) { struct mp_port *mtpt = (struct mp_port *)data; spin_lock(&mtpt->port.lock); multi_handle_port(mtpt); spin_unlock(&mtpt->port.lock); mod_timer(&mtpt->timer, jiffies+1 ); } static unsigned int multi_tx_empty(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; unsigned long flags; unsigned int ret; spin_lock_irqsave(&mtpt->port.lock, flags); ret = serial_in(mtpt, UART_LSR) & UART_LSR_TEMT ? TIOCSER_TEMT : 0; spin_unlock_irqrestore(&mtpt->port.lock, flags); return ret; } static unsigned int multi_get_mctrl(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; unsigned char status; unsigned int ret; status = serial_in(mtpt, UART_MSR); ret = 0; if (status & UART_MSR_DCD) ret |= TIOCM_CAR; if (status & UART_MSR_RI) ret |= TIOCM_RNG; if (status & UART_MSR_DSR) ret |= TIOCM_DSR; if (status & UART_MSR_CTS) ret |= TIOCM_CTS; return ret; } static void multi_set_mctrl(struct sb_uart_port *port, unsigned int mctrl) { struct mp_port *mtpt = (struct mp_port *)port; unsigned char mcr = 0; mctrl &= 0xff; if (mctrl & TIOCM_RTS) mcr |= UART_MCR_RTS; if (mctrl & TIOCM_DTR) mcr |= UART_MCR_DTR; if (mctrl & TIOCM_OUT1) mcr |= UART_MCR_OUT1; if (mctrl & TIOCM_OUT2) mcr |= UART_MCR_OUT2; if (mctrl & TIOCM_LOOP) mcr |= UART_MCR_LOOP; serial_out(mtpt, UART_MCR, mcr); } static void multi_break_ctl(struct sb_uart_port *port, int break_state) { struct mp_port *mtpt = (struct mp_port *)port; unsigned long flags; spin_lock_irqsave(&mtpt->port.lock, flags); if (break_state == -1) mtpt->lcr |= UART_LCR_SBC; else mtpt->lcr &= ~UART_LCR_SBC; serial_out(mtpt, UART_LCR, mtpt->lcr); spin_unlock_irqrestore(&mtpt->port.lock, flags); } static int multi_startup(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; unsigned long flags; int retval; mtpt->capabilities = uart_config[mtpt->port.type].flags; mtpt->mcr = 0; if (mtpt->capabilities & UART_CLEAR_FIFO) { serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO); serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT); serial_outp(mtpt, UART_FCR, 0); } (void) serial_inp(mtpt, UART_LSR); (void) serial_inp(mtpt, UART_RX); (void) serial_inp(mtpt, UART_IIR); (void) serial_inp(mtpt, UART_MSR); //test-wlee 9-bit disable serial_outp(mtpt, UART_MSR, 0); if (!(mtpt->port.flags & UPF_BUGGY_UART) && (serial_inp(mtpt, UART_LSR) == 0xff)) { printk("ttyS%d: LSR safety check engaged!\n", mtpt->port.line); //return -ENODEV; } if ((!is_real_interrupt(mtpt->port.irq)) || (mtpt->poll_type==TYPE_POLL)) { unsigned int timeout = mtpt->port.timeout; timeout = timeout > 6 ? (timeout / 2 - 2) : 1; mtpt->timer.data = (unsigned long)mtpt; mod_timer(&mtpt->timer, jiffies + timeout); } else { retval = serial_link_irq_chain(mtpt); if (retval) return retval; } serial_outp(mtpt, UART_LCR, UART_LCR_WLEN8); spin_lock_irqsave(&mtpt->port.lock, flags); if ((is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_INTERRUPT)) mtpt->port.mctrl |= TIOCM_OUT2; multi_set_mctrl(&mtpt->port, mtpt->port.mctrl); spin_unlock_irqrestore(&mtpt->port.lock, flags); mtpt->ier = UART_IER_RLSI | UART_IER_RDI; serial_outp(mtpt, UART_IER, mtpt->ier); (void) serial_inp(mtpt, UART_LSR); (void) serial_inp(mtpt, UART_RX); (void) serial_inp(mtpt, UART_IIR); (void) serial_inp(mtpt, UART_MSR); return 0; } static void multi_shutdown(struct sb_uart_port *port) { struct mp_port *mtpt = (struct mp_port *)port; unsigned long flags; mtpt->ier = 0; serial_outp(mtpt, UART_IER, 0); spin_lock_irqsave(&mtpt->port.lock, flags); mtpt->port.mctrl &= ~TIOCM_OUT2; multi_set_mctrl(&mtpt->port, mtpt->port.mctrl); spin_unlock_irqrestore(&mtpt->port.lock, flags); serial_out(mtpt, UART_LCR, serial_inp(mtpt, UART_LCR) & ~UART_LCR_SBC); serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT); serial_outp(mtpt, UART_FCR, 0); (void) serial_in(mtpt, UART_RX); if ((!is_real_interrupt(mtpt->port.irq))||(mtpt->poll_type==TYPE_POLL)) { del_timer_sync(&mtpt->timer); } else { serial_unlink_irq_chain(mtpt); } } static unsigned int multi_get_divisor(struct sb_uart_port *port, unsigned int baud) { unsigned int quot; if ((port->flags & UPF_MAGIC_MULTIPLIER) && baud == (port->uartclk/4)) quot = 0x8001; else if ((port->flags & UPF_MAGIC_MULTIPLIER) && baud == (port->uartclk/8)) quot = 0x8002; else quot = sb_uart_get_divisor(port, baud); return quot; } static void multi_set_termios(struct sb_uart_port *port, struct MP_TERMIOS *termios, struct MP_TERMIOS *old) { struct mp_port *mtpt = (struct mp_port *)port; unsigned char cval, fcr = 0; unsigned long flags; unsigned int baud, quot; switch (termios->c_cflag & CSIZE) { case CS5: cval = 0x00; break; case CS6: cval = 0x01; break; case CS7: cval = 0x02; break; default: case CS8: cval = 0x03; break; } if (termios->c_cflag & CSTOPB) cval |= 0x04; if (termios->c_cflag & PARENB) cval |= UART_LCR_PARITY; if (!(termios->c_cflag & PARODD)) cval |= UART_LCR_EPAR; #ifdef CMSPAR if (termios->c_cflag & CMSPAR) cval |= UART_LCR_SPAR; #endif baud = sb_uart_get_baud_rate(port, termios, old, 0, port->uartclk/16); quot = multi_get_divisor(port, baud); if (mtpt->capabilities & UART_USE_FIFO) { //if (baud < 2400) // fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1; //else // fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8; // fcr = UART_FCR_ENABLE_FIFO | 0x90; fcr = fcr_arr[mtpt->port.line]; } spin_lock_irqsave(&mtpt->port.lock, flags); sb_uart_update_timeout(port, termios->c_cflag, baud); mtpt->port.read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR; if (termios->c_iflag & INPCK) mtpt->port.read_status_mask |= UART_LSR_FE | UART_LSR_PE; if (termios->c_iflag & (BRKINT | PARMRK)) mtpt->port.read_status_mask |= UART_LSR_BI; mtpt->port.ignore_status_mask = 0; if (termios->c_iflag & IGNPAR) mtpt->port.ignore_status_mask |= UART_LSR_PE | UART_LSR_FE; if (termios->c_iflag & IGNBRK) { mtpt->port.ignore_status_mask |= UART_LSR_BI; if (termios->c_iflag & IGNPAR) mtpt->port.ignore_status_mask |= UART_LSR_OE; } if ((termios->c_cflag & CREAD) == 0) mtpt->port.ignore_status_mask |= UART_LSR_DR; mtpt->ier &= ~UART_IER_MSI; if (UART_ENABLE_MS(&mtpt->port, termios->c_cflag)) mtpt->ier |= UART_IER_MSI; serial_out(mtpt, UART_IER, mtpt->ier); if (mtpt->capabilities & UART_STARTECH) { serial_outp(mtpt, UART_LCR, 0xBF); serial_outp(mtpt, UART_EFR, termios->c_cflag & CRTSCTS ? UART_EFR_CTS :0); } serial_outp(mtpt, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */ serial_outp(mtpt, UART_DLL, quot & 0xff); /* LS of divisor */ serial_outp(mtpt, UART_DLM, quot >> 8); /* MS of divisor */ serial_outp(mtpt, UART_LCR, cval); /* reset DLAB */ mtpt->lcr = cval; /* Save LCR */ if (fcr & UART_FCR_ENABLE_FIFO) { /* emulated UARTs (Lucent Venus 167x) need two steps */ serial_outp(mtpt, UART_FCR, UART_FCR_ENABLE_FIFO); } serial_outp(mtpt, UART_FCR, fcr); /* set fcr */ if ((mtpt->port.type == PORT_16C105X) || (mtpt->port.type == PORT_16C105XA)) { if(deep[mtpt->port.line]!=0) set_deep_fifo(port, ENABLE); if (mtpt->interface != RS232) set_auto_rts(port,mtpt->interface); } else { if (mtpt->interface >= RS485NE) { uart_clear_mctrl(&mtpt->port, TIOCM_RTS); } } if(mtpt->device->device_id == PCI_DEVICE_ID_MP4M) { SendATCommand(mtpt); printk("SendATCommand\n"); } multi_set_mctrl(&mtpt->port, mtpt->port.mctrl); spin_unlock_irqrestore(&mtpt->port.lock, flags); } static void multi_pm(struct sb_uart_port *port, unsigned int state, unsigned int oldstate) { struct mp_port *mtpt = (struct mp_port *)port; if (state) { if (mtpt->capabilities & UART_STARTECH) { serial_outp(mtpt, UART_LCR, 0xBF); serial_outp(mtpt, UART_EFR, UART_EFR_ECB); serial_outp(mtpt, UART_LCR, 0); serial_outp(mtpt, UART_IER, UART_IERX_SLEEP); serial_outp(mtpt, UART_LCR, 0xBF); serial_outp(mtpt, UART_EFR, 0); serial_outp(mtpt, UART_LCR, 0); } if (mtpt->pm) mtpt->pm(port, state, oldstate); } else { if (mtpt->capabilities & UART_STARTECH) { serial_outp(mtpt, UART_LCR, 0xBF); serial_outp(mtpt, UART_EFR, UART_EFR_ECB); serial_outp(mtpt, UART_LCR, 0); serial_outp(mtpt, UART_IER, 0); serial_outp(mtpt, UART_LCR, 0xBF); serial_outp(mtpt, UART_EFR, 0); serial_outp(mtpt, UART_LCR, 0); } if (mtpt->pm) mtpt->pm(port, state, oldstate); } } static void multi_release_std_resource(struct mp_port *mtpt) { unsigned int size = 8 << mtpt->port.regshift; switch (mtpt->port.iotype) { case UPIO_MEM: if (!mtpt->port.mapbase) break; if (mtpt->port.flags & UPF_IOREMAP) { iounmap(mtpt->port.membase); mtpt->port.membase = NULL; } release_mem_region(mtpt->port.mapbase, size); break; case UPIO_HUB6: case UPIO_PORT: release_region(mtpt->port.iobase,size); break; } } static void multi_release_port(struct sb_uart_port *port) { } static int multi_request_port(struct sb_uart_port *port) { return 0; } static void multi_config_port(struct sb_uart_port *port, int flags) { struct mp_port *mtpt = (struct mp_port *)port; int probeflags = PROBE_ANY; if (flags & UART_CONFIG_TYPE) autoconfig(mtpt, probeflags); if (mtpt->port.type != PORT_UNKNOWN && flags & UART_CONFIG_IRQ) autoconfig_irq(mtpt); if (mtpt->port.type == PORT_UNKNOWN) multi_release_std_resource(mtpt); } static int multi_verify_port(struct sb_uart_port *port, struct serial_struct *ser) { if (ser->irq >= NR_IRQS || ser->irq < 0 || ser->baud_base < 9600 || ser->type < PORT_UNKNOWN || ser->type == PORT_STARTECH) return -EINVAL; return 0; } static const char *multi_type(struct sb_uart_port *port) { int type = port->type; if (type >= ARRAY_SIZE(uart_config)) type = 0; return uart_config[type].name; } static struct sb_uart_ops multi_pops = { .tx_empty = multi_tx_empty, .set_mctrl = multi_set_mctrl, .get_mctrl = multi_get_mctrl, .stop_tx = multi_stop_tx, .start_tx = multi_start_tx, .stop_rx = multi_stop_rx, .enable_ms = multi_enable_ms, .break_ctl = multi_break_ctl, .startup = multi_startup, .shutdown = multi_shutdown, .set_termios = multi_set_termios, .pm = multi_pm, .type = multi_type, .release_port = multi_release_port, .request_port = multi_request_port, .config_port = multi_config_port, .verify_port = multi_verify_port, }; static struct uart_driver multi_reg = { .owner = THIS_MODULE, .driver_name = "goldel_tulip", .dev_name = "ttyMP", .major = SB_TTY_MP_MAJOR, .minor = 0, .nr = MAX_MP_PORT, .cons = NULL, }; static void __init multi_init_ports(void) { struct mp_port *mtpt; static int first = 1; int i,j,k; unsigned char osc; unsigned char b_ret = 0; static struct mp_device_t *sbdev; if (!first) return; first = 0; mtpt = multi_ports; for (k=0;k<NR_BOARD;k++) { sbdev = &mp_devs[k]; for (i = 0; i < sbdev->nr_ports; i++, mtpt++) { mtpt->device = sbdev; mtpt->port.iobase = sbdev->uart_access_addr + 8*i; mtpt->port.irq = sbdev->irq; if ( ((sbdev->device_id == PCI_DEVICE_ID_MP4)&&(sbdev->revision==0x91))) mtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i; else if (sbdev->revision == 0xc0) mtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + (i & 0x1); else mtpt->interface_config_addr = sbdev->option_reg_addr + 0x08 + i/8; mtpt->option_base_addr = sbdev->option_reg_addr; mtpt->poll_type = sbdev->poll_type; mtpt->port.uartclk = BASE_BAUD * 16; /* get input clock information */ osc = inb(sbdev->option_reg_addr + MP_OPTR_DIR0 + i/8) & 0x0F; if (osc==0x0f) osc = 0; for(j=0;j<osc;j++) mtpt->port.uartclk *= 2; mtpt->port.flags |= STD_COM_FLAGS | UPF_SHARE_IRQ ; mtpt->port.iotype = UPIO_PORT; mtpt->port.ops = &multi_pops; if (sbdev->revision == 0xc0) { /* for SB16C1053APCI */ b_ret = sb1053a_get_interface(mtpt, i); } else { b_ret = read_option_register(mtpt,(MP_OPTR_IIR0 + i/8)); printk("IIR_RET = %x\n",b_ret); } /* default to RS232 */ mtpt->interface = RS232; if (IIR_RS422 == (b_ret & IIR_TYPE_MASK)) mtpt->interface = RS422PTP; if (IIR_RS485 == (b_ret & IIR_TYPE_MASK)) mtpt->interface = RS485NE; } } } static void __init multi_register_ports(struct uart_driver *drv) { int i; multi_init_ports(); for (i = 0; i < NR_PORTS; i++) { struct mp_port *mtpt = &multi_ports[i]; mtpt->port.line = i; mtpt->port.ops = &multi_pops; init_timer(&mtpt->timer); mtpt->timer.function = multi_timeout; mp_add_one_port(drv, &mtpt->port); } } /** * pci_remap_base - remap BAR value of pci device * * PARAMETERS * pcidev - pci_dev structure address * offset - BAR offset PCI_BASE_ADDRESS_0 ~ PCI_BASE_ADDRESS_4 * address - address to be changed BAR value * size - size of address space * * RETURNS * If this function performs successful, it returns 0. Otherwise, It returns -1. */ static int pci_remap_base(struct pci_dev *pcidev, unsigned int offset, unsigned int address, unsigned int size) { #if 0 struct resource *root; unsigned index = (offset - 0x10) >> 2; #endif pci_write_config_dword(pcidev, offset, address); #if 0 root = pcidev->resource[index].parent; release_resource(&pcidev->resource[index]); address &= ~0x1; pcidev->resource[index].start = address; pcidev->resource[index].end = address + size - 1; if (request_resource(root, &pcidev->resource[index]) != NULL) { printk(KERN_ERR "pci remap conflict!! 0x%x\n", address); return (-1); } #endif return (0); } static int init_mp_dev(struct pci_dev *pcidev, mppcibrd_t brd) { static struct mp_device_t *sbdev = mp_devs; unsigned long addr = 0; int j; struct resource *ret = NULL; sbdev->device_id = brd.device_id; pci_read_config_byte(pcidev, PCI_CLASS_REVISION, &(sbdev->revision)); sbdev->name = brd.name; sbdev->uart_access_addr = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK; /* check revision. The SB16C1053APCI's option i/o address is BAR4 */ if (sbdev->revision == 0xc0) { /* SB16C1053APCI */ sbdev->option_reg_addr = pcidev->resource[4].start & PCI_BASE_ADDRESS_IO_MASK; } else { sbdev->option_reg_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK; } #if 1 if (sbdev->revision == 0xc0) { outb(0x00, sbdev->option_reg_addr + MP_OPTR_GPOCR); inb(sbdev->option_reg_addr + MP_OPTR_GPOCR); outb(0x83, sbdev->option_reg_addr + MP_OPTR_GPOCR); } #endif sbdev->irq = pcidev->irq; if ((brd.device_id & 0x0800) || !(brd.device_id &0xff00)) { sbdev->poll_type = TYPE_INTERRUPT; } else { sbdev->poll_type = TYPE_POLL; } /* codes which is specific to each board*/ switch(brd.device_id){ case PCI_DEVICE_ID_MP1 : case PCIE_DEVICE_ID_MP1 : case PCIE_DEVICE_ID_MP1E : case PCIE_DEVICE_ID_GT_MP1 : sbdev->nr_ports = 1; break; case PCI_DEVICE_ID_MP2 : case PCIE_DEVICE_ID_MP2 : case PCIE_DEVICE_ID_GT_MP2 : case PCIE_DEVICE_ID_MP2B : case PCIE_DEVICE_ID_MP2E : sbdev->nr_ports = 2; /* serial base address remap */ if (sbdev->revision == 0xc0) { int prev_port_addr = 0; pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr); pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8); } break; case PCI_DEVICE_ID_MP4 : case PCI_DEVICE_ID_MP4A : case PCIE_DEVICE_ID_MP4 : case PCI_DEVICE_ID_GT_MP4 : case PCI_DEVICE_ID_GT_MP4A : case PCIE_DEVICE_ID_GT_MP4 : case PCI_DEVICE_ID_MP4M : case PCIE_DEVICE_ID_MP4B : sbdev->nr_ports = 4; if(sbdev->revision == 0x91){ sbdev->reserved_addr[0] = pcidev->resource[0].start & PCI_BASE_ADDRESS_IO_MASK; outb(0x03 , sbdev->reserved_addr[0] + 0x01); outb(0x03 , sbdev->reserved_addr[0] + 0x02); outb(0x01 , sbdev->reserved_addr[0] + 0x20); outb(0x00 , sbdev->reserved_addr[0] + 0x21); request_region(sbdev->reserved_addr[0], 32, sbdev->name); sbdev->uart_access_addr = pcidev->resource[1].start & PCI_BASE_ADDRESS_IO_MASK; sbdev->option_reg_addr = pcidev->resource[2].start & PCI_BASE_ADDRESS_IO_MASK; } /* SB16C1053APCI */ if (sbdev->revision == 0xc0) { int prev_port_addr = 0; pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr); pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8); pci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 8); pci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 24, 8); } break; case PCI_DEVICE_ID_MP6 : case PCI_DEVICE_ID_MP6A : case PCI_DEVICE_ID_GT_MP6 : case PCI_DEVICE_ID_GT_MP6A : sbdev->nr_ports = 6; /* SB16C1053APCI */ if (sbdev->revision == 0xc0) { int prev_port_addr = 0; pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr); pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8); pci_remap_base(pcidev, PCI_BASE_ADDRESS_2, prev_port_addr + 16, 16); pci_remap_base(pcidev, PCI_BASE_ADDRESS_3, prev_port_addr + 32, 16); } break; case PCI_DEVICE_ID_MP8 : case PCIE_DEVICE_ID_MP8 : case PCI_DEVICE_ID_GT_MP8 : case PCIE_DEVICE_ID_GT_MP8 : case PCIE_DEVICE_ID_MP8B : sbdev->nr_ports = 8; break; case PCI_DEVICE_ID_MP32 : case PCIE_DEVICE_ID_MP32 : case PCI_DEVICE_ID_GT_MP32 : case PCIE_DEVICE_ID_GT_MP32 : { int portnum_hex=0; portnum_hex = inb(sbdev->option_reg_addr); sbdev->nr_ports = ((portnum_hex/16)*10) + (portnum_hex % 16); } break; #ifdef CONFIG_PARPORT_PC case PCI_DEVICE_ID_MP2S1P : sbdev->nr_ports = 2; /* SB16C1053APCI */ if (sbdev->revision == 0xc0) { int prev_port_addr = 0; pci_read_config_dword(pcidev, PCI_BASE_ADDRESS_0, &prev_port_addr); pci_remap_base(pcidev, PCI_BASE_ADDRESS_1, prev_port_addr + 8, 8); } /* add PC compatible parallel port */ parport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0); break; case PCI_DEVICE_ID_MP1P : /* add PC compatible parallel port */ parport_pc_probe_port(pcidev->resource[2].start, pcidev->resource[3].start, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, &pcidev->dev, 0); break; #endif } ret = request_region(sbdev->uart_access_addr, (8*sbdev->nr_ports), sbdev->name); if (sbdev->revision == 0xc0) { ret = request_region(sbdev->option_reg_addr, 0x40, sbdev->name); } else { ret = request_region(sbdev->option_reg_addr, 0x20, sbdev->name); } NR_BOARD++; NR_PORTS += sbdev->nr_ports; /* Enable PCI interrupt */ addr = sbdev->option_reg_addr + MP_OPTR_IMR0; for(j=0; j < (sbdev->nr_ports/8)+1; j++) { if (sbdev->poll_type == TYPE_INTERRUPT) { outb(0xff,addr +j); } } sbdev++; return 0; } static int __init multi_init(void) { int ret, i; struct pci_dev *dev = NULL; if(fcr_count==0) { for(i=0;i<256;i++) { fcr_arr[i] = 0x01; } } if(deep_count==0) { for(i=0;i<256;i++) { deep[i] = 1; } } if(rtr_count==0) { for(i=0;i<256;i++) { rtr[i] = 0x10; } } if(ttr_count==0) { for(i=0;i<256;i++) { ttr[i] = 0x38; } } printk("MULTI INIT\n"); for( i=0; i< mp_nrpcibrds; i++) { while( (dev = pci_get_device(mp_pciboards[i].vendor_id, mp_pciboards[i].device_id, dev) ) ) { printk("FOUND~~~\n"); // Cent OS bug fix // if (mp_pciboards[i].device_id & 0x0800) { int status; pci_disable_device(dev); status = pci_enable_device(dev); if (status != 0) { printk("Multiport Board Enable Fail !\n\n"); status = -ENXIO; return status; } } init_mp_dev(dev, mp_pciboards[i]); } } for (i = 0; i < NR_IRQS; i++) spin_lock_init(&irq_lists[i].lock); ret = mp_register_driver(&multi_reg); if (ret >= 0) multi_register_ports(&multi_reg); return ret; } static void __exit multi_exit(void) { int i; for (i = 0; i < NR_PORTS; i++) mp_remove_one_port(&multi_reg, &multi_ports[i].port); mp_unregister_driver(&multi_reg); } module_init(multi_init); module_exit(multi_exit); MODULE_DESCRIPTION("SystemBase Multiport PCI/PCIe CORE"); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_5760_0