id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_5523_1 | /*
* Copyright 1999-2006, Gisle Aas.
*
* This library is free software; you can redistribute it and/or
* modify it under the same terms as Perl itself.
*/
#ifndef EXTERN
#define EXTERN extern
#endif
EXTERN SV*
sv_lower(pTHX_ SV* sv)
{
STRLEN len;
char *s = SvPV_force(sv, len);
for (; len--; s++)
*s = toLOWER(*s);
return sv;
}
EXTERN int
strnEQx(const char* s1, const char* s2, STRLEN n, int ignore_case)
{
while (n--) {
if (ignore_case) {
if (toLOWER(*s1) != toLOWER(*s2))
return 0;
}
else {
if (*s1 != *s2)
return 0;
}
s1++;
s2++;
}
return 1;
}
static void
grow_gap(pTHX_ SV* sv, STRLEN grow, char** t, char** s, char** e)
{
/*
SvPVX ---> AAAAAA...BBBBBB
^ ^ ^
t s e
*/
STRLEN t_offset = *t - SvPVX(sv);
STRLEN s_offset = *s - SvPVX(sv);
STRLEN e_offset = *e - SvPVX(sv);
SvGROW(sv, e_offset + grow + 1);
*t = SvPVX(sv) + t_offset;
*s = SvPVX(sv) + s_offset;
*e = SvPVX(sv) + e_offset;
Move(*s, *s+grow, *e - *s, char);
*s += grow;
*e += grow;
}
EXTERN SV*
decode_entities(pTHX_ SV* sv, HV* entity2char, bool expand_prefix)
{
STRLEN len;
char *s = SvPV_force(sv, len);
char *t = s;
char *end = s + len;
char *ent_start;
char *repl;
STRLEN repl_len;
#ifdef UNICODE_HTML_PARSER
char buf[UTF8_MAXLEN];
int repl_utf8;
int high_surrogate = 0;
#else
char buf[1];
#endif
#if defined(__GNUC__) && defined(UNICODE_HTML_PARSER)
/* gcc -Wall reports this variable as possibly used uninitialized */
repl_utf8 = 0;
#endif
while (s < end) {
assert(t <= s);
if ((*t++ = *s++) != '&')
continue;
ent_start = s;
repl = 0;
if (*s == '#') {
UV num = 0;
UV prev = 0;
int ok = 0;
s++;
if (*s == 'x' || *s == 'X') {
s++;
while (*s) {
char *tmp = strchr(PL_hexdigit, *s);
if (!tmp)
break;
num = num << 4 | ((tmp - PL_hexdigit) & 15);
if (prev && num <= prev) {
/* overflow */
ok = 0;
break;
}
prev = num;
s++;
ok = 1;
}
}
else {
while (isDIGIT(*s)) {
num = num * 10 + (*s - '0');
if (prev && num < prev) {
/* overflow */
ok = 0;
break;
}
prev = num;
s++;
ok = 1;
}
}
if (ok) {
#ifdef UNICODE_HTML_PARSER
if (!SvUTF8(sv) && num <= 255) {
buf[0] = (char) num;
repl = buf;
repl_len = 1;
repl_utf8 = 0;
}
else {
char *tmp;
if ((num & 0xFFFFFC00) == 0xDC00) { /* low-surrogate */
if (high_surrogate != 0) {
t -= 3; /* Back up past 0xFFFD */
num = ((high_surrogate - 0xD800) << 10) +
(num - 0xDC00) + 0x10000;
high_surrogate = 0;
} else {
num = 0xFFFD;
}
}
else if ((num & 0xFFFFFC00) == 0xD800) { /* high-surrogate */
high_surrogate = num;
num = 0xFFFD;
}
else {
high_surrogate = 0;
/* otherwise invalid? */
if ((num >= 0xFDD0 && num <= 0xFDEF) ||
((num & 0xFFFE) == 0xFFFE) ||
num > 0x10FFFF)
{
num = 0xFFFD;
}
}
tmp = (char*)uvuni_to_utf8((U8*)buf, num);
repl = buf;
repl_len = tmp - buf;
repl_utf8 = 1;
}
#else
if (num <= 255) {
buf[0] = (char) num & 0xFF;
repl = buf;
repl_len = 1;
}
#endif
}
}
else {
char *ent_name = s;
while (isALNUM(*s))
s++;
if (ent_name != s && entity2char) {
SV** svp;
if ( (svp = hv_fetch(entity2char, ent_name, s - ent_name, 0)) ||
(*s == ';' && (svp = hv_fetch(entity2char, ent_name, s - ent_name + 1, 0)))
)
{
repl = SvPV(*svp, repl_len);
#ifdef UNICODE_HTML_PARSER
repl_utf8 = SvUTF8(*svp);
#endif
}
else if (expand_prefix) {
char *ss = s - 1;
while (ss > ent_name) {
svp = hv_fetch(entity2char, ent_name, ss - ent_name, 0);
if (svp) {
repl = SvPV(*svp, repl_len);
#ifdef UNICODE_HTML_PARSER
repl_utf8 = SvUTF8(*svp);
#endif
s = ss;
break;
}
ss--;
}
}
}
#ifdef UNICODE_HTML_PARSER
high_surrogate = 0;
#endif
}
if (repl) {
char *repl_allocated = 0;
if (*s == ';')
s++;
t--; /* '&' already copied, undo it */
#ifdef UNICODE_HTML_PARSER
if (*s != '&') {
high_surrogate = 0;
}
if (!SvUTF8(sv) && repl_utf8) {
/* need to upgrade sv before we continue */
STRLEN before_gap_len = t - SvPVX(sv);
char *before_gap = (char*)bytes_to_utf8((U8*)SvPVX(sv), &before_gap_len);
STRLEN after_gap_len = end - s;
char *after_gap = (char*)bytes_to_utf8((U8*)s, &after_gap_len);
sv_setpvn(sv, before_gap, before_gap_len);
sv_catpvn(sv, after_gap, after_gap_len);
SvUTF8_on(sv);
Safefree(before_gap);
Safefree(after_gap);
s = t = SvPVX(sv) + before_gap_len;
end = SvPVX(sv) + before_gap_len + after_gap_len;
}
else if (SvUTF8(sv) && !repl_utf8) {
repl = (char*)bytes_to_utf8((U8*)repl, &repl_len);
repl_allocated = repl;
}
#endif
if (t + repl_len > s) {
/* need to grow the string */
grow_gap(aTHX_ sv, repl_len - (s - t), &t, &s, &end);
}
/* copy replacement string into string */
while (repl_len--)
*t++ = *repl++;
if (repl_allocated)
Safefree(repl_allocated);
}
else {
while (ent_start < s)
*t++ = *ent_start++;
}
}
*t = '\0';
SvCUR_set(sv, t - SvPVX(sv));
return sv;
}
#ifdef UNICODE_HTML_PARSER
static bool
has_hibit(char *s, char *e)
{
while (s < e) {
U8 ch = *s++;
if (!UTF8_IS_INVARIANT(ch)) {
return 1;
}
}
return 0;
}
EXTERN bool
probably_utf8_chunk(pTHX_ char *s, STRLEN len)
{
char *e = s + len;
STRLEN clen;
/* ignore partial utf8 char at end of buffer */
while (s < e && UTF8_IS_CONTINUATION((U8)*(e - 1)))
e--;
if (s < e && UTF8_IS_START((U8)*(e - 1)))
e--;
clen = len - (e - s);
if (clen && UTF8SKIP(e) == clen) {
/* all promised continuation bytes are present */
e = s + len;
}
if (!has_hibit(s, e))
return 0;
return is_utf8_string((U8*)s, e - s);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5523_1 |
crossvul-cpp_data_bad_5845_3 | /** -*- linux-c -*- ***********************************************************
* Linux PPP over Ethernet (PPPoX/PPPoE) Sockets
*
* PPPoX --- Generic PPP encapsulation socket family
* PPPoE --- PPP over Ethernet (RFC 2516)
*
*
* Version: 0.7.0
*
* 070228 : Fix to allow multiple sessions with same remote MAC and same
* session id by including the local device ifindex in the
* tuple identifying a session. This also ensures packets can't
* be injected into a session from interfaces other than the one
* specified by userspace. Florian Zumbiehl <florz@florz.de>
* (Oh, BTW, this one is YYMMDD, in case you were wondering ...)
* 220102 : Fix module use count on failure in pppoe_create, pppox_sk -acme
* 030700 : Fixed connect logic to allow for disconnect.
* 270700 : Fixed potential SMP problems; we must protect against
* simultaneous invocation of ppp_input
* and ppp_unregister_channel.
* 040800 : Respect reference count mechanisms on net-devices.
* 200800 : fix kfree(skb) in pppoe_rcv (acme)
* Module reference count is decremented in the right spot now,
* guards against sock_put not actually freeing the sk
* in pppoe_release.
* 051000 : Initialization cleanup.
* 111100 : Fix recvmsg.
* 050101 : Fix PADT procesing.
* 140501 : Use pppoe_rcv_core to handle all backlog. (Alexey)
* 170701 : Do not lock_sock with rwlock held. (DaveM)
* Ignore discovery frames if user has socket
* locked. (DaveM)
* Ignore return value of dev_queue_xmit in __pppoe_xmit
* or else we may kfree an SKB twice. (DaveM)
* 190701 : When doing copies of skb's in __pppoe_xmit, always delete
* the original skb that was passed in on success, never on
* failure. Delete the copy of the skb on failure to avoid
* a memory leak.
* 081001 : Misc. cleanup (licence string, non-blocking, prevent
* reference of device on close).
* 121301 : New ppp channels interface; cannot unregister a channel
* from interrupts. Thus, we mark the socket as a ZOMBIE
* and do the unregistration later.
* 081002 : seq_file support for proc stuff -acme
* 111602 : Merge all 2.4 fixes into 2.5/2.6 tree. Label 2.5/2.6
* as version 0.7. Spacing cleanup.
* Author: Michal Ostrowski <mostrows@speakeasy.net>
* Contributors:
* Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* David S. Miller (davem@redhat.com)
*
* License:
* 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/inetdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/if_ether.h>
#include <linux/if_pppox.h>
#include <linux/ppp_channel.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/notifier.h>
#include <linux/file.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#define PPPOE_HASH_BITS 4
#define PPPOE_HASH_SIZE (1 << PPPOE_HASH_BITS)
#define PPPOE_HASH_MASK (PPPOE_HASH_SIZE - 1)
static int __pppoe_xmit(struct sock *sk, struct sk_buff *skb);
static const struct proto_ops pppoe_ops;
static const struct ppp_channel_ops pppoe_chan_ops;
/* per-net private data for this module */
static int pppoe_net_id __read_mostly;
struct pppoe_net {
/*
* we could use _single_ hash table for all
* nets by injecting net id into the hash but
* it would increase hash chains and add
* a few additional math comparations messy
* as well, moreover in case of SMP less locking
* controversy here
*/
struct pppox_sock *hash_table[PPPOE_HASH_SIZE];
rwlock_t hash_lock;
};
/*
* PPPoE could be in the following stages:
* 1) Discovery stage (to obtain remote MAC and Session ID)
* 2) Session stage (MAC and SID are known)
*
* Ethernet frames have a special tag for this but
* we use simpler approach based on session id
*/
static inline bool stage_session(__be16 sid)
{
return sid != 0;
}
static inline struct pppoe_net *pppoe_pernet(struct net *net)
{
BUG_ON(!net);
return net_generic(net, pppoe_net_id);
}
static inline int cmp_2_addr(struct pppoe_addr *a, struct pppoe_addr *b)
{
return a->sid == b->sid && !memcmp(a->remote, b->remote, ETH_ALEN);
}
static inline int cmp_addr(struct pppoe_addr *a, __be16 sid, char *addr)
{
return a->sid == sid && !memcmp(a->remote, addr, ETH_ALEN);
}
#if 8 % PPPOE_HASH_BITS
#error 8 must be a multiple of PPPOE_HASH_BITS
#endif
static int hash_item(__be16 sid, unsigned char *addr)
{
unsigned char hash = 0;
unsigned int i;
for (i = 0; i < ETH_ALEN; i++)
hash ^= addr[i];
for (i = 0; i < sizeof(sid_t) * 8; i += 8)
hash ^= (__force __u32)sid >> i;
for (i = 8; (i >>= 1) >= PPPOE_HASH_BITS;)
hash ^= hash >> i;
return hash & PPPOE_HASH_MASK;
}
/**********************************************************************
*
* Set/get/delete/rehash items (internal versions)
*
**********************************************************************/
static struct pppox_sock *__get_item(struct pppoe_net *pn, __be16 sid,
unsigned char *addr, int ifindex)
{
int hash = hash_item(sid, addr);
struct pppox_sock *ret;
ret = pn->hash_table[hash];
while (ret) {
if (cmp_addr(&ret->pppoe_pa, sid, addr) &&
ret->pppoe_ifindex == ifindex)
return ret;
ret = ret->next;
}
return NULL;
}
static int __set_item(struct pppoe_net *pn, struct pppox_sock *po)
{
int hash = hash_item(po->pppoe_pa.sid, po->pppoe_pa.remote);
struct pppox_sock *ret;
ret = pn->hash_table[hash];
while (ret) {
if (cmp_2_addr(&ret->pppoe_pa, &po->pppoe_pa) &&
ret->pppoe_ifindex == po->pppoe_ifindex)
return -EALREADY;
ret = ret->next;
}
po->next = pn->hash_table[hash];
pn->hash_table[hash] = po;
return 0;
}
static void __delete_item(struct pppoe_net *pn, __be16 sid,
char *addr, int ifindex)
{
int hash = hash_item(sid, addr);
struct pppox_sock *ret, **src;
ret = pn->hash_table[hash];
src = &pn->hash_table[hash];
while (ret) {
if (cmp_addr(&ret->pppoe_pa, sid, addr) &&
ret->pppoe_ifindex == ifindex) {
*src = ret->next;
break;
}
src = &ret->next;
ret = ret->next;
}
}
/**********************************************************************
*
* Set/get/delete/rehash items
*
**********************************************************************/
static inline struct pppox_sock *get_item(struct pppoe_net *pn, __be16 sid,
unsigned char *addr, int ifindex)
{
struct pppox_sock *po;
read_lock_bh(&pn->hash_lock);
po = __get_item(pn, sid, addr, ifindex);
if (po)
sock_hold(sk_pppox(po));
read_unlock_bh(&pn->hash_lock);
return po;
}
static inline struct pppox_sock *get_item_by_addr(struct net *net,
struct sockaddr_pppox *sp)
{
struct net_device *dev;
struct pppoe_net *pn;
struct pppox_sock *pppox_sock = NULL;
int ifindex;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, sp->sa_addr.pppoe.dev);
if (dev) {
ifindex = dev->ifindex;
pn = pppoe_pernet(net);
pppox_sock = get_item(pn, sp->sa_addr.pppoe.sid,
sp->sa_addr.pppoe.remote, ifindex);
}
rcu_read_unlock();
return pppox_sock;
}
static inline void delete_item(struct pppoe_net *pn, __be16 sid,
char *addr, int ifindex)
{
write_lock_bh(&pn->hash_lock);
__delete_item(pn, sid, addr, ifindex);
write_unlock_bh(&pn->hash_lock);
}
/***************************************************************************
*
* Handler for device events.
* Certain device events require that sockets be unconnected.
*
**************************************************************************/
static void pppoe_flush_dev(struct net_device *dev)
{
struct pppoe_net *pn;
int i;
pn = pppoe_pernet(dev_net(dev));
write_lock_bh(&pn->hash_lock);
for (i = 0; i < PPPOE_HASH_SIZE; i++) {
struct pppox_sock *po = pn->hash_table[i];
struct sock *sk;
while (po) {
while (po && po->pppoe_dev != dev) {
po = po->next;
}
if (!po)
break;
sk = sk_pppox(po);
/* We always grab the socket lock, followed by the
* hash_lock, in that order. Since we should hold the
* sock lock while doing any unbinding, we need to
* release the lock we're holding. Hold a reference to
* the sock so it doesn't disappear as we're jumping
* between locks.
*/
sock_hold(sk);
write_unlock_bh(&pn->hash_lock);
lock_sock(sk);
if (po->pppoe_dev == dev &&
sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND | PPPOX_ZOMBIE)) {
pppox_unbind_sock(sk);
sk->sk_state = PPPOX_ZOMBIE;
sk->sk_state_change(sk);
po->pppoe_dev = NULL;
dev_put(dev);
}
release_sock(sk);
sock_put(sk);
/* Restart the process from the start of the current
* hash chain. We dropped locks so the world may have
* change from underneath us.
*/
BUG_ON(pppoe_pernet(dev_net(dev)) == NULL);
write_lock_bh(&pn->hash_lock);
po = pn->hash_table[i];
}
}
write_unlock_bh(&pn->hash_lock);
}
static int pppoe_device_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
/* Only look at sockets that are using this specific device. */
switch (event) {
case NETDEV_CHANGEADDR:
case NETDEV_CHANGEMTU:
/* A change in mtu or address is a bad thing, requiring
* LCP re-negotiation.
*/
case NETDEV_GOING_DOWN:
case NETDEV_DOWN:
/* Find every socket on this device and kill it. */
pppoe_flush_dev(dev);
break;
default:
break;
}
return NOTIFY_DONE;
}
static struct notifier_block pppoe_notifier = {
.notifier_call = pppoe_device_event,
};
/************************************************************************
*
* Do the real work of receiving a PPPoE Session frame.
*
***********************************************************************/
static int pppoe_rcv_core(struct sock *sk, struct sk_buff *skb)
{
struct pppox_sock *po = pppox_sk(sk);
struct pppox_sock *relay_po;
/* Backlog receive. Semantics of backlog rcv preclude any code from
* executing in lock_sock()/release_sock() bounds; meaning sk->sk_state
* can't change.
*/
if (sk->sk_state & PPPOX_BOUND) {
ppp_input(&po->chan, skb);
} else if (sk->sk_state & PPPOX_RELAY) {
relay_po = get_item_by_addr(sock_net(sk),
&po->pppoe_relay);
if (relay_po == NULL)
goto abort_kfree;
if ((sk_pppox(relay_po)->sk_state & PPPOX_CONNECTED) == 0)
goto abort_put;
if (!__pppoe_xmit(sk_pppox(relay_po), skb))
goto abort_put;
} else {
if (sock_queue_rcv_skb(sk, skb))
goto abort_kfree;
}
return NET_RX_SUCCESS;
abort_put:
sock_put(sk_pppox(relay_po));
abort_kfree:
kfree_skb(skb);
return NET_RX_DROP;
}
/************************************************************************
*
* Receive wrapper called in BH context.
*
***********************************************************************/
static int pppoe_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct pppoe_hdr *ph;
struct pppox_sock *po;
struct pppoe_net *pn;
int len;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto out;
if (!pskb_may_pull(skb, sizeof(struct pppoe_hdr)))
goto drop;
ph = pppoe_hdr(skb);
len = ntohs(ph->length);
skb_pull_rcsum(skb, sizeof(*ph));
if (skb->len < len)
goto drop;
if (pskb_trim_rcsum(skb, len))
goto drop;
pn = pppoe_pernet(dev_net(dev));
/* Note that get_item does a sock_hold(), so sk_pppox(po)
* is known to be safe.
*/
po = get_item(pn, ph->sid, eth_hdr(skb)->h_source, dev->ifindex);
if (!po)
goto drop;
return sk_receive_skb(sk_pppox(po), skb, 0);
drop:
kfree_skb(skb);
out:
return NET_RX_DROP;
}
/************************************************************************
*
* Receive a PPPoE Discovery frame.
* This is solely for detection of PADT frames
*
***********************************************************************/
static int pppoe_disc_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct pppoe_hdr *ph;
struct pppox_sock *po;
struct pppoe_net *pn;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto out;
if (!pskb_may_pull(skb, sizeof(struct pppoe_hdr)))
goto abort;
ph = pppoe_hdr(skb);
if (ph->code != PADT_CODE)
goto abort;
pn = pppoe_pernet(dev_net(dev));
po = get_item(pn, ph->sid, eth_hdr(skb)->h_source, dev->ifindex);
if (po) {
struct sock *sk = sk_pppox(po);
bh_lock_sock(sk);
/* If the user has locked the socket, just ignore
* the packet. With the way two rcv protocols hook into
* one socket family type, we cannot (easily) distinguish
* what kind of SKB it is during backlog rcv.
*/
if (sock_owned_by_user(sk) == 0) {
/* We're no longer connect at the PPPOE layer,
* and must wait for ppp channel to disconnect us.
*/
sk->sk_state = PPPOX_ZOMBIE;
}
bh_unlock_sock(sk);
sock_put(sk);
}
abort:
kfree_skb(skb);
out:
return NET_RX_SUCCESS; /* Lies... :-) */
}
static struct packet_type pppoes_ptype __read_mostly = {
.type = cpu_to_be16(ETH_P_PPP_SES),
.func = pppoe_rcv,
};
static struct packet_type pppoed_ptype __read_mostly = {
.type = cpu_to_be16(ETH_P_PPP_DISC),
.func = pppoe_disc_rcv,
};
static struct proto pppoe_sk_proto __read_mostly = {
.name = "PPPOE",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pppox_sock),
};
/***********************************************************************
*
* Initialize a new struct sock.
*
**********************************************************************/
static int pppoe_create(struct net *net, struct socket *sock)
{
struct sock *sk;
sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pppoe_sk_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->state = SS_UNCONNECTED;
sock->ops = &pppoe_ops;
sk->sk_backlog_rcv = pppoe_rcv_core;
sk->sk_state = PPPOX_NONE;
sk->sk_type = SOCK_STREAM;
sk->sk_family = PF_PPPOX;
sk->sk_protocol = PX_PROTO_OE;
return 0;
}
static int pppoe_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct pppox_sock *po;
struct pppoe_net *pn;
struct net *net = NULL;
if (!sk)
return 0;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD)) {
release_sock(sk);
return -EBADF;
}
po = pppox_sk(sk);
if (sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND | PPPOX_ZOMBIE)) {
dev_put(po->pppoe_dev);
po->pppoe_dev = NULL;
}
pppox_unbind_sock(sk);
/* Signal the death of the socket. */
sk->sk_state = PPPOX_DEAD;
net = sock_net(sk);
pn = pppoe_pernet(net);
/*
* protect "po" from concurrent updates
* on pppoe_flush_dev
*/
delete_item(pn, po->pppoe_pa.sid, po->pppoe_pa.remote,
po->pppoe_ifindex);
sock_orphan(sk);
sock->sk = NULL;
skb_queue_purge(&sk->sk_receive_queue);
release_sock(sk);
sock_put(sk);
return 0;
}
static int pppoe_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 net_device *dev = NULL;
struct pppoe_net *pn;
struct net *net = NULL;
int error;
lock_sock(sk);
error = -EINVAL;
if (sp->sa_protocol != PX_PROTO_OE)
goto end;
/* Check for already bound sockets */
error = -EBUSY;
if ((sk->sk_state & PPPOX_CONNECTED) &&
stage_session(sp->sa_addr.pppoe.sid))
goto end;
/* Check for already disconnected sockets, on attempts to disconnect */
error = -EALREADY;
if ((sk->sk_state & PPPOX_DEAD) &&
!stage_session(sp->sa_addr.pppoe.sid))
goto end;
error = 0;
/* Delete the old binding */
if (stage_session(po->pppoe_pa.sid)) {
pppox_unbind_sock(sk);
pn = pppoe_pernet(sock_net(sk));
delete_item(pn, po->pppoe_pa.sid,
po->pppoe_pa.remote, po->pppoe_ifindex);
if (po->pppoe_dev) {
dev_put(po->pppoe_dev);
po->pppoe_dev = NULL;
}
memset(sk_pppox(po) + 1, 0,
sizeof(struct pppox_sock) - sizeof(struct sock));
sk->sk_state = PPPOX_NONE;
}
/* Re-bind in session stage only */
if (stage_session(sp->sa_addr.pppoe.sid)) {
error = -ENODEV;
net = sock_net(sk);
dev = dev_get_by_name(net, sp->sa_addr.pppoe.dev);
if (!dev)
goto err_put;
po->pppoe_dev = dev;
po->pppoe_ifindex = dev->ifindex;
pn = pppoe_pernet(net);
if (!(dev->flags & IFF_UP)) {
goto err_put;
}
memcpy(&po->pppoe_pa,
&sp->sa_addr.pppoe,
sizeof(struct pppoe_addr));
write_lock_bh(&pn->hash_lock);
error = __set_item(pn, po);
write_unlock_bh(&pn->hash_lock);
if (error < 0)
goto err_put;
po->chan.hdrlen = (sizeof(struct pppoe_hdr) +
dev->hard_header_len);
po->chan.mtu = dev->mtu - sizeof(struct pppoe_hdr);
po->chan.private = sk;
po->chan.ops = &pppoe_chan_ops;
error = ppp_register_net_channel(dev_net(dev), &po->chan);
if (error) {
delete_item(pn, po->pppoe_pa.sid,
po->pppoe_pa.remote, po->pppoe_ifindex);
goto err_put;
}
sk->sk_state = PPPOX_CONNECTED;
}
po->num = sp->sa_addr.pppoe.sid;
end:
release_sock(sk);
return error;
err_put:
if (po->pppoe_dev) {
dev_put(po->pppoe_dev);
po->pppoe_dev = NULL;
}
goto end;
}
static int pppoe_getname(struct socket *sock, struct sockaddr *uaddr,
int *usockaddr_len, int peer)
{
int len = sizeof(struct sockaddr_pppox);
struct sockaddr_pppox sp;
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OE;
memcpy(&sp.sa_addr.pppoe, &pppox_sk(sock->sk)->pppoe_pa,
sizeof(struct pppoe_addr));
memcpy(uaddr, &sp, len);
*usockaddr_len = len;
return 0;
}
static int pppoe_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
struct pppox_sock *po = pppox_sk(sk);
int val;
int err;
switch (cmd) {
case PPPIOCGMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (put_user(po->pppoe_dev->mtu -
sizeof(struct pppoe_hdr) -
PPP_HDRLEN,
(int __user *)arg))
break;
err = 0;
break;
case PPPIOCSMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (get_user(val, (int __user *)arg))
break;
if (val < (po->pppoe_dev->mtu
- sizeof(struct pppoe_hdr)
- PPP_HDRLEN))
err = 0;
else
err = -EINVAL;
break;
case PPPIOCSFLAGS:
err = -EFAULT;
if (get_user(val, (int __user *)arg))
break;
err = 0;
break;
case PPPOEIOCSFWD:
{
struct pppox_sock *relay_po;
err = -EBUSY;
if (sk->sk_state & (PPPOX_BOUND | PPPOX_ZOMBIE | PPPOX_DEAD))
break;
err = -ENOTCONN;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
/* PPPoE address from the user specifies an outbound
PPPoE address which frames are forwarded to */
err = -EFAULT;
if (copy_from_user(&po->pppoe_relay,
(void __user *)arg,
sizeof(struct sockaddr_pppox)))
break;
err = -EINVAL;
if (po->pppoe_relay.sa_family != AF_PPPOX ||
po->pppoe_relay.sa_protocol != PX_PROTO_OE)
break;
/* Check that the socket referenced by the address
actually exists. */
relay_po = get_item_by_addr(sock_net(sk), &po->pppoe_relay);
if (!relay_po)
break;
sock_put(sk_pppox(relay_po));
sk->sk_state |= PPPOX_RELAY;
err = 0;
break;
}
case PPPOEIOCDFWD:
err = -EALREADY;
if (!(sk->sk_state & PPPOX_RELAY))
break;
sk->sk_state &= ~PPPOX_RELAY;
err = 0;
break;
default:
err = -ENOTTY;
}
return err;
}
static int pppoe_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct sk_buff *skb;
struct sock *sk = sock->sk;
struct pppox_sock *po = pppox_sk(sk);
int error;
struct pppoe_hdr hdr;
struct pppoe_hdr *ph;
struct net_device *dev;
char *start;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED)) {
error = -ENOTCONN;
goto end;
}
hdr.ver = 1;
hdr.type = 1;
hdr.code = 0;
hdr.sid = po->num;
dev = po->pppoe_dev;
error = -EMSGSIZE;
if (total_len > (dev->mtu + dev->hard_header_len))
goto end;
skb = sock_wmalloc(sk, total_len + dev->hard_header_len + 32,
0, GFP_KERNEL);
if (!skb) {
error = -ENOMEM;
goto end;
}
/* Reserve space for headers. */
skb_reserve(skb, dev->hard_header_len);
skb_reset_network_header(skb);
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->protocol = cpu_to_be16(ETH_P_PPP_SES);
ph = (struct pppoe_hdr *)skb_put(skb, total_len + sizeof(struct pppoe_hdr));
start = (char *)&ph->tag[0];
error = memcpy_fromiovec(start, m->msg_iov, total_len);
if (error < 0) {
kfree_skb(skb);
goto end;
}
error = total_len;
dev_hard_header(skb, dev, ETH_P_PPP_SES,
po->pppoe_pa.remote, NULL, total_len);
memcpy(ph, &hdr, sizeof(struct pppoe_hdr));
ph->length = htons(total_len);
dev_queue_xmit(skb);
end:
release_sock(sk);
return error;
}
/************************************************************************
*
* xmit function for internal use.
*
***********************************************************************/
static int __pppoe_xmit(struct sock *sk, struct sk_buff *skb)
{
struct pppox_sock *po = pppox_sk(sk);
struct net_device *dev = po->pppoe_dev;
struct pppoe_hdr *ph;
int data_len = skb->len;
/* The higher-level PPP code (ppp_unregister_channel()) ensures the PPP
* xmit operations conclude prior to an unregistration call. Thus
* sk->sk_state cannot change, so we don't need to do lock_sock().
* But, we also can't do a lock_sock since that introduces a potential
* deadlock as we'd reverse the lock ordering used when calling
* ppp_unregister_channel().
*/
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto abort;
if (!dev)
goto abort;
/* Copy the data if there is no space for the header or if it's
* read-only.
*/
if (skb_cow_head(skb, sizeof(*ph) + dev->hard_header_len))
goto abort;
__skb_push(skb, sizeof(*ph));
skb_reset_network_header(skb);
ph = pppoe_hdr(skb);
ph->ver = 1;
ph->type = 1;
ph->code = 0;
ph->sid = po->num;
ph->length = htons(data_len);
skb->protocol = cpu_to_be16(ETH_P_PPP_SES);
skb->dev = dev;
dev_hard_header(skb, dev, ETH_P_PPP_SES,
po->pppoe_pa.remote, NULL, data_len);
dev_queue_xmit(skb);
return 1;
abort:
kfree_skb(skb);
return 1;
}
/************************************************************************
*
* xmit function called by generic PPP driver
* sends PPP frame over PPPoE socket
*
***********************************************************************/
static int pppoe_xmit(struct ppp_channel *chan, struct sk_buff *skb)
{
struct sock *sk = (struct sock *)chan->private;
return __pppoe_xmit(sk, skb);
}
static const struct ppp_channel_ops pppoe_chan_ops = {
.start_xmit = pppoe_xmit,
};
static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int error = 0;
if (sk->sk_state & PPPOX_BOUND) {
error = -EIO;
goto end;
}
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &error);
if (error < 0)
goto end;
m->msg_namelen = 0;
if (skb) {
total_len = min_t(size_t, total_len, skb->len);
error = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);
if (error == 0) {
consume_skb(skb);
return total_len;
}
}
kfree_skb(skb);
end:
return error;
}
#ifdef CONFIG_PROC_FS
static int pppoe_seq_show(struct seq_file *seq, void *v)
{
struct pppox_sock *po;
char *dev_name;
if (v == SEQ_START_TOKEN) {
seq_puts(seq, "Id Address Device\n");
goto out;
}
po = v;
dev_name = po->pppoe_pa.dev;
seq_printf(seq, "%08X %pM %8s\n",
po->pppoe_pa.sid, po->pppoe_pa.remote, dev_name);
out:
return 0;
}
static inline struct pppox_sock *pppoe_get_idx(struct pppoe_net *pn, loff_t pos)
{
struct pppox_sock *po;
int i;
for (i = 0; i < PPPOE_HASH_SIZE; i++) {
po = pn->hash_table[i];
while (po) {
if (!pos--)
goto out;
po = po->next;
}
}
out:
return po;
}
static void *pppoe_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(pn->hash_lock)
{
struct pppoe_net *pn = pppoe_pernet(seq_file_net(seq));
loff_t l = *pos;
read_lock_bh(&pn->hash_lock);
return l ? pppoe_get_idx(pn, --l) : SEQ_START_TOKEN;
}
static void *pppoe_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct pppoe_net *pn = pppoe_pernet(seq_file_net(seq));
struct pppox_sock *po;
++*pos;
if (v == SEQ_START_TOKEN) {
po = pppoe_get_idx(pn, 0);
goto out;
}
po = v;
if (po->next)
po = po->next;
else {
int hash = hash_item(po->pppoe_pa.sid, po->pppoe_pa.remote);
po = NULL;
while (++hash < PPPOE_HASH_SIZE) {
po = pn->hash_table[hash];
if (po)
break;
}
}
out:
return po;
}
static void pppoe_seq_stop(struct seq_file *seq, void *v)
__releases(pn->hash_lock)
{
struct pppoe_net *pn = pppoe_pernet(seq_file_net(seq));
read_unlock_bh(&pn->hash_lock);
}
static const struct seq_operations pppoe_seq_ops = {
.start = pppoe_seq_start,
.next = pppoe_seq_next,
.stop = pppoe_seq_stop,
.show = pppoe_seq_show,
};
static int pppoe_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pppoe_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations pppoe_seq_fops = {
.owner = THIS_MODULE,
.open = pppoe_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif /* CONFIG_PROC_FS */
static const struct proto_ops pppoe_ops = {
.family = AF_PPPOX,
.owner = THIS_MODULE,
.release = pppoe_release,
.bind = sock_no_bind,
.connect = pppoe_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pppoe_getname,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = pppoe_sendmsg,
.recvmsg = pppoe_recvmsg,
.mmap = sock_no_mmap,
.ioctl = pppox_ioctl,
};
static const struct pppox_proto pppoe_proto = {
.create = pppoe_create,
.ioctl = pppoe_ioctl,
.owner = THIS_MODULE,
};
static __net_init int pppoe_init_net(struct net *net)
{
struct pppoe_net *pn = pppoe_pernet(net);
struct proc_dir_entry *pde;
rwlock_init(&pn->hash_lock);
pde = proc_create("pppoe", S_IRUGO, net->proc_net, &pppoe_seq_fops);
#ifdef CONFIG_PROC_FS
if (!pde)
return -ENOMEM;
#endif
return 0;
}
static __net_exit void pppoe_exit_net(struct net *net)
{
remove_proc_entry("pppoe", net->proc_net);
}
static struct pernet_operations pppoe_net_ops = {
.init = pppoe_init_net,
.exit = pppoe_exit_net,
.id = &pppoe_net_id,
.size = sizeof(struct pppoe_net),
};
static int __init pppoe_init(void)
{
int err;
err = register_pernet_device(&pppoe_net_ops);
if (err)
goto out;
err = proto_register(&pppoe_sk_proto, 0);
if (err)
goto out_unregister_net_ops;
err = register_pppox_proto(PX_PROTO_OE, &pppoe_proto);
if (err)
goto out_unregister_pppoe_proto;
dev_add_pack(&pppoes_ptype);
dev_add_pack(&pppoed_ptype);
register_netdevice_notifier(&pppoe_notifier);
return 0;
out_unregister_pppoe_proto:
proto_unregister(&pppoe_sk_proto);
out_unregister_net_ops:
unregister_pernet_device(&pppoe_net_ops);
out:
return err;
}
static void __exit pppoe_exit(void)
{
unregister_netdevice_notifier(&pppoe_notifier);
dev_remove_pack(&pppoed_ptype);
dev_remove_pack(&pppoes_ptype);
unregister_pppox_proto(PX_PROTO_OE);
proto_unregister(&pppoe_sk_proto);
unregister_pernet_device(&pppoe_net_ops);
}
module_init(pppoe_init);
module_exit(pppoe_exit);
MODULE_AUTHOR("Michal Ostrowski <mostrows@speakeasy.net>");
MODULE_DESCRIPTION("PPP over Ethernet driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_PPPOX);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_3 |
crossvul-cpp_data_bad_1026_0 | /*
* Copyright (c) 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* sf-pcapng.c - pcapng-file-format-specific code from savefile.c
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <pcap/pcap-inttypes.h>
#include <errno.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pcap-int.h"
#include "pcap-common.h"
#ifdef HAVE_OS_PROTO_H
#include "os-proto.h"
#endif
#include "sf-pcapng.h"
/*
* Block types.
*/
/*
* Common part at the beginning of all blocks.
*/
struct block_header {
bpf_u_int32 block_type;
bpf_u_int32 total_length;
};
/*
* Common trailer at the end of all blocks.
*/
struct block_trailer {
bpf_u_int32 total_length;
};
/*
* Common options.
*/
#define OPT_ENDOFOPT 0 /* end of options */
#define OPT_COMMENT 1 /* comment string */
/*
* Option header.
*/
struct option_header {
u_short option_code;
u_short option_length;
};
/*
* Structures for the part of each block type following the common
* part.
*/
/*
* Section Header Block.
*/
#define BT_SHB 0x0A0D0D0A
struct section_header_block {
bpf_u_int32 byte_order_magic;
u_short major_version;
u_short minor_version;
uint64_t section_length;
/* followed by options and trailer */
};
/*
* Byte-order magic value.
*/
#define BYTE_ORDER_MAGIC 0x1A2B3C4D
/*
* Current version number. If major_version isn't PCAP_NG_VERSION_MAJOR,
* that means that this code can't read the file.
*/
#define PCAP_NG_VERSION_MAJOR 1
#define PCAP_NG_VERSION_MINOR 0
/*
* Interface Description Block.
*/
#define BT_IDB 0x00000001
struct interface_description_block {
u_short linktype;
u_short reserved;
bpf_u_int32 snaplen;
/* followed by options and trailer */
};
/*
* Options in the IDB.
*/
#define IF_NAME 2 /* interface name string */
#define IF_DESCRIPTION 3 /* interface description string */
#define IF_IPV4ADDR 4 /* interface's IPv4 address and netmask */
#define IF_IPV6ADDR 5 /* interface's IPv6 address and prefix length */
#define IF_MACADDR 6 /* interface's MAC address */
#define IF_EUIADDR 7 /* interface's EUI address */
#define IF_SPEED 8 /* interface's speed, in bits/s */
#define IF_TSRESOL 9 /* interface's time stamp resolution */
#define IF_TZONE 10 /* interface's time zone */
#define IF_FILTER 11 /* filter used when capturing on interface */
#define IF_OS 12 /* string OS on which capture on this interface was done */
#define IF_FCSLEN 13 /* FCS length for this interface */
#define IF_TSOFFSET 14 /* time stamp offset for this interface */
/*
* Enhanced Packet Block.
*/
#define BT_EPB 0x00000006
struct enhanced_packet_block {
bpf_u_int32 interface_id;
bpf_u_int32 timestamp_high;
bpf_u_int32 timestamp_low;
bpf_u_int32 caplen;
bpf_u_int32 len;
/* followed by packet data, options, and trailer */
};
/*
* Simple Packet Block.
*/
#define BT_SPB 0x00000003
struct simple_packet_block {
bpf_u_int32 len;
/* followed by packet data and trailer */
};
/*
* Packet Block.
*/
#define BT_PB 0x00000002
struct packet_block {
u_short interface_id;
u_short drops_count;
bpf_u_int32 timestamp_high;
bpf_u_int32 timestamp_low;
bpf_u_int32 caplen;
bpf_u_int32 len;
/* followed by packet data, options, and trailer */
};
/*
* Block cursor - used when processing the contents of a block.
* Contains a pointer into the data being processed and a count
* of bytes remaining in the block.
*/
struct block_cursor {
u_char *data;
size_t data_remaining;
bpf_u_int32 block_type;
};
typedef enum {
PASS_THROUGH,
SCALE_UP_DEC,
SCALE_DOWN_DEC,
SCALE_UP_BIN,
SCALE_DOWN_BIN
} tstamp_scale_type_t;
/*
* Per-interface information.
*/
struct pcap_ng_if {
uint64_t tsresol; /* time stamp resolution */
tstamp_scale_type_t scale_type; /* how to scale */
uint64_t scale_factor; /* time stamp scale factor for power-of-10 tsresol */
uint64_t tsoffset; /* time stamp offset */
};
/*
* Per-pcap_t private data.
*
* max_blocksize is the maximum size of a block that we'll accept. We
* reject blocks bigger than this, so we don't consume too much memory
* with a truly huge block. It can change as we see IDBs with different
* link-layer header types. (Currently, we don't support IDBs with
* different link-layer header types, but we will support it in the
* future, when we offer file-reading APIs that support it.)
*
* XXX - that's an issue on ILP32 platforms, where the maximum block
* size of 2^31-1 would eat all but one byte of the entire address space.
* It's less of an issue on ILP64/LLP64 platforms, but the actual size
* of the address space may be limited by 1) the number of *significant*
* address bits (currently, x86-64 only supports 48 bits of address), 2)
* any limitations imposed by the operating system; 3) any limitations
* imposed by the amount of available backing store for anonymous pages,
* so we impose a limit regardless of the size of a pointer.
*/
struct pcap_ng_sf {
uint64_t user_tsresol; /* time stamp resolution requested by the user */
u_int max_blocksize; /* don't grow buffer size past this */
bpf_u_int32 ifcount; /* number of interfaces seen in this capture */
bpf_u_int32 ifaces_size; /* size of array below */
struct pcap_ng_if *ifaces; /* array of interface information */
};
/*
* The maximum block size we start with; we use an arbitrary value of
* 16 MiB.
*/
#define INITIAL_MAX_BLOCKSIZE (16*1024*1024)
/*
* Maximum block size for a given maximum snapshot length; we define it
* as the size of an EPB with a max_snaplen-sized packet and 128KB of
* options.
*/
#define MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen) \
(sizeof (struct block_header) + \
sizeof (struct enhanced_packet_block) + \
(max_snaplen) + 131072 + \
sizeof (struct block_trailer))
static void pcap_ng_cleanup(pcap_t *p);
static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr,
u_char **data);
static int
read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof,
char *errbuf)
{
size_t amt_read;
amt_read = fread(buf, 1, bytes_to_read, fp);
if (amt_read != bytes_to_read) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
} else {
if (amt_read == 0 && !fail_on_eof)
return (0); /* EOF */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"truncated dump file; tried to read %" PRIsize " bytes, only got %" PRIsize,
bytes_to_read, amt_read);
}
return (-1);
}
return (1);
}
static int
read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
struct pcap_ng_sf *ps;
int status;
struct block_header bhdr;
struct block_trailer *btrlr;
u_char *bdata;
size_t data_remaining;
ps = p->priv;
status = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf);
if (status <= 0)
return (status); /* error or EOF */
if (p->swapped) {
bhdr.block_type = SWAPLONG(bhdr.block_type);
bhdr.total_length = SWAPLONG(bhdr.total_length);
}
/*
* Is this block "too small" - i.e., is it shorter than a block
* header plus a block trailer?
*/
if (bhdr.total_length < sizeof(struct block_header) +
sizeof(struct block_trailer)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block in pcapng dump file has a length of %u < %" PRIsize,
bhdr.total_length,
sizeof(struct block_header) + sizeof(struct block_trailer));
return (-1);
}
/*
* Is the block total length a multiple of 4?
*/
if ((bhdr.total_length % 4) != 0) {
/*
* No. Report that as an error.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block in pcapng dump file has a length of %u that is not a multiple of 4" PRIsize,
bhdr.total_length);
return (-1);
}
/*
* Is the buffer big enough?
*/
if (p->bufsize < bhdr.total_length) {
/*
* No - make it big enough, unless it's too big, in
* which case we fail.
*/
void *bigger_buffer;
if (bhdr.total_length > ps->max_blocksize) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "pcapng block size %u > maximum %u", bhdr.total_length,
ps->max_blocksize);
return (-1);
}
bigger_buffer = realloc(p->buffer, bhdr.total_length);
if (bigger_buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
return (-1);
}
p->buffer = bigger_buffer;
}
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the block.
*/
memcpy(p->buffer, &bhdr, sizeof(bhdr));
bdata = (u_char *)p->buffer + sizeof(bhdr);
data_remaining = bhdr.total_length - sizeof(bhdr);
if (read_bytes(fp, bdata, data_remaining, 1, errbuf) == -1)
return (-1);
/*
* Get the block size from the trailer.
*/
btrlr = (struct block_trailer *)(bdata + data_remaining - sizeof (struct block_trailer));
if (p->swapped)
btrlr->total_length = SWAPLONG(btrlr->total_length);
/*
* Is the total length from the trailer the same as the total
* length from the header?
*/
if (bhdr.total_length != btrlr->total_length) {
/*
* No.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block total length in header and trailer don't match");
return (-1);
}
/*
* Initialize the cursor.
*/
cursor->data = bdata;
cursor->data_remaining = data_remaining - sizeof(struct block_trailer);
cursor->block_type = bhdr.block_type;
return (1);
}
static void *
get_from_block_data(struct block_cursor *cursor, size_t chunk_size,
char *errbuf)
{
void *data;
/*
* Make sure we have the specified amount of data remaining in
* the block data.
*/
if (cursor->data_remaining < chunk_size) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block of type %u in pcapng dump file is too short",
cursor->block_type);
return (NULL);
}
/*
* Return the current pointer, and skip past the chunk.
*/
data = cursor->data;
cursor->data += chunk_size;
cursor->data_remaining -= chunk_size;
return (data);
}
static struct option_header *
get_opthdr_from_block_data(pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
struct option_header *opthdr;
opthdr = get_from_block_data(cursor, sizeof(*opthdr), errbuf);
if (opthdr == NULL) {
/*
* Option header is cut short.
*/
return (NULL);
}
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
opthdr->option_code = SWAPSHORT(opthdr->option_code);
opthdr->option_length = SWAPSHORT(opthdr->option_length);
}
return (opthdr);
}
static void *
get_optvalue_from_block_data(struct block_cursor *cursor,
struct option_header *opthdr, char *errbuf)
{
size_t padded_option_len;
void *optvalue;
/* Pad option length to 4-byte boundary */
padded_option_len = opthdr->option_length;
padded_option_len = ((padded_option_len + 3)/4)*4;
optvalue = get_from_block_data(cursor, padded_option_len, errbuf);
if (optvalue == NULL) {
/*
* Option value is cut short.
*/
return (NULL);
}
return (optvalue);
}
static int
process_idb_options(pcap_t *p, struct block_cursor *cursor, uint64_t *tsresol,
uint64_t *tsoffset, int *is_binary, char *errbuf)
{
struct option_header *opthdr;
void *optvalue;
int saw_tsresol, saw_tsoffset;
uint8_t tsresol_opt;
u_int i;
saw_tsresol = 0;
saw_tsoffset = 0;
while (cursor->data_remaining != 0) {
/*
* Get the option header.
*/
opthdr = get_opthdr_from_block_data(p, cursor, errbuf);
if (opthdr == NULL) {
/*
* Option header is cut short.
*/
return (-1);
}
/*
* Get option value.
*/
optvalue = get_optvalue_from_block_data(cursor, opthdr,
errbuf);
if (optvalue == NULL) {
/*
* Option value is cut short.
*/
return (-1);
}
switch (opthdr->option_code) {
case OPT_ENDOFOPT:
if (opthdr->option_length != 0) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has opt_endofopt option with length %u != 0",
opthdr->option_length);
return (-1);
}
goto done;
case IF_TSRESOL:
if (opthdr->option_length != 1) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has if_tsresol option with length %u != 1",
opthdr->option_length);
return (-1);
}
if (saw_tsresol) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has more than one if_tsresol option");
return (-1);
}
saw_tsresol = 1;
memcpy(&tsresol_opt, optvalue, sizeof(tsresol_opt));
if (tsresol_opt & 0x80) {
/*
* Resolution is negative power of 2.
*/
uint8_t tsresol_shift = (tsresol_opt & 0x7F);
if (tsresol_shift > 63) {
/*
* Resolution is too high; 2^-{res}
* won't fit in a 64-bit value.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block if_tsresol option resolution 2^-%u is too high",
tsresol_shift);
return (-1);
}
*is_binary = 1;
*tsresol = ((uint64_t)1) << tsresol_shift;
} else {
/*
* Resolution is negative power of 10.
*/
if (tsresol_opt > 19) {
/*
* Resolution is too high; 2^-{res}
* won't fit in a 64-bit value (the
* largest power of 10 that fits
* in a 64-bit value is 10^19, as
* the largest 64-bit unsigned
* value is ~1.8*10^19).
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block if_tsresol option resolution 10^-%u is too high",
tsresol_opt);
return (-1);
}
*is_binary = 0;
*tsresol = 1;
for (i = 0; i < tsresol_opt; i++)
*tsresol *= 10;
}
break;
case IF_TSOFFSET:
if (opthdr->option_length != 8) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has if_tsoffset option with length %u != 8",
opthdr->option_length);
return (-1);
}
if (saw_tsoffset) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has more than one if_tsoffset option");
return (-1);
}
saw_tsoffset = 1;
memcpy(tsoffset, optvalue, sizeof(*tsoffset));
if (p->swapped)
*tsoffset = SWAPLL(*tsoffset);
break;
default:
break;
}
}
done:
return (0);
}
static int
add_interface(pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
struct pcap_ng_sf *ps;
uint64_t tsresol;
uint64_t tsoffset;
int is_binary;
ps = p->priv;
/*
* Count this interface.
*/
ps->ifcount++;
/*
* Grow the array of per-interface information as necessary.
*/
if (ps->ifcount > ps->ifaces_size) {
/*
* We need to grow the array.
*/
bpf_u_int32 new_ifaces_size;
struct pcap_ng_if *new_ifaces;
if (ps->ifaces_size == 0) {
/*
* It's currently empty.
*
* (The Clang static analyzer doesn't do enough,
* err, umm, dataflow *analysis* to realize that
* ps->ifaces_size == 0 if ps->ifaces == NULL,
* and so complains about a possible zero argument
* to realloc(), so we check for the former
* condition to shut it up.
*
* However, it doesn't complain that one of the
* multiplications below could overflow, which is
* a real, albeit extremely unlikely, problem (you'd
* need a pcapng file with tens of millions of
* interfaces).)
*/
new_ifaces_size = 1;
new_ifaces = malloc(sizeof (struct pcap_ng_if));
} else {
/*
* It's not currently empty; double its size.
* (Perhaps overkill once we have a lot of interfaces.)
*
* Check for overflow if we double it.
*/
if (ps->ifaces_size * 2 < ps->ifaces_size) {
/*
* The maximum number of interfaces before
* ps->ifaces_size overflows is the largest
* possible 32-bit power of 2, as we do
* size doubling.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"more than %u interfaces in the file",
0x80000000U);
return (0);
}
/*
* ps->ifaces_size * 2 doesn't overflow, so it's
* safe to multiply.
*/
new_ifaces_size = ps->ifaces_size * 2;
/*
* Now make sure that's not so big that it overflows
* if we multiply by sizeof (struct pcap_ng_if).
*
* That can happen on 32-bit platforms, with a 32-bit
* size_t; it shouldn't happen on 64-bit platforms,
* with a 64-bit size_t, as new_ifaces_size is
* 32 bits.
*/
if (new_ifaces_size * sizeof (struct pcap_ng_if) < new_ifaces_size) {
/*
* As this fails only with 32-bit size_t,
* the multiplication was 32x32->32, and
* the largest 32-bit value that can safely
* be multiplied by sizeof (struct pcap_ng_if)
* without overflow is the largest 32-bit
* (unsigned) value divided by
* sizeof (struct pcap_ng_if).
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"more than %u interfaces in the file",
0xFFFFFFFFU / ((u_int)sizeof (struct pcap_ng_if)));
return (0);
}
new_ifaces = realloc(ps->ifaces, new_ifaces_size * sizeof (struct pcap_ng_if));
}
if (new_ifaces == NULL) {
/*
* We ran out of memory.
* Give up.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"out of memory for per-interface information (%u interfaces)",
ps->ifcount);
return (0);
}
ps->ifaces_size = new_ifaces_size;
ps->ifaces = new_ifaces;
}
/*
* Set the default time stamp resolution and offset.
*/
tsresol = 1000000; /* microsecond resolution */
is_binary = 0; /* which is a power of 10 */
tsoffset = 0; /* absolute timestamps */
/*
* Now look for various time stamp options, so we know
* how to interpret the time stamps for this interface.
*/
if (process_idb_options(p, cursor, &tsresol, &tsoffset, &is_binary,
errbuf) == -1)
return (0);
ps->ifaces[ps->ifcount - 1].tsresol = tsresol;
ps->ifaces[ps->ifcount - 1].tsoffset = tsoffset;
/*
* Determine whether we're scaling up or down or not
* at all for this interface.
*/
if (tsresol == ps->user_tsresol) {
/*
* The resolution is the resolution the user wants,
* so we don't have to do scaling.
*/
ps->ifaces[ps->ifcount - 1].scale_type = PASS_THROUGH;
} else if (tsresol > ps->user_tsresol) {
/*
* The resolution is greater than what the user wants,
* so we have to scale the timestamps down.
*/
if (is_binary)
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_BIN;
else {
/*
* Calculate the scale factor.
*/
ps->ifaces[ps->ifcount - 1].scale_factor = tsresol/ps->user_tsresol;
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_DEC;
}
} else {
/*
* The resolution is less than what the user wants,
* so we have to scale the timestamps up.
*/
if (is_binary)
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_BIN;
else {
/*
* Calculate the scale factor.
*/
ps->ifaces[ps->ifcount - 1].scale_factor = ps->user_tsresol/tsresol;
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_DEC;
}
}
return (1);
}
/*
* Check whether this is a pcapng savefile and, if it is, extract the
* relevant information from the header.
*/
pcap_t *
pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,
char *errbuf, int *err)
{
bpf_u_int32 magic_int;
size_t amt_read;
bpf_u_int32 total_length;
bpf_u_int32 byte_order_magic;
struct block_header *bhdrp;
struct section_header_block *shbp;
pcap_t *p;
int swapped = 0;
struct pcap_ng_sf *ps;
int status;
struct block_cursor cursor;
struct interface_description_block *idbp;
/*
* Assume no read errors.
*/
*err = 0;
/*
* Check whether the first 4 bytes of the file are the block
* type for a pcapng savefile.
*/
memcpy(&magic_int, magic, sizeof(magic_int));
if (magic_int != BT_SHB) {
/*
* XXX - check whether this looks like what the block
* type would be after being munged by mapping between
* UN*X and DOS/Windows text file format and, if it
* does, look for the byte-order magic number in
* the appropriate place and, if we find it, report
* this as possibly being a pcapng file transferred
* between UN*X and Windows in text file format?
*/
return (NULL); /* nope */
}
/*
* OK, they are. However, that's just \n\r\r\n, so it could,
* conceivably, be an ordinary text file.
*
* It could not, however, conceivably be any other type of
* capture file, so we can read the rest of the putative
* Section Header Block; put the block type in the common
* header, read the rest of the common header and the
* fixed-length portion of the SHB, and look for the byte-order
* magic value.
*/
amt_read = fread(&total_length, 1, sizeof(total_length), fp);
if (amt_read < sizeof(total_length)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
if (amt_read < sizeof(byte_order_magic)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
if (byte_order_magic != BYTE_ORDER_MAGIC) {
byte_order_magic = SWAPLONG(byte_order_magic);
if (byte_order_magic != BYTE_ORDER_MAGIC) {
/*
* Not a pcapng file.
*/
return (NULL);
}
swapped = 1;
total_length = SWAPLONG(total_length);
}
/*
* Check the sanity of the total length.
*/
if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Section Header Block in pcapng dump file has a length of %u < %" PRIsize,
total_length,
sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer));
*err = 1;
return (NULL);
}
/*
* Make sure it's not too big.
*/
if (total_length > INITIAL_MAX_BLOCKSIZE) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"pcapng block size %u > maximum %u",
total_length, INITIAL_MAX_BLOCKSIZE);
*err = 1;
return (NULL);
}
/*
* OK, this is a good pcapng file.
* Allocate a pcap_t for it.
*/
p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf));
if (p == NULL) {
/* Allocation failed. */
*err = 1;
return (NULL);
}
p->swapped = swapped;
ps = p->priv;
/*
* What precision does the user want?
*/
switch (precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
ps->user_tsresol = 1000000;
break;
case PCAP_TSTAMP_PRECISION_NANO:
ps->user_tsresol = 1000000000;
break;
default:
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unknown time stamp resolution %u", precision);
free(p);
*err = 1;
return (NULL);
}
p->opt.tstamp_precision = precision;
/*
* Allocate a buffer into which to read blocks. We default to
* the maximum of:
*
* the total length of the SHB for which we read the header;
*
* 2K, which should be more than large enough for an Enhanced
* Packet Block containing a full-size Ethernet frame, and
* leaving room for some options.
*
* If we find a bigger block, we reallocate the buffer, up to
* the maximum size. We start out with a maximum size of
* INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types
* with a maximum snapshot that results in a larger maximum
* block length, we boost the maximum.
*/
p->bufsize = 2048;
if (p->bufsize < total_length)
p->bufsize = total_length;
p->buffer = malloc(p->bufsize);
if (p->buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
free(p);
*err = 1;
return (NULL);
}
ps->max_blocksize = INITIAL_MAX_BLOCKSIZE;
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the SHB.
*/
bhdrp = (struct block_header *)p->buffer;
shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header));
bhdrp->block_type = magic_int;
bhdrp->total_length = total_length;
shbp->byte_order_magic = byte_order_magic;
if (read_bytes(fp,
(u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
1, errbuf) == -1)
goto fail;
if (p->swapped) {
/*
* Byte-swap the fields we've read.
*/
shbp->major_version = SWAPSHORT(shbp->major_version);
shbp->minor_version = SWAPSHORT(shbp->minor_version);
/*
* XXX - we don't care about the section length.
*/
}
/* currently only SHB version 1.0 is supported */
if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR &&
shbp->minor_version == PCAP_NG_VERSION_MINOR)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unsupported pcapng savefile version %u.%u",
shbp->major_version, shbp->minor_version);
goto fail;
}
p->version_major = shbp->major_version;
p->version_minor = shbp->minor_version;
/*
* Save the time stamp resolution the user requested.
*/
p->opt.tstamp_precision = precision;
/*
* Now start looking for an Interface Description Block.
*/
for (;;) {
/*
* Read the next block.
*/
status = read_block(fp, p, &cursor, errbuf);
if (status == 0) {
/* EOF - no IDB in this file */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has no Interface Description Blocks");
goto fail;
}
if (status == -1)
goto fail; /* error */
switch (cursor.block_type) {
case BT_IDB:
/*
* Get a pointer to the fixed-length portion of the
* IDB.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
errbuf);
if (idbp == NULL)
goto fail; /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, errbuf))
goto fail;
goto done;
case BT_EPB:
case BT_SPB:
case BT_PB:
/*
* Saw a packet before we saw any IDBs. That's
* not valid, as we don't know what link-layer
* encapsulation the packet has.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has a packet block before any Interface Description Blocks");
goto fail;
default:
/*
* Just ignore it.
*/
break;
}
}
done:
p->tzoff = 0; /* XXX - not used in pcap */
p->linktype = linktype_to_dlt(idbp->linktype);
p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen);
p->linktype_ext = 0;
/*
* If the maximum block size for a packet with the maximum
* snapshot length for this DLT_ is bigger than the current
* maximum block size, increase the maximum.
*/
if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize)
ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype));
p->next_packet_op = pcap_ng_next_packet;
p->cleanup_op = pcap_ng_cleanup;
return (p);
fail:
free(ps->ifaces);
free(p->buffer);
free(p);
*err = 1;
return (NULL);
}
static void
pcap_ng_cleanup(pcap_t *p)
{
struct pcap_ng_sf *ps = p->priv;
free(ps->ifaces);
sf_cleanup(p);
}
/*
* Read and return the next packet from the savefile. Return the header
* in hdr and a pointer to the contents in data. Return 0 on success, 1
* if there were no more packets, and -1 on an error.
*/
static int
pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data)
{
struct pcap_ng_sf *ps = p->priv;
struct block_cursor cursor;
int status;
struct enhanced_packet_block *epbp;
struct simple_packet_block *spbp;
struct packet_block *pbp;
bpf_u_int32 interface_id = 0xFFFFFFFF;
struct interface_description_block *idbp;
struct section_header_block *shbp;
FILE *fp = p->rfile;
uint64_t t, sec, frac;
/*
* Look for an Enhanced Packet Block, a Simple Packet Block,
* or a Packet Block.
*/
for (;;) {
/*
* Read the block type and length; those are common
* to all blocks.
*/
status = read_block(fp, p, &cursor, p->errbuf);
if (status == 0)
return (1); /* EOF */
if (status == -1)
return (-1); /* error */
switch (cursor.block_type) {
case BT_EPB:
/*
* Get a pointer to the fixed-length portion of the
* EPB.
*/
epbp = get_from_block_data(&cursor, sizeof(*epbp),
p->errbuf);
if (epbp == NULL)
return (-1); /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
/* these were written in opposite byte order */
interface_id = SWAPLONG(epbp->interface_id);
hdr->caplen = SWAPLONG(epbp->caplen);
hdr->len = SWAPLONG(epbp->len);
t = ((uint64_t)SWAPLONG(epbp->timestamp_high)) << 32 |
SWAPLONG(epbp->timestamp_low);
} else {
interface_id = epbp->interface_id;
hdr->caplen = epbp->caplen;
hdr->len = epbp->len;
t = ((uint64_t)epbp->timestamp_high) << 32 |
epbp->timestamp_low;
}
goto found;
case BT_SPB:
/*
* Get a pointer to the fixed-length portion of the
* SPB.
*/
spbp = get_from_block_data(&cursor, sizeof(*spbp),
p->errbuf);
if (spbp == NULL)
return (-1); /* error */
/*
* SPB packets are assumed to have arrived on
* the first interface.
*/
interface_id = 0;
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
/* these were written in opposite byte order */
hdr->len = SWAPLONG(spbp->len);
} else
hdr->len = spbp->len;
/*
* The SPB doesn't give the captured length;
* it's the minimum of the snapshot length
* and the packet length.
*/
hdr->caplen = hdr->len;
if (hdr->caplen > (bpf_u_int32)p->snapshot)
hdr->caplen = p->snapshot;
t = 0; /* no time stamps */
goto found;
case BT_PB:
/*
* Get a pointer to the fixed-length portion of the
* PB.
*/
pbp = get_from_block_data(&cursor, sizeof(*pbp),
p->errbuf);
if (pbp == NULL)
return (-1); /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
/* these were written in opposite byte order */
interface_id = SWAPSHORT(pbp->interface_id);
hdr->caplen = SWAPLONG(pbp->caplen);
hdr->len = SWAPLONG(pbp->len);
t = ((uint64_t)SWAPLONG(pbp->timestamp_high)) << 32 |
SWAPLONG(pbp->timestamp_low);
} else {
interface_id = pbp->interface_id;
hdr->caplen = pbp->caplen;
hdr->len = pbp->len;
t = ((uint64_t)pbp->timestamp_high) << 32 |
pbp->timestamp_low;
}
goto found;
case BT_IDB:
/*
* Interface Description Block. Get a pointer
* to its fixed-length portion.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
p->errbuf);
if (idbp == NULL)
return (-1); /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* If the link-layer type or snapshot length
* differ from the ones for the first IDB we
* saw, quit.
*
* XXX - just discard packets from those
* interfaces?
*/
if (p->linktype != idbp->linktype) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"an interface has a type %u different from the type of the first interface",
idbp->linktype);
return (-1);
}
/*
* Check against the *adjusted* value of this IDB's
* snapshot length.
*/
if ((bpf_u_int32)p->snapshot !=
pcap_adjust_snapshot(p->linktype, idbp->snaplen)) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"an interface has a snapshot length %u different from the type of the first interface",
idbp->snaplen);
return (-1);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, p->errbuf))
return (-1);
break;
case BT_SHB:
/*
* Section Header Block. Get a pointer
* to its fixed-length portion.
*/
shbp = get_from_block_data(&cursor, sizeof(*shbp),
p->errbuf);
if (shbp == NULL)
return (-1); /* error */
/*
* Assume the byte order of this section is
* the same as that of the previous section.
* We'll check for that later.
*/
if (p->swapped) {
shbp->byte_order_magic =
SWAPLONG(shbp->byte_order_magic);
shbp->major_version =
SWAPSHORT(shbp->major_version);
}
/*
* Make sure the byte order doesn't change;
* pcap_is_swapped() shouldn't change its
* return value in the middle of reading a capture.
*/
switch (shbp->byte_order_magic) {
case BYTE_ORDER_MAGIC:
/*
* OK.
*/
break;
case SWAPLONG(BYTE_ORDER_MAGIC):
/*
* Byte order changes.
*/
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"the file has sections with different byte orders");
return (-1);
default:
/*
* Not a valid SHB.
*/
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"the file has a section with a bad byte order magic field");
return (-1);
}
/*
* Make sure the major version is the version
* we handle.
*/
if (shbp->major_version != PCAP_NG_VERSION_MAJOR) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"unknown pcapng savefile major version number %u",
shbp->major_version);
return (-1);
}
/*
* Reset the interface count; this section should
* have its own set of IDBs. If any of them
* don't have the same interface type, snapshot
* length, or resolution as the first interface
* we saw, we'll fail. (And if we don't see
* any IDBs, we'll fail when we see a packet
* block.)
*/
ps->ifcount = 0;
break;
default:
/*
* Not a packet block, IDB, or SHB; ignore it.
*/
break;
}
}
found:
/*
* Is the interface ID an interface we know?
*/
if (interface_id >= ps->ifcount) {
/*
* Yes. Fail.
*/
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"a packet arrived on interface %u, but there's no Interface Description Block for that interface",
interface_id);
return (-1);
}
if (hdr->caplen > (bpf_u_int32)p->snapshot) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"invalid packet capture length %u, bigger than "
"snaplen of %d", hdr->caplen, p->snapshot);
return (-1);
}
/*
* Convert the time stamp to seconds and fractions of a second,
* with the fractions being in units of the file-supplied resolution.
*/
sec = t / ps->ifaces[interface_id].tsresol + ps->ifaces[interface_id].tsoffset;
frac = t % ps->ifaces[interface_id].tsresol;
/*
* Convert the fractions from units of the file-supplied resolution
* to units of the user-requested resolution.
*/
switch (ps->ifaces[interface_id].scale_type) {
case PASS_THROUGH:
/*
* The interface resolution is what the user wants,
* so we're done.
*/
break;
case SCALE_UP_DEC:
/*
* The interface resolution is less than what the user
* wants; scale the fractional part up to the units of
* the resolution the user requested by multiplying by
* the quotient of the user-requested resolution and the
* file-supplied resolution.
*
* Those resolutions are both powers of 10, and the user-
* requested resolution is greater than the file-supplied
* resolution, so the quotient in question is an integer.
* We've calculated that quotient already, so we just
* multiply by it.
*/
frac *= ps->ifaces[interface_id].scale_factor;
break;
case SCALE_UP_BIN:
/*
* The interface resolution is less than what the user
* wants; scale the fractional part up to the units of
* the resolution the user requested by multiplying by
* the quotient of the user-requested resolution and the
* file-supplied resolution.
*
* The file-supplied resolution is a power of 2, so the
* quotient is not an integer, so, in order to do this
* entirely with integer arithmetic, we multiply by the
* user-requested resolution and divide by the file-
* supplied resolution.
*
* XXX - Is there something clever we could do here,
* given that we know that the file-supplied resolution
* is a power of 2? Doing a multiplication followed by
* a division runs the risk of overflowing, and involves
* two non-simple arithmetic operations.
*/
frac *= ps->user_tsresol;
frac /= ps->ifaces[interface_id].tsresol;
break;
case SCALE_DOWN_DEC:
/*
* The interface resolution is greater than what the user
* wants; scale the fractional part up to the units of
* the resolution the user requested by multiplying by
* the quotient of the user-requested resolution and the
* file-supplied resolution.
*
* Those resolutions are both powers of 10, and the user-
* requested resolution is less than the file-supplied
* resolution, so the quotient in question isn't an
* integer, but its reciprocal is, and we can just divide
* by the reciprocal of the quotient. We've calculated
* the reciprocal of that quotient already, so we must
* divide by it.
*/
frac /= ps->ifaces[interface_id].scale_factor;
break;
case SCALE_DOWN_BIN:
/*
* The interface resolution is greater than what the user
* wants; convert the fractional part to units of the
* resolution the user requested by multiplying by the
* quotient of the user-requested resolution and the
* file-supplied resolution. We do that by multiplying
* by the user-requested resolution and dividing by the
* file-supplied resolution, as the quotient might not
* fit in an integer.
*
* The file-supplied resolution is a power of 2, so the
* quotient is not an integer, and neither is its
* reciprocal, so, in order to do this entirely with
* integer arithmetic, we multiply by the user-requested
* resolution and divide by the file-supplied resolution.
*
* XXX - Is there something clever we could do here,
* given that we know that the file-supplied resolution
* is a power of 2? Doing a multiplication followed by
* a division runs the risk of overflowing, and involves
* two non-simple arithmetic operations.
*/
frac *= ps->user_tsresol;
frac /= ps->ifaces[interface_id].tsresol;
break;
}
#ifdef _WIN32
/*
* tv_sec and tv_used in the Windows struct timeval are both
* longs.
*/
hdr->ts.tv_sec = (long)sec;
hdr->ts.tv_usec = (long)frac;
#else
/*
* tv_sec in the UN*X struct timeval is a time_t; tv_usec is
* suseconds_t in UN*Xes that work the way the current Single
* UNIX Standard specify - but not all older UN*Xes necessarily
* support that type, so just cast to int.
*/
hdr->ts.tv_sec = (time_t)sec;
hdr->ts.tv_usec = (int)frac;
#endif
/*
* Get a pointer to the packet data.
*/
*data = get_from_block_data(&cursor, hdr->caplen, p->errbuf);
if (*data == NULL)
return (-1);
if (p->swapped)
swap_pseudo_headers(p->linktype, hdr, *data);
return (0);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1026_0 |
crossvul-cpp_data_bad_2117_0 | /*
* Copyright (c) 2004-2007 Intel Corporation. All rights reserved.
* Copyright (c) 2004 Topspin Corporation. All rights reserved.
* Copyright (c) 2004, 2005 Voltaire Corporation. All rights reserved.
* Copyright (c) 2005 Sun Microsystems, Inc. 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/completion.h>
#include <linux/dma-mapping.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/idr.h>
#include <linux/interrupt.h>
#include <linux/random.h>
#include <linux/rbtree.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/workqueue.h>
#include <linux/kdev_t.h>
#include <linux/etherdevice.h>
#include <rdma/ib_cache.h>
#include <rdma/ib_cm.h>
#include "cm_msgs.h"
MODULE_AUTHOR("Sean Hefty");
MODULE_DESCRIPTION("InfiniBand CM");
MODULE_LICENSE("Dual BSD/GPL");
static void cm_add_one(struct ib_device *device);
static void cm_remove_one(struct ib_device *device);
static struct ib_client cm_client = {
.name = "cm",
.add = cm_add_one,
.remove = cm_remove_one
};
static struct ib_cm {
spinlock_t lock;
struct list_head device_list;
rwlock_t device_lock;
struct rb_root listen_service_table;
u64 listen_service_id;
/* struct rb_root peer_service_table; todo: fix peer to peer */
struct rb_root remote_qp_table;
struct rb_root remote_id_table;
struct rb_root remote_sidr_table;
struct idr local_id_table;
__be32 random_id_operand;
struct list_head timewait_list;
struct workqueue_struct *wq;
} cm;
/* Counter indexes ordered by attribute ID */
enum {
CM_REQ_COUNTER,
CM_MRA_COUNTER,
CM_REJ_COUNTER,
CM_REP_COUNTER,
CM_RTU_COUNTER,
CM_DREQ_COUNTER,
CM_DREP_COUNTER,
CM_SIDR_REQ_COUNTER,
CM_SIDR_REP_COUNTER,
CM_LAP_COUNTER,
CM_APR_COUNTER,
CM_ATTR_COUNT,
CM_ATTR_ID_OFFSET = 0x0010,
};
enum {
CM_XMIT,
CM_XMIT_RETRIES,
CM_RECV,
CM_RECV_DUPLICATES,
CM_COUNTER_GROUPS
};
static char const counter_group_names[CM_COUNTER_GROUPS]
[sizeof("cm_rx_duplicates")] = {
"cm_tx_msgs", "cm_tx_retries",
"cm_rx_msgs", "cm_rx_duplicates"
};
struct cm_counter_group {
struct kobject obj;
atomic_long_t counter[CM_ATTR_COUNT];
};
struct cm_counter_attribute {
struct attribute attr;
int index;
};
#define CM_COUNTER_ATTR(_name, _index) \
struct cm_counter_attribute cm_##_name##_counter_attr = { \
.attr = { .name = __stringify(_name), .mode = 0444 }, \
.index = _index \
}
static CM_COUNTER_ATTR(req, CM_REQ_COUNTER);
static CM_COUNTER_ATTR(mra, CM_MRA_COUNTER);
static CM_COUNTER_ATTR(rej, CM_REJ_COUNTER);
static CM_COUNTER_ATTR(rep, CM_REP_COUNTER);
static CM_COUNTER_ATTR(rtu, CM_RTU_COUNTER);
static CM_COUNTER_ATTR(dreq, CM_DREQ_COUNTER);
static CM_COUNTER_ATTR(drep, CM_DREP_COUNTER);
static CM_COUNTER_ATTR(sidr_req, CM_SIDR_REQ_COUNTER);
static CM_COUNTER_ATTR(sidr_rep, CM_SIDR_REP_COUNTER);
static CM_COUNTER_ATTR(lap, CM_LAP_COUNTER);
static CM_COUNTER_ATTR(apr, CM_APR_COUNTER);
static struct attribute *cm_counter_default_attrs[] = {
&cm_req_counter_attr.attr,
&cm_mra_counter_attr.attr,
&cm_rej_counter_attr.attr,
&cm_rep_counter_attr.attr,
&cm_rtu_counter_attr.attr,
&cm_dreq_counter_attr.attr,
&cm_drep_counter_attr.attr,
&cm_sidr_req_counter_attr.attr,
&cm_sidr_rep_counter_attr.attr,
&cm_lap_counter_attr.attr,
&cm_apr_counter_attr.attr,
NULL
};
struct cm_port {
struct cm_device *cm_dev;
struct ib_mad_agent *mad_agent;
struct kobject port_obj;
u8 port_num;
struct cm_counter_group counter_group[CM_COUNTER_GROUPS];
};
struct cm_device {
struct list_head list;
struct ib_device *ib_device;
struct device *device;
u8 ack_delay;
struct cm_port *port[0];
};
struct cm_av {
struct cm_port *port;
union ib_gid dgid;
struct ib_ah_attr ah_attr;
u16 pkey_index;
u8 timeout;
u8 valid;
u8 smac[ETH_ALEN];
};
struct cm_work {
struct delayed_work work;
struct list_head list;
struct cm_port *port;
struct ib_mad_recv_wc *mad_recv_wc; /* Received MADs */
__be32 local_id; /* Established / timewait */
__be32 remote_id;
struct ib_cm_event cm_event;
struct ib_sa_path_rec path[0];
};
struct cm_timewait_info {
struct cm_work work; /* Must be first. */
struct list_head list;
struct rb_node remote_qp_node;
struct rb_node remote_id_node;
__be64 remote_ca_guid;
__be32 remote_qpn;
u8 inserted_remote_qp;
u8 inserted_remote_id;
};
struct cm_id_private {
struct ib_cm_id id;
struct rb_node service_node;
struct rb_node sidr_id_node;
spinlock_t lock; /* Do not acquire inside cm.lock */
struct completion comp;
atomic_t refcount;
struct ib_mad_send_buf *msg;
struct cm_timewait_info *timewait_info;
/* todo: use alternate port on send failure */
struct cm_av av;
struct cm_av alt_av;
struct ib_cm_compare_data *compare_data;
void *private_data;
__be64 tid;
__be32 local_qpn;
__be32 remote_qpn;
enum ib_qp_type qp_type;
__be32 sq_psn;
__be32 rq_psn;
int timeout_ms;
enum ib_mtu path_mtu;
__be16 pkey;
u8 private_data_len;
u8 max_cm_retries;
u8 peer_to_peer;
u8 responder_resources;
u8 initiator_depth;
u8 retry_count;
u8 rnr_retry_count;
u8 service_timeout;
u8 target_ack_delay;
struct list_head work_list;
atomic_t work_count;
};
static void cm_work_handler(struct work_struct *work);
static inline void cm_deref_id(struct cm_id_private *cm_id_priv)
{
if (atomic_dec_and_test(&cm_id_priv->refcount))
complete(&cm_id_priv->comp);
}
static int cm_alloc_msg(struct cm_id_private *cm_id_priv,
struct ib_mad_send_buf **msg)
{
struct ib_mad_agent *mad_agent;
struct ib_mad_send_buf *m;
struct ib_ah *ah;
mad_agent = cm_id_priv->av.port->mad_agent;
ah = ib_create_ah(mad_agent->qp->pd, &cm_id_priv->av.ah_attr);
if (IS_ERR(ah))
return PTR_ERR(ah);
m = ib_create_send_mad(mad_agent, cm_id_priv->id.remote_cm_qpn,
cm_id_priv->av.pkey_index,
0, IB_MGMT_MAD_HDR, IB_MGMT_MAD_DATA,
GFP_ATOMIC);
if (IS_ERR(m)) {
ib_destroy_ah(ah);
return PTR_ERR(m);
}
/* Timeout set by caller if response is expected. */
m->ah = ah;
m->retries = cm_id_priv->max_cm_retries;
atomic_inc(&cm_id_priv->refcount);
m->context[0] = cm_id_priv;
*msg = m;
return 0;
}
static int cm_alloc_response_msg(struct cm_port *port,
struct ib_mad_recv_wc *mad_recv_wc,
struct ib_mad_send_buf **msg)
{
struct ib_mad_send_buf *m;
struct ib_ah *ah;
ah = ib_create_ah_from_wc(port->mad_agent->qp->pd, mad_recv_wc->wc,
mad_recv_wc->recv_buf.grh, port->port_num);
if (IS_ERR(ah))
return PTR_ERR(ah);
m = ib_create_send_mad(port->mad_agent, 1, mad_recv_wc->wc->pkey_index,
0, IB_MGMT_MAD_HDR, IB_MGMT_MAD_DATA,
GFP_ATOMIC);
if (IS_ERR(m)) {
ib_destroy_ah(ah);
return PTR_ERR(m);
}
m->ah = ah;
*msg = m;
return 0;
}
static void cm_free_msg(struct ib_mad_send_buf *msg)
{
ib_destroy_ah(msg->ah);
if (msg->context[0])
cm_deref_id(msg->context[0]);
ib_free_send_mad(msg);
}
static void * cm_copy_private_data(const void *private_data,
u8 private_data_len)
{
void *data;
if (!private_data || !private_data_len)
return NULL;
data = kmemdup(private_data, private_data_len, GFP_KERNEL);
if (!data)
return ERR_PTR(-ENOMEM);
return data;
}
static void cm_set_private_data(struct cm_id_private *cm_id_priv,
void *private_data, u8 private_data_len)
{
if (cm_id_priv->private_data && cm_id_priv->private_data_len)
kfree(cm_id_priv->private_data);
cm_id_priv->private_data = private_data;
cm_id_priv->private_data_len = private_data_len;
}
static void cm_init_av_for_response(struct cm_port *port, struct ib_wc *wc,
struct ib_grh *grh, struct cm_av *av)
{
av->port = port;
av->pkey_index = wc->pkey_index;
ib_init_ah_from_wc(port->cm_dev->ib_device, port->port_num, wc,
grh, &av->ah_attr);
}
int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
{
struct cm_id_private *cm_id_priv;
cm_id_priv = container_of(id, struct cm_id_private, id);
if (smac != NULL)
memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac));
if (alt_smac != NULL)
memcpy(cm_id_priv->alt_av.smac, alt_smac,
sizeof(cm_id_priv->alt_av.smac));
return 0;
}
EXPORT_SYMBOL(ib_update_cm_av);
static int cm_init_av_by_path(struct ib_sa_path_rec *path, struct cm_av *av)
{
struct cm_device *cm_dev;
struct cm_port *port = NULL;
unsigned long flags;
int ret;
u8 p;
read_lock_irqsave(&cm.device_lock, flags);
list_for_each_entry(cm_dev, &cm.device_list, list) {
if (!ib_find_cached_gid(cm_dev->ib_device, &path->sgid,
&p, NULL)) {
port = cm_dev->port[p-1];
break;
}
}
read_unlock_irqrestore(&cm.device_lock, flags);
if (!port)
return -EINVAL;
ret = ib_find_cached_pkey(cm_dev->ib_device, port->port_num,
be16_to_cpu(path->pkey), &av->pkey_index);
if (ret)
return ret;
av->port = port;
ib_init_ah_from_path(cm_dev->ib_device, port->port_num, path,
&av->ah_attr);
av->timeout = path->packet_life_time + 1;
memcpy(av->smac, path->smac, sizeof(av->smac));
av->valid = 1;
return 0;
}
static int cm_alloc_id(struct cm_id_private *cm_id_priv)
{
unsigned long flags;
int id;
idr_preload(GFP_KERNEL);
spin_lock_irqsave(&cm.lock, flags);
id = idr_alloc_cyclic(&cm.local_id_table, cm_id_priv, 0, 0, GFP_NOWAIT);
spin_unlock_irqrestore(&cm.lock, flags);
idr_preload_end();
cm_id_priv->id.local_id = (__force __be32)id ^ cm.random_id_operand;
return id < 0 ? id : 0;
}
static void cm_free_id(__be32 local_id)
{
spin_lock_irq(&cm.lock);
idr_remove(&cm.local_id_table,
(__force int) (local_id ^ cm.random_id_operand));
spin_unlock_irq(&cm.lock);
}
static struct cm_id_private * cm_get_id(__be32 local_id, __be32 remote_id)
{
struct cm_id_private *cm_id_priv;
cm_id_priv = idr_find(&cm.local_id_table,
(__force int) (local_id ^ cm.random_id_operand));
if (cm_id_priv) {
if (cm_id_priv->id.remote_id == remote_id)
atomic_inc(&cm_id_priv->refcount);
else
cm_id_priv = NULL;
}
return cm_id_priv;
}
static struct cm_id_private * cm_acquire_id(__be32 local_id, __be32 remote_id)
{
struct cm_id_private *cm_id_priv;
spin_lock_irq(&cm.lock);
cm_id_priv = cm_get_id(local_id, remote_id);
spin_unlock_irq(&cm.lock);
return cm_id_priv;
}
static void cm_mask_copy(u8 *dst, u8 *src, u8 *mask)
{
int i;
for (i = 0; i < IB_CM_COMPARE_SIZE / sizeof(unsigned long); i++)
((unsigned long *) dst)[i] = ((unsigned long *) src)[i] &
((unsigned long *) mask)[i];
}
static int cm_compare_data(struct ib_cm_compare_data *src_data,
struct ib_cm_compare_data *dst_data)
{
u8 src[IB_CM_COMPARE_SIZE];
u8 dst[IB_CM_COMPARE_SIZE];
if (!src_data || !dst_data)
return 0;
cm_mask_copy(src, src_data->data, dst_data->mask);
cm_mask_copy(dst, dst_data->data, src_data->mask);
return memcmp(src, dst, IB_CM_COMPARE_SIZE);
}
static int cm_compare_private_data(u8 *private_data,
struct ib_cm_compare_data *dst_data)
{
u8 src[IB_CM_COMPARE_SIZE];
if (!dst_data)
return 0;
cm_mask_copy(src, private_data, dst_data->mask);
return memcmp(src, dst_data->data, IB_CM_COMPARE_SIZE);
}
/*
* Trivial helpers to strip endian annotation and compare; the
* endianness doesn't actually matter since we just need a stable
* order for the RB tree.
*/
static int be32_lt(__be32 a, __be32 b)
{
return (__force u32) a < (__force u32) b;
}
static int be32_gt(__be32 a, __be32 b)
{
return (__force u32) a > (__force u32) b;
}
static int be64_lt(__be64 a, __be64 b)
{
return (__force u64) a < (__force u64) b;
}
static int be64_gt(__be64 a, __be64 b)
{
return (__force u64) a > (__force u64) b;
}
static struct cm_id_private * cm_insert_listen(struct cm_id_private *cm_id_priv)
{
struct rb_node **link = &cm.listen_service_table.rb_node;
struct rb_node *parent = NULL;
struct cm_id_private *cur_cm_id_priv;
__be64 service_id = cm_id_priv->id.service_id;
__be64 service_mask = cm_id_priv->id.service_mask;
int data_cmp;
while (*link) {
parent = *link;
cur_cm_id_priv = rb_entry(parent, struct cm_id_private,
service_node);
data_cmp = cm_compare_data(cm_id_priv->compare_data,
cur_cm_id_priv->compare_data);
if ((cur_cm_id_priv->id.service_mask & service_id) ==
(service_mask & cur_cm_id_priv->id.service_id) &&
(cm_id_priv->id.device == cur_cm_id_priv->id.device) &&
!data_cmp)
return cur_cm_id_priv;
if (cm_id_priv->id.device < cur_cm_id_priv->id.device)
link = &(*link)->rb_left;
else if (cm_id_priv->id.device > cur_cm_id_priv->id.device)
link = &(*link)->rb_right;
else if (be64_lt(service_id, cur_cm_id_priv->id.service_id))
link = &(*link)->rb_left;
else if (be64_gt(service_id, cur_cm_id_priv->id.service_id))
link = &(*link)->rb_right;
else if (data_cmp < 0)
link = &(*link)->rb_left;
else
link = &(*link)->rb_right;
}
rb_link_node(&cm_id_priv->service_node, parent, link);
rb_insert_color(&cm_id_priv->service_node, &cm.listen_service_table);
return NULL;
}
static struct cm_id_private * cm_find_listen(struct ib_device *device,
__be64 service_id,
u8 *private_data)
{
struct rb_node *node = cm.listen_service_table.rb_node;
struct cm_id_private *cm_id_priv;
int data_cmp;
while (node) {
cm_id_priv = rb_entry(node, struct cm_id_private, service_node);
data_cmp = cm_compare_private_data(private_data,
cm_id_priv->compare_data);
if ((cm_id_priv->id.service_mask & service_id) ==
cm_id_priv->id.service_id &&
(cm_id_priv->id.device == device) && !data_cmp)
return cm_id_priv;
if (device < cm_id_priv->id.device)
node = node->rb_left;
else if (device > cm_id_priv->id.device)
node = node->rb_right;
else if (be64_lt(service_id, cm_id_priv->id.service_id))
node = node->rb_left;
else if (be64_gt(service_id, cm_id_priv->id.service_id))
node = node->rb_right;
else if (data_cmp < 0)
node = node->rb_left;
else
node = node->rb_right;
}
return NULL;
}
static struct cm_timewait_info * cm_insert_remote_id(struct cm_timewait_info
*timewait_info)
{
struct rb_node **link = &cm.remote_id_table.rb_node;
struct rb_node *parent = NULL;
struct cm_timewait_info *cur_timewait_info;
__be64 remote_ca_guid = timewait_info->remote_ca_guid;
__be32 remote_id = timewait_info->work.remote_id;
while (*link) {
parent = *link;
cur_timewait_info = rb_entry(parent, struct cm_timewait_info,
remote_id_node);
if (be32_lt(remote_id, cur_timewait_info->work.remote_id))
link = &(*link)->rb_left;
else if (be32_gt(remote_id, cur_timewait_info->work.remote_id))
link = &(*link)->rb_right;
else if (be64_lt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
link = &(*link)->rb_left;
else if (be64_gt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
link = &(*link)->rb_right;
else
return cur_timewait_info;
}
timewait_info->inserted_remote_id = 1;
rb_link_node(&timewait_info->remote_id_node, parent, link);
rb_insert_color(&timewait_info->remote_id_node, &cm.remote_id_table);
return NULL;
}
static struct cm_timewait_info * cm_find_remote_id(__be64 remote_ca_guid,
__be32 remote_id)
{
struct rb_node *node = cm.remote_id_table.rb_node;
struct cm_timewait_info *timewait_info;
while (node) {
timewait_info = rb_entry(node, struct cm_timewait_info,
remote_id_node);
if (be32_lt(remote_id, timewait_info->work.remote_id))
node = node->rb_left;
else if (be32_gt(remote_id, timewait_info->work.remote_id))
node = node->rb_right;
else if (be64_lt(remote_ca_guid, timewait_info->remote_ca_guid))
node = node->rb_left;
else if (be64_gt(remote_ca_guid, timewait_info->remote_ca_guid))
node = node->rb_right;
else
return timewait_info;
}
return NULL;
}
static struct cm_timewait_info * cm_insert_remote_qpn(struct cm_timewait_info
*timewait_info)
{
struct rb_node **link = &cm.remote_qp_table.rb_node;
struct rb_node *parent = NULL;
struct cm_timewait_info *cur_timewait_info;
__be64 remote_ca_guid = timewait_info->remote_ca_guid;
__be32 remote_qpn = timewait_info->remote_qpn;
while (*link) {
parent = *link;
cur_timewait_info = rb_entry(parent, struct cm_timewait_info,
remote_qp_node);
if (be32_lt(remote_qpn, cur_timewait_info->remote_qpn))
link = &(*link)->rb_left;
else if (be32_gt(remote_qpn, cur_timewait_info->remote_qpn))
link = &(*link)->rb_right;
else if (be64_lt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
link = &(*link)->rb_left;
else if (be64_gt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
link = &(*link)->rb_right;
else
return cur_timewait_info;
}
timewait_info->inserted_remote_qp = 1;
rb_link_node(&timewait_info->remote_qp_node, parent, link);
rb_insert_color(&timewait_info->remote_qp_node, &cm.remote_qp_table);
return NULL;
}
static struct cm_id_private * cm_insert_remote_sidr(struct cm_id_private
*cm_id_priv)
{
struct rb_node **link = &cm.remote_sidr_table.rb_node;
struct rb_node *parent = NULL;
struct cm_id_private *cur_cm_id_priv;
union ib_gid *port_gid = &cm_id_priv->av.dgid;
__be32 remote_id = cm_id_priv->id.remote_id;
while (*link) {
parent = *link;
cur_cm_id_priv = rb_entry(parent, struct cm_id_private,
sidr_id_node);
if (be32_lt(remote_id, cur_cm_id_priv->id.remote_id))
link = &(*link)->rb_left;
else if (be32_gt(remote_id, cur_cm_id_priv->id.remote_id))
link = &(*link)->rb_right;
else {
int cmp;
cmp = memcmp(port_gid, &cur_cm_id_priv->av.dgid,
sizeof *port_gid);
if (cmp < 0)
link = &(*link)->rb_left;
else if (cmp > 0)
link = &(*link)->rb_right;
else
return cur_cm_id_priv;
}
}
rb_link_node(&cm_id_priv->sidr_id_node, parent, link);
rb_insert_color(&cm_id_priv->sidr_id_node, &cm.remote_sidr_table);
return NULL;
}
static void cm_reject_sidr_req(struct cm_id_private *cm_id_priv,
enum ib_cm_sidr_status status)
{
struct ib_cm_sidr_rep_param param;
memset(¶m, 0, sizeof param);
param.status = status;
ib_send_cm_sidr_rep(&cm_id_priv->id, ¶m);
}
struct ib_cm_id *ib_create_cm_id(struct ib_device *device,
ib_cm_handler cm_handler,
void *context)
{
struct cm_id_private *cm_id_priv;
int ret;
cm_id_priv = kzalloc(sizeof *cm_id_priv, GFP_KERNEL);
if (!cm_id_priv)
return ERR_PTR(-ENOMEM);
cm_id_priv->id.state = IB_CM_IDLE;
cm_id_priv->id.device = device;
cm_id_priv->id.cm_handler = cm_handler;
cm_id_priv->id.context = context;
cm_id_priv->id.remote_cm_qpn = 1;
ret = cm_alloc_id(cm_id_priv);
if (ret)
goto error;
spin_lock_init(&cm_id_priv->lock);
init_completion(&cm_id_priv->comp);
INIT_LIST_HEAD(&cm_id_priv->work_list);
atomic_set(&cm_id_priv->work_count, -1);
atomic_set(&cm_id_priv->refcount, 1);
return &cm_id_priv->id;
error:
kfree(cm_id_priv);
return ERR_PTR(-ENOMEM);
}
EXPORT_SYMBOL(ib_create_cm_id);
static struct cm_work * cm_dequeue_work(struct cm_id_private *cm_id_priv)
{
struct cm_work *work;
if (list_empty(&cm_id_priv->work_list))
return NULL;
work = list_entry(cm_id_priv->work_list.next, struct cm_work, list);
list_del(&work->list);
return work;
}
static void cm_free_work(struct cm_work *work)
{
if (work->mad_recv_wc)
ib_free_recv_mad(work->mad_recv_wc);
kfree(work);
}
static inline int cm_convert_to_ms(int iba_time)
{
/* approximate conversion to ms from 4.096us x 2^iba_time */
return 1 << max(iba_time - 8, 0);
}
/*
* calculate: 4.096x2^ack_timeout = 4.096x2^ack_delay + 2x4.096x2^life_time
* Because of how ack_timeout is stored, adding one doubles the timeout.
* To avoid large timeouts, select the max(ack_delay, life_time + 1), and
* increment it (round up) only if the other is within 50%.
*/
static u8 cm_ack_timeout(u8 ca_ack_delay, u8 packet_life_time)
{
int ack_timeout = packet_life_time + 1;
if (ack_timeout >= ca_ack_delay)
ack_timeout += (ca_ack_delay >= (ack_timeout - 1));
else
ack_timeout = ca_ack_delay +
(ack_timeout >= (ca_ack_delay - 1));
return min(31, ack_timeout);
}
static void cm_cleanup_timewait(struct cm_timewait_info *timewait_info)
{
if (timewait_info->inserted_remote_id) {
rb_erase(&timewait_info->remote_id_node, &cm.remote_id_table);
timewait_info->inserted_remote_id = 0;
}
if (timewait_info->inserted_remote_qp) {
rb_erase(&timewait_info->remote_qp_node, &cm.remote_qp_table);
timewait_info->inserted_remote_qp = 0;
}
}
static struct cm_timewait_info * cm_create_timewait_info(__be32 local_id)
{
struct cm_timewait_info *timewait_info;
timewait_info = kzalloc(sizeof *timewait_info, GFP_KERNEL);
if (!timewait_info)
return ERR_PTR(-ENOMEM);
timewait_info->work.local_id = local_id;
INIT_DELAYED_WORK(&timewait_info->work.work, cm_work_handler);
timewait_info->work.cm_event.event = IB_CM_TIMEWAIT_EXIT;
return timewait_info;
}
static void cm_enter_timewait(struct cm_id_private *cm_id_priv)
{
int wait_time;
unsigned long flags;
spin_lock_irqsave(&cm.lock, flags);
cm_cleanup_timewait(cm_id_priv->timewait_info);
list_add_tail(&cm_id_priv->timewait_info->list, &cm.timewait_list);
spin_unlock_irqrestore(&cm.lock, flags);
/*
* The cm_id could be destroyed by the user before we exit timewait.
* To protect against this, we search for the cm_id after exiting
* timewait before notifying the user that we've exited timewait.
*/
cm_id_priv->id.state = IB_CM_TIMEWAIT;
wait_time = cm_convert_to_ms(cm_id_priv->av.timeout);
queue_delayed_work(cm.wq, &cm_id_priv->timewait_info->work.work,
msecs_to_jiffies(wait_time));
cm_id_priv->timewait_info = NULL;
}
static void cm_reset_to_idle(struct cm_id_private *cm_id_priv)
{
unsigned long flags;
cm_id_priv->id.state = IB_CM_IDLE;
if (cm_id_priv->timewait_info) {
spin_lock_irqsave(&cm.lock, flags);
cm_cleanup_timewait(cm_id_priv->timewait_info);
spin_unlock_irqrestore(&cm.lock, flags);
kfree(cm_id_priv->timewait_info);
cm_id_priv->timewait_info = NULL;
}
}
static void cm_destroy_id(struct ib_cm_id *cm_id, int err)
{
struct cm_id_private *cm_id_priv;
struct cm_work *work;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
retest:
spin_lock_irq(&cm_id_priv->lock);
switch (cm_id->state) {
case IB_CM_LISTEN:
cm_id->state = IB_CM_IDLE;
spin_unlock_irq(&cm_id_priv->lock);
spin_lock_irq(&cm.lock);
rb_erase(&cm_id_priv->service_node, &cm.listen_service_table);
spin_unlock_irq(&cm.lock);
break;
case IB_CM_SIDR_REQ_SENT:
cm_id->state = IB_CM_IDLE;
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
spin_unlock_irq(&cm_id_priv->lock);
break;
case IB_CM_SIDR_REQ_RCVD:
spin_unlock_irq(&cm_id_priv->lock);
cm_reject_sidr_req(cm_id_priv, IB_SIDR_REJECT);
break;
case IB_CM_REQ_SENT:
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
spin_unlock_irq(&cm_id_priv->lock);
ib_send_cm_rej(cm_id, IB_CM_REJ_TIMEOUT,
&cm_id_priv->id.device->node_guid,
sizeof cm_id_priv->id.device->node_guid,
NULL, 0);
break;
case IB_CM_REQ_RCVD:
if (err == -ENOMEM) {
/* Do not reject to allow future retries. */
cm_reset_to_idle(cm_id_priv);
spin_unlock_irq(&cm_id_priv->lock);
} else {
spin_unlock_irq(&cm_id_priv->lock);
ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED,
NULL, 0, NULL, 0);
}
break;
case IB_CM_MRA_REQ_RCVD:
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
/* Fall through */
case IB_CM_MRA_REQ_SENT:
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
spin_unlock_irq(&cm_id_priv->lock);
ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED,
NULL, 0, NULL, 0);
break;
case IB_CM_ESTABLISHED:
spin_unlock_irq(&cm_id_priv->lock);
if (cm_id_priv->qp_type == IB_QPT_XRC_TGT)
break;
ib_send_cm_dreq(cm_id, NULL, 0);
goto retest;
case IB_CM_DREQ_SENT:
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
cm_enter_timewait(cm_id_priv);
spin_unlock_irq(&cm_id_priv->lock);
break;
case IB_CM_DREQ_RCVD:
spin_unlock_irq(&cm_id_priv->lock);
ib_send_cm_drep(cm_id, NULL, 0);
break;
default:
spin_unlock_irq(&cm_id_priv->lock);
break;
}
cm_free_id(cm_id->local_id);
cm_deref_id(cm_id_priv);
wait_for_completion(&cm_id_priv->comp);
while ((work = cm_dequeue_work(cm_id_priv)) != NULL)
cm_free_work(work);
kfree(cm_id_priv->compare_data);
kfree(cm_id_priv->private_data);
kfree(cm_id_priv);
}
void ib_destroy_cm_id(struct ib_cm_id *cm_id)
{
cm_destroy_id(cm_id, 0);
}
EXPORT_SYMBOL(ib_destroy_cm_id);
int ib_cm_listen(struct ib_cm_id *cm_id, __be64 service_id, __be64 service_mask,
struct ib_cm_compare_data *compare_data)
{
struct cm_id_private *cm_id_priv, *cur_cm_id_priv;
unsigned long flags;
int ret = 0;
service_mask = service_mask ? service_mask : ~cpu_to_be64(0);
service_id &= service_mask;
if ((service_id & IB_SERVICE_ID_AGN_MASK) == IB_CM_ASSIGN_SERVICE_ID &&
(service_id != IB_CM_ASSIGN_SERVICE_ID))
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
if (cm_id->state != IB_CM_IDLE)
return -EINVAL;
if (compare_data) {
cm_id_priv->compare_data = kzalloc(sizeof *compare_data,
GFP_KERNEL);
if (!cm_id_priv->compare_data)
return -ENOMEM;
cm_mask_copy(cm_id_priv->compare_data->data,
compare_data->data, compare_data->mask);
memcpy(cm_id_priv->compare_data->mask, compare_data->mask,
IB_CM_COMPARE_SIZE);
}
cm_id->state = IB_CM_LISTEN;
spin_lock_irqsave(&cm.lock, flags);
if (service_id == IB_CM_ASSIGN_SERVICE_ID) {
cm_id->service_id = cpu_to_be64(cm.listen_service_id++);
cm_id->service_mask = ~cpu_to_be64(0);
} else {
cm_id->service_id = service_id;
cm_id->service_mask = service_mask;
}
cur_cm_id_priv = cm_insert_listen(cm_id_priv);
spin_unlock_irqrestore(&cm.lock, flags);
if (cur_cm_id_priv) {
cm_id->state = IB_CM_IDLE;
kfree(cm_id_priv->compare_data);
cm_id_priv->compare_data = NULL;
ret = -EBUSY;
}
return ret;
}
EXPORT_SYMBOL(ib_cm_listen);
static __be64 cm_form_tid(struct cm_id_private *cm_id_priv,
enum cm_msg_sequence msg_seq)
{
u64 hi_tid, low_tid;
hi_tid = ((u64) cm_id_priv->av.port->mad_agent->hi_tid) << 32;
low_tid = (u64) ((__force u32)cm_id_priv->id.local_id |
(msg_seq << 30));
return cpu_to_be64(hi_tid | low_tid);
}
static void cm_format_mad_hdr(struct ib_mad_hdr *hdr,
__be16 attr_id, __be64 tid)
{
hdr->base_version = IB_MGMT_BASE_VERSION;
hdr->mgmt_class = IB_MGMT_CLASS_CM;
hdr->class_version = IB_CM_CLASS_VERSION;
hdr->method = IB_MGMT_METHOD_SEND;
hdr->attr_id = attr_id;
hdr->tid = tid;
}
static void cm_format_req(struct cm_req_msg *req_msg,
struct cm_id_private *cm_id_priv,
struct ib_cm_req_param *param)
{
struct ib_sa_path_rec *pri_path = param->primary_path;
struct ib_sa_path_rec *alt_path = param->alternate_path;
cm_format_mad_hdr(&req_msg->hdr, CM_REQ_ATTR_ID,
cm_form_tid(cm_id_priv, CM_MSG_SEQUENCE_REQ));
req_msg->local_comm_id = cm_id_priv->id.local_id;
req_msg->service_id = param->service_id;
req_msg->local_ca_guid = cm_id_priv->id.device->node_guid;
cm_req_set_local_qpn(req_msg, cpu_to_be32(param->qp_num));
cm_req_set_init_depth(req_msg, param->initiator_depth);
cm_req_set_remote_resp_timeout(req_msg,
param->remote_cm_response_timeout);
cm_req_set_qp_type(req_msg, param->qp_type);
cm_req_set_flow_ctrl(req_msg, param->flow_control);
cm_req_set_starting_psn(req_msg, cpu_to_be32(param->starting_psn));
cm_req_set_local_resp_timeout(req_msg,
param->local_cm_response_timeout);
req_msg->pkey = param->primary_path->pkey;
cm_req_set_path_mtu(req_msg, param->primary_path->mtu);
cm_req_set_max_cm_retries(req_msg, param->max_cm_retries);
if (param->qp_type != IB_QPT_XRC_INI) {
cm_req_set_resp_res(req_msg, param->responder_resources);
cm_req_set_retry_count(req_msg, param->retry_count);
cm_req_set_rnr_retry_count(req_msg, param->rnr_retry_count);
cm_req_set_srq(req_msg, param->srq);
}
if (pri_path->hop_limit <= 1) {
req_msg->primary_local_lid = pri_path->slid;
req_msg->primary_remote_lid = pri_path->dlid;
} else {
/* Work-around until there's a way to obtain remote LID info */
req_msg->primary_local_lid = IB_LID_PERMISSIVE;
req_msg->primary_remote_lid = IB_LID_PERMISSIVE;
}
req_msg->primary_local_gid = pri_path->sgid;
req_msg->primary_remote_gid = pri_path->dgid;
cm_req_set_primary_flow_label(req_msg, pri_path->flow_label);
cm_req_set_primary_packet_rate(req_msg, pri_path->rate);
req_msg->primary_traffic_class = pri_path->traffic_class;
req_msg->primary_hop_limit = pri_path->hop_limit;
cm_req_set_primary_sl(req_msg, pri_path->sl);
cm_req_set_primary_subnet_local(req_msg, (pri_path->hop_limit <= 1));
cm_req_set_primary_local_ack_timeout(req_msg,
cm_ack_timeout(cm_id_priv->av.port->cm_dev->ack_delay,
pri_path->packet_life_time));
if (alt_path) {
if (alt_path->hop_limit <= 1) {
req_msg->alt_local_lid = alt_path->slid;
req_msg->alt_remote_lid = alt_path->dlid;
} else {
req_msg->alt_local_lid = IB_LID_PERMISSIVE;
req_msg->alt_remote_lid = IB_LID_PERMISSIVE;
}
req_msg->alt_local_gid = alt_path->sgid;
req_msg->alt_remote_gid = alt_path->dgid;
cm_req_set_alt_flow_label(req_msg,
alt_path->flow_label);
cm_req_set_alt_packet_rate(req_msg, alt_path->rate);
req_msg->alt_traffic_class = alt_path->traffic_class;
req_msg->alt_hop_limit = alt_path->hop_limit;
cm_req_set_alt_sl(req_msg, alt_path->sl);
cm_req_set_alt_subnet_local(req_msg, (alt_path->hop_limit <= 1));
cm_req_set_alt_local_ack_timeout(req_msg,
cm_ack_timeout(cm_id_priv->av.port->cm_dev->ack_delay,
alt_path->packet_life_time));
}
if (param->private_data && param->private_data_len)
memcpy(req_msg->private_data, param->private_data,
param->private_data_len);
}
static int cm_validate_req_param(struct ib_cm_req_param *param)
{
/* peer-to-peer not supported */
if (param->peer_to_peer)
return -EINVAL;
if (!param->primary_path)
return -EINVAL;
if (param->qp_type != IB_QPT_RC && param->qp_type != IB_QPT_UC &&
param->qp_type != IB_QPT_XRC_INI)
return -EINVAL;
if (param->private_data &&
param->private_data_len > IB_CM_REQ_PRIVATE_DATA_SIZE)
return -EINVAL;
if (param->alternate_path &&
(param->alternate_path->pkey != param->primary_path->pkey ||
param->alternate_path->mtu != param->primary_path->mtu))
return -EINVAL;
return 0;
}
int ib_send_cm_req(struct ib_cm_id *cm_id,
struct ib_cm_req_param *param)
{
struct cm_id_private *cm_id_priv;
struct cm_req_msg *req_msg;
unsigned long flags;
int ret;
ret = cm_validate_req_param(param);
if (ret)
return ret;
/* Verify that we're not in timewait. */
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_IDLE) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
ret = -EINVAL;
goto out;
}
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_id_priv->timewait_info = cm_create_timewait_info(cm_id_priv->
id.local_id);
if (IS_ERR(cm_id_priv->timewait_info)) {
ret = PTR_ERR(cm_id_priv->timewait_info);
goto out;
}
ret = cm_init_av_by_path(param->primary_path, &cm_id_priv->av);
if (ret)
goto error1;
if (param->alternate_path) {
ret = cm_init_av_by_path(param->alternate_path,
&cm_id_priv->alt_av);
if (ret)
goto error1;
}
cm_id->service_id = param->service_id;
cm_id->service_mask = ~cpu_to_be64(0);
cm_id_priv->timeout_ms = cm_convert_to_ms(
param->primary_path->packet_life_time) * 2 +
cm_convert_to_ms(
param->remote_cm_response_timeout);
cm_id_priv->max_cm_retries = param->max_cm_retries;
cm_id_priv->initiator_depth = param->initiator_depth;
cm_id_priv->responder_resources = param->responder_resources;
cm_id_priv->retry_count = param->retry_count;
cm_id_priv->path_mtu = param->primary_path->mtu;
cm_id_priv->pkey = param->primary_path->pkey;
cm_id_priv->qp_type = param->qp_type;
ret = cm_alloc_msg(cm_id_priv, &cm_id_priv->msg);
if (ret)
goto error1;
req_msg = (struct cm_req_msg *) cm_id_priv->msg->mad;
cm_format_req(req_msg, cm_id_priv, param);
cm_id_priv->tid = req_msg->hdr.tid;
cm_id_priv->msg->timeout_ms = cm_id_priv->timeout_ms;
cm_id_priv->msg->context[1] = (void *) (unsigned long) IB_CM_REQ_SENT;
cm_id_priv->local_qpn = cm_req_get_local_qpn(req_msg);
cm_id_priv->rq_psn = cm_req_get_starting_psn(req_msg);
spin_lock_irqsave(&cm_id_priv->lock, flags);
ret = ib_post_send_mad(cm_id_priv->msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
goto error2;
}
BUG_ON(cm_id->state != IB_CM_IDLE);
cm_id->state = IB_CM_REQ_SENT;
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return 0;
error2: cm_free_msg(cm_id_priv->msg);
error1: kfree(cm_id_priv->timewait_info);
out: return ret;
}
EXPORT_SYMBOL(ib_send_cm_req);
static int cm_issue_rej(struct cm_port *port,
struct ib_mad_recv_wc *mad_recv_wc,
enum ib_cm_rej_reason reason,
enum cm_msg_response msg_rejected,
void *ari, u8 ari_length)
{
struct ib_mad_send_buf *msg = NULL;
struct cm_rej_msg *rej_msg, *rcv_msg;
int ret;
ret = cm_alloc_response_msg(port, mad_recv_wc, &msg);
if (ret)
return ret;
/* We just need common CM header information. Cast to any message. */
rcv_msg = (struct cm_rej_msg *) mad_recv_wc->recv_buf.mad;
rej_msg = (struct cm_rej_msg *) msg->mad;
cm_format_mad_hdr(&rej_msg->hdr, CM_REJ_ATTR_ID, rcv_msg->hdr.tid);
rej_msg->remote_comm_id = rcv_msg->local_comm_id;
rej_msg->local_comm_id = rcv_msg->remote_comm_id;
cm_rej_set_msg_rejected(rej_msg, msg_rejected);
rej_msg->reason = cpu_to_be16(reason);
if (ari && ari_length) {
cm_rej_set_reject_info_len(rej_msg, ari_length);
memcpy(rej_msg->ari, ari, ari_length);
}
ret = ib_post_send_mad(msg, NULL);
if (ret)
cm_free_msg(msg);
return ret;
}
static inline int cm_is_active_peer(__be64 local_ca_guid, __be64 remote_ca_guid,
__be32 local_qpn, __be32 remote_qpn)
{
return (be64_to_cpu(local_ca_guid) > be64_to_cpu(remote_ca_guid) ||
((local_ca_guid == remote_ca_guid) &&
(be32_to_cpu(local_qpn) > be32_to_cpu(remote_qpn))));
}
static void cm_format_paths_from_req(struct cm_req_msg *req_msg,
struct ib_sa_path_rec *primary_path,
struct ib_sa_path_rec *alt_path)
{
memset(primary_path, 0, sizeof *primary_path);
primary_path->dgid = req_msg->primary_local_gid;
primary_path->sgid = req_msg->primary_remote_gid;
primary_path->dlid = req_msg->primary_local_lid;
primary_path->slid = req_msg->primary_remote_lid;
primary_path->flow_label = cm_req_get_primary_flow_label(req_msg);
primary_path->hop_limit = req_msg->primary_hop_limit;
primary_path->traffic_class = req_msg->primary_traffic_class;
primary_path->reversible = 1;
primary_path->pkey = req_msg->pkey;
primary_path->sl = cm_req_get_primary_sl(req_msg);
primary_path->mtu_selector = IB_SA_EQ;
primary_path->mtu = cm_req_get_path_mtu(req_msg);
primary_path->rate_selector = IB_SA_EQ;
primary_path->rate = cm_req_get_primary_packet_rate(req_msg);
primary_path->packet_life_time_selector = IB_SA_EQ;
primary_path->packet_life_time =
cm_req_get_primary_local_ack_timeout(req_msg);
primary_path->packet_life_time -= (primary_path->packet_life_time > 0);
if (req_msg->alt_local_lid) {
memset(alt_path, 0, sizeof *alt_path);
alt_path->dgid = req_msg->alt_local_gid;
alt_path->sgid = req_msg->alt_remote_gid;
alt_path->dlid = req_msg->alt_local_lid;
alt_path->slid = req_msg->alt_remote_lid;
alt_path->flow_label = cm_req_get_alt_flow_label(req_msg);
alt_path->hop_limit = req_msg->alt_hop_limit;
alt_path->traffic_class = req_msg->alt_traffic_class;
alt_path->reversible = 1;
alt_path->pkey = req_msg->pkey;
alt_path->sl = cm_req_get_alt_sl(req_msg);
alt_path->mtu_selector = IB_SA_EQ;
alt_path->mtu = cm_req_get_path_mtu(req_msg);
alt_path->rate_selector = IB_SA_EQ;
alt_path->rate = cm_req_get_alt_packet_rate(req_msg);
alt_path->packet_life_time_selector = IB_SA_EQ;
alt_path->packet_life_time =
cm_req_get_alt_local_ack_timeout(req_msg);
alt_path->packet_life_time -= (alt_path->packet_life_time > 0);
}
}
static void cm_format_req_event(struct cm_work *work,
struct cm_id_private *cm_id_priv,
struct ib_cm_id *listen_id)
{
struct cm_req_msg *req_msg;
struct ib_cm_req_event_param *param;
req_msg = (struct cm_req_msg *)work->mad_recv_wc->recv_buf.mad;
param = &work->cm_event.param.req_rcvd;
param->listen_id = listen_id;
param->port = cm_id_priv->av.port->port_num;
param->primary_path = &work->path[0];
if (req_msg->alt_local_lid)
param->alternate_path = &work->path[1];
else
param->alternate_path = NULL;
param->remote_ca_guid = req_msg->local_ca_guid;
param->remote_qkey = be32_to_cpu(req_msg->local_qkey);
param->remote_qpn = be32_to_cpu(cm_req_get_local_qpn(req_msg));
param->qp_type = cm_req_get_qp_type(req_msg);
param->starting_psn = be32_to_cpu(cm_req_get_starting_psn(req_msg));
param->responder_resources = cm_req_get_init_depth(req_msg);
param->initiator_depth = cm_req_get_resp_res(req_msg);
param->local_cm_response_timeout =
cm_req_get_remote_resp_timeout(req_msg);
param->flow_control = cm_req_get_flow_ctrl(req_msg);
param->remote_cm_response_timeout =
cm_req_get_local_resp_timeout(req_msg);
param->retry_count = cm_req_get_retry_count(req_msg);
param->rnr_retry_count = cm_req_get_rnr_retry_count(req_msg);
param->srq = cm_req_get_srq(req_msg);
work->cm_event.private_data = &req_msg->private_data;
}
static void cm_process_work(struct cm_id_private *cm_id_priv,
struct cm_work *work)
{
int ret;
/* We will typically only have the current event to report. */
ret = cm_id_priv->id.cm_handler(&cm_id_priv->id, &work->cm_event);
cm_free_work(work);
while (!ret && !atomic_add_negative(-1, &cm_id_priv->work_count)) {
spin_lock_irq(&cm_id_priv->lock);
work = cm_dequeue_work(cm_id_priv);
spin_unlock_irq(&cm_id_priv->lock);
BUG_ON(!work);
ret = cm_id_priv->id.cm_handler(&cm_id_priv->id,
&work->cm_event);
cm_free_work(work);
}
cm_deref_id(cm_id_priv);
if (ret)
cm_destroy_id(&cm_id_priv->id, ret);
}
static void cm_format_mra(struct cm_mra_msg *mra_msg,
struct cm_id_private *cm_id_priv,
enum cm_msg_response msg_mraed, u8 service_timeout,
const void *private_data, u8 private_data_len)
{
cm_format_mad_hdr(&mra_msg->hdr, CM_MRA_ATTR_ID, cm_id_priv->tid);
cm_mra_set_msg_mraed(mra_msg, msg_mraed);
mra_msg->local_comm_id = cm_id_priv->id.local_id;
mra_msg->remote_comm_id = cm_id_priv->id.remote_id;
cm_mra_set_service_timeout(mra_msg, service_timeout);
if (private_data && private_data_len)
memcpy(mra_msg->private_data, private_data, private_data_len);
}
static void cm_format_rej(struct cm_rej_msg *rej_msg,
struct cm_id_private *cm_id_priv,
enum ib_cm_rej_reason reason,
void *ari,
u8 ari_length,
const void *private_data,
u8 private_data_len)
{
cm_format_mad_hdr(&rej_msg->hdr, CM_REJ_ATTR_ID, cm_id_priv->tid);
rej_msg->remote_comm_id = cm_id_priv->id.remote_id;
switch(cm_id_priv->id.state) {
case IB_CM_REQ_RCVD:
rej_msg->local_comm_id = 0;
cm_rej_set_msg_rejected(rej_msg, CM_MSG_RESPONSE_REQ);
break;
case IB_CM_MRA_REQ_SENT:
rej_msg->local_comm_id = cm_id_priv->id.local_id;
cm_rej_set_msg_rejected(rej_msg, CM_MSG_RESPONSE_REQ);
break;
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
rej_msg->local_comm_id = cm_id_priv->id.local_id;
cm_rej_set_msg_rejected(rej_msg, CM_MSG_RESPONSE_REP);
break;
default:
rej_msg->local_comm_id = cm_id_priv->id.local_id;
cm_rej_set_msg_rejected(rej_msg, CM_MSG_RESPONSE_OTHER);
break;
}
rej_msg->reason = cpu_to_be16(reason);
if (ari && ari_length) {
cm_rej_set_reject_info_len(rej_msg, ari_length);
memcpy(rej_msg->ari, ari, ari_length);
}
if (private_data && private_data_len)
memcpy(rej_msg->private_data, private_data, private_data_len);
}
static void cm_dup_req_handler(struct cm_work *work,
struct cm_id_private *cm_id_priv)
{
struct ib_mad_send_buf *msg = NULL;
int ret;
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_REQ_COUNTER]);
/* Quick state check to discard duplicate REQs. */
if (cm_id_priv->id.state == IB_CM_REQ_RCVD)
return;
ret = cm_alloc_response_msg(work->port, work->mad_recv_wc, &msg);
if (ret)
return;
spin_lock_irq(&cm_id_priv->lock);
switch (cm_id_priv->id.state) {
case IB_CM_MRA_REQ_SENT:
cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
CM_MSG_RESPONSE_REQ, cm_id_priv->service_timeout,
cm_id_priv->private_data,
cm_id_priv->private_data_len);
break;
case IB_CM_TIMEWAIT:
cm_format_rej((struct cm_rej_msg *) msg->mad, cm_id_priv,
IB_CM_REJ_STALE_CONN, NULL, 0, NULL, 0);
break;
default:
goto unlock;
}
spin_unlock_irq(&cm_id_priv->lock);
ret = ib_post_send_mad(msg, NULL);
if (ret)
goto free;
return;
unlock: spin_unlock_irq(&cm_id_priv->lock);
free: cm_free_msg(msg);
}
static struct cm_id_private * cm_match_req(struct cm_work *work,
struct cm_id_private *cm_id_priv)
{
struct cm_id_private *listen_cm_id_priv, *cur_cm_id_priv;
struct cm_timewait_info *timewait_info;
struct cm_req_msg *req_msg;
req_msg = (struct cm_req_msg *)work->mad_recv_wc->recv_buf.mad;
/* Check for possible duplicate REQ. */
spin_lock_irq(&cm.lock);
timewait_info = cm_insert_remote_id(cm_id_priv->timewait_info);
if (timewait_info) {
cur_cm_id_priv = cm_get_id(timewait_info->work.local_id,
timewait_info->work.remote_id);
spin_unlock_irq(&cm.lock);
if (cur_cm_id_priv) {
cm_dup_req_handler(work, cur_cm_id_priv);
cm_deref_id(cur_cm_id_priv);
}
return NULL;
}
/* Check for stale connections. */
timewait_info = cm_insert_remote_qpn(cm_id_priv->timewait_info);
if (timewait_info) {
cm_cleanup_timewait(cm_id_priv->timewait_info);
spin_unlock_irq(&cm.lock);
cm_issue_rej(work->port, work->mad_recv_wc,
IB_CM_REJ_STALE_CONN, CM_MSG_RESPONSE_REQ,
NULL, 0);
return NULL;
}
/* Find matching listen request. */
listen_cm_id_priv = cm_find_listen(cm_id_priv->id.device,
req_msg->service_id,
req_msg->private_data);
if (!listen_cm_id_priv) {
cm_cleanup_timewait(cm_id_priv->timewait_info);
spin_unlock_irq(&cm.lock);
cm_issue_rej(work->port, work->mad_recv_wc,
IB_CM_REJ_INVALID_SERVICE_ID, CM_MSG_RESPONSE_REQ,
NULL, 0);
goto out;
}
atomic_inc(&listen_cm_id_priv->refcount);
atomic_inc(&cm_id_priv->refcount);
cm_id_priv->id.state = IB_CM_REQ_RCVD;
atomic_inc(&cm_id_priv->work_count);
spin_unlock_irq(&cm.lock);
out:
return listen_cm_id_priv;
}
/*
* Work-around for inter-subnet connections. If the LIDs are permissive,
* we need to override the LID/SL data in the REQ with the LID information
* in the work completion.
*/
static void cm_process_routed_req(struct cm_req_msg *req_msg, struct ib_wc *wc)
{
if (!cm_req_get_primary_subnet_local(req_msg)) {
if (req_msg->primary_local_lid == IB_LID_PERMISSIVE) {
req_msg->primary_local_lid = cpu_to_be16(wc->slid);
cm_req_set_primary_sl(req_msg, wc->sl);
}
if (req_msg->primary_remote_lid == IB_LID_PERMISSIVE)
req_msg->primary_remote_lid = cpu_to_be16(wc->dlid_path_bits);
}
if (!cm_req_get_alt_subnet_local(req_msg)) {
if (req_msg->alt_local_lid == IB_LID_PERMISSIVE) {
req_msg->alt_local_lid = cpu_to_be16(wc->slid);
cm_req_set_alt_sl(req_msg, wc->sl);
}
if (req_msg->alt_remote_lid == IB_LID_PERMISSIVE)
req_msg->alt_remote_lid = cpu_to_be16(wc->dlid_path_bits);
}
}
static int cm_req_handler(struct cm_work *work)
{
struct ib_cm_id *cm_id;
struct cm_id_private *cm_id_priv, *listen_cm_id_priv;
struct cm_req_msg *req_msg;
int ret;
req_msg = (struct cm_req_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id = ib_create_cm_id(work->port->cm_dev->ib_device, NULL, NULL);
if (IS_ERR(cm_id))
return PTR_ERR(cm_id);
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
cm_id_priv->id.remote_id = req_msg->local_comm_id;
cm_init_av_for_response(work->port, work->mad_recv_wc->wc,
work->mad_recv_wc->recv_buf.grh,
&cm_id_priv->av);
cm_id_priv->timewait_info = cm_create_timewait_info(cm_id_priv->
id.local_id);
if (IS_ERR(cm_id_priv->timewait_info)) {
ret = PTR_ERR(cm_id_priv->timewait_info);
goto destroy;
}
cm_id_priv->timewait_info->work.remote_id = req_msg->local_comm_id;
cm_id_priv->timewait_info->remote_ca_guid = req_msg->local_ca_guid;
cm_id_priv->timewait_info->remote_qpn = cm_req_get_local_qpn(req_msg);
listen_cm_id_priv = cm_match_req(work, cm_id_priv);
if (!listen_cm_id_priv) {
ret = -EINVAL;
kfree(cm_id_priv->timewait_info);
goto destroy;
}
cm_id_priv->id.cm_handler = listen_cm_id_priv->id.cm_handler;
cm_id_priv->id.context = listen_cm_id_priv->id.context;
cm_id_priv->id.service_id = req_msg->service_id;
cm_id_priv->id.service_mask = ~cpu_to_be64(0);
cm_process_routed_req(req_msg, work->mad_recv_wc->wc);
cm_format_paths_from_req(req_msg, &work->path[0], &work->path[1]);
memcpy(work->path[0].dmac, cm_id_priv->av.ah_attr.dmac, ETH_ALEN);
work->path[0].vlan_id = cm_id_priv->av.ah_attr.vlan_id;
ret = cm_init_av_by_path(&work->path[0], &cm_id_priv->av);
if (ret) {
ib_get_cached_gid(work->port->cm_dev->ib_device,
work->port->port_num, 0, &work->path[0].sgid);
ib_send_cm_rej(cm_id, IB_CM_REJ_INVALID_GID,
&work->path[0].sgid, sizeof work->path[0].sgid,
NULL, 0);
goto rejected;
}
if (req_msg->alt_local_lid) {
ret = cm_init_av_by_path(&work->path[1], &cm_id_priv->alt_av);
if (ret) {
ib_send_cm_rej(cm_id, IB_CM_REJ_INVALID_ALT_GID,
&work->path[0].sgid,
sizeof work->path[0].sgid, NULL, 0);
goto rejected;
}
}
cm_id_priv->tid = req_msg->hdr.tid;
cm_id_priv->timeout_ms = cm_convert_to_ms(
cm_req_get_local_resp_timeout(req_msg));
cm_id_priv->max_cm_retries = cm_req_get_max_cm_retries(req_msg);
cm_id_priv->remote_qpn = cm_req_get_local_qpn(req_msg);
cm_id_priv->initiator_depth = cm_req_get_resp_res(req_msg);
cm_id_priv->responder_resources = cm_req_get_init_depth(req_msg);
cm_id_priv->path_mtu = cm_req_get_path_mtu(req_msg);
cm_id_priv->pkey = req_msg->pkey;
cm_id_priv->sq_psn = cm_req_get_starting_psn(req_msg);
cm_id_priv->retry_count = cm_req_get_retry_count(req_msg);
cm_id_priv->rnr_retry_count = cm_req_get_rnr_retry_count(req_msg);
cm_id_priv->qp_type = cm_req_get_qp_type(req_msg);
cm_format_req_event(work, cm_id_priv, &listen_cm_id_priv->id);
cm_process_work(cm_id_priv, work);
cm_deref_id(listen_cm_id_priv);
return 0;
rejected:
atomic_dec(&cm_id_priv->refcount);
cm_deref_id(listen_cm_id_priv);
destroy:
ib_destroy_cm_id(cm_id);
return ret;
}
static void cm_format_rep(struct cm_rep_msg *rep_msg,
struct cm_id_private *cm_id_priv,
struct ib_cm_rep_param *param)
{
cm_format_mad_hdr(&rep_msg->hdr, CM_REP_ATTR_ID, cm_id_priv->tid);
rep_msg->local_comm_id = cm_id_priv->id.local_id;
rep_msg->remote_comm_id = cm_id_priv->id.remote_id;
cm_rep_set_starting_psn(rep_msg, cpu_to_be32(param->starting_psn));
rep_msg->resp_resources = param->responder_resources;
cm_rep_set_target_ack_delay(rep_msg,
cm_id_priv->av.port->cm_dev->ack_delay);
cm_rep_set_failover(rep_msg, param->failover_accepted);
cm_rep_set_rnr_retry_count(rep_msg, param->rnr_retry_count);
rep_msg->local_ca_guid = cm_id_priv->id.device->node_guid;
if (cm_id_priv->qp_type != IB_QPT_XRC_TGT) {
rep_msg->initiator_depth = param->initiator_depth;
cm_rep_set_flow_ctrl(rep_msg, param->flow_control);
cm_rep_set_srq(rep_msg, param->srq);
cm_rep_set_local_qpn(rep_msg, cpu_to_be32(param->qp_num));
} else {
cm_rep_set_srq(rep_msg, 1);
cm_rep_set_local_eecn(rep_msg, cpu_to_be32(param->qp_num));
}
if (param->private_data && param->private_data_len)
memcpy(rep_msg->private_data, param->private_data,
param->private_data_len);
}
int ib_send_cm_rep(struct ib_cm_id *cm_id,
struct ib_cm_rep_param *param)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
struct cm_rep_msg *rep_msg;
unsigned long flags;
int ret;
if (param->private_data &&
param->private_data_len > IB_CM_REP_PRIVATE_DATA_SIZE)
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_REQ_RCVD &&
cm_id->state != IB_CM_MRA_REQ_SENT) {
ret = -EINVAL;
goto out;
}
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto out;
rep_msg = (struct cm_rep_msg *) msg->mad;
cm_format_rep(rep_msg, cm_id_priv, param);
msg->timeout_ms = cm_id_priv->timeout_ms;
msg->context[1] = (void *) (unsigned long) IB_CM_REP_SENT;
ret = ib_post_send_mad(msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
return ret;
}
cm_id->state = IB_CM_REP_SENT;
cm_id_priv->msg = msg;
cm_id_priv->initiator_depth = param->initiator_depth;
cm_id_priv->responder_resources = param->responder_resources;
cm_id_priv->rq_psn = cm_rep_get_starting_psn(rep_msg);
cm_id_priv->local_qpn = cpu_to_be32(param->qp_num & 0xFFFFFF);
out: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_rep);
static void cm_format_rtu(struct cm_rtu_msg *rtu_msg,
struct cm_id_private *cm_id_priv,
const void *private_data,
u8 private_data_len)
{
cm_format_mad_hdr(&rtu_msg->hdr, CM_RTU_ATTR_ID, cm_id_priv->tid);
rtu_msg->local_comm_id = cm_id_priv->id.local_id;
rtu_msg->remote_comm_id = cm_id_priv->id.remote_id;
if (private_data && private_data_len)
memcpy(rtu_msg->private_data, private_data, private_data_len);
}
int ib_send_cm_rtu(struct ib_cm_id *cm_id,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
void *data;
int ret;
if (private_data && private_data_len > IB_CM_RTU_PRIVATE_DATA_SIZE)
return -EINVAL;
data = cm_copy_private_data(private_data, private_data_len);
if (IS_ERR(data))
return PTR_ERR(data);
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_REP_RCVD &&
cm_id->state != IB_CM_MRA_REP_SENT) {
ret = -EINVAL;
goto error;
}
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto error;
cm_format_rtu((struct cm_rtu_msg *) msg->mad, cm_id_priv,
private_data, private_data_len);
ret = ib_post_send_mad(msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
kfree(data);
return ret;
}
cm_id->state = IB_CM_ESTABLISHED;
cm_set_private_data(cm_id_priv, data, private_data_len);
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return 0;
error: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
kfree(data);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_rtu);
static void cm_format_rep_event(struct cm_work *work, enum ib_qp_type qp_type)
{
struct cm_rep_msg *rep_msg;
struct ib_cm_rep_event_param *param;
rep_msg = (struct cm_rep_msg *)work->mad_recv_wc->recv_buf.mad;
param = &work->cm_event.param.rep_rcvd;
param->remote_ca_guid = rep_msg->local_ca_guid;
param->remote_qkey = be32_to_cpu(rep_msg->local_qkey);
param->remote_qpn = be32_to_cpu(cm_rep_get_qpn(rep_msg, qp_type));
param->starting_psn = be32_to_cpu(cm_rep_get_starting_psn(rep_msg));
param->responder_resources = rep_msg->initiator_depth;
param->initiator_depth = rep_msg->resp_resources;
param->target_ack_delay = cm_rep_get_target_ack_delay(rep_msg);
param->failover_accepted = cm_rep_get_failover(rep_msg);
param->flow_control = cm_rep_get_flow_ctrl(rep_msg);
param->rnr_retry_count = cm_rep_get_rnr_retry_count(rep_msg);
param->srq = cm_rep_get_srq(rep_msg);
work->cm_event.private_data = &rep_msg->private_data;
}
static void cm_dup_rep_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_rep_msg *rep_msg;
struct ib_mad_send_buf *msg = NULL;
int ret;
rep_msg = (struct cm_rep_msg *) work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(rep_msg->remote_comm_id,
rep_msg->local_comm_id);
if (!cm_id_priv)
return;
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_REP_COUNTER]);
ret = cm_alloc_response_msg(work->port, work->mad_recv_wc, &msg);
if (ret)
goto deref;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state == IB_CM_ESTABLISHED)
cm_format_rtu((struct cm_rtu_msg *) msg->mad, cm_id_priv,
cm_id_priv->private_data,
cm_id_priv->private_data_len);
else if (cm_id_priv->id.state == IB_CM_MRA_REP_SENT)
cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
CM_MSG_RESPONSE_REP, cm_id_priv->service_timeout,
cm_id_priv->private_data,
cm_id_priv->private_data_len);
else
goto unlock;
spin_unlock_irq(&cm_id_priv->lock);
ret = ib_post_send_mad(msg, NULL);
if (ret)
goto free;
goto deref;
unlock: spin_unlock_irq(&cm_id_priv->lock);
free: cm_free_msg(msg);
deref: cm_deref_id(cm_id_priv);
}
static int cm_rep_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_rep_msg *rep_msg;
int ret;
rep_msg = (struct cm_rep_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(rep_msg->remote_comm_id, 0);
if (!cm_id_priv) {
cm_dup_rep_handler(work);
return -EINVAL;
}
cm_format_rep_event(work, cm_id_priv->qp_type);
spin_lock_irq(&cm_id_priv->lock);
switch (cm_id_priv->id.state) {
case IB_CM_REQ_SENT:
case IB_CM_MRA_REQ_RCVD:
break;
default:
spin_unlock_irq(&cm_id_priv->lock);
ret = -EINVAL;
goto error;
}
cm_id_priv->timewait_info->work.remote_id = rep_msg->local_comm_id;
cm_id_priv->timewait_info->remote_ca_guid = rep_msg->local_ca_guid;
cm_id_priv->timewait_info->remote_qpn = cm_rep_get_qpn(rep_msg, cm_id_priv->qp_type);
spin_lock(&cm.lock);
/* Check for duplicate REP. */
if (cm_insert_remote_id(cm_id_priv->timewait_info)) {
spin_unlock(&cm.lock);
spin_unlock_irq(&cm_id_priv->lock);
ret = -EINVAL;
goto error;
}
/* Check for a stale connection. */
if (cm_insert_remote_qpn(cm_id_priv->timewait_info)) {
rb_erase(&cm_id_priv->timewait_info->remote_id_node,
&cm.remote_id_table);
cm_id_priv->timewait_info->inserted_remote_id = 0;
spin_unlock(&cm.lock);
spin_unlock_irq(&cm_id_priv->lock);
cm_issue_rej(work->port, work->mad_recv_wc,
IB_CM_REJ_STALE_CONN, CM_MSG_RESPONSE_REP,
NULL, 0);
ret = -EINVAL;
goto error;
}
spin_unlock(&cm.lock);
cm_id_priv->id.state = IB_CM_REP_RCVD;
cm_id_priv->id.remote_id = rep_msg->local_comm_id;
cm_id_priv->remote_qpn = cm_rep_get_qpn(rep_msg, cm_id_priv->qp_type);
cm_id_priv->initiator_depth = rep_msg->resp_resources;
cm_id_priv->responder_resources = rep_msg->initiator_depth;
cm_id_priv->sq_psn = cm_rep_get_starting_psn(rep_msg);
cm_id_priv->rnr_retry_count = cm_rep_get_rnr_retry_count(rep_msg);
cm_id_priv->target_ack_delay = cm_rep_get_target_ack_delay(rep_msg);
cm_id_priv->av.timeout =
cm_ack_timeout(cm_id_priv->target_ack_delay,
cm_id_priv->av.timeout - 1);
cm_id_priv->alt_av.timeout =
cm_ack_timeout(cm_id_priv->target_ack_delay,
cm_id_priv->alt_av.timeout - 1);
/* todo: handle peer_to_peer */
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
error:
cm_deref_id(cm_id_priv);
return ret;
}
static int cm_establish_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
int ret;
/* See comment in cm_establish about lookup. */
cm_id_priv = cm_acquire_id(work->local_id, work->remote_id);
if (!cm_id_priv)
return -EINVAL;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_ESTABLISHED) {
spin_unlock_irq(&cm_id_priv->lock);
goto out;
}
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
static int cm_rtu_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_rtu_msg *rtu_msg;
int ret;
rtu_msg = (struct cm_rtu_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(rtu_msg->remote_comm_id,
rtu_msg->local_comm_id);
if (!cm_id_priv)
return -EINVAL;
work->cm_event.private_data = &rtu_msg->private_data;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_REP_SENT &&
cm_id_priv->id.state != IB_CM_MRA_REP_RCVD) {
spin_unlock_irq(&cm_id_priv->lock);
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_RTU_COUNTER]);
goto out;
}
cm_id_priv->id.state = IB_CM_ESTABLISHED;
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
static void cm_format_dreq(struct cm_dreq_msg *dreq_msg,
struct cm_id_private *cm_id_priv,
const void *private_data,
u8 private_data_len)
{
cm_format_mad_hdr(&dreq_msg->hdr, CM_DREQ_ATTR_ID,
cm_form_tid(cm_id_priv, CM_MSG_SEQUENCE_DREQ));
dreq_msg->local_comm_id = cm_id_priv->id.local_id;
dreq_msg->remote_comm_id = cm_id_priv->id.remote_id;
cm_dreq_set_remote_qpn(dreq_msg, cm_id_priv->remote_qpn);
if (private_data && private_data_len)
memcpy(dreq_msg->private_data, private_data, private_data_len);
}
int ib_send_cm_dreq(struct ib_cm_id *cm_id,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
int ret;
if (private_data && private_data_len > IB_CM_DREQ_PRIVATE_DATA_SIZE)
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_ESTABLISHED) {
ret = -EINVAL;
goto out;
}
if (cm_id->lap_state == IB_CM_LAP_SENT ||
cm_id->lap_state == IB_CM_MRA_LAP_RCVD)
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret) {
cm_enter_timewait(cm_id_priv);
goto out;
}
cm_format_dreq((struct cm_dreq_msg *) msg->mad, cm_id_priv,
private_data, private_data_len);
msg->timeout_ms = cm_id_priv->timeout_ms;
msg->context[1] = (void *) (unsigned long) IB_CM_DREQ_SENT;
ret = ib_post_send_mad(msg, NULL);
if (ret) {
cm_enter_timewait(cm_id_priv);
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
return ret;
}
cm_id->state = IB_CM_DREQ_SENT;
cm_id_priv->msg = msg;
out: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_dreq);
static void cm_format_drep(struct cm_drep_msg *drep_msg,
struct cm_id_private *cm_id_priv,
const void *private_data,
u8 private_data_len)
{
cm_format_mad_hdr(&drep_msg->hdr, CM_DREP_ATTR_ID, cm_id_priv->tid);
drep_msg->local_comm_id = cm_id_priv->id.local_id;
drep_msg->remote_comm_id = cm_id_priv->id.remote_id;
if (private_data && private_data_len)
memcpy(drep_msg->private_data, private_data, private_data_len);
}
int ib_send_cm_drep(struct ib_cm_id *cm_id,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
void *data;
int ret;
if (private_data && private_data_len > IB_CM_DREP_PRIVATE_DATA_SIZE)
return -EINVAL;
data = cm_copy_private_data(private_data, private_data_len);
if (IS_ERR(data))
return PTR_ERR(data);
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_DREQ_RCVD) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
kfree(data);
return -EINVAL;
}
cm_set_private_data(cm_id_priv, data, private_data_len);
cm_enter_timewait(cm_id_priv);
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto out;
cm_format_drep((struct cm_drep_msg *) msg->mad, cm_id_priv,
private_data, private_data_len);
ret = ib_post_send_mad(msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
return ret;
}
out: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_drep);
static int cm_issue_drep(struct cm_port *port,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_mad_send_buf *msg = NULL;
struct cm_dreq_msg *dreq_msg;
struct cm_drep_msg *drep_msg;
int ret;
ret = cm_alloc_response_msg(port, mad_recv_wc, &msg);
if (ret)
return ret;
dreq_msg = (struct cm_dreq_msg *) mad_recv_wc->recv_buf.mad;
drep_msg = (struct cm_drep_msg *) msg->mad;
cm_format_mad_hdr(&drep_msg->hdr, CM_DREP_ATTR_ID, dreq_msg->hdr.tid);
drep_msg->remote_comm_id = dreq_msg->local_comm_id;
drep_msg->local_comm_id = dreq_msg->remote_comm_id;
ret = ib_post_send_mad(msg, NULL);
if (ret)
cm_free_msg(msg);
return ret;
}
static int cm_dreq_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_dreq_msg *dreq_msg;
struct ib_mad_send_buf *msg = NULL;
int ret;
dreq_msg = (struct cm_dreq_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(dreq_msg->remote_comm_id,
dreq_msg->local_comm_id);
if (!cm_id_priv) {
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_DREQ_COUNTER]);
cm_issue_drep(work->port, work->mad_recv_wc);
return -EINVAL;
}
work->cm_event.private_data = &dreq_msg->private_data;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->local_qpn != cm_dreq_get_remote_qpn(dreq_msg))
goto unlock;
switch (cm_id_priv->id.state) {
case IB_CM_REP_SENT:
case IB_CM_DREQ_SENT:
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
break;
case IB_CM_ESTABLISHED:
if (cm_id_priv->id.lap_state == IB_CM_LAP_SENT ||
cm_id_priv->id.lap_state == IB_CM_MRA_LAP_RCVD)
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
break;
case IB_CM_MRA_REP_RCVD:
break;
case IB_CM_TIMEWAIT:
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_DREQ_COUNTER]);
if (cm_alloc_response_msg(work->port, work->mad_recv_wc, &msg))
goto unlock;
cm_format_drep((struct cm_drep_msg *) msg->mad, cm_id_priv,
cm_id_priv->private_data,
cm_id_priv->private_data_len);
spin_unlock_irq(&cm_id_priv->lock);
if (ib_post_send_mad(msg, NULL))
cm_free_msg(msg);
goto deref;
case IB_CM_DREQ_RCVD:
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_DREQ_COUNTER]);
goto unlock;
default:
goto unlock;
}
cm_id_priv->id.state = IB_CM_DREQ_RCVD;
cm_id_priv->tid = dreq_msg->hdr.tid;
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
unlock: spin_unlock_irq(&cm_id_priv->lock);
deref: cm_deref_id(cm_id_priv);
return -EINVAL;
}
static int cm_drep_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_drep_msg *drep_msg;
int ret;
drep_msg = (struct cm_drep_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(drep_msg->remote_comm_id,
drep_msg->local_comm_id);
if (!cm_id_priv)
return -EINVAL;
work->cm_event.private_data = &drep_msg->private_data;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_DREQ_SENT &&
cm_id_priv->id.state != IB_CM_DREQ_RCVD) {
spin_unlock_irq(&cm_id_priv->lock);
goto out;
}
cm_enter_timewait(cm_id_priv);
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
int ib_send_cm_rej(struct ib_cm_id *cm_id,
enum ib_cm_rej_reason reason,
void *ari,
u8 ari_length,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
int ret;
if ((private_data && private_data_len > IB_CM_REJ_PRIVATE_DATA_SIZE) ||
(ari && ari_length > IB_CM_REJ_ARI_LENGTH))
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
switch (cm_id->state) {
case IB_CM_REQ_SENT:
case IB_CM_MRA_REQ_RCVD:
case IB_CM_REQ_RCVD:
case IB_CM_MRA_REQ_SENT:
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
ret = cm_alloc_msg(cm_id_priv, &msg);
if (!ret)
cm_format_rej((struct cm_rej_msg *) msg->mad,
cm_id_priv, reason, ari, ari_length,
private_data, private_data_len);
cm_reset_to_idle(cm_id_priv);
break;
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
ret = cm_alloc_msg(cm_id_priv, &msg);
if (!ret)
cm_format_rej((struct cm_rej_msg *) msg->mad,
cm_id_priv, reason, ari, ari_length,
private_data, private_data_len);
cm_enter_timewait(cm_id_priv);
break;
default:
ret = -EINVAL;
goto out;
}
if (ret)
goto out;
ret = ib_post_send_mad(msg, NULL);
if (ret)
cm_free_msg(msg);
out: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_rej);
static void cm_format_rej_event(struct cm_work *work)
{
struct cm_rej_msg *rej_msg;
struct ib_cm_rej_event_param *param;
rej_msg = (struct cm_rej_msg *)work->mad_recv_wc->recv_buf.mad;
param = &work->cm_event.param.rej_rcvd;
param->ari = rej_msg->ari;
param->ari_length = cm_rej_get_reject_info_len(rej_msg);
param->reason = __be16_to_cpu(rej_msg->reason);
work->cm_event.private_data = &rej_msg->private_data;
}
static struct cm_id_private * cm_acquire_rejected_id(struct cm_rej_msg *rej_msg)
{
struct cm_timewait_info *timewait_info;
struct cm_id_private *cm_id_priv;
__be32 remote_id;
remote_id = rej_msg->local_comm_id;
if (__be16_to_cpu(rej_msg->reason) == IB_CM_REJ_TIMEOUT) {
spin_lock_irq(&cm.lock);
timewait_info = cm_find_remote_id( *((__be64 *) rej_msg->ari),
remote_id);
if (!timewait_info) {
spin_unlock_irq(&cm.lock);
return NULL;
}
cm_id_priv = idr_find(&cm.local_id_table, (__force int)
(timewait_info->work.local_id ^
cm.random_id_operand));
if (cm_id_priv) {
if (cm_id_priv->id.remote_id == remote_id)
atomic_inc(&cm_id_priv->refcount);
else
cm_id_priv = NULL;
}
spin_unlock_irq(&cm.lock);
} else if (cm_rej_get_msg_rejected(rej_msg) == CM_MSG_RESPONSE_REQ)
cm_id_priv = cm_acquire_id(rej_msg->remote_comm_id, 0);
else
cm_id_priv = cm_acquire_id(rej_msg->remote_comm_id, remote_id);
return cm_id_priv;
}
static int cm_rej_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_rej_msg *rej_msg;
int ret;
rej_msg = (struct cm_rej_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_rejected_id(rej_msg);
if (!cm_id_priv)
return -EINVAL;
cm_format_rej_event(work);
spin_lock_irq(&cm_id_priv->lock);
switch (cm_id_priv->id.state) {
case IB_CM_REQ_SENT:
case IB_CM_MRA_REQ_RCVD:
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
/* fall through */
case IB_CM_REQ_RCVD:
case IB_CM_MRA_REQ_SENT:
if (__be16_to_cpu(rej_msg->reason) == IB_CM_REJ_STALE_CONN)
cm_enter_timewait(cm_id_priv);
else
cm_reset_to_idle(cm_id_priv);
break;
case IB_CM_DREQ_SENT:
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
/* fall through */
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
cm_enter_timewait(cm_id_priv);
break;
case IB_CM_ESTABLISHED:
if (cm_id_priv->id.lap_state == IB_CM_LAP_UNINIT ||
cm_id_priv->id.lap_state == IB_CM_LAP_SENT) {
if (cm_id_priv->id.lap_state == IB_CM_LAP_SENT)
ib_cancel_mad(cm_id_priv->av.port->mad_agent,
cm_id_priv->msg);
cm_enter_timewait(cm_id_priv);
break;
}
/* fall through */
default:
spin_unlock_irq(&cm_id_priv->lock);
ret = -EINVAL;
goto out;
}
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
int ib_send_cm_mra(struct ib_cm_id *cm_id,
u8 service_timeout,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
enum ib_cm_state cm_state;
enum ib_cm_lap_state lap_state;
enum cm_msg_response msg_response;
void *data;
unsigned long flags;
int ret;
if (private_data && private_data_len > IB_CM_MRA_PRIVATE_DATA_SIZE)
return -EINVAL;
data = cm_copy_private_data(private_data, private_data_len);
if (IS_ERR(data))
return PTR_ERR(data);
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
switch(cm_id_priv->id.state) {
case IB_CM_REQ_RCVD:
cm_state = IB_CM_MRA_REQ_SENT;
lap_state = cm_id->lap_state;
msg_response = CM_MSG_RESPONSE_REQ;
break;
case IB_CM_REP_RCVD:
cm_state = IB_CM_MRA_REP_SENT;
lap_state = cm_id->lap_state;
msg_response = CM_MSG_RESPONSE_REP;
break;
case IB_CM_ESTABLISHED:
if (cm_id->lap_state == IB_CM_LAP_RCVD) {
cm_state = cm_id->state;
lap_state = IB_CM_MRA_LAP_SENT;
msg_response = CM_MSG_RESPONSE_OTHER;
break;
}
default:
ret = -EINVAL;
goto error1;
}
if (!(service_timeout & IB_CM_MRA_FLAG_DELAY)) {
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto error1;
cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
msg_response, service_timeout,
private_data, private_data_len);
ret = ib_post_send_mad(msg, NULL);
if (ret)
goto error2;
}
cm_id->state = cm_state;
cm_id->lap_state = lap_state;
cm_id_priv->service_timeout = service_timeout;
cm_set_private_data(cm_id_priv, data, private_data_len);
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return 0;
error1: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
kfree(data);
return ret;
error2: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
kfree(data);
cm_free_msg(msg);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_mra);
static struct cm_id_private * cm_acquire_mraed_id(struct cm_mra_msg *mra_msg)
{
switch (cm_mra_get_msg_mraed(mra_msg)) {
case CM_MSG_RESPONSE_REQ:
return cm_acquire_id(mra_msg->remote_comm_id, 0);
case CM_MSG_RESPONSE_REP:
case CM_MSG_RESPONSE_OTHER:
return cm_acquire_id(mra_msg->remote_comm_id,
mra_msg->local_comm_id);
default:
return NULL;
}
}
static int cm_mra_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_mra_msg *mra_msg;
int timeout, ret;
mra_msg = (struct cm_mra_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_mraed_id(mra_msg);
if (!cm_id_priv)
return -EINVAL;
work->cm_event.private_data = &mra_msg->private_data;
work->cm_event.param.mra_rcvd.service_timeout =
cm_mra_get_service_timeout(mra_msg);
timeout = cm_convert_to_ms(cm_mra_get_service_timeout(mra_msg)) +
cm_convert_to_ms(cm_id_priv->av.timeout);
spin_lock_irq(&cm_id_priv->lock);
switch (cm_id_priv->id.state) {
case IB_CM_REQ_SENT:
if (cm_mra_get_msg_mraed(mra_msg) != CM_MSG_RESPONSE_REQ ||
ib_modify_mad(cm_id_priv->av.port->mad_agent,
cm_id_priv->msg, timeout))
goto out;
cm_id_priv->id.state = IB_CM_MRA_REQ_RCVD;
break;
case IB_CM_REP_SENT:
if (cm_mra_get_msg_mraed(mra_msg) != CM_MSG_RESPONSE_REP ||
ib_modify_mad(cm_id_priv->av.port->mad_agent,
cm_id_priv->msg, timeout))
goto out;
cm_id_priv->id.state = IB_CM_MRA_REP_RCVD;
break;
case IB_CM_ESTABLISHED:
if (cm_mra_get_msg_mraed(mra_msg) != CM_MSG_RESPONSE_OTHER ||
cm_id_priv->id.lap_state != IB_CM_LAP_SENT ||
ib_modify_mad(cm_id_priv->av.port->mad_agent,
cm_id_priv->msg, timeout)) {
if (cm_id_priv->id.lap_state == IB_CM_MRA_LAP_RCVD)
atomic_long_inc(&work->port->
counter_group[CM_RECV_DUPLICATES].
counter[CM_MRA_COUNTER]);
goto out;
}
cm_id_priv->id.lap_state = IB_CM_MRA_LAP_RCVD;
break;
case IB_CM_MRA_REQ_RCVD:
case IB_CM_MRA_REP_RCVD:
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_MRA_COUNTER]);
/* fall through */
default:
goto out;
}
cm_id_priv->msg->context[1] = (void *) (unsigned long)
cm_id_priv->id.state;
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
spin_unlock_irq(&cm_id_priv->lock);
cm_deref_id(cm_id_priv);
return -EINVAL;
}
static void cm_format_lap(struct cm_lap_msg *lap_msg,
struct cm_id_private *cm_id_priv,
struct ib_sa_path_rec *alternate_path,
const void *private_data,
u8 private_data_len)
{
cm_format_mad_hdr(&lap_msg->hdr, CM_LAP_ATTR_ID,
cm_form_tid(cm_id_priv, CM_MSG_SEQUENCE_LAP));
lap_msg->local_comm_id = cm_id_priv->id.local_id;
lap_msg->remote_comm_id = cm_id_priv->id.remote_id;
cm_lap_set_remote_qpn(lap_msg, cm_id_priv->remote_qpn);
/* todo: need remote CM response timeout */
cm_lap_set_remote_resp_timeout(lap_msg, 0x1F);
lap_msg->alt_local_lid = alternate_path->slid;
lap_msg->alt_remote_lid = alternate_path->dlid;
lap_msg->alt_local_gid = alternate_path->sgid;
lap_msg->alt_remote_gid = alternate_path->dgid;
cm_lap_set_flow_label(lap_msg, alternate_path->flow_label);
cm_lap_set_traffic_class(lap_msg, alternate_path->traffic_class);
lap_msg->alt_hop_limit = alternate_path->hop_limit;
cm_lap_set_packet_rate(lap_msg, alternate_path->rate);
cm_lap_set_sl(lap_msg, alternate_path->sl);
cm_lap_set_subnet_local(lap_msg, 1); /* local only... */
cm_lap_set_local_ack_timeout(lap_msg,
cm_ack_timeout(cm_id_priv->av.port->cm_dev->ack_delay,
alternate_path->packet_life_time));
if (private_data && private_data_len)
memcpy(lap_msg->private_data, private_data, private_data_len);
}
int ib_send_cm_lap(struct ib_cm_id *cm_id,
struct ib_sa_path_rec *alternate_path,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
int ret;
if (private_data && private_data_len > IB_CM_LAP_PRIVATE_DATA_SIZE)
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_ESTABLISHED ||
(cm_id->lap_state != IB_CM_LAP_UNINIT &&
cm_id->lap_state != IB_CM_LAP_IDLE)) {
ret = -EINVAL;
goto out;
}
ret = cm_init_av_by_path(alternate_path, &cm_id_priv->alt_av);
if (ret)
goto out;
cm_id_priv->alt_av.timeout =
cm_ack_timeout(cm_id_priv->target_ack_delay,
cm_id_priv->alt_av.timeout - 1);
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto out;
cm_format_lap((struct cm_lap_msg *) msg->mad, cm_id_priv,
alternate_path, private_data, private_data_len);
msg->timeout_ms = cm_id_priv->timeout_ms;
msg->context[1] = (void *) (unsigned long) IB_CM_ESTABLISHED;
ret = ib_post_send_mad(msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
return ret;
}
cm_id->lap_state = IB_CM_LAP_SENT;
cm_id_priv->msg = msg;
out: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_lap);
static void cm_format_path_from_lap(struct cm_id_private *cm_id_priv,
struct ib_sa_path_rec *path,
struct cm_lap_msg *lap_msg)
{
memset(path, 0, sizeof *path);
path->dgid = lap_msg->alt_local_gid;
path->sgid = lap_msg->alt_remote_gid;
path->dlid = lap_msg->alt_local_lid;
path->slid = lap_msg->alt_remote_lid;
path->flow_label = cm_lap_get_flow_label(lap_msg);
path->hop_limit = lap_msg->alt_hop_limit;
path->traffic_class = cm_lap_get_traffic_class(lap_msg);
path->reversible = 1;
path->pkey = cm_id_priv->pkey;
path->sl = cm_lap_get_sl(lap_msg);
path->mtu_selector = IB_SA_EQ;
path->mtu = cm_id_priv->path_mtu;
path->rate_selector = IB_SA_EQ;
path->rate = cm_lap_get_packet_rate(lap_msg);
path->packet_life_time_selector = IB_SA_EQ;
path->packet_life_time = cm_lap_get_local_ack_timeout(lap_msg);
path->packet_life_time -= (path->packet_life_time > 0);
}
static int cm_lap_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_lap_msg *lap_msg;
struct ib_cm_lap_event_param *param;
struct ib_mad_send_buf *msg = NULL;
int ret;
/* todo: verify LAP request and send reject APR if invalid. */
lap_msg = (struct cm_lap_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(lap_msg->remote_comm_id,
lap_msg->local_comm_id);
if (!cm_id_priv)
return -EINVAL;
param = &work->cm_event.param.lap_rcvd;
param->alternate_path = &work->path[0];
cm_format_path_from_lap(cm_id_priv, param->alternate_path, lap_msg);
work->cm_event.private_data = &lap_msg->private_data;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_ESTABLISHED)
goto unlock;
switch (cm_id_priv->id.lap_state) {
case IB_CM_LAP_UNINIT:
case IB_CM_LAP_IDLE:
break;
case IB_CM_MRA_LAP_SENT:
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_LAP_COUNTER]);
if (cm_alloc_response_msg(work->port, work->mad_recv_wc, &msg))
goto unlock;
cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
CM_MSG_RESPONSE_OTHER,
cm_id_priv->service_timeout,
cm_id_priv->private_data,
cm_id_priv->private_data_len);
spin_unlock_irq(&cm_id_priv->lock);
if (ib_post_send_mad(msg, NULL))
cm_free_msg(msg);
goto deref;
case IB_CM_LAP_RCVD:
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_LAP_COUNTER]);
goto unlock;
default:
goto unlock;
}
cm_id_priv->id.lap_state = IB_CM_LAP_RCVD;
cm_id_priv->tid = lap_msg->hdr.tid;
cm_init_av_for_response(work->port, work->mad_recv_wc->wc,
work->mad_recv_wc->recv_buf.grh,
&cm_id_priv->av);
cm_init_av_by_path(param->alternate_path, &cm_id_priv->alt_av);
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
unlock: spin_unlock_irq(&cm_id_priv->lock);
deref: cm_deref_id(cm_id_priv);
return -EINVAL;
}
static void cm_format_apr(struct cm_apr_msg *apr_msg,
struct cm_id_private *cm_id_priv,
enum ib_cm_apr_status status,
void *info,
u8 info_length,
const void *private_data,
u8 private_data_len)
{
cm_format_mad_hdr(&apr_msg->hdr, CM_APR_ATTR_ID, cm_id_priv->tid);
apr_msg->local_comm_id = cm_id_priv->id.local_id;
apr_msg->remote_comm_id = cm_id_priv->id.remote_id;
apr_msg->ap_status = (u8) status;
if (info && info_length) {
apr_msg->info_length = info_length;
memcpy(apr_msg->info, info, info_length);
}
if (private_data && private_data_len)
memcpy(apr_msg->private_data, private_data, private_data_len);
}
int ib_send_cm_apr(struct ib_cm_id *cm_id,
enum ib_cm_apr_status status,
void *info,
u8 info_length,
const void *private_data,
u8 private_data_len)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
int ret;
if ((private_data && private_data_len > IB_CM_APR_PRIVATE_DATA_SIZE) ||
(info && info_length > IB_CM_APR_INFO_LENGTH))
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_ESTABLISHED ||
(cm_id->lap_state != IB_CM_LAP_RCVD &&
cm_id->lap_state != IB_CM_MRA_LAP_SENT)) {
ret = -EINVAL;
goto out;
}
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto out;
cm_format_apr((struct cm_apr_msg *) msg->mad, cm_id_priv, status,
info, info_length, private_data, private_data_len);
ret = ib_post_send_mad(msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
return ret;
}
cm_id->lap_state = IB_CM_LAP_IDLE;
out: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_apr);
static int cm_apr_handler(struct cm_work *work)
{
struct cm_id_private *cm_id_priv;
struct cm_apr_msg *apr_msg;
int ret;
apr_msg = (struct cm_apr_msg *)work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(apr_msg->remote_comm_id,
apr_msg->local_comm_id);
if (!cm_id_priv)
return -EINVAL; /* Unmatched reply. */
work->cm_event.param.apr_rcvd.ap_status = apr_msg->ap_status;
work->cm_event.param.apr_rcvd.apr_info = &apr_msg->info;
work->cm_event.param.apr_rcvd.info_len = apr_msg->info_length;
work->cm_event.private_data = &apr_msg->private_data;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_ESTABLISHED ||
(cm_id_priv->id.lap_state != IB_CM_LAP_SENT &&
cm_id_priv->id.lap_state != IB_CM_MRA_LAP_RCVD)) {
spin_unlock_irq(&cm_id_priv->lock);
goto out;
}
cm_id_priv->id.lap_state = IB_CM_LAP_IDLE;
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
cm_id_priv->msg = NULL;
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
static int cm_timewait_handler(struct cm_work *work)
{
struct cm_timewait_info *timewait_info;
struct cm_id_private *cm_id_priv;
int ret;
timewait_info = (struct cm_timewait_info *)work;
spin_lock_irq(&cm.lock);
list_del(&timewait_info->list);
spin_unlock_irq(&cm.lock);
cm_id_priv = cm_acquire_id(timewait_info->work.local_id,
timewait_info->work.remote_id);
if (!cm_id_priv)
return -EINVAL;
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_TIMEWAIT ||
cm_id_priv->remote_qpn != timewait_info->remote_qpn) {
spin_unlock_irq(&cm_id_priv->lock);
goto out;
}
cm_id_priv->id.state = IB_CM_IDLE;
ret = atomic_inc_and_test(&cm_id_priv->work_count);
if (!ret)
list_add_tail(&work->list, &cm_id_priv->work_list);
spin_unlock_irq(&cm_id_priv->lock);
if (ret)
cm_process_work(cm_id_priv, work);
else
cm_deref_id(cm_id_priv);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
static void cm_format_sidr_req(struct cm_sidr_req_msg *sidr_req_msg,
struct cm_id_private *cm_id_priv,
struct ib_cm_sidr_req_param *param)
{
cm_format_mad_hdr(&sidr_req_msg->hdr, CM_SIDR_REQ_ATTR_ID,
cm_form_tid(cm_id_priv, CM_MSG_SEQUENCE_SIDR));
sidr_req_msg->request_id = cm_id_priv->id.local_id;
sidr_req_msg->pkey = param->path->pkey;
sidr_req_msg->service_id = param->service_id;
if (param->private_data && param->private_data_len)
memcpy(sidr_req_msg->private_data, param->private_data,
param->private_data_len);
}
int ib_send_cm_sidr_req(struct ib_cm_id *cm_id,
struct ib_cm_sidr_req_param *param)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
int ret;
if (!param->path || (param->private_data &&
param->private_data_len > IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE))
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
ret = cm_init_av_by_path(param->path, &cm_id_priv->av);
if (ret)
goto out;
cm_id->service_id = param->service_id;
cm_id->service_mask = ~cpu_to_be64(0);
cm_id_priv->timeout_ms = param->timeout_ms;
cm_id_priv->max_cm_retries = param->max_cm_retries;
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto out;
cm_format_sidr_req((struct cm_sidr_req_msg *) msg->mad, cm_id_priv,
param);
msg->timeout_ms = cm_id_priv->timeout_ms;
msg->context[1] = (void *) (unsigned long) IB_CM_SIDR_REQ_SENT;
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state == IB_CM_IDLE)
ret = ib_post_send_mad(msg, NULL);
else
ret = -EINVAL;
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
goto out;
}
cm_id->state = IB_CM_SIDR_REQ_SENT;
cm_id_priv->msg = msg;
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
out:
return ret;
}
EXPORT_SYMBOL(ib_send_cm_sidr_req);
static void cm_format_sidr_req_event(struct cm_work *work,
struct ib_cm_id *listen_id)
{
struct cm_sidr_req_msg *sidr_req_msg;
struct ib_cm_sidr_req_event_param *param;
sidr_req_msg = (struct cm_sidr_req_msg *)
work->mad_recv_wc->recv_buf.mad;
param = &work->cm_event.param.sidr_req_rcvd;
param->pkey = __be16_to_cpu(sidr_req_msg->pkey);
param->listen_id = listen_id;
param->port = work->port->port_num;
work->cm_event.private_data = &sidr_req_msg->private_data;
}
static int cm_sidr_req_handler(struct cm_work *work)
{
struct ib_cm_id *cm_id;
struct cm_id_private *cm_id_priv, *cur_cm_id_priv;
struct cm_sidr_req_msg *sidr_req_msg;
struct ib_wc *wc;
cm_id = ib_create_cm_id(work->port->cm_dev->ib_device, NULL, NULL);
if (IS_ERR(cm_id))
return PTR_ERR(cm_id);
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
/* Record SGID/SLID and request ID for lookup. */
sidr_req_msg = (struct cm_sidr_req_msg *)
work->mad_recv_wc->recv_buf.mad;
wc = work->mad_recv_wc->wc;
cm_id_priv->av.dgid.global.subnet_prefix = cpu_to_be64(wc->slid);
cm_id_priv->av.dgid.global.interface_id = 0;
cm_init_av_for_response(work->port, work->mad_recv_wc->wc,
work->mad_recv_wc->recv_buf.grh,
&cm_id_priv->av);
cm_id_priv->id.remote_id = sidr_req_msg->request_id;
cm_id_priv->tid = sidr_req_msg->hdr.tid;
atomic_inc(&cm_id_priv->work_count);
spin_lock_irq(&cm.lock);
cur_cm_id_priv = cm_insert_remote_sidr(cm_id_priv);
if (cur_cm_id_priv) {
spin_unlock_irq(&cm.lock);
atomic_long_inc(&work->port->counter_group[CM_RECV_DUPLICATES].
counter[CM_SIDR_REQ_COUNTER]);
goto out; /* Duplicate message. */
}
cm_id_priv->id.state = IB_CM_SIDR_REQ_RCVD;
cur_cm_id_priv = cm_find_listen(cm_id->device,
sidr_req_msg->service_id,
sidr_req_msg->private_data);
if (!cur_cm_id_priv) {
spin_unlock_irq(&cm.lock);
cm_reject_sidr_req(cm_id_priv, IB_SIDR_UNSUPPORTED);
goto out; /* No match. */
}
atomic_inc(&cur_cm_id_priv->refcount);
atomic_inc(&cm_id_priv->refcount);
spin_unlock_irq(&cm.lock);
cm_id_priv->id.cm_handler = cur_cm_id_priv->id.cm_handler;
cm_id_priv->id.context = cur_cm_id_priv->id.context;
cm_id_priv->id.service_id = sidr_req_msg->service_id;
cm_id_priv->id.service_mask = ~cpu_to_be64(0);
cm_format_sidr_req_event(work, &cur_cm_id_priv->id);
cm_process_work(cm_id_priv, work);
cm_deref_id(cur_cm_id_priv);
return 0;
out:
ib_destroy_cm_id(&cm_id_priv->id);
return -EINVAL;
}
static void cm_format_sidr_rep(struct cm_sidr_rep_msg *sidr_rep_msg,
struct cm_id_private *cm_id_priv,
struct ib_cm_sidr_rep_param *param)
{
cm_format_mad_hdr(&sidr_rep_msg->hdr, CM_SIDR_REP_ATTR_ID,
cm_id_priv->tid);
sidr_rep_msg->request_id = cm_id_priv->id.remote_id;
sidr_rep_msg->status = param->status;
cm_sidr_rep_set_qpn(sidr_rep_msg, cpu_to_be32(param->qp_num));
sidr_rep_msg->service_id = cm_id_priv->id.service_id;
sidr_rep_msg->qkey = cpu_to_be32(param->qkey);
if (param->info && param->info_length)
memcpy(sidr_rep_msg->info, param->info, param->info_length);
if (param->private_data && param->private_data_len)
memcpy(sidr_rep_msg->private_data, param->private_data,
param->private_data_len);
}
int ib_send_cm_sidr_rep(struct ib_cm_id *cm_id,
struct ib_cm_sidr_rep_param *param)
{
struct cm_id_private *cm_id_priv;
struct ib_mad_send_buf *msg;
unsigned long flags;
int ret;
if ((param->info && param->info_length > IB_CM_SIDR_REP_INFO_LENGTH) ||
(param->private_data &&
param->private_data_len > IB_CM_SIDR_REP_PRIVATE_DATA_SIZE))
return -EINVAL;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state != IB_CM_SIDR_REQ_RCVD) {
ret = -EINVAL;
goto error;
}
ret = cm_alloc_msg(cm_id_priv, &msg);
if (ret)
goto error;
cm_format_sidr_rep((struct cm_sidr_rep_msg *) msg->mad, cm_id_priv,
param);
ret = ib_post_send_mad(msg, NULL);
if (ret) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
cm_free_msg(msg);
return ret;
}
cm_id->state = IB_CM_IDLE;
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
spin_lock_irqsave(&cm.lock, flags);
rb_erase(&cm_id_priv->sidr_id_node, &cm.remote_sidr_table);
spin_unlock_irqrestore(&cm.lock, flags);
return 0;
error: spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
EXPORT_SYMBOL(ib_send_cm_sidr_rep);
static void cm_format_sidr_rep_event(struct cm_work *work)
{
struct cm_sidr_rep_msg *sidr_rep_msg;
struct ib_cm_sidr_rep_event_param *param;
sidr_rep_msg = (struct cm_sidr_rep_msg *)
work->mad_recv_wc->recv_buf.mad;
param = &work->cm_event.param.sidr_rep_rcvd;
param->status = sidr_rep_msg->status;
param->qkey = be32_to_cpu(sidr_rep_msg->qkey);
param->qpn = be32_to_cpu(cm_sidr_rep_get_qpn(sidr_rep_msg));
param->info = &sidr_rep_msg->info;
param->info_len = sidr_rep_msg->info_length;
work->cm_event.private_data = &sidr_rep_msg->private_data;
}
static int cm_sidr_rep_handler(struct cm_work *work)
{
struct cm_sidr_rep_msg *sidr_rep_msg;
struct cm_id_private *cm_id_priv;
sidr_rep_msg = (struct cm_sidr_rep_msg *)
work->mad_recv_wc->recv_buf.mad;
cm_id_priv = cm_acquire_id(sidr_rep_msg->request_id, 0);
if (!cm_id_priv)
return -EINVAL; /* Unmatched reply. */
spin_lock_irq(&cm_id_priv->lock);
if (cm_id_priv->id.state != IB_CM_SIDR_REQ_SENT) {
spin_unlock_irq(&cm_id_priv->lock);
goto out;
}
cm_id_priv->id.state = IB_CM_IDLE;
ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg);
spin_unlock_irq(&cm_id_priv->lock);
cm_format_sidr_rep_event(work);
cm_process_work(cm_id_priv, work);
return 0;
out:
cm_deref_id(cm_id_priv);
return -EINVAL;
}
static void cm_process_send_error(struct ib_mad_send_buf *msg,
enum ib_wc_status wc_status)
{
struct cm_id_private *cm_id_priv;
struct ib_cm_event cm_event;
enum ib_cm_state state;
int ret;
memset(&cm_event, 0, sizeof cm_event);
cm_id_priv = msg->context[0];
/* Discard old sends or ones without a response. */
spin_lock_irq(&cm_id_priv->lock);
state = (enum ib_cm_state) (unsigned long) msg->context[1];
if (msg != cm_id_priv->msg || state != cm_id_priv->id.state)
goto discard;
switch (state) {
case IB_CM_REQ_SENT:
case IB_CM_MRA_REQ_RCVD:
cm_reset_to_idle(cm_id_priv);
cm_event.event = IB_CM_REQ_ERROR;
break;
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
cm_reset_to_idle(cm_id_priv);
cm_event.event = IB_CM_REP_ERROR;
break;
case IB_CM_DREQ_SENT:
cm_enter_timewait(cm_id_priv);
cm_event.event = IB_CM_DREQ_ERROR;
break;
case IB_CM_SIDR_REQ_SENT:
cm_id_priv->id.state = IB_CM_IDLE;
cm_event.event = IB_CM_SIDR_REQ_ERROR;
break;
default:
goto discard;
}
spin_unlock_irq(&cm_id_priv->lock);
cm_event.param.send_status = wc_status;
/* No other events can occur on the cm_id at this point. */
ret = cm_id_priv->id.cm_handler(&cm_id_priv->id, &cm_event);
cm_free_msg(msg);
if (ret)
ib_destroy_cm_id(&cm_id_priv->id);
return;
discard:
spin_unlock_irq(&cm_id_priv->lock);
cm_free_msg(msg);
}
static void cm_send_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_send_wc *mad_send_wc)
{
struct ib_mad_send_buf *msg = mad_send_wc->send_buf;
struct cm_port *port;
u16 attr_index;
port = mad_agent->context;
attr_index = be16_to_cpu(((struct ib_mad_hdr *)
msg->mad)->attr_id) - CM_ATTR_ID_OFFSET;
/*
* If the send was in response to a received message (context[0] is not
* set to a cm_id), and is not a REJ, then it is a send that was
* manually retried.
*/
if (!msg->context[0] && (attr_index != CM_REJ_COUNTER))
msg->retries = 1;
atomic_long_add(1 + msg->retries,
&port->counter_group[CM_XMIT].counter[attr_index]);
if (msg->retries)
atomic_long_add(msg->retries,
&port->counter_group[CM_XMIT_RETRIES].
counter[attr_index]);
switch (mad_send_wc->status) {
case IB_WC_SUCCESS:
case IB_WC_WR_FLUSH_ERR:
cm_free_msg(msg);
break;
default:
if (msg->context[0] && msg->context[1])
cm_process_send_error(msg, mad_send_wc->status);
else
cm_free_msg(msg);
break;
}
}
static void cm_work_handler(struct work_struct *_work)
{
struct cm_work *work = container_of(_work, struct cm_work, work.work);
int ret;
switch (work->cm_event.event) {
case IB_CM_REQ_RECEIVED:
ret = cm_req_handler(work);
break;
case IB_CM_MRA_RECEIVED:
ret = cm_mra_handler(work);
break;
case IB_CM_REJ_RECEIVED:
ret = cm_rej_handler(work);
break;
case IB_CM_REP_RECEIVED:
ret = cm_rep_handler(work);
break;
case IB_CM_RTU_RECEIVED:
ret = cm_rtu_handler(work);
break;
case IB_CM_USER_ESTABLISHED:
ret = cm_establish_handler(work);
break;
case IB_CM_DREQ_RECEIVED:
ret = cm_dreq_handler(work);
break;
case IB_CM_DREP_RECEIVED:
ret = cm_drep_handler(work);
break;
case IB_CM_SIDR_REQ_RECEIVED:
ret = cm_sidr_req_handler(work);
break;
case IB_CM_SIDR_REP_RECEIVED:
ret = cm_sidr_rep_handler(work);
break;
case IB_CM_LAP_RECEIVED:
ret = cm_lap_handler(work);
break;
case IB_CM_APR_RECEIVED:
ret = cm_apr_handler(work);
break;
case IB_CM_TIMEWAIT_EXIT:
ret = cm_timewait_handler(work);
break;
default:
ret = -EINVAL;
break;
}
if (ret)
cm_free_work(work);
}
static int cm_establish(struct ib_cm_id *cm_id)
{
struct cm_id_private *cm_id_priv;
struct cm_work *work;
unsigned long flags;
int ret = 0;
work = kmalloc(sizeof *work, GFP_ATOMIC);
if (!work)
return -ENOMEM;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
switch (cm_id->state)
{
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
cm_id->state = IB_CM_ESTABLISHED;
break;
case IB_CM_ESTABLISHED:
ret = -EISCONN;
break;
default:
ret = -EINVAL;
break;
}
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
if (ret) {
kfree(work);
goto out;
}
/*
* The CM worker thread may try to destroy the cm_id before it
* can execute this work item. To prevent potential deadlock,
* we need to find the cm_id once we're in the context of the
* worker thread, rather than holding a reference on it.
*/
INIT_DELAYED_WORK(&work->work, cm_work_handler);
work->local_id = cm_id->local_id;
work->remote_id = cm_id->remote_id;
work->mad_recv_wc = NULL;
work->cm_event.event = IB_CM_USER_ESTABLISHED;
queue_delayed_work(cm.wq, &work->work, 0);
out:
return ret;
}
static int cm_migrate(struct ib_cm_id *cm_id)
{
struct cm_id_private *cm_id_priv;
unsigned long flags;
int ret = 0;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
spin_lock_irqsave(&cm_id_priv->lock, flags);
if (cm_id->state == IB_CM_ESTABLISHED &&
(cm_id->lap_state == IB_CM_LAP_UNINIT ||
cm_id->lap_state == IB_CM_LAP_IDLE)) {
cm_id->lap_state = IB_CM_LAP_IDLE;
cm_id_priv->av = cm_id_priv->alt_av;
} else
ret = -EINVAL;
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
int ib_cm_notify(struct ib_cm_id *cm_id, enum ib_event_type event)
{
int ret;
switch (event) {
case IB_EVENT_COMM_EST:
ret = cm_establish(cm_id);
break;
case IB_EVENT_PATH_MIG:
ret = cm_migrate(cm_id);
break;
default:
ret = -EINVAL;
}
return ret;
}
EXPORT_SYMBOL(ib_cm_notify);
static void cm_recv_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct cm_port *port = mad_agent->context;
struct cm_work *work;
enum ib_cm_event_type event;
u16 attr_id;
int paths = 0;
switch (mad_recv_wc->recv_buf.mad->mad_hdr.attr_id) {
case CM_REQ_ATTR_ID:
paths = 1 + (((struct cm_req_msg *) mad_recv_wc->recv_buf.mad)->
alt_local_lid != 0);
event = IB_CM_REQ_RECEIVED;
break;
case CM_MRA_ATTR_ID:
event = IB_CM_MRA_RECEIVED;
break;
case CM_REJ_ATTR_ID:
event = IB_CM_REJ_RECEIVED;
break;
case CM_REP_ATTR_ID:
event = IB_CM_REP_RECEIVED;
break;
case CM_RTU_ATTR_ID:
event = IB_CM_RTU_RECEIVED;
break;
case CM_DREQ_ATTR_ID:
event = IB_CM_DREQ_RECEIVED;
break;
case CM_DREP_ATTR_ID:
event = IB_CM_DREP_RECEIVED;
break;
case CM_SIDR_REQ_ATTR_ID:
event = IB_CM_SIDR_REQ_RECEIVED;
break;
case CM_SIDR_REP_ATTR_ID:
event = IB_CM_SIDR_REP_RECEIVED;
break;
case CM_LAP_ATTR_ID:
paths = 1;
event = IB_CM_LAP_RECEIVED;
break;
case CM_APR_ATTR_ID:
event = IB_CM_APR_RECEIVED;
break;
default:
ib_free_recv_mad(mad_recv_wc);
return;
}
attr_id = be16_to_cpu(mad_recv_wc->recv_buf.mad->mad_hdr.attr_id);
atomic_long_inc(&port->counter_group[CM_RECV].
counter[attr_id - CM_ATTR_ID_OFFSET]);
work = kmalloc(sizeof *work + sizeof(struct ib_sa_path_rec) * paths,
GFP_KERNEL);
if (!work) {
ib_free_recv_mad(mad_recv_wc);
return;
}
INIT_DELAYED_WORK(&work->work, cm_work_handler);
work->cm_event.event = event;
work->mad_recv_wc = mad_recv_wc;
work->port = port;
queue_delayed_work(cm.wq, &work->work, 0);
}
static int cm_init_qp_init_attr(struct cm_id_private *cm_id_priv,
struct ib_qp_attr *qp_attr,
int *qp_attr_mask)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&cm_id_priv->lock, flags);
switch (cm_id_priv->id.state) {
case IB_CM_REQ_SENT:
case IB_CM_MRA_REQ_RCVD:
case IB_CM_REQ_RCVD:
case IB_CM_MRA_REQ_SENT:
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
case IB_CM_ESTABLISHED:
*qp_attr_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX | IB_QP_PORT;
qp_attr->qp_access_flags = IB_ACCESS_REMOTE_WRITE;
if (cm_id_priv->responder_resources)
qp_attr->qp_access_flags |= IB_ACCESS_REMOTE_READ |
IB_ACCESS_REMOTE_ATOMIC;
qp_attr->pkey_index = cm_id_priv->av.pkey_index;
qp_attr->port_num = cm_id_priv->av.port->port_num;
ret = 0;
break;
default:
ret = -EINVAL;
break;
}
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
static int cm_init_qp_rtr_attr(struct cm_id_private *cm_id_priv,
struct ib_qp_attr *qp_attr,
int *qp_attr_mask)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&cm_id_priv->lock, flags);
switch (cm_id_priv->id.state) {
case IB_CM_REQ_RCVD:
case IB_CM_MRA_REQ_SENT:
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
case IB_CM_ESTABLISHED:
*qp_attr_mask = IB_QP_STATE | IB_QP_AV | IB_QP_PATH_MTU |
IB_QP_DEST_QPN | IB_QP_RQ_PSN;
qp_attr->ah_attr = cm_id_priv->av.ah_attr;
if (!cm_id_priv->av.valid) {
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return -EINVAL;
}
if (cm_id_priv->av.ah_attr.vlan_id != 0xffff) {
qp_attr->vlan_id = cm_id_priv->av.ah_attr.vlan_id;
*qp_attr_mask |= IB_QP_VID;
}
if (!is_zero_ether_addr(cm_id_priv->av.smac)) {
memcpy(qp_attr->smac, cm_id_priv->av.smac,
sizeof(qp_attr->smac));
*qp_attr_mask |= IB_QP_SMAC;
}
if (cm_id_priv->alt_av.valid) {
if (cm_id_priv->alt_av.ah_attr.vlan_id != 0xffff) {
qp_attr->alt_vlan_id =
cm_id_priv->alt_av.ah_attr.vlan_id;
*qp_attr_mask |= IB_QP_ALT_VID;
}
if (!is_zero_ether_addr(cm_id_priv->alt_av.smac)) {
memcpy(qp_attr->alt_smac,
cm_id_priv->alt_av.smac,
sizeof(qp_attr->alt_smac));
*qp_attr_mask |= IB_QP_ALT_SMAC;
}
}
qp_attr->path_mtu = cm_id_priv->path_mtu;
qp_attr->dest_qp_num = be32_to_cpu(cm_id_priv->remote_qpn);
qp_attr->rq_psn = be32_to_cpu(cm_id_priv->rq_psn);
if (cm_id_priv->qp_type == IB_QPT_RC ||
cm_id_priv->qp_type == IB_QPT_XRC_TGT) {
*qp_attr_mask |= IB_QP_MAX_DEST_RD_ATOMIC |
IB_QP_MIN_RNR_TIMER;
qp_attr->max_dest_rd_atomic =
cm_id_priv->responder_resources;
qp_attr->min_rnr_timer = 0;
}
if (cm_id_priv->alt_av.ah_attr.dlid) {
*qp_attr_mask |= IB_QP_ALT_PATH;
qp_attr->alt_port_num = cm_id_priv->alt_av.port->port_num;
qp_attr->alt_pkey_index = cm_id_priv->alt_av.pkey_index;
qp_attr->alt_timeout = cm_id_priv->alt_av.timeout;
qp_attr->alt_ah_attr = cm_id_priv->alt_av.ah_attr;
}
ret = 0;
break;
default:
ret = -EINVAL;
break;
}
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
static int cm_init_qp_rts_attr(struct cm_id_private *cm_id_priv,
struct ib_qp_attr *qp_attr,
int *qp_attr_mask)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&cm_id_priv->lock, flags);
switch (cm_id_priv->id.state) {
/* Allow transition to RTS before sending REP */
case IB_CM_REQ_RCVD:
case IB_CM_MRA_REQ_SENT:
case IB_CM_REP_RCVD:
case IB_CM_MRA_REP_SENT:
case IB_CM_REP_SENT:
case IB_CM_MRA_REP_RCVD:
case IB_CM_ESTABLISHED:
if (cm_id_priv->id.lap_state == IB_CM_LAP_UNINIT) {
*qp_attr_mask = IB_QP_STATE | IB_QP_SQ_PSN;
qp_attr->sq_psn = be32_to_cpu(cm_id_priv->sq_psn);
switch (cm_id_priv->qp_type) {
case IB_QPT_RC:
case IB_QPT_XRC_INI:
*qp_attr_mask |= IB_QP_RETRY_CNT | IB_QP_RNR_RETRY |
IB_QP_MAX_QP_RD_ATOMIC;
qp_attr->retry_cnt = cm_id_priv->retry_count;
qp_attr->rnr_retry = cm_id_priv->rnr_retry_count;
qp_attr->max_rd_atomic = cm_id_priv->initiator_depth;
/* fall through */
case IB_QPT_XRC_TGT:
*qp_attr_mask |= IB_QP_TIMEOUT;
qp_attr->timeout = cm_id_priv->av.timeout;
break;
default:
break;
}
if (cm_id_priv->alt_av.ah_attr.dlid) {
*qp_attr_mask |= IB_QP_PATH_MIG_STATE;
qp_attr->path_mig_state = IB_MIG_REARM;
}
} else {
*qp_attr_mask = IB_QP_ALT_PATH | IB_QP_PATH_MIG_STATE;
qp_attr->alt_port_num = cm_id_priv->alt_av.port->port_num;
qp_attr->alt_pkey_index = cm_id_priv->alt_av.pkey_index;
qp_attr->alt_timeout = cm_id_priv->alt_av.timeout;
qp_attr->alt_ah_attr = cm_id_priv->alt_av.ah_attr;
qp_attr->path_mig_state = IB_MIG_REARM;
}
ret = 0;
break;
default:
ret = -EINVAL;
break;
}
spin_unlock_irqrestore(&cm_id_priv->lock, flags);
return ret;
}
int ib_cm_init_qp_attr(struct ib_cm_id *cm_id,
struct ib_qp_attr *qp_attr,
int *qp_attr_mask)
{
struct cm_id_private *cm_id_priv;
int ret;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
switch (qp_attr->qp_state) {
case IB_QPS_INIT:
ret = cm_init_qp_init_attr(cm_id_priv, qp_attr, qp_attr_mask);
break;
case IB_QPS_RTR:
ret = cm_init_qp_rtr_attr(cm_id_priv, qp_attr, qp_attr_mask);
break;
case IB_QPS_RTS:
ret = cm_init_qp_rts_attr(cm_id_priv, qp_attr, qp_attr_mask);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
EXPORT_SYMBOL(ib_cm_init_qp_attr);
static void cm_get_ack_delay(struct cm_device *cm_dev)
{
struct ib_device_attr attr;
if (ib_query_device(cm_dev->ib_device, &attr))
cm_dev->ack_delay = 0; /* acks will rely on packet life time */
else
cm_dev->ack_delay = attr.local_ca_ack_delay;
}
static ssize_t cm_show_counter(struct kobject *obj, struct attribute *attr,
char *buf)
{
struct cm_counter_group *group;
struct cm_counter_attribute *cm_attr;
group = container_of(obj, struct cm_counter_group, obj);
cm_attr = container_of(attr, struct cm_counter_attribute, attr);
return sprintf(buf, "%ld\n",
atomic_long_read(&group->counter[cm_attr->index]));
}
static const struct sysfs_ops cm_counter_ops = {
.show = cm_show_counter
};
static struct kobj_type cm_counter_obj_type = {
.sysfs_ops = &cm_counter_ops,
.default_attrs = cm_counter_default_attrs
};
static void cm_release_port_obj(struct kobject *obj)
{
struct cm_port *cm_port;
cm_port = container_of(obj, struct cm_port, port_obj);
kfree(cm_port);
}
static struct kobj_type cm_port_obj_type = {
.release = cm_release_port_obj
};
static char *cm_devnode(struct device *dev, umode_t *mode)
{
if (mode)
*mode = 0666;
return kasprintf(GFP_KERNEL, "infiniband/%s", dev_name(dev));
}
struct class cm_class = {
.owner = THIS_MODULE,
.name = "infiniband_cm",
.devnode = cm_devnode,
};
EXPORT_SYMBOL(cm_class);
static int cm_create_port_fs(struct cm_port *port)
{
int i, ret;
ret = kobject_init_and_add(&port->port_obj, &cm_port_obj_type,
&port->cm_dev->device->kobj,
"%d", port->port_num);
if (ret) {
kfree(port);
return ret;
}
for (i = 0; i < CM_COUNTER_GROUPS; i++) {
ret = kobject_init_and_add(&port->counter_group[i].obj,
&cm_counter_obj_type,
&port->port_obj,
"%s", counter_group_names[i]);
if (ret)
goto error;
}
return 0;
error:
while (i--)
kobject_put(&port->counter_group[i].obj);
kobject_put(&port->port_obj);
return ret;
}
static void cm_remove_port_fs(struct cm_port *port)
{
int i;
for (i = 0; i < CM_COUNTER_GROUPS; i++)
kobject_put(&port->counter_group[i].obj);
kobject_put(&port->port_obj);
}
static void cm_add_one(struct ib_device *ib_device)
{
struct cm_device *cm_dev;
struct cm_port *port;
struct ib_mad_reg_req reg_req = {
.mgmt_class = IB_MGMT_CLASS_CM,
.mgmt_class_version = IB_CM_CLASS_VERSION
};
struct ib_port_modify port_modify = {
.set_port_cap_mask = IB_PORT_CM_SUP
};
unsigned long flags;
int ret;
u8 i;
if (rdma_node_get_transport(ib_device->node_type) != RDMA_TRANSPORT_IB)
return;
cm_dev = kzalloc(sizeof(*cm_dev) + sizeof(*port) *
ib_device->phys_port_cnt, GFP_KERNEL);
if (!cm_dev)
return;
cm_dev->ib_device = ib_device;
cm_get_ack_delay(cm_dev);
cm_dev->device = device_create(&cm_class, &ib_device->dev,
MKDEV(0, 0), NULL,
"%s", ib_device->name);
if (IS_ERR(cm_dev->device)) {
kfree(cm_dev);
return;
}
set_bit(IB_MGMT_METHOD_SEND, reg_req.method_mask);
for (i = 1; i <= ib_device->phys_port_cnt; i++) {
port = kzalloc(sizeof *port, GFP_KERNEL);
if (!port)
goto error1;
cm_dev->port[i-1] = port;
port->cm_dev = cm_dev;
port->port_num = i;
ret = cm_create_port_fs(port);
if (ret)
goto error1;
port->mad_agent = ib_register_mad_agent(ib_device, i,
IB_QPT_GSI,
®_req,
0,
cm_send_handler,
cm_recv_handler,
port);
if (IS_ERR(port->mad_agent))
goto error2;
ret = ib_modify_port(ib_device, i, 0, &port_modify);
if (ret)
goto error3;
}
ib_set_client_data(ib_device, &cm_client, cm_dev);
write_lock_irqsave(&cm.device_lock, flags);
list_add_tail(&cm_dev->list, &cm.device_list);
write_unlock_irqrestore(&cm.device_lock, flags);
return;
error3:
ib_unregister_mad_agent(port->mad_agent);
error2:
cm_remove_port_fs(port);
error1:
port_modify.set_port_cap_mask = 0;
port_modify.clr_port_cap_mask = IB_PORT_CM_SUP;
while (--i) {
port = cm_dev->port[i-1];
ib_modify_port(ib_device, port->port_num, 0, &port_modify);
ib_unregister_mad_agent(port->mad_agent);
cm_remove_port_fs(port);
}
device_unregister(cm_dev->device);
kfree(cm_dev);
}
static void cm_remove_one(struct ib_device *ib_device)
{
struct cm_device *cm_dev;
struct cm_port *port;
struct ib_port_modify port_modify = {
.clr_port_cap_mask = IB_PORT_CM_SUP
};
unsigned long flags;
int i;
cm_dev = ib_get_client_data(ib_device, &cm_client);
if (!cm_dev)
return;
write_lock_irqsave(&cm.device_lock, flags);
list_del(&cm_dev->list);
write_unlock_irqrestore(&cm.device_lock, flags);
for (i = 1; i <= ib_device->phys_port_cnt; i++) {
port = cm_dev->port[i-1];
ib_modify_port(ib_device, port->port_num, 0, &port_modify);
ib_unregister_mad_agent(port->mad_agent);
flush_workqueue(cm.wq);
cm_remove_port_fs(port);
}
device_unregister(cm_dev->device);
kfree(cm_dev);
}
static int __init ib_cm_init(void)
{
int ret;
memset(&cm, 0, sizeof cm);
INIT_LIST_HEAD(&cm.device_list);
rwlock_init(&cm.device_lock);
spin_lock_init(&cm.lock);
cm.listen_service_table = RB_ROOT;
cm.listen_service_id = be64_to_cpu(IB_CM_ASSIGN_SERVICE_ID);
cm.remote_id_table = RB_ROOT;
cm.remote_qp_table = RB_ROOT;
cm.remote_sidr_table = RB_ROOT;
idr_init(&cm.local_id_table);
get_random_bytes(&cm.random_id_operand, sizeof cm.random_id_operand);
INIT_LIST_HEAD(&cm.timewait_list);
ret = class_register(&cm_class);
if (ret) {
ret = -ENOMEM;
goto error1;
}
cm.wq = create_workqueue("ib_cm");
if (!cm.wq) {
ret = -ENOMEM;
goto error2;
}
ret = ib_register_client(&cm_client);
if (ret)
goto error3;
return 0;
error3:
destroy_workqueue(cm.wq);
error2:
class_unregister(&cm_class);
error1:
idr_destroy(&cm.local_id_table);
return ret;
}
static void __exit ib_cm_cleanup(void)
{
struct cm_timewait_info *timewait_info, *tmp;
spin_lock_irq(&cm.lock);
list_for_each_entry(timewait_info, &cm.timewait_list, list)
cancel_delayed_work(&timewait_info->work.work);
spin_unlock_irq(&cm.lock);
ib_unregister_client(&cm_client);
destroy_workqueue(cm.wq);
list_for_each_entry_safe(timewait_info, tmp, &cm.timewait_list, list) {
list_del(&timewait_info->list);
kfree(timewait_info);
}
class_unregister(&cm_class);
idr_destroy(&cm.local_id_table);
}
module_init(ib_cm_init);
module_exit(ib_cm_cleanup);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2117_0 |
crossvul-cpp_data_bad_1448_1 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mod_lua.h"
#include "lua_apr.h"
#include "lua_dbd.h"
#include "lua_passwd.h"
#include "scoreboard.h"
#include "util_md5.h"
#include "util_script.h"
#include "util_varbuf.h"
#include "apr_date.h"
#include "apr_pools.h"
#include "apr_thread_mutex.h"
#include "apr_tables.h"
#include "util_cookies.h"
#define APR_WANT_BYTEFUNC
#include "apr_want.h"
extern apr_global_mutex_t* lua_ivm_mutex;
extern apr_shm_t *lua_ivm_shm;
APLOG_USE_MODULE(lua);
#define POST_MAX_VARS 500
#ifndef MODLUA_MAX_REG_MATCH
#define MODLUA_MAX_REG_MATCH 25
#endif
typedef char *(*req_field_string_f) (request_rec * r);
typedef int (*req_field_int_f) (request_rec * r);
typedef req_table_t *(*req_field_apr_table_f) (request_rec * r);
void ap_lua_rstack_dump(lua_State *L, request_rec *r, const char *msg)
{
int i;
int top = lua_gettop(L);
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01484) "Lua Stack Dump: [%s]", msg);
for (i = 1; i <= top; i++) {
int t = lua_type(L, i);
switch (t) {
case LUA_TSTRING:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: '%s'", i, lua_tostring(L, i));
break;
}
case LUA_TUSERDATA:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%d: userdata",
i);
break;
}
case LUA_TLIGHTUSERDATA:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: lightuserdata", i);
break;
}
case LUA_TNIL:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%d: NIL", i);
break;
}
case LUA_TNONE:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%d: None", i);
break;
}
case LUA_TBOOLEAN:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: %s", i, lua_toboolean(L,
i) ? "true" :
"false");
break;
}
case LUA_TNUMBER:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: %g", i, lua_tonumber(L, i));
break;
}
case LUA_TTABLE:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: <table>", i);
break;
}
case LUA_TFUNCTION:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: <function>", i);
break;
}
default:{
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"%d: unknown: -[%s]-", i, lua_typename(L, i));
break;
}
}
}
}
/**
* Verify that the thing at index is a request_rec wrapping
* userdata thingamajig and return it if it is. if it is not
* lua will enter its error handling routine.
*/
static request_rec *ap_lua_check_request_rec(lua_State *L, int index)
{
request_rec *r;
luaL_checkudata(L, index, "Apache2.Request");
r = (request_rec *) lua_unboxpointer(L, index);
return r;
}
/* ------------------ request methods -------------------- */
/* helper callback for req_parseargs */
static int req_aprtable2luatable_cb(void *l, const char *key,
const char *value)
{
int t;
lua_State *L = (lua_State *) l; /* [table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "start of cb"); */
/* L is [table<s,t>, table<s,s>] */
/* build complex */
lua_getfield(L, -1, key); /* [VALUE, table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "after getfield"); */
t = lua_type(L, -1);
switch (t) {
case LUA_TNIL:
case LUA_TNONE:{
lua_pop(L, 1); /* [table<s,t>, table<s,s>] */
lua_newtable(L); /* [array, table<s,t>, table<s,s>] */
lua_pushnumber(L, 1); /* [1, array, table<s,t>, table<s,s>] */
lua_pushstring(L, value); /* [string, 1, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
case LUA_TTABLE:{
/* [array, table<s,t>, table<s,s>] */
int size = lua_rawlen(L, -1);
lua_pushnumber(L, size + 1); /* [#, array, table<s,t>, table<s,s>] */
lua_pushstring(L, value); /* [string, #, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
}
/* L is [table<s,t>, table<s,s>] */
/* build simple */
lua_getfield(L, -2, key); /* [VALUE, table<s,s>, table<s,t>] */
if (lua_isnoneornil(L, -1)) { /* only set if not already set */
lua_pop(L, 1); /* [table<s,s>, table<s,t>]] */
lua_pushstring(L, value); /* [string, table<s,s>, table<s,t>] */
lua_setfield(L, -3, key); /* [table<s,s>, table<s,t>] */
}
else {
lua_pop(L, 1);
}
return 1;
}
/* helper callback for req_parseargs */
static int req_aprtable2luatable_cb_len(void *l, const char *key,
const char *value, size_t len)
{
int t;
lua_State *L = (lua_State *) l; /* [table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "start of cb"); */
/* L is [table<s,t>, table<s,s>] */
/* build complex */
lua_getfield(L, -1, key); /* [VALUE, table<s,t>, table<s,s>] */
/* rstack_dump(L, RRR, "after getfield"); */
t = lua_type(L, -1);
switch (t) {
case LUA_TNIL:
case LUA_TNONE:{
lua_pop(L, 1); /* [table<s,t>, table<s,s>] */
lua_newtable(L); /* [array, table<s,t>, table<s,s>] */
lua_pushnumber(L, 1); /* [1, array, table<s,t>, table<s,s>] */
lua_pushlstring(L, value, len); /* [string, 1, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
case LUA_TTABLE:{
/* [array, table<s,t>, table<s,s>] */
int size = lua_rawlen(L, -1);
lua_pushnumber(L, size + 1); /* [#, array, table<s,t>, table<s,s>] */
lua_pushlstring(L, value, len); /* [string, #, array, table<s,t>, table<s,s>] */
lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */
lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */
break;
}
}
/* L is [table<s,t>, table<s,s>] */
/* build simple */
lua_getfield(L, -2, key); /* [VALUE, table<s,s>, table<s,t>] */
if (lua_isnoneornil(L, -1)) { /* only set if not already set */
lua_pop(L, 1); /* [table<s,s>, table<s,t>]] */
lua_pushlstring(L, value, len); /* [string, table<s,s>, table<s,t>] */
lua_setfield(L, -3, key); /* [table<s,s>, table<s,t>] */
}
else {
lua_pop(L, 1);
}
return 1;
}
/*
=======================================================================================================================
lua_read_body(request_rec *r, const char **rbuf, apr_off_t *size): Reads any additional form data sent in POST/PUT
requests. Used for multipart POST data.
=======================================================================================================================
*/
static int lua_read_body(request_rec *r, const char **rbuf, apr_off_t *size,
apr_off_t maxsize)
{
int rc = OK;
if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) {
return (rc);
}
if (ap_should_client_block(r)) {
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
char argsbuffer[HUGE_STRING_LEN];
apr_off_t rsize, len_read, rpos = 0;
apr_off_t length = r->remaining;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if (maxsize != 0 && length > maxsize) {
return APR_EINCOMPLETE; /* Only room for incomplete data chunk :( */
}
*rbuf = (const char *) apr_pcalloc(r->pool, (apr_size_t) (length + 1));
*size = length;
while ((len_read = ap_get_client_block(r, argsbuffer, sizeof(argsbuffer))) > 0) {
if ((rpos + len_read) > length) {
rsize = length - rpos;
}
else {
rsize = len_read;
}
memcpy((char *) *rbuf + rpos, argsbuffer, (size_t) rsize);
rpos += rsize;
}
}
return (rc);
}
/*
* =======================================================================================================================
* lua_write_body: Reads any additional form data sent in POST/PUT requests
* and writes to a file.
* =======================================================================================================================
*/
static apr_status_t lua_write_body(request_rec *r, apr_file_t *file, apr_off_t *size)
{
apr_status_t rc = OK;
if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
return rc;
if (ap_should_client_block(r)) {
char argsbuffer[HUGE_STRING_LEN];
apr_off_t rsize,
len_read,
rpos = 0;
apr_off_t length = r->remaining;
*size = length;
while ((len_read =
ap_get_client_block(r, argsbuffer,
sizeof(argsbuffer))) > 0) {
if ((rpos + len_read) > length)
rsize = (apr_size_t) length - rpos;
else
rsize = len_read;
rc = apr_file_write_full(file, argsbuffer, (apr_size_t) rsize,
NULL);
if (rc != APR_SUCCESS)
return rc;
rpos += rsize;
}
}
return rc;
}
/* r:parseargs() returning a lua table */
static int req_parseargs(lua_State *L)
{
apr_table_t *form_table;
request_rec *r = ap_lua_check_request_rec(L, 1);
lua_newtable(L);
lua_newtable(L); /* [table, table] */
ap_args_to_table(r, &form_table);
apr_table_do(req_aprtable2luatable_cb, L, form_table, NULL);
return 2; /* [table<string, string>, table<string, array<string>>] */
}
/* ap_lua_binstrstr: Binary strstr function for uploaded data with NULL bytes */
static char* ap_lua_binstrstr (const char * haystack, size_t hsize, const char* needle, size_t nsize)
{
size_t p;
if (haystack == NULL) return NULL;
if (needle == NULL) return NULL;
if (hsize < nsize) return NULL;
for (p = 0; p <= (hsize - nsize); ++p) {
if (memcmp(haystack + p, needle, nsize) == 0) {
return (char*) (haystack + p);
}
}
return NULL;
}
/* r:parsebody(): Parses regular (url-enocded) or multipart POST data and returns two tables*/
static int req_parsebody(lua_State *L)
{
apr_array_header_t *pairs;
apr_off_t len;
int res;
apr_size_t size;
apr_size_t max_post_size;
char *multipart;
const char *contentType;
request_rec *r = ap_lua_check_request_rec(L, 1);
max_post_size = (apr_size_t) luaL_optint(L, 2, MAX_STRING_LEN);
multipart = apr_pcalloc(r->pool, 256);
contentType = apr_table_get(r->headers_in, "Content-Type");
lua_newtable(L);
lua_newtable(L); /* [table, table] */
if (contentType != NULL && (sscanf(contentType, "multipart/form-data; boundary=%250c", multipart) == 1)) {
char *buffer, *key, *filename;
char *start = 0, *end = 0, *crlf = 0;
const char *data;
int i;
size_t vlen = 0;
size_t len = 0;
if (lua_read_body(r, &data, (apr_off_t*) &size, max_post_size) != OK) {
return 2;
}
len = strlen(multipart);
i = 0;
for
(
start = strstr((char *) data, multipart);
start != NULL;
start = end
) {
i++;
if (i == POST_MAX_VARS) break;
crlf = strstr((char *) start, "\r\n\r\n");
if (!crlf) break;
end = ap_lua_binstrstr(crlf, (size - (crlf - data)), multipart, len);
if (end == NULL) break;
key = (char *) apr_pcalloc(r->pool, 256);
filename = (char *) apr_pcalloc(r->pool, 256);
vlen = end - crlf - 8;
buffer = (char *) apr_pcalloc(r->pool, vlen+1);
memcpy(buffer, crlf + 4, vlen);
sscanf(start + len + 2,
"Content-Disposition: form-data; name=\"%255[^\"]\"; filename=\"%255[^\"]\"",
key, filename);
if (strlen(key)) {
req_aprtable2luatable_cb_len(L, key, buffer, vlen);
}
}
}
else {
char *buffer;
res = ap_parse_form_data(r, NULL, &pairs, -1, max_post_size);
if (res == OK) {
while(pairs && !apr_is_empty_array(pairs)) {
ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs);
apr_brigade_length(pair->value, 1, &len);
size = (apr_size_t) len;
buffer = apr_palloc(r->pool, size + 1);
apr_brigade_flatten(pair->value, buffer, &size);
buffer[len] = 0;
req_aprtable2luatable_cb(L, pair->name, buffer);
}
}
}
return 2; /* [table<string, string>, table<string, array<string>>] */
}
/*
* lua_ap_requestbody; r:requestbody([filename]) - Reads or stores the request
* body
*/
static int lua_ap_requestbody(lua_State *L)
{
const char *filename;
request_rec *r;
apr_off_t maxSize;
r = ap_lua_check_request_rec(L, 1);
filename = luaL_optstring(L, 2, 0);
maxSize = luaL_optint(L, 3, 0);
if (r) {
apr_off_t size;
if (maxSize > 0 && r->remaining > maxSize) {
lua_pushnil(L);
lua_pushliteral(L, "Request body was larger than the permitted size.");
return 2;
}
if (r->method_number != M_POST && r->method_number != M_PUT)
return (0);
if (!filename) {
const char *data;
if (lua_read_body(r, &data, &size, maxSize) != OK)
return (0);
lua_pushlstring(L, data, (size_t) size);
lua_pushinteger(L, (lua_Integer) size);
return (2);
} else {
apr_status_t rc;
apr_file_t *file;
rc = apr_file_open(&file, filename, APR_CREATE | APR_FOPEN_WRITE,
APR_FPROT_OS_DEFAULT, r->pool);
lua_settop(L, 0);
if (rc == APR_SUCCESS) {
rc = lua_write_body(r, file, &size);
apr_file_close(file);
if (rc != OK) {
lua_pushboolean(L, 0);
return 1;
}
lua_pushinteger(L, (lua_Integer) size);
return (1);
} else
lua_pushboolean(L, 0);
return (1);
}
}
return (0);
}
/* wrap ap_rputs as r:puts(String) */
static int req_puts(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
int argc = lua_gettop(L);
int i;
for (i = 2; i <= argc; i++) {
ap_rputs(luaL_checkstring(L, i), r);
}
return 0;
}
/* wrap ap_rwrite as r:write(String) */
static int req_write(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
size_t n;
int rv;
const char *buf = luaL_checklstring(L, 2, &n);
rv = ap_rwrite((void *) buf, n, r);
lua_pushinteger(L, rv);
return 1;
}
/* r:addoutputfilter(name|function) */
static int req_add_output_filter(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *name = luaL_checkstring(L, 2);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01485) "adding output filter %s",
name);
ap_add_output_filter(name, L, r, r->connection);
return 0;
}
/* wrap ap_construct_url as r:construct_url(String) */
static int req_construct_url(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *name = luaL_checkstring(L, 2);
lua_pushstring(L, ap_construct_url(r->pool, name, r));
return 1;
}
/* wrap ap_escape_html r:escape_html(String) */
static int req_escape_html(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *s = luaL_checkstring(L, 2);
lua_pushstring(L, ap_escape_html(r->pool, s));
return 1;
}
/* wrap optional ssl_var_lookup as r:ssl_var_lookup(String) */
static int req_ssl_var_lookup(lua_State *L)
{
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *s = luaL_checkstring(L, 2);
const char *res = ap_lua_ssl_val(r->pool, r->server, r->connection, r,
(char *)s);
lua_pushstring(L, res);
return 1;
}
/* BEGIN dispatch mathods for request_rec fields */
/* not really a field, but we treat it like one */
static const char *req_document_root(request_rec *r)
{
return ap_document_root(r);
}
static const char *req_context_prefix(request_rec *r)
{
return ap_context_prefix(r);
}
static const char *req_context_document_root(request_rec *r)
{
return ap_context_document_root(r);
}
static char *req_uri_field(request_rec *r)
{
return r->uri;
}
static const char *req_method_field(request_rec *r)
{
return r->method;
}
static const char *req_handler_field(request_rec *r)
{
return r->handler;
}
static const char *req_proxyreq_field(request_rec *r)
{
switch (r->proxyreq) {
case PROXYREQ_NONE: return "PROXYREQ_NONE";
case PROXYREQ_PROXY: return "PROXYREQ_PROXY";
case PROXYREQ_REVERSE: return "PROXYREQ_REVERSE";
case PROXYREQ_RESPONSE: return "PROXYREQ_RESPONSE";
default: return NULL;
}
}
static const char *req_hostname_field(request_rec *r)
{
return r->hostname;
}
static const char *req_args_field(request_rec *r)
{
return r->args;
}
static const char *req_path_info_field(request_rec *r)
{
return r->path_info;
}
static const char *req_canonical_filename_field(request_rec *r)
{
return r->canonical_filename;
}
static const char *req_filename_field(request_rec *r)
{
return r->filename;
}
static const char *req_user_field(request_rec *r)
{
return r->user;
}
static const char *req_unparsed_uri_field(request_rec *r)
{
return r->unparsed_uri;
}
static const char *req_ap_auth_type_field(request_rec *r)
{
return r->ap_auth_type;
}
static const char *req_content_encoding_field(request_rec *r)
{
return r->content_encoding;
}
static const char *req_content_type_field(request_rec *r)
{
return r->content_type;
}
static const char *req_range_field(request_rec *r)
{
return r->range;
}
static const char *req_protocol_field(request_rec *r)
{
return r->protocol;
}
static const char *req_the_request_field(request_rec *r)
{
return r->the_request;
}
static const char *req_log_id_field(request_rec *r)
{
return r->log_id;
}
static const char *req_useragent_ip_field(request_rec *r)
{
return r->useragent_ip;
}
static int req_remaining_field(request_rec *r)
{
return r->remaining;
}
static int req_status_field(request_rec *r)
{
return r->status;
}
static int req_assbackwards_field(request_rec *r)
{
return r->assbackwards;
}
static req_table_t* req_headers_in(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->headers_in;
t->n = "headers_in";
return t;
}
static req_table_t* req_headers_out(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->headers_out;
t->n = "headers_out";
return t;
}
static req_table_t* req_err_headers_out(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->err_headers_out;
t->n = "err_headers_out";
return t;
}
static req_table_t* req_subprocess_env(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->subprocess_env;
t->n = "subprocess_env";
return t;
}
static req_table_t* req_notes(request_rec *r)
{
req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t));
t->r = r;
t->t = r->notes;
t->n = "notes";
return t;
}
static int req_ssl_is_https_field(request_rec *r)
{
return ap_lua_ssl_is_https(r->connection);
}
static int req_ap_get_server_port(request_rec *r)
{
return (int) ap_get_server_port(r);
}
static int lua_ap_rflush (lua_State *L) {
int returnValue;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
returnValue = ap_rflush(r);
lua_pushboolean(L, (returnValue == 0));
return 1;
}
static const char* lua_ap_options(request_rec* r)
{
int opts;
opts = ap_allow_options(r);
return apr_psprintf(r->pool, "%s %s %s %s %s %s", (opts&OPT_INDEXES) ? "Indexes" : "", (opts&OPT_INCLUDES) ? "Includes" : "", (opts&OPT_SYM_LINKS) ? "FollowSymLinks" : "", (opts&OPT_EXECCGI) ? "ExecCGI" : "", (opts&OPT_MULTI) ? "MultiViews" : "", (opts&OPT_ALL) == OPT_ALL ? "All" : "" );
}
static const char* lua_ap_allowoverrides(request_rec* r)
{
int opts;
opts = ap_allow_overrides(r);
if ( (opts & OR_ALL) == OR_ALL) {
return "All";
}
else if (opts == OR_NONE) {
return "None";
}
return apr_psprintf(r->pool, "%s %s %s %s %s", (opts & OR_LIMIT) ? "Limit" : "", (opts & OR_OPTIONS) ? "Options" : "", (opts & OR_FILEINFO) ? "FileInfo" : "", (opts & OR_AUTHCFG) ? "AuthCfg" : "", (opts & OR_INDEXES) ? "Indexes" : "" );
}
static int lua_ap_started(request_rec* r)
{
return (int)(ap_scoreboard_image->global->restart_time / 1000000);
}
static const char* lua_ap_basic_auth_pw(request_rec* r)
{
const char* pw = NULL;
ap_get_basic_auth_pw(r, &pw);
return pw ? pw : "";
}
static int lua_ap_limit_req_body(request_rec* r)
{
return (int) ap_get_limit_req_body(r);
}
static int lua_ap_is_initial_req(request_rec *r)
{
return ap_is_initial_req(r);
}
static int lua_ap_some_auth_required(request_rec *r)
{
return ap_some_auth_required(r);
}
static int lua_ap_sendfile(lua_State *L)
{
apr_finfo_t file_info;
const char *filename;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
filename = lua_tostring(L, 2);
apr_stat(&file_info, filename, APR_FINFO_MIN, r->pool);
if (file_info.filetype == APR_NOFILE || file_info.filetype == APR_DIR) {
lua_pushboolean(L, 0);
}
else {
apr_size_t sent;
apr_status_t rc;
apr_file_t *file;
rc = apr_file_open(&file, filename, APR_READ, APR_OS_DEFAULT,
r->pool);
if (rc == APR_SUCCESS) {
ap_send_fd(file, r, 0, (apr_size_t)file_info.size, &sent);
apr_file_close(file);
lua_pushinteger(L, sent);
}
else {
lua_pushboolean(L, 0);
}
}
return (1);
}
/*
* lua_apr_b64encode; r:encode_base64(string) - encodes a string to Base64
* format
*/
static int lua_apr_b64encode(lua_State *L)
{
const char *plain;
char *encoded;
size_t plain_len, encoded_len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
plain = lua_tolstring(L, 2, &plain_len);
encoded_len = apr_base64_encode_len(plain_len);
if (encoded_len) {
encoded = apr_palloc(r->pool, encoded_len);
encoded_len = apr_base64_encode(encoded, plain, plain_len);
if (encoded_len > 0 && encoded[encoded_len - 1] == '\0')
encoded_len--;
lua_pushlstring(L, encoded, encoded_len);
return 1;
}
return 0;
}
/*
* lua_apr_b64decode; r:decode_base64(string) - decodes a Base64 string
*/
static int lua_apr_b64decode(lua_State *L)
{
const char *encoded;
char *plain;
size_t encoded_len, decoded_len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
encoded = lua_tolstring(L, 2, &encoded_len);
decoded_len = apr_base64_decode_len(encoded);
if (decoded_len) {
plain = apr_palloc(r->pool, decoded_len);
decoded_len = apr_base64_decode(plain, encoded);
if (decoded_len > 0 && plain[decoded_len - 1] == '\0')
decoded_len--;
lua_pushlstring(L, plain, decoded_len);
return 1;
}
return 0;
}
/*
* lua_ap_unescape; r:unescape(string) - Unescapes an URL-encoded string
*/
static int lua_ap_unescape(lua_State *L)
{
const char *escaped;
char *plain;
size_t x,
y;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
escaped = lua_tolstring(L, 2, &x);
plain = apr_pstrdup(r->pool, escaped);
y = ap_unescape_urlencoded(plain);
if (!y) {
lua_pushstring(L, plain);
return 1;
}
return 0;
}
/*
* lua_ap_escape; r:escape(string) - URL-escapes a string
*/
static int lua_ap_escape(lua_State *L)
{
const char *plain;
char *escaped;
size_t x;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
plain = lua_tolstring(L, 2, &x);
escaped = ap_escape_urlencoded(r->pool, plain);
lua_pushstring(L, escaped);
return 1;
}
/*
* lua_apr_md5; r:md5(string) - Calculates an MD5 digest of a string
*/
static int lua_apr_md5(lua_State *L)
{
const char *buffer;
char *result;
size_t len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
buffer = lua_tolstring(L, 2, &len);
result = ap_md5_binary(r->pool, (const unsigned char *)buffer, len);
lua_pushstring(L, result);
return 1;
}
/*
* lua_apr_sha1; r:sha1(string) - Calculates the SHA1 digest of a string
*/
static int lua_apr_sha1(lua_State *L)
{
unsigned char digest[APR_SHA1_DIGESTSIZE];
apr_sha1_ctx_t sha1;
const char *buffer;
char *result;
size_t len;
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
result = apr_pcalloc(r->pool, sizeof(digest) * 2 + 1);
buffer = lua_tolstring(L, 2, &len);
apr_sha1_init(&sha1);
apr_sha1_update(&sha1, buffer, len);
apr_sha1_final(digest, &sha1);
ap_bin2hex(digest, sizeof(digest), result);
lua_pushstring(L, result);
return 1;
}
/*
* lua_apr_htpassword; r:htpassword(string [, algorithm [, cost]]) - Creates
* a htpassword hash from a string
*/
static int lua_apr_htpassword(lua_State *L)
{
passwd_ctx ctx = { 0 };
request_rec *r;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
ctx.passwd = apr_pstrdup(r->pool, lua_tostring(L, 2));
ctx.alg = luaL_optinteger(L, 3, ALG_APMD5);
ctx.cost = luaL_optinteger(L, 4, 0);
ctx.pool = r->pool;
ctx.out = apr_pcalloc(r->pool, MAX_PASSWD_LEN);
ctx.out_len = MAX_PASSWD_LEN;
if (mk_password_hash(&ctx)) {
lua_pushboolean(L, 0);
lua_pushstring(L, ctx.errstr);
return 2;
} else {
lua_pushstring(L, ctx.out);
}
return 1;
}
/*
* lua_apr_touch; r:touch(string [, time]) - Sets mtime of a file
*/
static int lua_apr_touch(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
apr_time_t mtime;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
mtime = (apr_time_t)luaL_optnumber(L, 3, (lua_Number)apr_time_now());
status = apr_file_mtime_set(path, mtime, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_mkdir; r:mkdir(string [, permissions]) - Creates a directory
*/
static int lua_apr_mkdir(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
apr_fileperms_t perms;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
perms = luaL_optinteger(L, 3, APR_OS_DEFAULT);
status = apr_dir_make(path, perms, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_mkrdir; r:mkrdir(string [, permissions]) - Creates directories
* recursive
*/
static int lua_apr_mkrdir(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
apr_fileperms_t perms;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
perms = luaL_optinteger(L, 3, APR_OS_DEFAULT);
status = apr_dir_make_recursive(path, perms, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_rmdir; r:rmdir(string) - Removes a directory
*/
static int lua_apr_rmdir(lua_State *L)
{
request_rec *r;
const char *path;
apr_status_t status;
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
status = apr_dir_remove(path, r->pool);
lua_pushboolean(L, (status == 0));
return 1;
}
/*
* lua_apr_date_parse_rfc; r.date_parse_rfc(string) - Parses a DateTime string
*/
static int lua_apr_date_parse_rfc(lua_State *L)
{
const char *input;
apr_time_t result;
luaL_checktype(L, 1, LUA_TSTRING);
input = lua_tostring(L, 1);
result = apr_date_parse_rfc(input);
if (result == 0)
return 0;
lua_pushnumber(L, (lua_Number)(result / APR_USEC_PER_SEC));
return 1;
}
/*
* lua_ap_mpm_query; r:mpm_query(info) - Queries for MPM info
*/
static int lua_ap_mpm_query(lua_State *L)
{
int x,
y;
x = lua_tointeger(L, 1);
ap_mpm_query(x, &y);
lua_pushinteger(L, y);
return 1;
}
/*
* lua_ap_expr; r:expr(string) - Evaluates an expr statement.
*/
static int lua_ap_expr(lua_State *L)
{
request_rec *r;
int x = 0;
const char *expr,
*err;
ap_expr_info_t res;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
expr = lua_tostring(L, 2);
res.filename = NULL;
res.flags = 0;
res.line_number = 0;
res.module_index = APLOG_MODULE_INDEX;
err = ap_expr_parse(r->pool, r->pool, &res, expr, NULL);
if (!err) {
x = ap_expr_exec(r, &res, &err);
lua_pushboolean(L, x);
if (x < 0) {
lua_pushstring(L, err);
return 2;
}
return 1;
} else {
lua_pushboolean(L, 0);
lua_pushstring(L, err);
return 2;
}
lua_pushboolean(L, 0);
return 1;
}
/*
* lua_ap_regex; r:regex(string, pattern [, flags])
* - Evaluates a regex and returns captures if matched
*/
static int lua_ap_regex(lua_State *L)
{
request_rec *r;
int i,
rv,
flags;
const char *pattern,
*source;
char *err;
ap_regex_t regex;
ap_regmatch_t matches[MODLUA_MAX_REG_MATCH+1];
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
luaL_checktype(L, 3, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
source = lua_tostring(L, 2);
pattern = lua_tostring(L, 3);
flags = luaL_optinteger(L, 4, 0);
rv = ap_regcomp(®ex, pattern, flags);
if (rv) {
lua_pushboolean(L, 0);
err = apr_palloc(r->pool, 256);
ap_regerror(rv, ®ex, err, 256);
lua_pushstring(L, err);
return 2;
}
if (regex.re_nsub > MODLUA_MAX_REG_MATCH) {
lua_pushboolean(L, 0);
err = apr_palloc(r->pool, 64);
apr_snprintf(err, 64,
"regcomp found %d matches; only %d allowed.",
regex.re_nsub, MODLUA_MAX_REG_MATCH);
lua_pushstring(L, err);
return 2;
}
rv = ap_regexec(®ex, source, MODLUA_MAX_REG_MATCH, matches, 0);
if (rv == AP_REG_NOMATCH) {
lua_pushboolean(L, 0);
return 1;
}
lua_newtable(L);
for (i = 0; i <= regex.re_nsub; i++) {
lua_pushinteger(L, i);
if (matches[i].rm_so >= 0 && matches[i].rm_eo >= 0)
lua_pushstring(L,
apr_pstrndup(r->pool, source + matches[i].rm_so,
matches[i].rm_eo - matches[i].rm_so));
else
lua_pushnil(L);
lua_settable(L, -3);
}
return 1;
}
/*
* lua_ap_scoreboard_process; r:scoreboard_process(a) - returns scoreboard info
*/
static int lua_ap_scoreboard_process(lua_State *L)
{
int i;
process_score *ps_record;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TNUMBER);
i = lua_tointeger(L, 2);
ps_record = ap_get_scoreboard_process(i);
if (ps_record) {
lua_newtable(L);
lua_pushstring(L, "connections");
lua_pushnumber(L, ps_record->connections);
lua_settable(L, -3);
lua_pushstring(L, "keepalive");
lua_pushnumber(L, ps_record->keep_alive);
lua_settable(L, -3);
lua_pushstring(L, "lingering_close");
lua_pushnumber(L, ps_record->lingering_close);
lua_settable(L, -3);
lua_pushstring(L, "pid");
lua_pushnumber(L, ps_record->pid);
lua_settable(L, -3);
lua_pushstring(L, "suspended");
lua_pushnumber(L, ps_record->suspended);
lua_settable(L, -3);
lua_pushstring(L, "write_completion");
lua_pushnumber(L, ps_record->write_completion);
lua_settable(L, -3);
lua_pushstring(L, "not_accepting");
lua_pushnumber(L, ps_record->not_accepting);
lua_settable(L, -3);
lua_pushstring(L, "quiescing");
lua_pushnumber(L, ps_record->quiescing);
lua_settable(L, -3);
return 1;
}
return 0;
}
/*
* lua_ap_scoreboard_worker; r:scoreboard_worker(proc, thread) - Returns thread
* info
*/
static int lua_ap_scoreboard_worker(lua_State *L)
{
int i, j;
worker_score *ws_record = NULL;
request_rec *r = NULL;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TNUMBER);
luaL_checktype(L, 3, LUA_TNUMBER);
r = ap_lua_check_request_rec(L, 1);
if (!r) return 0;
i = lua_tointeger(L, 2);
j = lua_tointeger(L, 3);
ws_record = apr_palloc(r->pool, sizeof *ws_record);
ap_copy_scoreboard_worker(ws_record, i, j);
if (ws_record) {
lua_newtable(L);
lua_pushstring(L, "access_count");
lua_pushnumber(L, ws_record->access_count);
lua_settable(L, -3);
lua_pushstring(L, "bytes_served");
lua_pushnumber(L, (lua_Number) ws_record->bytes_served);
lua_settable(L, -3);
lua_pushstring(L, "client");
lua_pushstring(L, ws_record->client);
lua_settable(L, -3);
lua_pushstring(L, "conn_bytes");
lua_pushnumber(L, (lua_Number) ws_record->conn_bytes);
lua_settable(L, -3);
lua_pushstring(L, "conn_count");
lua_pushnumber(L, ws_record->conn_count);
lua_settable(L, -3);
lua_pushstring(L, "generation");
lua_pushnumber(L, ws_record->generation);
lua_settable(L, -3);
lua_pushstring(L, "last_used");
lua_pushnumber(L, (lua_Number) ws_record->last_used);
lua_settable(L, -3);
lua_pushstring(L, "pid");
lua_pushnumber(L, ws_record->pid);
lua_settable(L, -3);
lua_pushstring(L, "request");
lua_pushstring(L, ws_record->request);
lua_settable(L, -3);
lua_pushstring(L, "start_time");
lua_pushnumber(L, (lua_Number) ws_record->start_time);
lua_settable(L, -3);
lua_pushstring(L, "status");
lua_pushnumber(L, ws_record->status);
lua_settable(L, -3);
lua_pushstring(L, "stop_time");
lua_pushnumber(L, (lua_Number) ws_record->stop_time);
lua_settable(L, -3);
lua_pushstring(L, "tid");
lua_pushinteger(L, (lua_Integer) ws_record->tid);
lua_settable(L, -3);
lua_pushstring(L, "vhost");
lua_pushstring(L, ws_record->vhost);
lua_settable(L, -3);
#ifdef HAVE_TIMES
lua_pushstring(L, "stimes");
lua_pushnumber(L, ws_record->times.tms_stime);
lua_settable(L, -3);
lua_pushstring(L, "utimes");
lua_pushnumber(L, ws_record->times.tms_utime);
lua_settable(L, -3);
#endif
return 1;
}
return 0;
}
/*
* lua_ap_clock; r:clock() - Returns timestamp with microsecond precision
*/
static int lua_ap_clock(lua_State *L)
{
apr_time_t now;
now = apr_time_now();
lua_pushnumber(L, (lua_Number) now);
return 1;
}
/*
* lua_ap_add_input_filter; r:add_input_filter(name) - Adds an input filter to
* the chain
*/
static int lua_ap_add_input_filter(lua_State *L)
{
request_rec *r;
const char *filterName;
ap_filter_rec_t *filter;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
filterName = lua_tostring(L, 2);
filter = ap_get_input_filter_handle(filterName);
if (filter) {
ap_add_input_filter_handle(filter, NULL, r, r->connection);
lua_pushboolean(L, 1);
} else
lua_pushboolean(L, 0);
return 1;
}
/*
* lua_ap_module_info; r:module_info(mod_name) - Returns information about a
* loaded module
*/
static int lua_ap_module_info(lua_State *L)
{
const char *moduleName;
module *mod;
luaL_checktype(L, 1, LUA_TSTRING);
moduleName = lua_tostring(L, 1);
mod = ap_find_linked_module(moduleName);
if (mod && mod->cmds) {
const command_rec *cmd;
lua_newtable(L);
lua_pushstring(L, "commands");
lua_newtable(L);
for (cmd = mod->cmds; cmd->name; ++cmd) {
lua_pushstring(L, cmd->name);
lua_pushstring(L, cmd->errmsg);
lua_settable(L, -3);
}
lua_settable(L, -3);
return 1;
}
return 0;
}
/*
* lua_ap_runtime_dir_relative: r:runtime_dir_relative(file): Returns the
* filename as relative to the runtime dir
*/
static int lua_ap_runtime_dir_relative(lua_State *L)
{
request_rec *r;
const char *file;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
file = luaL_optstring(L, 2, ".");
lua_pushstring(L, ap_runtime_dir_relative(r->pool, file));
return 1;
}
/*
* lua_ap_set_document_root; r:set_document_root(path) - sets the current doc
* root for the request
*/
static int lua_ap_set_document_root(lua_State *L)
{
request_rec *r;
const char *root;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
root = lua_tostring(L, 2);
ap_set_document_root(r, root);
return 0;
}
/*
* lua_ap_getdir; r:get_direntries(directory) - Gets all entries of a
* directory and returns the directory info as a table
*/
static int lua_ap_getdir(lua_State *L)
{
request_rec *r;
apr_dir_t *thedir;
apr_finfo_t file_info;
apr_status_t status;
const char *directory;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
directory = lua_tostring(L, 2);
if (apr_dir_open(&thedir, directory, r->pool) == APR_SUCCESS) {
int i = 0;
lua_newtable(L);
do {
status = apr_dir_read(&file_info, APR_FINFO_NAME, thedir);
if (APR_STATUS_IS_INCOMPLETE(status)) {
continue; /* ignore un-stat()able files */
}
else if (status != APR_SUCCESS) {
break;
}
lua_pushinteger(L, ++i);
lua_pushstring(L, file_info.name);
lua_settable(L, -3);
} while (1);
apr_dir_close(thedir);
return 1;
}
else {
return 0;
}
}
/*
* lua_ap_stat; r:stat(filename [, wanted]) - Runs stat on a file and
* returns the file info as a table
*/
static int lua_ap_stat(lua_State *L)
{
request_rec *r;
const char *filename;
apr_finfo_t file_info;
apr_int32_t wanted;
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checktype(L, 2, LUA_TSTRING);
r = ap_lua_check_request_rec(L, 1);
filename = lua_tostring(L, 2);
wanted = luaL_optinteger(L, 3, APR_FINFO_MIN);
if (apr_stat(&file_info, filename, wanted, r->pool) == OK) {
lua_newtable(L);
if (wanted & APR_FINFO_MTIME) {
lua_pushstring(L, "mtime");
lua_pushnumber(L, (lua_Number) file_info.mtime);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_ATIME) {
lua_pushstring(L, "atime");
lua_pushnumber(L, (lua_Number) file_info.atime);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_CTIME) {
lua_pushstring(L, "ctime");
lua_pushnumber(L, (lua_Number) file_info.ctime);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_SIZE) {
lua_pushstring(L, "size");
lua_pushnumber(L, (lua_Number) file_info.size);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_TYPE) {
lua_pushstring(L, "filetype");
lua_pushinteger(L, file_info.filetype);
lua_settable(L, -3);
}
if (wanted & APR_FINFO_PROT) {
lua_pushstring(L, "protection");
lua_pushinteger(L, file_info.protection);
lua_settable(L, -3);
}
return 1;
}
else {
return 0;
}
}
/*
* lua_ap_loaded_modules; r:loaded_modules() - Returns a list of loaded modules
*/
static int lua_ap_loaded_modules(lua_State *L)
{
int i;
lua_newtable(L);
for (i = 0; ap_loaded_modules[i] && ap_loaded_modules[i]->name; i++) {
lua_pushinteger(L, i + 1);
lua_pushstring(L, ap_loaded_modules[i]->name);
lua_settable(L, -3);
}
return 1;
}
/*
* lua_ap_server_info; r:server_info() - Returns server info, such as the
* executable filename, server root, mpm etc
*/
static int lua_ap_server_info(lua_State *L)
{
lua_newtable(L);
lua_pushstring(L, "server_executable");
lua_pushstring(L, ap_server_argv0);
lua_settable(L, -3);
lua_pushstring(L, "server_root");
lua_pushstring(L, ap_server_root);
lua_settable(L, -3);
lua_pushstring(L, "scoreboard_fname");
lua_pushstring(L, ap_scoreboard_fname);
lua_settable(L, -3);
lua_pushstring(L, "server_mpm");
lua_pushstring(L, ap_show_mpm());
lua_settable(L, -3);
return 1;
}
/*
* === Auto-scraped functions ===
*/
/**
* ap_set_context_info: Set context_prefix and context_document_root.
* @param r The request
* @param prefix the URI prefix, without trailing slash
* @param document_root the corresponding directory on disk, without trailing
* slash
* @note If one of prefix of document_root is NULL, the corrsponding
* property will not be changed.
*/
static int lua_ap_set_context_info(lua_State *L)
{
request_rec *r;
const char *prefix;
const char *document_root;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
prefix = lua_tostring(L, 2);
luaL_checktype(L, 3, LUA_TSTRING);
document_root = lua_tostring(L, 3);
ap_set_context_info(r, prefix, document_root);
return 0;
}
/**
* ap_os_escape_path (apr_pool_t *p, const char *path, int partial)
* convert an OS path to a URL in an OS dependant way.
* @param p The pool to allocate from
* @param path The path to convert
* @param partial if set, assume that the path will be appended to something
* with a '/' in it (and thus does not prefix "./")
* @return The converted URL
*/
static int lua_ap_os_escape_path(lua_State *L)
{
char *returnValue;
request_rec *r;
const char *path;
int partial = 0;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
path = lua_tostring(L, 2);
if (lua_isboolean(L, 3))
partial = lua_toboolean(L, 3);
returnValue = ap_os_escape_path(r->pool, path, partial);
lua_pushstring(L, returnValue);
return 1;
}
/**
* ap_escape_logitem (apr_pool_t *p, const char *str)
* Escape a string for logging
* @param p The pool to allocate from
* @param str The string to escape
* @return The escaped string
*/
static int lua_ap_escape_logitem(lua_State *L)
{
char *returnValue;
request_rec *r;
const char *str;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
str = lua_tostring(L, 2);
returnValue = ap_escape_logitem(r->pool, str);
lua_pushstring(L, returnValue);
return 1;
}
/**
* ap_strcmp_match (const char *str, const char *expected)
* Determine if a string matches a patterm containing the wildcards '?' or '*'
* @param str The string to check
* @param expected The pattern to match against
* @param ignoreCase Whether to ignore case when matching
* @return 1 if the two strings match, 0 otherwise
*/
static int lua_ap_strcmp_match(lua_State *L)
{
int returnValue;
const char *str;
const char *expected;
int ignoreCase = 0;
luaL_checktype(L, 1, LUA_TSTRING);
str = lua_tostring(L, 1);
luaL_checktype(L, 2, LUA_TSTRING);
expected = lua_tostring(L, 2);
if (lua_isboolean(L, 3))
ignoreCase = lua_toboolean(L, 3);
if (!ignoreCase)
returnValue = ap_strcmp_match(str, expected);
else
returnValue = ap_strcasecmp_match(str, expected);
lua_pushboolean(L, (!returnValue));
return 1;
}
/**
* ap_set_keepalive (request_rec *r)
* Set the keepalive status for this request
* @param r The current request
* @return 1 if keepalive can be set, 0 otherwise
*/
static int lua_ap_set_keepalive(lua_State *L)
{
int returnValue;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
returnValue = ap_set_keepalive(r);
lua_pushboolean(L, returnValue);
return 1;
}
/**
* ap_make_etag (request_rec *r, int force_weak)
* Construct an entity tag from the resource information. If it's a real
* file, build in some of the file characteristics.
* @param r The current request
* @param force_weak Force the entity tag to be weak - it could be modified
* again in as short an interval.
* @return The entity tag
*/
static int lua_ap_make_etag(lua_State *L)
{
char *returnValue;
request_rec *r;
int force_weak;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TBOOLEAN);
force_weak = luaL_optint(L, 2, 0);
returnValue = ap_make_etag(r, force_weak);
lua_pushstring(L, returnValue);
return 1;
}
/**
* ap_send_interim_response (request_rec *r, int send_headers)
* Send an interim (HTTP 1xx) response immediately.
* @param r The request
* @param send_headers Whether to send&clear headers in r->headers_out
*/
static int lua_ap_send_interim_response(lua_State *L)
{
request_rec *r;
int send_headers = 0;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
if (lua_isboolean(L, 2))
send_headers = lua_toboolean(L, 2);
ap_send_interim_response(r, send_headers);
return 0;
}
/**
* ap_custom_response (request_rec *r, int status, const char *string)
* Install a custom response handler for a given status
* @param r The current request
* @param status The status for which the custom response should be used
* @param string The custom response. This can be a static string, a file
* or a URL
*/
static int lua_ap_custom_response(lua_State *L)
{
request_rec *r;
int status;
const char *string;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
luaL_checktype(L, 2, LUA_TNUMBER);
status = lua_tointeger(L, 2);
luaL_checktype(L, 3, LUA_TSTRING);
string = lua_tostring(L, 3);
ap_custom_response(r, status, string);
return 0;
}
/**
* ap_exists_config_define (const char *name)
* Check for a definition from the server command line
* @param name The define to check for
* @return 1 if defined, 0 otherwise
*/
static int lua_ap_exists_config_define(lua_State *L)
{
int returnValue;
const char *name;
luaL_checktype(L, 1, LUA_TSTRING);
name = lua_tostring(L, 1);
returnValue = ap_exists_config_define(name);
lua_pushboolean(L, returnValue);
return 1;
}
static int lua_ap_get_server_name_for_url(lua_State *L)
{
const char *servername;
request_rec *r;
luaL_checktype(L, 1, LUA_TUSERDATA);
r = ap_lua_check_request_rec(L, 1);
servername = ap_get_server_name_for_url(r);
lua_pushstring(L, servername);
return 1;
}
/* ap_state_query (int query_code) item starts a new field */
static int lua_ap_state_query(lua_State *L)
{
int returnValue;
int query_code;
luaL_checktype(L, 1, LUA_TNUMBER);
query_code = lua_tointeger(L, 1);
returnValue = ap_state_query(query_code);
lua_pushinteger(L, returnValue);
return 1;
}
/*
* lua_ap_usleep; r:usleep(microseconds)
* - Sleep for the specified number of microseconds.
*/
static int lua_ap_usleep(lua_State *L)
{
apr_interval_time_t msec;
luaL_checktype(L, 1, LUA_TNUMBER);
msec = (apr_interval_time_t)lua_tonumber(L, 1);
apr_sleep(msec);
return 0;
}
/* END dispatch methods for request_rec fields */
static int req_dispatch(lua_State *L)
{
apr_hash_t *dispatch;
req_fun_t *rft;
request_rec *r = ap_lua_check_request_rec(L, 1);
const char *name = luaL_checkstring(L, 2);
lua_pop(L, 2);
lua_getfield(L, LUA_REGISTRYINDEX, "Apache2.Request.dispatch");
dispatch = lua_touserdata(L, 1);
lua_pop(L, 1);
rft = apr_hash_get(dispatch, name, APR_HASH_KEY_STRING);
if (rft) {
switch (rft->type) {
case APL_REQ_FUNTYPE_TABLE:{
req_table_t *rs;
req_field_apr_table_f func = (req_field_apr_table_f)rft->fun;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01486)
"request_rec->dispatching %s -> apr table",
name);
rs = (*func)(r);
ap_lua_push_apr_table(L, rs);
return 1;
}
case APL_REQ_FUNTYPE_LUACFUN:{
lua_CFunction func = (lua_CFunction)rft->fun;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01487)
"request_rec->dispatching %s -> lua_CFunction",
name);
lua_pushcfunction(L, func);
return 1;
}
case APL_REQ_FUNTYPE_STRING:{
req_field_string_f func = (req_field_string_f)rft->fun;
char *rs;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01488)
"request_rec->dispatching %s -> string", name);
rs = (*func) (r);
lua_pushstring(L, rs);
return 1;
}
case APL_REQ_FUNTYPE_INT:{
req_field_int_f func = (req_field_int_f)rft->fun;
int rs;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01489)
"request_rec->dispatching %s -> int", name);
rs = (*func) (r);
lua_pushinteger(L, rs);
return 1;
}
case APL_REQ_FUNTYPE_BOOLEAN:{
req_field_int_f func = (req_field_int_f)rft->fun;
int rs;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01490)
"request_rec->dispatching %s -> boolean", name);
rs = (*func) (r);
lua_pushboolean(L, rs);
return 1;
}
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01491) "nothing for %s", name);
return 0;
}
/* helper function for the logging functions below */
static int req_log_at(lua_State *L, int level)
{
const char *msg;
request_rec *r = ap_lua_check_request_rec(L, 1);
lua_Debug dbg;
lua_getstack(L, 1, &dbg);
lua_getinfo(L, "Sl", &dbg);
msg = luaL_checkstring(L, 2);
ap_log_rerror(dbg.source, dbg.currentline, APLOG_MODULE_INDEX, level, 0,
r, "%s", msg);
return 0;
}
/* r:debug(String) and friends which use apache logging */
static int req_emerg(lua_State *L)
{
return req_log_at(L, APLOG_EMERG);
}
static int req_alert(lua_State *L)
{
return req_log_at(L, APLOG_ALERT);
}
static int req_crit(lua_State *L)
{
return req_log_at(L, APLOG_CRIT);
}
static int req_err(lua_State *L)
{
return req_log_at(L, APLOG_ERR);
}
static int req_warn(lua_State *L)
{
return req_log_at(L, APLOG_WARNING);
}
static int req_notice(lua_State *L)
{
return req_log_at(L, APLOG_NOTICE);
}
static int req_info(lua_State *L)
{
return req_log_at(L, APLOG_INFO);
}
static int req_debug(lua_State *L)
{
return req_log_at(L, APLOG_DEBUG);
}
static int lua_ivm_get(lua_State *L)
{
const char *key, *raw_key;
apr_pool_t *pool;
lua_ivm_object *object = NULL;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
raw_key = apr_pstrcat(r->pool, "lua_ivm_", key, NULL);
apr_global_mutex_lock(lua_ivm_mutex);
pool = *((apr_pool_t**) apr_shm_baseaddr_get(lua_ivm_shm));
apr_pool_userdata_get((void **)&object, raw_key, pool);
if (object) {
if (object->type == LUA_TBOOLEAN) lua_pushboolean(L, (int) object->number);
else if (object->type == LUA_TNUMBER) lua_pushnumber(L, object->number);
else if (object->type == LUA_TSTRING) lua_pushlstring(L, object->vb.buf, object->size);
apr_global_mutex_unlock(lua_ivm_mutex);
return 1;
}
else {
apr_global_mutex_unlock(lua_ivm_mutex);
return 0;
}
}
static int lua_ivm_set(lua_State *L)
{
const char *key, *raw_key;
const char *value = NULL;
apr_pool_t *pool;
size_t str_len;
lua_ivm_object *object = NULL;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
luaL_checkany(L, 3);
raw_key = apr_pstrcat(r->pool, "lua_ivm_", key, NULL);
apr_global_mutex_lock(lua_ivm_mutex);
pool = *((apr_pool_t**) apr_shm_baseaddr_get(lua_ivm_shm));
apr_pool_userdata_get((void **)&object, raw_key, pool);
if (!object) {
object = apr_pcalloc(pool, sizeof(lua_ivm_object));
ap_varbuf_init(pool, &object->vb, 2);
object->size = 1;
object->vb_size = 1;
}
object->type = lua_type(L, 3);
if (object->type == LUA_TNUMBER) object->number = lua_tonumber(L, 3);
else if (object->type == LUA_TBOOLEAN) object->number = lua_tonumber(L, 3);
else if (object->type == LUA_TSTRING) {
value = lua_tolstring(L, 3, &str_len);
str_len++; /* add trailing \0 */
if ( str_len > object->vb_size) {
ap_varbuf_grow(&object->vb, str_len);
object->vb_size = str_len;
}
object->size = str_len-1;
memset(object->vb.buf, 0, str_len);
memcpy(object->vb.buf, value, str_len-1);
}
apr_pool_userdata_set(object, raw_key, NULL, pool);
apr_global_mutex_unlock(lua_ivm_mutex);
return 0;
}
static int lua_get_cookie(lua_State *L)
{
const char *key, *cookie;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
cookie = NULL;
ap_cookie_read(r, key, &cookie, 0);
if (cookie != NULL) {
lua_pushstring(L, cookie);
return 1;
}
return 0;
}
static int lua_set_cookie(lua_State *L)
{
const char *key, *value, *out, *path = "", *domain = "";
const char *strexpires = "", *strdomain = "", *strpath = "";
int secure = 0, expires = 0, httponly = 0;
char cdate[APR_RFC822_DATE_LEN+1];
apr_status_t rv;
request_rec *r = ap_lua_check_request_rec(L, 1);
/* New >= 2.4.8 method: */
if (lua_istable(L, 2)) {
/* key */
lua_pushstring(L, "key");
lua_gettable(L, -2);
key = luaL_checkstring(L, -1);
lua_pop(L, 1);
/* value */
lua_pushstring(L, "value");
lua_gettable(L, -2);
value = luaL_checkstring(L, -1);
lua_pop(L, 1);
/* expiry */
lua_pushstring(L, "expires");
lua_gettable(L, -2);
expires = luaL_optint(L, -1, 0);
lua_pop(L, 1);
/* secure */
lua_pushstring(L, "secure");
lua_gettable(L, -2);
if (lua_isboolean(L, -1)) {
secure = lua_toboolean(L, -1);
}
lua_pop(L, 1);
/* httponly */
lua_pushstring(L, "httponly");
lua_gettable(L, -2);
if (lua_isboolean(L, -1)) {
httponly = lua_toboolean(L, -1);
}
lua_pop(L, 1);
/* path */
lua_pushstring(L, "path");
lua_gettable(L, -2);
path = luaL_optstring(L, -1, "/");
lua_pop(L, 1);
/* domain */
lua_pushstring(L, "domain");
lua_gettable(L, -2);
domain = luaL_optstring(L, -1, "");
lua_pop(L, 1);
}
/* Old <= 2.4.7 method: */
else {
key = luaL_checkstring(L, 2);
value = luaL_checkstring(L, 3);
secure = 0;
if (lua_isboolean(L, 4)) {
secure = lua_toboolean(L, 4);
}
expires = luaL_optinteger(L, 5, 0);
}
/* Calculate expiry if set */
if (expires > 0) {
rv = apr_rfc822_date(cdate, apr_time_from_sec(expires));
if (rv == APR_SUCCESS) {
strexpires = apr_psprintf(r->pool, "Expires=%s;", cdate);
}
}
/* Create path segment */
if (path != NULL && strlen(path) > 0) {
strpath = apr_psprintf(r->pool, "Path=%s;", path);
}
/* Create domain segment */
if (domain != NULL && strlen(domain) > 0) {
/* Domain does NOT like quotes in most browsers, so let's avoid that */
strdomain = apr_psprintf(r->pool, "Domain=%s;", domain);
}
/* URL-encode key/value */
value = ap_escape_urlencoded(r->pool, value);
key = ap_escape_urlencoded(r->pool, key);
/* Create the header */
out = apr_psprintf(r->pool, "%s=%s; %s %s %s %s %s", key, value,
secure ? "Secure;" : "",
expires ? strexpires : "",
httponly ? "HttpOnly;" : "",
strlen(strdomain) ? strdomain : "",
strlen(strpath) ? strpath : "");
apr_table_add(r->err_headers_out, "Set-Cookie", out);
return 0;
}
static apr_uint64_t ap_ntoh64(const apr_uint64_t *input)
{
apr_uint64_t rval;
unsigned char *data = (unsigned char *)&rval;
if (APR_IS_BIGENDIAN) {
return *input;
}
data[0] = *input >> 56;
data[1] = *input >> 48;
data[2] = *input >> 40;
data[3] = *input >> 32;
data[4] = *input >> 24;
data[5] = *input >> 16;
data[6] = *input >> 8;
data[7] = *input >> 0;
return rval;
}
static int lua_websocket_greet(lua_State *L)
{
const char *key = NULL;
unsigned char digest[APR_SHA1_DIGESTSIZE];
apr_sha1_ctx_t sha1;
char *encoded;
int encoded_len;
request_rec *r = ap_lua_check_request_rec(L, 1);
key = apr_table_get(r->headers_in, "Sec-WebSocket-Key");
if (key != NULL) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Got websocket key: %s", key);
key = apr_pstrcat(r->pool, key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
NULL);
apr_sha1_init(&sha1);
apr_sha1_update(&sha1, key, strlen(key));
apr_sha1_final(digest, &sha1);
encoded_len = apr_base64_encode_len(APR_SHA1_DIGESTSIZE);
if (encoded_len) {
encoded = apr_palloc(r->pool, encoded_len);
encoded_len = apr_base64_encode(encoded, (char*) digest, APR_SHA1_DIGESTSIZE);
r->status = 101;
apr_table_set(r->headers_out, "Upgrade", "websocket");
apr_table_set(r->headers_out, "Connection", "Upgrade");
apr_table_set(r->headers_out, "Sec-WebSocket-Accept", encoded);
/* Trick httpd into NOT using the chunked filter, IMPORTANT!!!111*/
apr_table_set(r->headers_out, "Transfer-Encoding", "chunked");
r->clength = 0;
r->bytes_sent = 0;
r->read_chunked = 0;
ap_rflush(r);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Upgraded from HTTP to Websocket");
lua_pushboolean(L, 1);
return 1;
}
}
ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r, APLOGNO(02666)
"Websocket: Upgrade from HTTP to Websocket failed");
return 0;
}
static apr_status_t lua_websocket_readbytes(conn_rec* c, char* buffer,
apr_off_t len)
{
apr_bucket_brigade *brigade = apr_brigade_create(c->pool, c->bucket_alloc);
apr_status_t rv;
rv = ap_get_brigade(c->input_filters, brigade, AP_MODE_READBYTES,
APR_BLOCK_READ, len);
if (rv == APR_SUCCESS) {
if (!APR_BRIGADE_EMPTY(brigade)) {
apr_bucket* bucket = APR_BRIGADE_FIRST(brigade);
const char* data = NULL;
apr_size_t data_length = 0;
rv = apr_bucket_read(bucket, &data, &data_length, APR_BLOCK_READ);
if (rv == APR_SUCCESS) {
memcpy(buffer, data, len);
}
apr_bucket_delete(bucket);
}
}
apr_brigade_cleanup(brigade);
return rv;
}
static int lua_websocket_peek(lua_State *L)
{
apr_status_t rv;
apr_bucket_brigade *brigade;
request_rec *r = ap_lua_check_request_rec(L, 1);
brigade = apr_brigade_create(r->connection->pool,
r->connection->bucket_alloc);
rv = ap_get_brigade(r->connection->input_filters, brigade,
AP_MODE_READBYTES, APR_NONBLOCK_READ, 1);
if (rv == APR_SUCCESS) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
apr_brigade_cleanup(brigade);
return 1;
}
static int lua_websocket_read(lua_State *L)
{
apr_socket_t *sock;
apr_status_t rv;
int n = 0;
apr_size_t len = 1;
apr_size_t plen = 0;
unsigned short payload_short = 0;
apr_uint64_t payload_long = 0;
unsigned char *mask_bytes;
char byte;
int plaintext;
request_rec *r = ap_lua_check_request_rec(L, 1);
plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1;
mask_bytes = apr_pcalloc(r->pool, 4);
sock = ap_get_conn_socket(r->connection);
/* Get opcode and FIN bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
unsigned char ubyte, fin, opcode, mask, payload;
ubyte = (unsigned char)byte;
/* fin bit is the first bit */
fin = ubyte >> (CHAR_BIT - 1);
/* opcode is the last four bits (there's 3 reserved bits we don't care about) */
opcode = ubyte & 0xf;
/* Get the payload length and mask bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
ubyte = (unsigned char)byte;
/* Mask is the first bit */
mask = ubyte >> (CHAR_BIT - 1);
/* Payload is the last 7 bits */
payload = ubyte & 0x7f;
plen = payload;
/* Extended payload? */
if (payload == 126) {
len = 2;
if (plaintext) {
/* XXX: apr_socket_recv does not receive len bits, only up to len bits! */
rv = apr_socket_recv(sock, (char*) &payload_short, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_short, 2);
}
payload_short = ntohs(payload_short);
if (rv == APR_SUCCESS) {
plen = payload_short;
}
else {
return 0;
}
}
/* Super duper extended payload? */
if (payload == 127) {
len = 8;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) &payload_long, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_long, 8);
}
if (rv == APR_SUCCESS) {
plen = ap_ntoh64(&payload_long);
}
else {
return 0;
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s",
plen,
(payload >= 126) ? "extra payload" : "no extra payload",
mask ? "on" : "off",
fin ? "This is a final frame" : "more to follow");
if (mask) {
len = 4;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) mask_bytes, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) mask_bytes, 4);
}
if (rv != APR_SUCCESS) {
return 0;
}
}
if (plen < (HUGE_STRING_LEN*1024) && plen > 0) {
apr_size_t remaining = plen;
apr_size_t received;
apr_off_t at = 0;
char *buffer = apr_palloc(r->pool, plen+1);
buffer[plen] = 0;
if (plaintext) {
while (remaining > 0) {
received = remaining;
rv = apr_socket_recv(sock, buffer+at, &received);
if (received > 0 ) {
remaining -= received;
at += received;
}
}
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack",
at);
}
else {
rv = lua_websocket_readbytes(r->connection, buffer,
remaining);
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\
"pushed to Lua stack",
remaining);
}
if (mask) {
for (n = 0; n < plen; n++) {
buffer[n] ^= mask_bytes[n%4];
}
}
lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */
lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */
return 2;
}
/* Decide if we need to react to the opcode or not */
if (opcode == 0x09) { /* ping */
char frame[2];
plen = 2;
frame[0] = 0x8A;
frame[1] = 0;
apr_socket_send(sock, frame, &plen); /* Pong! */
lua_websocket_read(L); /* read the next frame instead */
}
}
}
return 0;
}
static int lua_websocket_write(lua_State *L)
{
const char *string;
apr_status_t rv;
size_t len;
int raw = 0;
char prelude;
request_rec *r = ap_lua_check_request_rec(L, 1);
if (lua_isboolean(L, 3)) {
raw = lua_toboolean(L, 3);
}
string = lua_tolstring(L, 2, &len);
if (raw != 1) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Writing framed message to client");
prelude = 0x81; /* text frame, FIN */
ap_rputc(prelude, r);
if (len < 126) {
ap_rputc(len, r);
}
else if (len < 65535) {
apr_uint16_t slen = len;
ap_rputc(126, r);
slen = htons(slen);
ap_rwrite((char*) &slen, 2, r);
}
else {
apr_uint64_t llen = len;
ap_rputc(127, r);
llen = ap_ntoh64(&llen); /* ntoh doubles as hton */
ap_rwrite((char*) &llen, 8, r);
}
}
else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Writing raw message to client");
}
ap_rwrite(string, len, r);
rv = ap_rflush(r);
if (rv == APR_SUCCESS) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
static int lua_websocket_close(lua_State *L)
{
apr_socket_t *sock;
char prelude[2];
request_rec *r = ap_lua_check_request_rec(L, 1);
sock = ap_get_conn_socket(r->connection);
/* Send a header that says: socket is closing. */
prelude[0] = 0x88; /* closing socket opcode */
prelude[1] = 0; /* zero length frame */
ap_rwrite(prelude, 2, r);
/* Close up tell the MPM and filters to back off */
apr_socket_close(sock);
r->output_filters = NULL;
r->connection->keepalive = AP_CONN_CLOSE;
return 0;
}
static int lua_websocket_ping(lua_State *L)
{
apr_socket_t *sock;
apr_size_t plen;
char prelude[2];
apr_status_t rv;
request_rec *r = ap_lua_check_request_rec(L, 1);
sock = ap_get_conn_socket(r->connection);
/* Send a header that says: PING. */
prelude[0] = 0x89; /* ping opcode */
prelude[1] = 0;
plen = 2;
apr_socket_send(sock, prelude, &plen);
/* Get opcode and FIN bit from pong */
plen = 2;
rv = apr_socket_recv(sock, prelude, &plen);
if (rv == APR_SUCCESS) {
unsigned char opcode = prelude[0];
unsigned char len = prelude[1];
unsigned char mask = len >> 7;
if (mask) len -= 128;
plen = len;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Got PONG opcode: %x", opcode);
if (opcode == 0x8A) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
if (plen > 0) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: Reading %" APR_SIZE_T_FMT " bytes of PONG", plen);
return 1;
}
if (mask) {
plen = 2;
apr_socket_recv(sock, prelude, &plen);
plen = 2;
apr_socket_recv(sock, prelude, &plen);
}
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
#define APLUA_REQ_TRACE(lev) static int req_trace##lev(lua_State *L) \
{ \
return req_log_at(L, APLOG_TRACE##lev); \
}
APLUA_REQ_TRACE(1)
APLUA_REQ_TRACE(2)
APLUA_REQ_TRACE(3)
APLUA_REQ_TRACE(4)
APLUA_REQ_TRACE(5)
APLUA_REQ_TRACE(6)
APLUA_REQ_TRACE(7)
APLUA_REQ_TRACE(8)
/* handle r.status = 201 */
static int req_newindex(lua_State *L)
{
const char *key;
/* request_rec* r = lua_touserdata(L, lua_upvalueindex(1)); */
/* const char* key = luaL_checkstring(L, -2); */
request_rec *r = ap_lua_check_request_rec(L, 1);
key = luaL_checkstring(L, 2);
if (0 == strcmp("args", key)) {
const char *value = luaL_checkstring(L, 3);
r->args = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("content_type", key)) {
const char *value = luaL_checkstring(L, 3);
ap_set_content_type(r, apr_pstrdup(r->pool, value));
return 0;
}
if (0 == strcmp("filename", key)) {
const char *value = luaL_checkstring(L, 3);
r->filename = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("handler", key)) {
const char *value = luaL_checkstring(L, 3);
r->handler = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("proxyreq", key)) {
int value = luaL_checkinteger(L, 3);
r->proxyreq = value;
return 0;
}
if (0 == strcmp("status", key)) {
int code = luaL_checkinteger(L, 3);
r->status = code;
return 0;
}
if (0 == strcmp("uri", key)) {
const char *value = luaL_checkstring(L, 3);
r->uri = apr_pstrdup(r->pool, value);
return 0;
}
if (0 == strcmp("user", key)) {
const char *value = luaL_checkstring(L, 3);
r->user = apr_pstrdup(r->pool, value);
return 0;
}
lua_pushstring(L,
apr_psprintf(r->pool,
"Property [%s] may not be set on a request_rec",
key));
lua_error(L);
return 0;
}
/* helper function for walking config trees */
static void read_cfg_tree(lua_State *L, request_rec *r, ap_directive_t *rcfg) {
int x = 0;
const char* value;
ap_directive_t *cfg;
lua_newtable(L);
for (cfg = rcfg; cfg; cfg = cfg->next) {
x++;
lua_pushnumber(L, x);
lua_newtable(L);
value = apr_psprintf(r->pool, "%s %s", cfg->directive, cfg->args);
lua_pushstring(L, "directive");
lua_pushstring(L, value);
lua_settable(L, -3);
lua_pushstring(L, "file");
lua_pushstring(L, cfg->filename);
lua_settable(L, -3);
lua_pushstring(L, "line");
lua_pushnumber(L, cfg->line_num);
lua_settable(L, -3);
if (cfg->first_child) {
lua_pushstring(L, "children");
read_cfg_tree(L, r, cfg->first_child);
lua_settable(L, -3);
}
lua_settable(L, -3);
}
}
static int lua_ap_get_config(lua_State *L) {
request_rec *r = ap_lua_check_request_rec(L, 1);
read_cfg_tree(L, r, ap_conftree);
return 1;
}
/* Hack, hack, hack...! TODO: Make this actually work properly */
static int lua_ap_get_active_config(lua_State *L) {
ap_directive_t *subdir;
ap_directive_t *dir = ap_conftree;
request_rec *r = ap_lua_check_request_rec(L, 1);
for (dir = ap_conftree; dir; dir = dir->next) {
if (ap_strcasestr(dir->directive, "<virtualhost") && dir->first_child) {
for (subdir = dir->first_child; subdir; subdir = subdir->next) {
if (ap_strcasecmp_match(subdir->directive, "servername") &&
!ap_strcasecmp_match(r->hostname, subdir->args)) {
read_cfg_tree(L, r, dir->first_child);
return 1;
}
if (ap_strcasecmp_match(subdir->directive, "serveralias") &&
!ap_strcasecmp_match(r->hostname, subdir->args)) {
read_cfg_tree(L, r, dir->first_child);
return 1;
}
}
}
}
return 0;
}
static const struct luaL_Reg request_methods[] = {
{"__index", req_dispatch},
{"__newindex", req_newindex},
/* {"__newindex", req_set_field}, */
{NULL, NULL}
};
static const struct luaL_Reg connection_methods[] = {
{NULL, NULL}
};
static const char* lua_ap_auth_name(request_rec* r)
{
const char *name;
name = ap_auth_name(r);
return name ? name : "";
}
static const char* lua_ap_get_server_name(request_rec* r)
{
const char *name;
name = ap_get_server_name(r);
return name ? name : "localhost";
}
static const struct luaL_Reg server_methods[] = {
{NULL, NULL}
};
static req_fun_t *makefun(const void *fun, int type, apr_pool_t *pool)
{
req_fun_t *rft = apr_palloc(pool, sizeof(req_fun_t));
rft->fun = fun;
rft->type = type;
return rft;
}
void ap_lua_load_request_lmodule(lua_State *L, apr_pool_t *p)
{
apr_hash_t *dispatch = apr_hash_make(p);
apr_hash_set(dispatch, "puts", APR_HASH_KEY_STRING,
makefun(&req_puts, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "write", APR_HASH_KEY_STRING,
makefun(&req_write, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "document_root", APR_HASH_KEY_STRING,
makefun(&req_document_root, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "context_prefix", APR_HASH_KEY_STRING,
makefun(&req_context_prefix, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "context_document_root", APR_HASH_KEY_STRING,
makefun(&req_context_document_root, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "parseargs", APR_HASH_KEY_STRING,
makefun(&req_parseargs, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "parsebody", APR_HASH_KEY_STRING,
makefun(&req_parsebody, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "debug", APR_HASH_KEY_STRING,
makefun(&req_debug, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "info", APR_HASH_KEY_STRING,
makefun(&req_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "notice", APR_HASH_KEY_STRING,
makefun(&req_notice, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "warn", APR_HASH_KEY_STRING,
makefun(&req_warn, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "err", APR_HASH_KEY_STRING,
makefun(&req_err, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "crit", APR_HASH_KEY_STRING,
makefun(&req_crit, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "alert", APR_HASH_KEY_STRING,
makefun(&req_alert, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "emerg", APR_HASH_KEY_STRING,
makefun(&req_emerg, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace1", APR_HASH_KEY_STRING,
makefun(&req_trace1, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace2", APR_HASH_KEY_STRING,
makefun(&req_trace2, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace3", APR_HASH_KEY_STRING,
makefun(&req_trace3, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace4", APR_HASH_KEY_STRING,
makefun(&req_trace4, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace5", APR_HASH_KEY_STRING,
makefun(&req_trace5, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace6", APR_HASH_KEY_STRING,
makefun(&req_trace6, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace7", APR_HASH_KEY_STRING,
makefun(&req_trace7, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "trace8", APR_HASH_KEY_STRING,
makefun(&req_trace8, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "add_output_filter", APR_HASH_KEY_STRING,
makefun(&req_add_output_filter, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "construct_url", APR_HASH_KEY_STRING,
makefun(&req_construct_url, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "escape_html", APR_HASH_KEY_STRING,
makefun(&req_escape_html, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "ssl_var_lookup", APR_HASH_KEY_STRING,
makefun(&req_ssl_var_lookup, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "is_https", APR_HASH_KEY_STRING,
makefun(&req_ssl_is_https_field, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "assbackwards", APR_HASH_KEY_STRING,
makefun(&req_assbackwards_field, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "status", APR_HASH_KEY_STRING,
makefun(&req_status_field, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "protocol", APR_HASH_KEY_STRING,
makefun(&req_protocol_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "range", APR_HASH_KEY_STRING,
makefun(&req_range_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "content_type", APR_HASH_KEY_STRING,
makefun(&req_content_type_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "content_encoding", APR_HASH_KEY_STRING,
makefun(&req_content_encoding_field, APL_REQ_FUNTYPE_STRING,
p));
apr_hash_set(dispatch, "ap_auth_type", APR_HASH_KEY_STRING,
makefun(&req_ap_auth_type_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "unparsed_uri", APR_HASH_KEY_STRING,
makefun(&req_unparsed_uri_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "user", APR_HASH_KEY_STRING,
makefun(&req_user_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "filename", APR_HASH_KEY_STRING,
makefun(&req_filename_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "canonical_filename", APR_HASH_KEY_STRING,
makefun(&req_canonical_filename_field,
APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "path_info", APR_HASH_KEY_STRING,
makefun(&req_path_info_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "args", APR_HASH_KEY_STRING,
makefun(&req_args_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "handler", APR_HASH_KEY_STRING,
makefun(&req_handler_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "hostname", APR_HASH_KEY_STRING,
makefun(&req_hostname_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "uri", APR_HASH_KEY_STRING,
makefun(&req_uri_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "the_request", APR_HASH_KEY_STRING,
makefun(&req_the_request_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "log_id", APR_HASH_KEY_STRING,
makefun(&req_log_id_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "useragent_ip", APR_HASH_KEY_STRING,
makefun(&req_useragent_ip_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "method", APR_HASH_KEY_STRING,
makefun(&req_method_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "proxyreq", APR_HASH_KEY_STRING,
makefun(&req_proxyreq_field, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "headers_in", APR_HASH_KEY_STRING,
makefun(&req_headers_in, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "headers_out", APR_HASH_KEY_STRING,
makefun(&req_headers_out, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "err_headers_out", APR_HASH_KEY_STRING,
makefun(&req_err_headers_out, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "notes", APR_HASH_KEY_STRING,
makefun(&req_notes, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "subprocess_env", APR_HASH_KEY_STRING,
makefun(&req_subprocess_env, APL_REQ_FUNTYPE_TABLE, p));
apr_hash_set(dispatch, "flush", APR_HASH_KEY_STRING,
makefun(&lua_ap_rflush, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "port", APR_HASH_KEY_STRING,
makefun(&req_ap_get_server_port, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "banner", APR_HASH_KEY_STRING,
makefun(&ap_get_server_banner, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "options", APR_HASH_KEY_STRING,
makefun(&lua_ap_options, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "allowoverrides", APR_HASH_KEY_STRING,
makefun(&lua_ap_allowoverrides, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "started", APR_HASH_KEY_STRING,
makefun(&lua_ap_started, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "basic_auth_pw", APR_HASH_KEY_STRING,
makefun(&lua_ap_basic_auth_pw, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "limit_req_body", APR_HASH_KEY_STRING,
makefun(&lua_ap_limit_req_body, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "server_built", APR_HASH_KEY_STRING,
makefun(&ap_get_server_built, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "is_initial_req", APR_HASH_KEY_STRING,
makefun(&lua_ap_is_initial_req, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "remaining", APR_HASH_KEY_STRING,
makefun(&req_remaining_field, APL_REQ_FUNTYPE_INT, p));
apr_hash_set(dispatch, "some_auth_required", APR_HASH_KEY_STRING,
makefun(&lua_ap_some_auth_required, APL_REQ_FUNTYPE_BOOLEAN, p));
apr_hash_set(dispatch, "server_name", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_server_name, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "auth_name", APR_HASH_KEY_STRING,
makefun(&lua_ap_auth_name, APL_REQ_FUNTYPE_STRING, p));
apr_hash_set(dispatch, "sendfile", APR_HASH_KEY_STRING,
makefun(&lua_ap_sendfile, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "dbacquire", APR_HASH_KEY_STRING,
makefun(&lua_db_acquire, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "stat", APR_HASH_KEY_STRING,
makefun(&lua_ap_stat, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "get_direntries", APR_HASH_KEY_STRING,
makefun(&lua_ap_getdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "regex", APR_HASH_KEY_STRING,
makefun(&lua_ap_regex, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "usleep", APR_HASH_KEY_STRING,
makefun(&lua_ap_usleep, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "base64_encode", APR_HASH_KEY_STRING,
makefun(&lua_apr_b64encode, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "base64_decode", APR_HASH_KEY_STRING,
makefun(&lua_apr_b64decode, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "md5", APR_HASH_KEY_STRING,
makefun(&lua_apr_md5, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "sha1", APR_HASH_KEY_STRING,
makefun(&lua_apr_sha1, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "htpassword", APR_HASH_KEY_STRING,
makefun(&lua_apr_htpassword, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "touch", APR_HASH_KEY_STRING,
makefun(&lua_apr_touch, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "mkdir", APR_HASH_KEY_STRING,
makefun(&lua_apr_mkdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "mkrdir", APR_HASH_KEY_STRING,
makefun(&lua_apr_mkrdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "rmdir", APR_HASH_KEY_STRING,
makefun(&lua_apr_rmdir, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "date_parse_rfc", APR_HASH_KEY_STRING,
makefun(&lua_apr_date_parse_rfc, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "escape", APR_HASH_KEY_STRING,
makefun(&lua_ap_escape, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "unescape", APR_HASH_KEY_STRING,
makefun(&lua_ap_unescape, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "mpm_query", APR_HASH_KEY_STRING,
makefun(&lua_ap_mpm_query, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "expr", APR_HASH_KEY_STRING,
makefun(&lua_ap_expr, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "scoreboard_process", APR_HASH_KEY_STRING,
makefun(&lua_ap_scoreboard_process, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "scoreboard_worker", APR_HASH_KEY_STRING,
makefun(&lua_ap_scoreboard_worker, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "clock", APR_HASH_KEY_STRING,
makefun(&lua_ap_clock, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "requestbody", APR_HASH_KEY_STRING,
makefun(&lua_ap_requestbody, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "add_input_filter", APR_HASH_KEY_STRING,
makefun(&lua_ap_add_input_filter, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "module_info", APR_HASH_KEY_STRING,
makefun(&lua_ap_module_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "loaded_modules", APR_HASH_KEY_STRING,
makefun(&lua_ap_loaded_modules, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "runtime_dir_relative", APR_HASH_KEY_STRING,
makefun(&lua_ap_runtime_dir_relative, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "server_info", APR_HASH_KEY_STRING,
makefun(&lua_ap_server_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "set_document_root", APR_HASH_KEY_STRING,
makefun(&lua_ap_set_document_root, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "set_context_info", APR_HASH_KEY_STRING,
makefun(&lua_ap_set_context_info, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "os_escape_path", APR_HASH_KEY_STRING,
makefun(&lua_ap_os_escape_path, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "escape_logitem", APR_HASH_KEY_STRING,
makefun(&lua_ap_escape_logitem, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "strcmp_match", APR_HASH_KEY_STRING,
makefun(&lua_ap_strcmp_match, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "set_keepalive", APR_HASH_KEY_STRING,
makefun(&lua_ap_set_keepalive, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "make_etag", APR_HASH_KEY_STRING,
makefun(&lua_ap_make_etag, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "send_interim_response", APR_HASH_KEY_STRING,
makefun(&lua_ap_send_interim_response, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "custom_response", APR_HASH_KEY_STRING,
makefun(&lua_ap_custom_response, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "exists_config_define", APR_HASH_KEY_STRING,
makefun(&lua_ap_exists_config_define, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "state_query", APR_HASH_KEY_STRING,
makefun(&lua_ap_state_query, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "get_server_name_for_url", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_server_name_for_url, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "ivm_get", APR_HASH_KEY_STRING,
makefun(&lua_ivm_get, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "ivm_set", APR_HASH_KEY_STRING,
makefun(&lua_ivm_set, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "getcookie", APR_HASH_KEY_STRING,
makefun(&lua_get_cookie, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "setcookie", APR_HASH_KEY_STRING,
makefun(&lua_set_cookie, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsupgrade", APR_HASH_KEY_STRING,
makefun(&lua_websocket_greet, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsread", APR_HASH_KEY_STRING,
makefun(&lua_websocket_read, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wspeek", APR_HASH_KEY_STRING,
makefun(&lua_websocket_peek, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wswrite", APR_HASH_KEY_STRING,
makefun(&lua_websocket_write, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsclose", APR_HASH_KEY_STRING,
makefun(&lua_websocket_close, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "wsping", APR_HASH_KEY_STRING,
makefun(&lua_websocket_ping, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "config", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_config, APL_REQ_FUNTYPE_LUACFUN, p));
apr_hash_set(dispatch, "activeconfig", APR_HASH_KEY_STRING,
makefun(&lua_ap_get_active_config, APL_REQ_FUNTYPE_LUACFUN, p));
lua_pushlightuserdata(L, dispatch);
lua_setfield(L, LUA_REGISTRYINDEX, "Apache2.Request.dispatch");
luaL_newmetatable(L, "Apache2.Request"); /* [metatable] */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, request_methods); /* [metatable] */
lua_pop(L, 2);
luaL_newmetatable(L, "Apache2.Connection"); /* [metatable] */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, connection_methods); /* [metatable] */
lua_pop(L, 2);
luaL_newmetatable(L, "Apache2.Server"); /* [metatable] */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, server_methods); /* [metatable] */
lua_pop(L, 2);
}
void ap_lua_push_connection(lua_State *L, conn_rec *c)
{
req_table_t* t;
lua_boxpointer(L, c);
luaL_getmetatable(L, "Apache2.Connection");
lua_setmetatable(L, -2);
luaL_getmetatable(L, "Apache2.Connection");
t = apr_pcalloc(c->pool, sizeof(req_table_t));
t->t = c->notes;
t->r = NULL;
t->n = "notes";
ap_lua_push_apr_table(L, t);
lua_setfield(L, -2, "notes");
lua_pushstring(L, c->client_ip);
lua_setfield(L, -2, "client_ip");
lua_pop(L, 1);
}
void ap_lua_push_server(lua_State *L, server_rec *s)
{
lua_boxpointer(L, s);
luaL_getmetatable(L, "Apache2.Server");
lua_setmetatable(L, -2);
luaL_getmetatable(L, "Apache2.Server");
lua_pushstring(L, s->server_hostname);
lua_setfield(L, -2, "server_hostname");
lua_pop(L, 1);
}
void ap_lua_push_request(lua_State *L, request_rec *r)
{
lua_boxpointer(L, r);
luaL_getmetatable(L, "Apache2.Request");
lua_setmetatable(L, -2);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1448_1 |
crossvul-cpp_data_good_539_0 | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* Copyright (c) 2006-2007, Parvatha Elangovan
* 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 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 "opj_includes.h"
/** @defgroup PI PI - Implementation of a packet iterator */
/*@{*/
/** @name Local static functions */
/*@{*/
/**
Get next packet in layer-resolution-component-precinct order.
@param pi packet iterator to modify
@return returns false if pi pointed to the last packet or else returns true
*/
static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi);
/**
Get next packet in resolution-layer-component-precinct order.
@param pi packet iterator to modify
@return returns false if pi pointed to the last packet or else returns true
*/
static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi);
/**
Get next packet in resolution-precinct-component-layer order.
@param pi packet iterator to modify
@return returns false if pi pointed to the last packet or else returns true
*/
static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi);
/**
Get next packet in precinct-component-resolution-layer order.
@param pi packet iterator to modify
@return returns false if pi pointed to the last packet or else returns true
*/
static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi);
/**
Get next packet in component-precinct-resolution-layer order.
@param pi packet iterator to modify
@return returns false if pi pointed to the last packet or else returns true
*/
static opj_bool pi_next_cprl(opj_pi_iterator_t * pi);
/*@}*/
/*@}*/
/*
==========================================================
local functions
==========================================================
*/
static void opj_pi_emit_error(opj_pi_iterator_t * pi, const char* msg)
{
(void)pi;
(void)msg;
}
static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1;
pi->resno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
static opj_bool pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
/*
==========================================================
Packet iterator interface
==========================================================
*/
opj_pi_iterator_t *pi_create_decode(opj_image_t *image, opj_cp_t *cp,
int tileno)
{
int p, q;
int compno, resno, pino;
opj_pi_iterator_t *pi = NULL;
opj_tcp_t *tcp = NULL;
opj_tccp_t *tccp = NULL;
tcp = &cp->tcps[tileno];
pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1),
sizeof(opj_pi_iterator_t));
if (!pi) {
/* TODO: throw an error */
return NULL;
}
for (pino = 0; pino < tcp->numpocs + 1; pino++) { /* change */
int maxres = 0;
int maxprec = 0;
p = tileno % cp->tw;
q = tileno / cp->tw;
pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0);
pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0);
pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1);
pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1);
pi[pino].numcomps = image->numcomps;
pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps,
sizeof(opj_pi_comp_t));
if (!pi[pino].comps) {
/* TODO: throw an error */
pi_destroy(pi, cp, tileno);
return NULL;
}
for (compno = 0; compno < pi->numcomps; compno++) {
int tcx0, tcy0, tcx1, tcy1;
opj_pi_comp_t *comp = &pi[pino].comps[compno];
tccp = &tcp->tccps[compno];
comp->dx = image->comps[compno].dx;
comp->dy = image->comps[compno].dy;
comp->numresolutions = tccp->numresolutions;
comp->resolutions = (opj_pi_resolution_t*) opj_calloc(comp->numresolutions,
sizeof(opj_pi_resolution_t));
if (!comp->resolutions) {
/* TODO: throw an error */
pi_destroy(pi, cp, tileno);
return NULL;
}
tcx0 = int_ceildiv(pi->tx0, comp->dx);
tcy0 = int_ceildiv(pi->ty0, comp->dy);
tcx1 = int_ceildiv(pi->tx1, comp->dx);
tcy1 = int_ceildiv(pi->ty1, comp->dy);
if (comp->numresolutions > maxres) {
maxres = comp->numresolutions;
}
for (resno = 0; resno < comp->numresolutions; resno++) {
int levelno;
int rx0, ry0, rx1, ry1;
int px0, py0, px1, py1;
opj_pi_resolution_t *res = &comp->resolutions[resno];
if (tccp->csty & J2K_CCP_CSTY_PRT) {
res->pdx = tccp->prcw[resno];
res->pdy = tccp->prch[resno];
} else {
res->pdx = 15;
res->pdy = 15;
}
levelno = comp->numresolutions - 1 - resno;
rx0 = int_ceildivpow2(tcx0, levelno);
ry0 = int_ceildivpow2(tcy0, levelno);
rx1 = int_ceildivpow2(tcx1, levelno);
ry1 = int_ceildivpow2(tcy1, levelno);
px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;
py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;
px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;
py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;
res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx);
res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy);
if (res->pw * res->ph > maxprec) {
maxprec = res->pw * res->ph;
}
}
}
tccp = &tcp->tccps[0];
pi[pino].step_p = 1;
pi[pino].step_c = maxprec * pi[pino].step_p;
pi[pino].step_r = image->numcomps * pi[pino].step_c;
pi[pino].step_l = maxres * pi[pino].step_r;
if (pino == 0) {
pi[pino].include = (short int*) opj_calloc(image->numcomps * maxres *
tcp->numlayers * maxprec, sizeof(short int));
if (!pi[pino].include) {
/* TODO: throw an error */
pi_destroy(pi, cp, tileno);
return NULL;
}
} else {
pi[pino].include = pi[pino - 1].include;
}
if (tcp->POC == 0) {
pi[pino].first = 1;
pi[pino].poc.resno0 = 0;
pi[pino].poc.compno0 = 0;
pi[pino].poc.layno1 = tcp->numlayers;
pi[pino].poc.resno1 = maxres;
pi[pino].poc.compno1 = image->numcomps;
pi[pino].poc.prg = tcp->prg;
} else {
pi[pino].first = 1;
pi[pino].poc.resno0 = tcp->pocs[pino].resno0;
pi[pino].poc.compno0 = tcp->pocs[pino].compno0;
pi[pino].poc.layno1 = tcp->pocs[pino].layno1;
pi[pino].poc.resno1 = tcp->pocs[pino].resno1;
pi[pino].poc.compno1 = tcp->pocs[pino].compno1;
pi[pino].poc.prg = tcp->pocs[pino].prg;
}
pi[pino].poc.layno0 = 0;
pi[pino].poc.precno0 = 0;
pi[pino].poc.precno1 = maxprec;
}
return pi;
}
opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp,
int tileno, J2K_T2_MODE t2_mode)
{
int p, q, pino;
int compno, resno;
int maxres = 0;
int maxprec = 0;
opj_pi_iterator_t *pi = NULL;
opj_tcp_t *tcp = NULL;
opj_tccp_t *tccp = NULL;
tcp = &cp->tcps[tileno];
pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1),
sizeof(opj_pi_iterator_t));
if (!pi) {
return NULL;
}
pi->tp_on = cp->tp_on;
for (pino = 0; pino < tcp->numpocs + 1 ; pino ++) {
p = tileno % cp->tw;
q = tileno / cp->tw;
pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0);
pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0);
pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1);
pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1);
pi[pino].numcomps = image->numcomps;
pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps,
sizeof(opj_pi_comp_t));
if (!pi[pino].comps) {
pi_destroy(pi, cp, tileno);
return NULL;
}
for (compno = 0; compno < pi[pino].numcomps; compno++) {
int tcx0, tcy0, tcx1, tcy1;
opj_pi_comp_t *comp = &pi[pino].comps[compno];
tccp = &tcp->tccps[compno];
comp->dx = image->comps[compno].dx;
comp->dy = image->comps[compno].dy;
comp->numresolutions = tccp->numresolutions;
comp->resolutions = (opj_pi_resolution_t*) opj_malloc(comp->numresolutions *
sizeof(opj_pi_resolution_t));
if (!comp->resolutions) {
pi_destroy(pi, cp, tileno);
return NULL;
}
tcx0 = int_ceildiv(pi[pino].tx0, comp->dx);
tcy0 = int_ceildiv(pi[pino].ty0, comp->dy);
tcx1 = int_ceildiv(pi[pino].tx1, comp->dx);
tcy1 = int_ceildiv(pi[pino].ty1, comp->dy);
if (comp->numresolutions > maxres) {
maxres = comp->numresolutions;
}
for (resno = 0; resno < comp->numresolutions; resno++) {
int levelno;
int rx0, ry0, rx1, ry1;
int px0, py0, px1, py1;
opj_pi_resolution_t *res = &comp->resolutions[resno];
if (tccp->csty & J2K_CCP_CSTY_PRT) {
res->pdx = tccp->prcw[resno];
res->pdy = tccp->prch[resno];
} else {
res->pdx = 15;
res->pdy = 15;
}
levelno = comp->numresolutions - 1 - resno;
rx0 = int_ceildivpow2(tcx0, levelno);
ry0 = int_ceildivpow2(tcy0, levelno);
rx1 = int_ceildivpow2(tcx1, levelno);
ry1 = int_ceildivpow2(tcy1, levelno);
px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;
py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;
px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;
py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;
res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx);
res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy);
if (res->pw * res->ph > maxprec) {
maxprec = res->pw * res->ph;
}
}
}
tccp = &tcp->tccps[0];
pi[pino].step_p = 1;
pi[pino].step_c = maxprec * pi[pino].step_p;
pi[pino].step_r = image->numcomps * pi[pino].step_c;
pi[pino].step_l = maxres * pi[pino].step_r;
for (compno = 0; compno < pi->numcomps; compno++) {
opj_pi_comp_t *comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
opj_pi_resolution_t *res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi[pino].dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi[pino].dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
if (pino == 0) {
pi[pino].include = (short int*) opj_calloc(tcp->numlayers * pi[pino].step_l,
sizeof(short int));
if (!pi[pino].include) {
pi_destroy(pi, cp, tileno);
return NULL;
}
} else {
pi[pino].include = pi[pino - 1].include;
}
/* Generation of boundaries for each prog flag*/
if (tcp->POC && (cp->cinema || ((!cp->cinema) && (t2_mode == FINAL_PASS)))) {
tcp->pocs[pino].compS = tcp->pocs[pino].compno0;
tcp->pocs[pino].compE = tcp->pocs[pino].compno1;
tcp->pocs[pino].resS = tcp->pocs[pino].resno0;
tcp->pocs[pino].resE = tcp->pocs[pino].resno1;
tcp->pocs[pino].layE = tcp->pocs[pino].layno1;
tcp->pocs[pino].prg = tcp->pocs[pino].prg1;
if (pino > 0) {
tcp->pocs[pino].layS = (tcp->pocs[pino].layE > tcp->pocs[pino - 1].layE) ?
tcp->pocs[pino - 1].layE : 0;
}
} else {
tcp->pocs[pino].compS = 0;
tcp->pocs[pino].compE = image->numcomps;
tcp->pocs[pino].resS = 0;
tcp->pocs[pino].resE = maxres;
tcp->pocs[pino].layS = 0;
tcp->pocs[pino].layE = tcp->numlayers;
tcp->pocs[pino].prg = tcp->prg;
}
tcp->pocs[pino].prcS = 0;
tcp->pocs[pino].prcE = maxprec;;
tcp->pocs[pino].txS = pi[pino].tx0;
tcp->pocs[pino].txE = pi[pino].tx1;
tcp->pocs[pino].tyS = pi[pino].ty0;
tcp->pocs[pino].tyE = pi[pino].ty1;
tcp->pocs[pino].dx = pi[pino].dx;
tcp->pocs[pino].dy = pi[pino].dy;
}
return pi;
}
void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno)
{
int compno, pino;
opj_tcp_t *tcp = &cp->tcps[tileno];
if (pi) {
for (pino = 0; pino < tcp->numpocs + 1; pino++) {
if (pi[pino].comps) {
for (compno = 0; compno < pi->numcomps; compno++) {
opj_pi_comp_t *comp = &pi[pino].comps[compno];
if (comp->resolutions) {
opj_free(comp->resolutions);
}
}
opj_free(pi[pino].comps);
}
}
if (pi->include) {
opj_free(pi->include);
}
opj_free(pi);
}
}
opj_bool pi_next(opj_pi_iterator_t * pi)
{
switch (pi->poc.prg) {
case LRCP:
return pi_next_lrcp(pi);
case RLCP:
return pi_next_rlcp(pi);
case RPCL:
return pi_next_rpcl(pi);
case PCRL:
return pi_next_pcrl(pi);
case CPRL:
return pi_next_cprl(pi);
case PROG_UNKNOWN:
return OPJ_FALSE;
}
return OPJ_FALSE;
}
opj_bool pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno,
int pino, int tpnum, int tppos, J2K_T2_MODE t2_mode, int cur_totnum_tp)
{
char prog[4];
int i;
int incr_top = 1, resetX = 0;
opj_tcp_t *tcps = &cp->tcps[tileno];
opj_poc_t *tcp = &tcps->pocs[pino];
pi[pino].first = 1;
pi[pino].poc.prg = tcp->prg;
switch (tcp->prg) {
case CPRL:
strncpy(prog, "CPRL", 4);
break;
case LRCP:
strncpy(prog, "LRCP", 4);
break;
case PCRL:
strncpy(prog, "PCRL", 4);
break;
case RLCP:
strncpy(prog, "RLCP", 4);
break;
case RPCL:
strncpy(prog, "RPCL", 4);
break;
case PROG_UNKNOWN:
return OPJ_TRUE;
}
if (!(cp->tp_on && ((!cp->cinema && (t2_mode == FINAL_PASS)) || cp->cinema))) {
pi[pino].poc.resno0 = tcp->resS;
pi[pino].poc.resno1 = tcp->resE;
pi[pino].poc.compno0 = tcp->compS;
pi[pino].poc.compno1 = tcp->compE;
pi[pino].poc.layno0 = tcp->layS;
pi[pino].poc.layno1 = tcp->layE;
pi[pino].poc.precno0 = tcp->prcS;
pi[pino].poc.precno1 = tcp->prcE;
pi[pino].poc.tx0 = tcp->txS;
pi[pino].poc.ty0 = tcp->tyS;
pi[pino].poc.tx1 = tcp->txE;
pi[pino].poc.ty1 = tcp->tyE;
} else {
if (tpnum < cur_totnum_tp) {
for (i = 3; i >= 0; i--) {
switch (prog[i]) {
case 'C':
if (i > tppos) {
pi[pino].poc.compno0 = tcp->compS;
pi[pino].poc.compno1 = tcp->compE;
} else {
if (tpnum == 0) {
tcp->comp_t = tcp->compS;
pi[pino].poc.compno0 = tcp->comp_t;
pi[pino].poc.compno1 = tcp->comp_t + 1;
tcp->comp_t += 1;
} else {
if (incr_top == 1) {
if (tcp->comp_t == tcp->compE) {
tcp->comp_t = tcp->compS;
pi[pino].poc.compno0 = tcp->comp_t;
pi[pino].poc.compno1 = tcp->comp_t + 1;
tcp->comp_t += 1;
incr_top = 1;
} else {
pi[pino].poc.compno0 = tcp->comp_t;
pi[pino].poc.compno1 = tcp->comp_t + 1;
tcp->comp_t += 1;
incr_top = 0;
}
} else {
pi[pino].poc.compno0 = tcp->comp_t - 1;
pi[pino].poc.compno1 = tcp->comp_t;
}
}
}
break;
case 'R':
if (i > tppos) {
pi[pino].poc.resno0 = tcp->resS;
pi[pino].poc.resno1 = tcp->resE;
} else {
if (tpnum == 0) {
tcp->res_t = tcp->resS;
pi[pino].poc.resno0 = tcp->res_t;
pi[pino].poc.resno1 = tcp->res_t + 1;
tcp->res_t += 1;
} else {
if (incr_top == 1) {
if (tcp->res_t == tcp->resE) {
tcp->res_t = tcp->resS;
pi[pino].poc.resno0 = tcp->res_t;
pi[pino].poc.resno1 = tcp->res_t + 1;
tcp->res_t += 1;
incr_top = 1;
} else {
pi[pino].poc.resno0 = tcp->res_t;
pi[pino].poc.resno1 = tcp->res_t + 1;
tcp->res_t += 1;
incr_top = 0;
}
} else {
pi[pino].poc.resno0 = tcp->res_t - 1;
pi[pino].poc.resno1 = tcp->res_t;
}
}
}
break;
case 'L':
if (i > tppos) {
pi[pino].poc.layno0 = tcp->layS;
pi[pino].poc.layno1 = tcp->layE;
} else {
if (tpnum == 0) {
tcp->lay_t = tcp->layS;
pi[pino].poc.layno0 = tcp->lay_t;
pi[pino].poc.layno1 = tcp->lay_t + 1;
tcp->lay_t += 1;
} else {
if (incr_top == 1) {
if (tcp->lay_t == tcp->layE) {
tcp->lay_t = tcp->layS;
pi[pino].poc.layno0 = tcp->lay_t;
pi[pino].poc.layno1 = tcp->lay_t + 1;
tcp->lay_t += 1;
incr_top = 1;
} else {
pi[pino].poc.layno0 = tcp->lay_t;
pi[pino].poc.layno1 = tcp->lay_t + 1;
tcp->lay_t += 1;
incr_top = 0;
}
} else {
pi[pino].poc.layno0 = tcp->lay_t - 1;
pi[pino].poc.layno1 = tcp->lay_t;
}
}
}
break;
case 'P':
switch (tcp->prg) {
case LRCP:
case RLCP:
if (i > tppos) {
pi[pino].poc.precno0 = tcp->prcS;
pi[pino].poc.precno1 = tcp->prcE;
} else {
if (tpnum == 0) {
tcp->prc_t = tcp->prcS;
pi[pino].poc.precno0 = tcp->prc_t;
pi[pino].poc.precno1 = tcp->prc_t + 1;
tcp->prc_t += 1;
} else {
if (incr_top == 1) {
if (tcp->prc_t == tcp->prcE) {
tcp->prc_t = tcp->prcS;
pi[pino].poc.precno0 = tcp->prc_t;
pi[pino].poc.precno1 = tcp->prc_t + 1;
tcp->prc_t += 1;
incr_top = 1;
} else {
pi[pino].poc.precno0 = tcp->prc_t;
pi[pino].poc.precno1 = tcp->prc_t + 1;
tcp->prc_t += 1;
incr_top = 0;
}
} else {
pi[pino].poc.precno0 = tcp->prc_t - 1;
pi[pino].poc.precno1 = tcp->prc_t;
}
}
}
break;
default:
if (i > tppos) {
pi[pino].poc.tx0 = tcp->txS;
pi[pino].poc.ty0 = tcp->tyS;
pi[pino].poc.tx1 = tcp->txE;
pi[pino].poc.ty1 = tcp->tyE;
} else {
if (tpnum == 0) {
tcp->tx0_t = tcp->txS;
tcp->ty0_t = tcp->tyS;
pi[pino].poc.tx0 = tcp->tx0_t;
pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
pi[pino].poc.ty0 = tcp->ty0_t;
pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
tcp->tx0_t = pi[pino].poc.tx1;
tcp->ty0_t = pi[pino].poc.ty1;
} else {
if (incr_top == 1) {
if (tcp->tx0_t >= tcp->txE) {
if (tcp->ty0_t >= tcp->tyE) {
tcp->ty0_t = tcp->tyS;
pi[pino].poc.ty0 = tcp->ty0_t;
pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
tcp->ty0_t = pi[pino].poc.ty1;
incr_top = 1;
resetX = 1;
} else {
pi[pino].poc.ty0 = tcp->ty0_t;
pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
tcp->ty0_t = pi[pino].poc.ty1;
incr_top = 0;
resetX = 1;
}
if (resetX == 1) {
tcp->tx0_t = tcp->txS;
pi[pino].poc.tx0 = tcp->tx0_t;
pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
tcp->tx0_t = pi[pino].poc.tx1;
}
} else {
pi[pino].poc.tx0 = tcp->tx0_t;
pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
tcp->tx0_t = pi[pino].poc.tx1;
pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy);
pi[pino].poc.ty1 = tcp->ty0_t ;
incr_top = 0;
}
} else {
pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx);
pi[pino].poc.tx1 = tcp->tx0_t ;
pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy);
pi[pino].poc.ty1 = tcp->ty0_t ;
}
}
}
break;
}
break;
}
}
}
}
return OPJ_FALSE;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_539_0 |
crossvul-cpp_data_bad_2212_0 | /*
* Copyright 2011-2013 Con Kolivas
* Copyright 2010 Jeff Garzik
*
* 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 3 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <jansson.h>
#ifdef HAVE_LIBCURL
#include <curl/curl.h>
#endif
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#ifndef WIN32
#include <fcntl.h>
# ifdef __linux__
# include <sys/prctl.h>
# endif
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <netdb.h>
#else
# include <windows.h>
# include <winsock2.h>
# include <ws2tcpip.h>
# include <mmsystem.h>
#endif
#include "miner.h"
#include "elist.h"
#include "compat.h"
#include "util.h"
#include "pool.h"
#define DEFAULT_SOCKWAIT 60
extern double opt_diff_mult;
bool successful_connect = false;
static void keep_sockalive(SOCKETTYPE fd)
{
const int tcp_one = 1;
#ifndef WIN32
const int tcp_keepidle = 45;
const int tcp_keepintvl = 30;
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, O_NONBLOCK | flags);
#else
u_long flags = 1;
ioctlsocket(fd, FIONBIO, &flags);
#endif
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one));
if (!opt_delaynet)
#ifndef __linux
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&tcp_one, sizeof(tcp_one));
#else /* __linux */
setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
#endif /* __linux__ */
#ifdef __APPLE_CC__
setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
#endif /* __APPLE_CC__ */
}
struct tq_ent {
void *data;
struct list_head q_node;
};
#ifdef HAVE_LIBCURL
struct timeval nettime;
struct data_buffer {
void *buf;
size_t len;
};
struct upload_buffer {
const void *buf;
size_t len;
};
struct header_info {
char *lp_path;
int rolltime;
char *reason;
char *stratum_url;
bool hadrolltime;
bool canroll;
bool hadexpire;
};
static void databuf_free(struct data_buffer *db)
{
if (!db)
return;
free(db->buf);
memset(db, 0, sizeof(*db));
}
static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct data_buffer *db = (struct data_buffer *)user_data;
size_t len = size * nmemb;
size_t oldlen, newlen;
void *newmem;
static const unsigned char zero = 0;
oldlen = db->len;
newlen = oldlen + len;
newmem = realloc(db->buf, newlen + 1);
if (!newmem)
return 0;
db->buf = newmem;
db->len = newlen;
memcpy((uint8_t*)db->buf + oldlen, ptr, len);
memcpy((uint8_t*)db->buf + newlen, &zero, 1); /* null terminate */
return len;
}
static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct upload_buffer *ub = (struct upload_buffer *)user_data;
unsigned int len = size * nmemb;
if (len > ub->len)
len = ub->len;
if (len) {
memcpy(ptr, ub->buf, len);
ub->buf = (uint8_t*)ub->buf + len;
ub->len -= len;
}
return len;
}
static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
{
struct header_info *hi = (struct header_info *)user_data;
size_t remlen, slen, ptrlen = size * nmemb;
char *rem, *val = NULL, *key = NULL;
void *tmp;
val = (char *)calloc(1, ptrlen);
key = (char *)calloc(1, ptrlen);
if (!key || !val)
goto out;
tmp = memchr(ptr, ':', ptrlen);
if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
goto out;
slen = (uint8_t*)tmp - (uint8_t*)ptr;
if ((slen + 1) == ptrlen) /* skip key w/ no value */
goto out;
memcpy(key, ptr, slen); /* store & nul term key */
key[slen] = 0;
rem = (char*)ptr + slen + 1; /* trim value's leading whitespace */
remlen = ptrlen - slen - 1;
while ((remlen > 0) && (isspace(*rem))) {
remlen--;
rem++;
}
memcpy(val, rem, remlen); /* store value, trim trailing ws */
val[remlen] = 0;
while ((*val) && (isspace(val[strlen(val) - 1])))
val[strlen(val) - 1] = 0;
if (!*val) /* skip blank value */
goto out;
if (opt_protocol)
applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
if (!strcasecmp("X-Roll-Ntime", key)) {
hi->hadrolltime = true;
if (!strncasecmp("N", val, 1))
applog(LOG_DEBUG, "X-Roll-Ntime: N found");
else {
hi->canroll = true;
/* Check to see if expire= is supported and if not, set
* the rolltime to the default scantime */
if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
sscanf(val + 7, "%d", &hi->rolltime);
hi->hadexpire = true;
} else
hi->rolltime = opt_scantime;
applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
}
}
if (!strcasecmp("X-Long-Polling", key)) {
hi->lp_path = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Reject-Reason", key)) {
hi->reason = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Stratum", key)) {
hi->stratum_url = val;
val = NULL;
}
out:
free(key);
free(val);
return ptrlen;
}
static void last_nettime(struct timeval *last)
{
rd_lock(&netacc_lock);
last->tv_sec = nettime.tv_sec;
last->tv_usec = nettime.tv_usec;
rd_unlock(&netacc_lock);
}
static void set_nettime(void)
{
wr_lock(&netacc_lock);
cgtime(&nettime);
wr_unlock(&netacc_lock);
}
#if CURL_HAS_KEEPALIVE
static void keep_curlalive(CURL *curl)
{
const long int keepalive = 1;
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, opt_tcp_keepalive);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, opt_tcp_keepalive);
}
#else
static void keep_curlalive(CURL *curl)
{
SOCKETTYPE sock;
curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
keep_sockalive(sock);
}
#endif
static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
__maybe_unused char *data, size_t size, void *userdata)
{
struct pool *pool = (struct pool *)userdata;
switch(type) {
case CURLINFO_HEADER_IN:
case CURLINFO_DATA_IN:
case CURLINFO_SSL_DATA_IN:
pool->sgminer_pool_stats.net_bytes_received += size;
break;
case CURLINFO_HEADER_OUT:
case CURLINFO_DATA_OUT:
case CURLINFO_SSL_DATA_OUT:
pool->sgminer_pool_stats.net_bytes_sent += size;
break;
case CURLINFO_TEXT:
default:
break;
}
return 0;
}
json_t *json_rpc_call(CURL *curl, const char *url,
const char *userpass, const char *rpc_req,
bool probe, bool longpoll, int *rolltime,
struct pool *pool, bool share)
{
long timeout = longpoll ? (60 * 60) : 60;
struct data_buffer all_data = {NULL, 0};
struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
char len_hdr[64], user_agent_hdr[128];
char curl_err_str[CURL_ERROR_SIZE];
struct curl_slist *headers = NULL;
struct upload_buffer upload_data;
json_t *val, *err_val, *res_val;
bool probing = false;
double byte_count;
json_error_t err;
int rc;
memset(&err, 0, sizeof(err));
/* it is assumed that 'curl' is freshly [re]initialized at this pt */
if (probe)
probing = !pool->probed;
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ENCODING, "");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
/* Shares are staggered already and delays in submission can be costly
* so do not delay them */
if (!opt_delaynet || share)
curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
if (pool->rpc_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
} else if (opt_socks_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
if (userpass) {
curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
if (longpoll)
keep_curlalive(curl);
curl_easy_setopt(curl, CURLOPT_POST, 1);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
upload_data.buf = rpc_req;
upload_data.len = strlen(rpc_req);
sprintf(len_hdr, "Content-Length: %lu",
(unsigned long) upload_data.len);
sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
headers = curl_slist_append(headers,
"Content-type: application/json");
headers = curl_slist_append(headers,
"X-Mining-Extensions: longpoll midstate rollntime submitold");
if (likely(global_hashrate)) {
char ghashrate[255];
sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
headers = curl_slist_append(headers, ghashrate);
}
headers = curl_slist_append(headers, len_hdr);
headers = curl_slist_append(headers, user_agent_hdr);
headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
if (opt_delaynet) {
/* Don't delay share submission, but still track the nettime */
if (!share) {
long long now_msecs, last_msecs;
struct timeval now, last;
cgtime(&now);
last_nettime(&last);
now_msecs = (long long)now.tv_sec * 1000;
now_msecs += now.tv_usec / 1000;
last_msecs = (long long)last.tv_sec * 1000;
last_msecs += last.tv_usec / 1000;
if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
struct timespec rgtp;
rgtp.tv_sec = 0;
rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
nanosleep(&rgtp, NULL);
}
}
set_nettime();
}
rc = curl_easy_perform(curl);
if (rc) {
applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
goto err_out;
}
if (!all_data.buf) {
applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
goto err_out;
}
pool->sgminer_pool_stats.times_sent++;
if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
pool->sgminer_pool_stats.bytes_sent += byte_count;
pool->sgminer_pool_stats.times_received++;
if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
pool->sgminer_pool_stats.bytes_received += byte_count;
if (probing) {
pool->probed = true;
/* If X-Long-Polling was found, activate long polling */
if (hi.lp_path) {
if (pool->hdr_path != NULL)
free(pool->hdr_path);
pool->hdr_path = hi.lp_path;
} else
pool->hdr_path = NULL;
if (hi.stratum_url) {
pool->stratum_url = hi.stratum_url;
hi.stratum_url = NULL;
}
} else {
if (hi.lp_path) {
free(hi.lp_path);
hi.lp_path = NULL;
}
if (hi.stratum_url) {
free(hi.stratum_url);
hi.stratum_url = NULL;
}
}
*rolltime = hi.rolltime;
pool->sgminer_pool_stats.rolltime = hi.rolltime;
pool->sgminer_pool_stats.hadrolltime = hi.hadrolltime;
pool->sgminer_pool_stats.canroll = hi.canroll;
pool->sgminer_pool_stats.hadexpire = hi.hadexpire;
val = JSON_LOADS((const char *)all_data.buf, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
goto err_out;
}
if (opt_protocol) {
char *s = json_dumps(val, JSON_INDENT(3));
applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
free(s);
}
/* JSON-RPC valid response returns a non-null 'result',
* and a null 'error'.
*/
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val ||(err_val && !json_is_null(err_val))) {
char *s;
if (err_val)
s = json_dumps(err_val, JSON_INDENT(3));
else
s = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC call failed: %s", s);
free(s);
goto err_out;
}
if (hi.reason) {
json_object_set_new(val, "reject-reason", json_string(hi.reason));
free(hi.reason);
hi.reason = NULL;
}
successful_connect = true;
databuf_free(&all_data);
curl_slist_free_all(headers);
curl_easy_reset(curl);
return val;
err_out:
databuf_free(&all_data);
curl_slist_free_all(headers);
curl_easy_reset(curl);
if (!successful_connect)
applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
return NULL;
}
#define PROXY_HTTP CURLPROXY_HTTP
#define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
#define PROXY_SOCKS4 CURLPROXY_SOCKS4
#define PROXY_SOCKS5 CURLPROXY_SOCKS5
#define PROXY_SOCKS4A CURLPROXY_SOCKS4A
#define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
#else /* HAVE_LIBCURL */
#define PROXY_HTTP 0
#define PROXY_HTTP_1_0 1
#define PROXY_SOCKS4 2
#define PROXY_SOCKS5 3
#define PROXY_SOCKS4A 4
#define PROXY_SOCKS5H 5
#endif /* HAVE_LIBCURL */
static struct {
const char *name;
proxytypes_t proxytype;
} proxynames[] = {
{ "http:", PROXY_HTTP },
{ "http0:", PROXY_HTTP_1_0 },
{ "socks4:", PROXY_SOCKS4 },
{ "socks5:", PROXY_SOCKS5 },
{ "socks4a:", PROXY_SOCKS4A },
{ "socks5h:", PROXY_SOCKS5H },
{ NULL, (proxytypes_t)NULL }
};
const char *proxytype(proxytypes_t proxytype)
{
int i;
for (i = 0; proxynames[i].name; i++)
if (proxynames[i].proxytype == proxytype)
return proxynames[i].name;
return "invalid";
}
char *get_proxy(char *url, struct pool *pool)
{
pool->rpc_proxy = NULL;
char *split;
int plen, len, i;
for (i = 0; proxynames[i].name; i++) {
plen = strlen(proxynames[i].name);
if (strncmp(url, proxynames[i].name, plen) == 0) {
if (!(split = strchr(url, '|')))
return url;
*split = '\0';
len = split - url;
pool->rpc_proxy = (char *)malloc(1 + len - plen);
if (!(pool->rpc_proxy))
quithere(1, "Failed to malloc rpc_proxy");
strcpy(pool->rpc_proxy, url + plen);
extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
pool->rpc_proxytype = proxynames[i].proxytype;
url = split + 1;
break;
}
}
return url;
}
/* Adequate size s==len*2 + 1 must be alloced to use this variant */
void __bin2hex(char *s, const unsigned char *p, size_t len)
{
int i;
static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (i = 0; i < (int)len; i++) {
*s++ = hex[p[i] >> 4];
*s++ = hex[p[i] & 0xF];
}
*s++ = '\0';
}
/* Returns a malloced array string of a binary value of arbitrary length. The
* array is rounded up to a 4 byte size to appease architectures that need
* aligned array sizes */
char *bin2hex(const unsigned char *p, size_t len)
{
ssize_t slen;
char *s;
slen = len * 2 + 1;
if (slen % 4)
slen += 4 - (slen % 4);
s = (char *)calloc(slen, 1);
if (unlikely(!s))
quithere(1, "Failed to calloc");
__bin2hex(s, p, len);
return s;
}
/* Does the reverse of bin2hex but does not allocate any ram */
static const int hex2bin_tbl[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
{
int nibble1, nibble2;
unsigned char idx;
bool ret = false;
while (*hexstr && len) {
if (unlikely(!hexstr[1])) {
applog(LOG_ERR, "hex2bin str truncated");
return ret;
}
idx = *hexstr++;
nibble1 = hex2bin_tbl[idx];
idx = *hexstr++;
nibble2 = hex2bin_tbl[idx];
if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
applog(LOG_ERR, "hex2bin scan failed");
return ret;
}
*p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
--len;
}
if (likely(len == 0 && *hexstr == 0))
ret = true;
return ret;
}
bool fulltest(const unsigned char *hash, const unsigned char *target)
{
uint32_t *hash32 = (uint32_t *)hash;
uint32_t *target32 = (uint32_t *)target;
bool rc = true;
int i;
for (i = 28 / 4; i >= 0; i--) {
uint32_t h32tmp = le32toh(hash32[i]);
uint32_t t32tmp = le32toh(target32[i]);
if (h32tmp > t32tmp) {
rc = false;
break;
}
if (h32tmp < t32tmp) {
rc = true;
break;
}
}
if (opt_debug) {
unsigned char hash_swap[32], target_swap[32];
char *hash_str, *target_str;
swab256(hash_swap, hash);
swab256(target_swap, target);
hash_str = bin2hex(hash_swap, 32);
target_str = bin2hex(target_swap, 32);
applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
hash_str,
target_str,
rc ? "YES (hash <= target)" :
"no (false positive; hash > target)");
free(hash_str);
free(target_str);
}
return rc;
}
struct thread_q *tq_new(void)
{
struct thread_q *tq;
tq = (struct thread_q *)calloc(1, sizeof(*tq));
if (!tq)
return NULL;
INIT_LIST_HEAD(&tq->q);
pthread_mutex_init(&tq->mutex, NULL);
pthread_cond_init(&tq->cond, NULL);
return tq;
}
void tq_free(struct thread_q *tq)
{
struct tq_ent *ent, *iter;
if (!tq)
return;
list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
list_del(&ent->q_node);
free(ent);
}
pthread_cond_destroy(&tq->cond);
pthread_mutex_destroy(&tq->mutex);
memset(tq, 0, sizeof(*tq)); /* poison */
free(tq);
}
static void tq_freezethaw(struct thread_q *tq, bool frozen)
{
mutex_lock(&tq->mutex);
tq->frozen = frozen;
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
}
void tq_freeze(struct thread_q *tq)
{
tq_freezethaw(tq, true);
}
void tq_thaw(struct thread_q *tq)
{
tq_freezethaw(tq, false);
}
bool tq_push(struct thread_q *tq, void *data)
{
struct tq_ent *ent;
bool rc = true;
ent = (struct tq_ent *)calloc(1, sizeof(*ent));
if (!ent)
return false;
ent->data = data;
INIT_LIST_HEAD(&ent->q_node);
mutex_lock(&tq->mutex);
if (!tq->frozen) {
list_add_tail(&ent->q_node, &tq->q);
} else {
free(ent);
rc = false;
}
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
return rc;
}
void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
{
struct tq_ent *ent;
void *rval = NULL;
int rc;
mutex_lock(&tq->mutex);
if (!list_empty(&tq->q))
goto pop;
if (abstime)
rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
else
rc = pthread_cond_wait(&tq->cond, &tq->mutex);
if (rc)
goto out;
if (list_empty(&tq->q))
goto out;
pop:
ent = list_entry(tq->q.next, struct tq_ent*, q_node);
rval = ent->data;
list_del(&ent->q_node);
free(ent);
out:
mutex_unlock(&tq->mutex);
return rval;
}
int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
{
cgsem_init(&thr->sem);
return pthread_create(&thr->pth, attr, start, arg);
}
void thr_info_cancel(struct thr_info *thr)
{
if (!thr)
return;
if (PTH(thr) != 0L) {
pthread_cancel(thr->pth);
PTH(thr) = 0L;
}
cgsem_destroy(&thr->sem);
}
void subtime(struct timeval *a, struct timeval *b)
{
timersub(a, b, b);
}
void addtime(struct timeval *a, struct timeval *b)
{
timeradd(a, b, b);
}
bool time_more(struct timeval *a, struct timeval *b)
{
return timercmp(a, b, >);
}
bool time_less(struct timeval *a, struct timeval *b)
{
return timercmp(a, b, <);
}
void copy_time(struct timeval *dest, const struct timeval *src)
{
memcpy(dest, src, sizeof(struct timeval));
}
void timespec_to_val(struct timeval *val, const struct timespec *spec)
{
val->tv_sec = spec->tv_sec;
val->tv_usec = spec->tv_nsec / 1000;
}
void timeval_to_spec(struct timespec *spec, const struct timeval *val)
{
spec->tv_sec = val->tv_sec;
spec->tv_nsec = val->tv_usec * 1000;
}
void us_to_timeval(struct timeval *val, int64_t us)
{
lldiv_t tvdiv = lldiv(us, 1000000);
val->tv_sec = tvdiv.quot;
val->tv_usec = tvdiv.rem;
}
void us_to_timespec(struct timespec *spec, int64_t us)
{
lldiv_t tvdiv = lldiv(us, 1000000);
spec->tv_sec = tvdiv.quot;
spec->tv_nsec = tvdiv.rem * 1000;
}
void ms_to_timespec(struct timespec *spec, int64_t ms)
{
lldiv_t tvdiv = lldiv(ms, 1000);
spec->tv_sec = tvdiv.quot;
spec->tv_nsec = tvdiv.rem * 1000000;
}
void ms_to_timeval(struct timeval *val, int64_t ms)
{
lldiv_t tvdiv = lldiv(ms, 1000);
val->tv_sec = tvdiv.quot;
val->tv_usec = tvdiv.rem * 1000;
}
void timeraddspec(struct timespec *a, const struct timespec *b)
{
a->tv_sec += b->tv_sec;
a->tv_nsec += b->tv_nsec;
if (a->tv_nsec >= 1000000000) {
a->tv_nsec -= 1000000000;
a->tv_sec++;
}
}
static int __maybe_unused timespec_to_ms(struct timespec *ts)
{
return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
}
/* Subtract b from a */
static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
{
a->tv_sec -= b->tv_sec;
a->tv_nsec -= b->tv_nsec;
if (a->tv_nsec < 0) {
a->tv_nsec += 1000000000;
a->tv_sec--;
}
}
/* These are sgminer specific sleep functions that use an absolute nanosecond
* resolution timer to avoid poor usleep accuracy and overruns. */
#ifdef WIN32
/* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
#define EPOCHFILETIME (116444736000000000LL)
/* Return the system time as an lldiv_t in decimicroseconds. */
static void decius_time(lldiv_t *lidiv)
{
FILETIME ft;
LARGE_INTEGER li;
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
li.QuadPart -= EPOCHFILETIME;
/* SystemTime is in decimicroseconds so divide by an unusual number */
*lidiv = lldiv(li.QuadPart, 10000000);
}
/* This is a sgminer gettimeofday wrapper. Since we always call gettimeofday
* with tz set to NULL, and windows' default resolution is only 15ms, this
* gives us higher resolution times on windows. */
void cgtime(struct timeval *tv)
{
lldiv_t lidiv;
decius_time(&lidiv);
tv->tv_sec = lidiv.quot;
tv->tv_usec = lidiv.rem / 10;
}
#else /* WIN32 */
void cgtime(struct timeval *tv)
{
gettimeofday(tv, NULL);
}
int cgtimer_to_ms(cgtimer_t *cgt)
{
return timespec_to_ms(cgt);
}
/* Subtracts b from a and stores it in res. */
void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
{
res->tv_sec = a->tv_sec - b->tv_sec;
res->tv_nsec = a->tv_nsec - b->tv_nsec;
if (res->tv_nsec < 0) {
res->tv_nsec += 1000000000;
res->tv_sec--;
}
}
#endif /* WIN32 */
#ifdef CLOCK_MONOTONIC /* Essentially just linux */
void cgtimer_time(cgtimer_t *ts_start)
{
clock_gettime(CLOCK_MONOTONIC, ts_start);
}
static void nanosleep_abstime(struct timespec *ts_end)
{
int ret;
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
} while (ret == EINTR);
}
/* Reentrant version of cgsleep functions allow start time to be set separately
* from the beginning of the actual sleep, allowing scheduling delays to be
* counted in the sleep. */
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
struct timespec ts_end;
ms_to_timespec(&ts_end, ms);
timeraddspec(&ts_end, ts_start);
nanosleep_abstime(&ts_end);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
struct timespec ts_end;
us_to_timespec(&ts_end, us);
timeraddspec(&ts_end, ts_start);
nanosleep_abstime(&ts_end);
}
#else /* CLOCK_MONOTONIC */
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
void cgtimer_time(cgtimer_t *ts_start)
{
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts_start->tv_sec = mts.tv_sec;
ts_start->tv_nsec = mts.tv_nsec;
}
#elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
void cgtimer_time(cgtimer_t *ts_start)
{
struct timeval tv;
cgtime(&tv);
ts_start->tv_sec = tv->tv_sec;
ts_start->tv_nsec = tv->tv_usec * 1000;
}
#endif /* __MACH__ */
#ifdef WIN32
/* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
* typedef, allowing us to have sub-microsecond resolution for times, do simple
* arithmetic for timer calculations, and use windows' own hTimers to get
* accurate absolute timeouts. */
int cgtimer_to_ms(cgtimer_t *cgt)
{
return (int)(cgt->QuadPart / 10000LL);
}
/* Subtracts b from a and stores it in res. */
void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
{
res->QuadPart = a->QuadPart - b->QuadPart;
}
/* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
* timeouts with hTimers. */
void cgtimer_time(cgtimer_t *ts_start)
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
ts_start->LowPart = ft.dwLowDateTime;
ts_start->HighPart = ft.dwHighDateTime;
}
static void liSleep(LARGE_INTEGER *li, int timeout)
{
HANDLE hTimer;
DWORD ret;
if (unlikely(timeout <= 0))
return;
hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
if (unlikely(!hTimer))
quit(1, "Failed to create hTimer in liSleep");
ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
if (unlikely(!ret))
quit(1, "Failed to SetWaitableTimer in liSleep");
/* We still use a timeout as a sanity check in case the system time
* is changed while we're running */
ret = WaitForSingleObject(hTimer, timeout);
if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
quit(1, "Failed to WaitForSingleObject in liSleep");
CloseHandle(hTimer);
}
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
LARGE_INTEGER li;
li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
liSleep(&li, ms);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
LARGE_INTEGER li;
int ms;
li.QuadPart = ts_start->QuadPart + us * 10LL;
ms = us / 1000;
if (!ms)
ms = 1;
liSleep(&li, ms);
}
#else /* WIN32 */
static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
{
struct timespec now;
timeraddspec(ts_diff, ts_start);
cgtimer_time(&now);
timersubspec(ts_diff, &now);
if (unlikely(ts_diff->tv_sec < 0))
return;
nanosleep(ts_diff, NULL);
}
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
struct timespec ts_diff;
ms_to_timespec(&ts_diff, ms);
cgsleep_spec(&ts_diff, ts_start);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
struct timespec ts_diff;
us_to_timespec(&ts_diff, us);
cgsleep_spec(&ts_diff, ts_start);
}
#endif /* WIN32 */
#endif /* CLOCK_MONOTONIC */
void cgsleep_ms(int ms)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_ms_r(&ts_start, ms);
}
void cgsleep_us(int64_t us)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_us_r(&ts_start, us);
}
/* Returns the microseconds difference between end and start times as a double */
double us_tdiff(struct timeval *end, struct timeval *start)
{
/* Sanity check. We should only be using this for small differences so
* limit the max to 60 seconds. */
if (unlikely(end->tv_sec - start->tv_sec > 60))
return 60000000;
return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
}
/* Returns the milliseconds difference between end and start times */
int ms_tdiff(struct timeval *end, struct timeval *start)
{
/* Like us_tdiff, limit to 1 hour. */
if (unlikely(end->tv_sec - start->tv_sec > 3600))
return 3600000;
return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
}
/* Returns the seconds difference between end and start times as a double */
double tdiff(struct timeval *end, struct timeval *start)
{
return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
}
bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
if (url_len >= sizeof(url_address))
{
applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
__func__, url_len, url_begin);
url_len = sizeof(url_address) - 1;
}
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
enum send_ret {
SEND_OK,
SEND_SELECTFAIL,
SEND_SENDFAIL,
SEND_INACTIVE
};
/* Send a single command across a socket, appending \n to it. This should all
* be done under stratum lock except when first establishing the socket */
static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
{
SOCKETTYPE sock = pool->sock;
ssize_t ssent = 0;
strcat(s, "\n");
len++;
while (len > 0 ) {
struct timeval timeout = {1, 0};
ssize_t sent;
fd_set wd;
retry:
FD_ZERO(&wd);
FD_SET(sock, &wd);
if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
if (interrupted())
goto retry;
return SEND_SELECTFAIL;
}
#ifdef __APPLE__
sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
#elif WIN32
sent = send(pool->sock, s + ssent, len, 0);
#else
sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
#endif
if (sent < 0) {
if (!sock_blocks())
return SEND_SENDFAIL;
sent = 0;
}
ssent += sent;
len -= sent;
}
pool->sgminer_pool_stats.times_sent++;
pool->sgminer_pool_stats.bytes_sent += ssent;
pool->sgminer_pool_stats.net_bytes_sent += ssent;
return SEND_OK;
}
bool stratum_send(struct pool *pool, char *s, ssize_t len)
{
enum send_ret ret = SEND_INACTIVE;
if (opt_protocol)
applog(LOG_DEBUG, "SEND: %s", s);
mutex_lock(&pool->stratum_lock);
if (pool->stratum_active)
ret = __stratum_send(pool, s, len);
mutex_unlock(&pool->stratum_lock);
/* This is to avoid doing applog under stratum_lock */
switch (ret) {
default:
case SEND_OK:
break;
case SEND_SELECTFAIL:
applog(LOG_DEBUG, "Write select failed on %s sock", get_pool_name(pool));
suspend_stratum(pool);
break;
case SEND_SENDFAIL:
applog(LOG_DEBUG, "Failed to send in stratum_send");
suspend_stratum(pool);
break;
case SEND_INACTIVE:
applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
break;
}
return (ret == SEND_OK);
}
static bool socket_full(struct pool *pool, int wait)
{
SOCKETTYPE sock = pool->sock;
struct timeval timeout;
fd_set rd;
if (unlikely(wait < 0))
wait = 0;
FD_ZERO(&rd);
FD_SET(sock, &rd);
timeout.tv_usec = 0;
timeout.tv_sec = wait;
if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
return true;
return false;
}
/* Check to see if Santa's been good to you */
bool sock_full(struct pool *pool)
{
if (strlen(pool->sockbuf))
return true;
return (socket_full(pool, 0));
}
static void clear_sockbuf(struct pool *pool)
{
strcpy(pool->sockbuf, "");
}
static void clear_sock(struct pool *pool)
{
ssize_t n;
mutex_lock(&pool->stratum_lock);
do {
if (pool->sock)
n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
else
n = 0;
} while (n > 0);
mutex_unlock(&pool->stratum_lock);
clear_sockbuf(pool);
}
/* Make sure the pool sockbuf is large enough to cope with any coinbase size
* by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
* and zeroing the new memory */
static void recalloc_sock(struct pool *pool, size_t len)
{
size_t old, newlen;
old = strlen(pool->sockbuf);
newlen = old + len + 1;
if (newlen < pool->sockbuf_size)
return;
newlen = newlen + (RBUFSIZE - (newlen % RBUFSIZE));
// Avoid potentially recursive locking
// applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
pool->sockbuf = (char *)realloc(pool->sockbuf, newlen);
if (!pool->sockbuf)
quithere(1, "Failed to realloc pool sockbuf");
memset(pool->sockbuf + old, 0, newlen - old);
pool->sockbuf_size = newlen;
}
/* Peeks at a socket to find the first end of line and then reads just that
* from the socket and returns that as a malloced char */
char *recv_line(struct pool *pool)
{
char *tok, *sret = NULL;
ssize_t len, buflen;
int waited = 0;
if (!strstr(pool->sockbuf, "\n")) {
struct timeval rstart, now;
cgtime(&rstart);
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
goto out;
}
do {
char s[RBUFSIZE];
size_t slen;
ssize_t n;
memset(s, 0, RBUFSIZE);
n = recv(pool->sock, s, RECVSIZE, 0);
if (!n) {
applog(LOG_DEBUG, "Socket closed waiting in recv_line");
suspend_stratum(pool);
break;
}
cgtime(&now);
waited = tdiff(&now, &rstart);
if (n < 0) {
if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
applog(LOG_DEBUG, "Failed to recv sock in recv_line");
suspend_stratum(pool);
break;
}
} else {
slen = strlen(s);
recalloc_sock(pool, slen);
strcat(pool->sockbuf, s);
}
} while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
}
buflen = strlen(pool->sockbuf);
tok = strtok(pool->sockbuf, "\n");
if (!tok) {
applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
goto out;
}
sret = strdup(tok);
len = strlen(sret);
/* Copy what's left in the buffer after the \n, including the
* terminating \0 */
if (buflen > len + 1)
memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
else
strcpy(pool->sockbuf, "");
pool->sgminer_pool_stats.times_received++;
pool->sgminer_pool_stats.bytes_received += len;
pool->sgminer_pool_stats.net_bytes_received += len;
out:
if (!sret)
clear_sock(pool);
else if (opt_protocol)
applog(LOG_DEBUG, "RECVD: %s", sret);
return sret;
}
/* Extracts a string value from a json array with error checking. To be used
* when the value of the string returned is only examined and not to be stored.
* See json_array_string below */
static char *__json_array_string(json_t *val, unsigned int entry)
{
json_t *arr_entry;
if (json_is_null(val))
return NULL;
if (!json_is_array(val))
return NULL;
if (entry > json_array_size(val))
return NULL;
arr_entry = json_array_get(val, entry);
if (!json_is_string(arr_entry))
return NULL;
return (char *)json_string_value(arr_entry);
}
/* Creates a freshly malloced dup of __json_array_string */
static char *json_array_string(json_t *val, unsigned int entry)
{
char *buf = __json_array_string(val, entry);
if (buf)
return strdup(buf);
return NULL;
}
static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, *header;
size_t cb1_len, cb2_len, alloc_len;
unsigned char *cb1, *cb2;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = json_array_string(val, 5);
nbit = json_array_string(val, 6);
ntime = json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (prev_hash)
free(prev_hash);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
if (bbversion)
free(bbversion);
if (nbit)
free(nbit);
if (ntime)
free(ntime);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
free(pool->swork.prev_hash);
free(pool->swork.bbversion);
free(pool->swork.nbit);
free(pool->swork.ntime);
pool->swork.job_id = job_id;
pool->swork.prev_hash = prev_hash;
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
pool->swork.bbversion = bbversion;
pool->swork.nbit = nbit;
pool->swork.ntime = ntime;
pool->swork.clean = clean;
alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->swork.merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin,
sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++) {
char *merkle = json_array_string(arr, i);
pool->swork.merkle_bin[i] = (unsigned char *)malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
}
}
pool->swork.merkles = merkles;
if (clean)
pool->nonce2 = 0;
pool->merkle_offset = strlen(pool->swork.bbversion) +
strlen(pool->swork.prev_hash);
pool->swork.header_len = pool->merkle_offset +
/* merkle_hash */ 32 +
strlen(pool->swork.ntime) +
strlen(pool->swork.nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
pool->merkle_offset /= 2;
pool->swork.header_len = pool->swork.header_len * 2 + 1;
align_len(&pool->swork.header_len);
header = (char *)alloca(pool->swork.header_len);
snprintf(header, pool->swork.header_len,
"%s%s%s%s%s%s%s",
pool->swork.bbversion,
pool->swork.prev_hash,
blank_merkel,
pool->swork.ntime,
pool->swork.nbit,
"00000000", /* nonce */
workpadding);
if (unlikely(!hex2bin(pool->header_bin, header, 128)))
quit(1, "Failed to convert header to header_bin in parse_notify");
cb1 = (unsigned char *)calloc(cb1_len, 1);
if (unlikely(!cb1))
quithere(1, "Failed to calloc cb1 in parse_notify");
hex2bin(cb1, coinbase1, cb1_len);
cb2 = (unsigned char *)calloc(cb2_len, 1);
if (unlikely(!cb2))
quithere(1, "Failed to calloc cb2 in parse_notify");
hex2bin(cb2, coinbase2, cb2_len);
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = (unsigned char *)calloc(alloc_len, 1);
if (unlikely(!pool->coinbase))
quit(1, "Failed to calloc pool coinbase in parse_notify");
memcpy(pool->coinbase, cb1, cb1_len);
memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
cg_wunlock(&pool->data_lock);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
free(coinbase1);
free(coinbase2);
free(cb1);
free(cb2);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
ret = true;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
static bool parse_diff(struct pool *pool, json_t *val)
{
double old_diff, diff;
if (opt_diff_mult == 0.0)
diff = json_number_value(json_array_get(val, 0)) * pool->algorithm.diff_multiplier1;
else
diff = json_number_value(json_array_get(val, 0)) * opt_diff_mult;
if (diff == 0)
return false;
cg_wlock(&pool->data_lock);
old_diff = pool->swork.diff;
pool->swork.diff = diff;
cg_wunlock(&pool->data_lock);
if (old_diff != diff) {
int idiff = diff;
if ((double)idiff == diff)
applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %d", get_pool_name(pool), idiff);
else
applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %.3f", get_pool_name(pool), diff);
} else
applog(LOG_DEBUG, "%s difficulty set to %f", get_pool_name(pool), diff);
return true;
}
static bool parse_extranonce(struct pool *pool, json_t *val)
{
char *nonce1;
int n2size;
nonce1 = json_array_string(val, 0);
if (!nonce1) {
return false;
}
n2size = json_integer_value(json_array_get(val, 1));
if (!n2size) {
free(nonce1);
return false;
}
cg_wlock(&pool->data_lock);
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
applog(LOG_NOTICE, "%s extranonce change requested", get_pool_name(pool));
return true;
}
static void __suspend_stratum(struct pool *pool)
{
clear_sockbuf(pool);
pool->stratum_active = pool->stratum_notify = false;
if (pool->sock)
CLOSESOCKET(pool->sock);
pool->sock = 0;
}
static bool parse_reconnect(struct pool *pool, json_t *val)
{
if (opt_disable_client_reconnect) {
applog(LOG_WARNING, "Stratum client.reconnect received but is disabled, not reconnecting.");
return false;
}
char *url, *port, address[256];
char *sockaddr_url, *stratum_port, *tmp; /* Tempvars. */
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
snprintf(address, sizeof(address), "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
static bool send_version(struct pool *pool, json_t *val)
{
char s[RBUFSIZE];
int id = json_integer_value(json_object_get(val, "id"));
if (!id)
return false;
sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
if (!stratum_send(pool, s, strlen(s)))
return false;
return true;
}
static bool show_message(struct pool *pool, json_t *val)
{
char *msg;
if (!json_is_array(val))
return false;
msg = (char *)json_string_value(json_array_get(val, 0));
if (!msg)
return false;
applog(LOG_NOTICE, "%s message: %s", get_pool_name(pool), msg);
return true;
}
bool parse_method(struct pool *pool, char *s)
{
json_t *val = NULL, *method, *err_val, *params;
json_error_t err;
bool ret = false;
char *buf;
if (!s)
return ret;
val = JSON_LOADS(s, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
return ret;
}
method = json_object_get(val, "method");
if (!method) {
json_decref(val);
return ret;
}
err_val = json_object_get(val, "error");
params = json_object_get(val, "params");
if (err_val && !json_is_null(err_val)) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
json_decref(val);
free(ss);
return ret;
}
buf = (char *)json_string_value(method);
if (!buf) {
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.notify", 13)) {
if (parse_notify(pool, params))
pool->stratum_notify = ret = true;
else
pool->stratum_notify = ret = false;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.set_extranonce", 21) && parse_extranonce(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
json_decref(val);
return ret;
}
bool subscribe_extranonce(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
swork_id++);
if (!stratum_send(pool, s, strlen(s)))
return ret;
/* Parse all data in the queue and anything left should be the response */
while (42) {
if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
/* some pool doesnt send anything, so this is normal */
ret = true;
goto out;
}
sret = recv_line(pool);
if (!sret)
return ret;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val) {
ss = __json_array_string(err_val, 1);
if (!ss)
ss = (char *)json_string_value(err_val);
if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool));
ret = true;
goto out;
}
if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool));
ret = true;
goto out;
}
ss = json_dumps(err_val, JSON_INDENT(3));
}
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss);
free(ss);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum extranonce subscribe for %s", get_pool_name(pool));
out:
json_decref(val);
return ret;
}
bool auth_stratum(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
swork_id++, pool->rpc_user, pool->rpc_pass);
if (!stratum_send(pool, s, strlen(s)))
return ret;
/* Parse all data in the queue and anything left should be auth */
while (42) {
sret = recv_line(pool);
if (!sret)
return ret;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss);
free(ss);
suspend_stratum(pool);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum authorisation success for %s", get_pool_name(pool));
pool->probed = true;
successful_connect = true;
out:
json_decref(val);
return ret;
}
static int recv_byte(int sockd)
{
char c;
if (recv(sockd, &c, 1, 0) != -1)
return c;
return -1;
}
static bool http_negotiate(struct pool *pool, int sockd, bool http0)
{
char buf[1024];
int i, len;
if (http0) {
snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
pool->sockaddr_url, pool->stratum_port);
} else {
snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
pool->stratum_port);
}
applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
send(sockd, buf, strlen(buf), 0);
len = recv(sockd, buf, 12, 0);
if (len <= 0) {
applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
buf[len] = '\0';
applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
return false;
}
/* Ignore unwanted headers till we get desired response */
for (i = 0; i < 4; i++) {
buf[i] = recv_byte(sockd);
if (buf[i] == (char)-1) {
applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
}
while (strncmp(buf, "\r\n\r\n", 4)) {
for (i = 0; i < 3; i++)
buf[i] = buf[i + 1];
buf[3] = recv_byte(sockd);
if (buf[3] == (char)-1) {
applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
}
applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return true;
}
static bool socks5_negotiate(struct pool *pool, int sockd)
{
unsigned char atyp, uclen;
unsigned short port;
char buf[515];
int i, len;
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
send(sockd, buf, 3, 0);
if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
buf[3] = 0x03;
len = (strlen(pool->sockaddr_url));
if (len > 255)
len = 255;
uclen = len;
buf[4] = (uclen & 0xff);
memcpy(buf + 5, pool->sockaddr_url, len);
port = atoi(pool->stratum_port);
buf[5 + len] = (port >> 8);
buf[6 + len] = (port & 0xff);
send(sockd, buf, (7 + len), 0);
if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
recv_byte(sockd);
atyp = recv_byte(sockd);
if (atyp == 0x01) {
for (i = 0; i < 4; i++)
recv_byte(sockd);
} else if (atyp == 0x03) {
len = recv_byte(sockd);
for (i = 0; i < len; i++)
recv_byte(sockd);
} else {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
for (i = 0; i < 2; i++)
recv_byte(sockd);
applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return true;
}
static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
{
unsigned short port;
in_addr_t inp;
char buf[515];
int i, len;
int ret;
buf[0] = 0x04;
buf[1] = 0x01;
port = atoi(pool->stratum_port);
buf[2] = port >> 8;
buf[3] = port & 0xff;
sprintf(&buf[8], "SGMINER");
/* See if we've been given an IP address directly to avoid needing to
* resolve it. */
inp = inet_addr(pool->sockaddr_url);
inp = ntohl(inp);
if ((int)inp != -1)
socks4a = false;
else {
/* Try to extract the IP address ourselves first */
struct addrinfo servinfobase, *servinfo, hints;
servinfo = &servinfobase;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* IPV4 only */
ret = getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo);
if (!ret) {
applog(LOG_ERR, "getaddrinfo() in socks4_negotiate() returned %i: %s", ret, gai_strerror(ret));
struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
inp = ntohl(saddr_in->sin_addr.s_addr);
socks4a = false;
freeaddrinfo(servinfo);
}
}
if (!socks4a) {
if ((int)inp == -1) {
applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
pool->sockaddr_url);
return false;
}
buf[4] = (inp >> 24) & 0xFF;
buf[5] = (inp >> 16) & 0xFF;
buf[6] = (inp >> 8) & 0xFF;
buf[7] = (inp >> 0) & 0xFF;
send(sockd, buf, 16, 0);
} else {
/* This appears to not be working but hopefully most will be
* able to resolve IP addresses themselves. */
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 1;
len = strlen(pool->sockaddr_url);
if (len > 255)
len = 255;
memcpy(&buf[16], pool->sockaddr_url, len);
len += 16;
buf[len++] = '\0';
send(sockd, buf, len, 0);
}
if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
for (i = 0; i < 6; i++)
recv_byte(sockd);
return true;
}
static void noblock_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, O_NONBLOCK | flags);
#else
u_long flags = 1;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
static void block_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
#else
u_long flags = 0;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
static bool sock_connecting(void)
{
#ifndef WIN32
return errno == EINPROGRESS;
#else
return WSAGetLastError() == WSAEWOULDBLOCK;
#endif
}
static bool setup_stratum_socket(struct pool *pool)
{
struct addrinfo servinfobase, *servinfo, *hints, *p;
char *sockaddr_url, *sockaddr_port;
int sockd;
int ret;
mutex_lock(&pool->stratum_lock);
pool->stratum_active = false;
if (pool->sock) {
/* FIXME: change to LOG_DEBUG if issue #88 resolved */
applog(LOG_INFO, "Closing %s socket", get_pool_name(pool));
CLOSESOCKET(pool->sock);
}
pool->sock = 0;
mutex_unlock(&pool->stratum_lock);
hints = &pool->stratum_hints;
memset(hints, 0, sizeof(struct addrinfo));
hints->ai_family = AF_UNSPEC;
hints->ai_socktype = SOCK_STREAM;
servinfo = &servinfobase;
if (!pool->rpc_proxy && opt_socks_proxy) {
pool->rpc_proxy = opt_socks_proxy;
extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
pool->rpc_proxytype = PROXY_SOCKS5;
}
if (pool->rpc_proxy) {
sockaddr_url = pool->sockaddr_proxy_url;
sockaddr_port = pool->sockaddr_proxy_port;
} else {
sockaddr_url = pool->sockaddr_url;
sockaddr_port = pool->stratum_port;
}
ret = getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo);
if (ret) {
applog(LOG_INFO, "getaddrinfo() in setup_stratum_socket() returned %i: %s", ret, gai_strerror(ret));
if (!pool->probed) {
applog(LOG_WARNING, "Failed to resolve (wrong URL?) %s:%s",
sockaddr_url, sockaddr_port);
pool->probed = true;
} else {
applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
sockaddr_url, sockaddr_port);
}
return false;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockd == -1) {
applog(LOG_DEBUG, "Failed socket");
continue;
}
/* Iterate non blocking over entries returned by getaddrinfo
* to cope with round robin DNS entries, finding the first one
* we can connect to quickly. */
noblock_socket(sockd);
if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
struct timeval tv_timeout = {1, 0};
int selret;
fd_set rw;
if (!sock_connecting()) {
CLOSESOCKET(sockd);
applog(LOG_DEBUG, "Failed sock connect");
continue;
}
retry:
FD_ZERO(&rw);
FD_SET(sockd, &rw);
selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
if (selret > 0 && FD_ISSET(sockd, &rw)) {
socklen_t len;
int err, n;
len = sizeof(err);
n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
if (!n && !err) {
applog(LOG_DEBUG, "Succeeded delayed connect");
block_socket(sockd);
break;
}
}
if (selret < 0 && interrupted())
goto retry;
CLOSESOCKET(sockd);
applog(LOG_DEBUG, "Select timeout/failed connect");
continue;
}
applog(LOG_WARNING, "Succeeded immediate connect");
block_socket(sockd);
break;
}
if (p == NULL) {
applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
sockaddr_url, sockaddr_port);
freeaddrinfo(servinfo);
return false;
}
freeaddrinfo(servinfo);
if (pool->rpc_proxy) {
switch (pool->rpc_proxytype) {
case PROXY_HTTP_1_0:
if (!http_negotiate(pool, sockd, true))
return false;
break;
case PROXY_HTTP:
if (!http_negotiate(pool, sockd, false))
return false;
break;
case PROXY_SOCKS5:
case PROXY_SOCKS5H:
if (!socks5_negotiate(pool, sockd))
return false;
break;
case PROXY_SOCKS4:
if (!socks4_negotiate(pool, sockd, false))
return false;
break;
case PROXY_SOCKS4A:
if (!socks4_negotiate(pool, sockd, true))
return false;
break;
default:
applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
break;
}
}
if (!pool->sockbuf) {
pool->sockbuf = (char *)calloc(RBUFSIZE, 1);
if (!pool->sockbuf)
quithere(1, "Failed to calloc pool sockbuf");
pool->sockbuf_size = RBUFSIZE;
}
pool->sock = sockd;
keep_sockalive(sockd);
return true;
}
static char *get_sessionid(json_t *val)
{
char *ret = NULL;
json_t *arr_val;
int arrsize, i;
arr_val = json_array_get(val, 0);
if (!arr_val || !json_is_array(arr_val))
goto out;
arrsize = json_array_size(arr_val);
for (i = 0; i < arrsize; i++) {
json_t *arr = json_array_get(arr_val, i);
char *notify;
if (!arr | !json_is_array(arr))
break;
notify = __json_array_string(arr, 0);
if (!notify)
continue;
if (!strncasecmp(notify, "mining.notify", 13)) {
ret = json_array_string(arr, 1);
break;
}
}
out:
return ret;
}
void suspend_stratum(struct pool *pool)
{
applog(LOG_INFO, "Closing socket for stratum %s", get_pool_name(pool));
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
mutex_unlock(&pool->stratum_lock);
}
bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (n2size < 1)
{
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
bool restart_stratum(struct pool *pool)
{
applog(LOG_DEBUG, "Restarting stratum on pool %s", get_pool_name(pool));
if (pool->stratum_active)
suspend_stratum(pool);
if (!initiate_stratum(pool))
return false;
if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
return false;
if (!auth_stratum(pool))
return false;
return true;
}
void dev_error(struct cgpu_info *dev, enum dev_reason reason)
{
dev->device_last_not_well = time(NULL);
dev->device_not_well_reason = reason;
switch (reason) {
case REASON_THREAD_FAIL_INIT:
dev->thread_fail_init_count++;
break;
case REASON_THREAD_ZERO_HASH:
dev->thread_zero_hash_count++;
break;
case REASON_THREAD_FAIL_QUEUE:
dev->thread_fail_queue_count++;
break;
case REASON_DEV_SICK_IDLE_60:
dev->dev_sick_idle_60_count++;
break;
case REASON_DEV_DEAD_IDLE_600:
dev->dev_dead_idle_600_count++;
break;
case REASON_DEV_NOSTART:
dev->dev_nostart_count++;
break;
case REASON_DEV_OVER_HEAT:
dev->dev_over_heat_count++;
break;
case REASON_DEV_THERMAL_CUTOFF:
dev->dev_thermal_cutoff_count++;
break;
case REASON_DEV_COMMS_ERROR:
dev->dev_comms_error_count++;
break;
case REASON_DEV_THROTTLE:
dev->dev_throttle_count++;
break;
}
}
/* Realloc an existing string to fit an extra string s, appending s to it. */
void *realloc_strcat(char *ptr, char *s)
{
size_t old = strlen(ptr), len = strlen(s);
char *ret;
if (!len)
return ptr;
len += old + 1;
align_len(&len);
ret = (char *)malloc(len);
if (unlikely(!ret))
quithere(1, "Failed to malloc");
sprintf(ret, "%s%s", ptr, s);
free(ptr);
return ret;
}
void RenameThread(const char* name)
{
char buf[16];
snprintf(buf, sizeof(buf), "cg@%s", name);
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
prctl(PR_SET_NAME, buf, 0, 0, 0);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__))
pthread_set_name_np(pthread_self(), buf);
#elif defined(MAC_OSX)
pthread_setname_np(buf);
#else
// Prevent warnings
(void)buf;
#endif
}
/* sgminer specific wrappers for true unnamed semaphore usage on platforms
* that support them and for apple which does not. We use a single byte across
* a pipe to emulate semaphore behaviour there. */
#ifdef __APPLE__
void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int flags, fd, i;
if (pipe(cgsem->pipefd) == -1)
quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
/* Make the pipes FD_CLOEXEC to allow them to close should we call
* execv on restart. */
for (i = 0; i < 2; i++) {
fd = cgsem->pipefd[i];
flags = fcntl(fd, F_GETFD, 0);
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1)
quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
}
}
void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
const char buf = 1;
int ret;
retry:
ret = write(cgsem->pipefd[1], &buf, 1);
if (unlikely(ret == 0))
applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
else if (unlikely(ret < 0 && interrupted))
goto retry;
}
void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
char buf;
int ret;
retry:
ret = read(cgsem->pipefd[0], &buf, 1);
if (unlikely(ret == 0))
applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
else if (unlikely(ret < 0 && interrupted))
goto retry;
}
void cgsem_destroy(cgsem_t *cgsem)
{
close(cgsem->pipefd[1]);
close(cgsem->pipefd[0]);
}
/* This is similar to sem_timedwait but takes a millisecond value */
int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
{
struct timeval timeout;
int ret, fd;
fd_set rd;
char buf;
retry:
fd = cgsem->pipefd[0];
FD_ZERO(&rd);
FD_SET(fd, &rd);
ms_to_timeval(&timeout, ms);
ret = select(fd + 1, &rd, NULL, NULL, &timeout);
if (ret > 0) {
ret = read(fd, &buf, 1);
return 0;
}
if (likely(!ret))
return ETIMEDOUT;
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
/* We don't reach here */
return 0;
}
/* Reset semaphore count back to zero */
void cgsem_reset(cgsem_t *cgsem)
{
int ret, fd;
fd_set rd;
char buf;
fd = cgsem->pipefd[0];
FD_ZERO(&rd);
FD_SET(fd, &rd);
do {
struct timeval timeout = {0, 0};
ret = select(fd + 1, &rd, NULL, NULL, &timeout);
if (ret > 0)
ret = read(fd, &buf, 1);
else if (unlikely(ret < 0 && interrupted()))
ret = 1;
} while (ret > 0);
}
#else
void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int ret;
if ((ret = sem_init(cgsem, 0, 0)))
quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
}
void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
if (unlikely(sem_post(cgsem)))
quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
}
void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
retry:
if (unlikely(sem_wait(cgsem))) {
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
}
}
int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
{
struct timespec abs_timeout, ts_now;
struct timeval tv_now;
int ret;
cgtime(&tv_now);
timeval_to_spec(&ts_now, &tv_now);
ms_to_timespec(&abs_timeout, ms);
retry:
timeraddspec(&abs_timeout, &ts_now);
ret = sem_timedwait(cgsem, &abs_timeout);
if (ret) {
if (likely(sock_timeout()))
return ETIMEDOUT;
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
}
return 0;
}
void cgsem_reset(cgsem_t *cgsem)
{
int ret;
do {
ret = sem_trywait(cgsem);
if (unlikely(ret < 0 && interrupted()))
ret = 0;
} while (!ret);
}
void cgsem_destroy(cgsem_t *cgsem)
{
sem_destroy(cgsem);
}
#endif
/* Provide a completion_timeout helper function for unreliable functions that
* may die due to driver issues etc that time out if the function fails and
* can then reliably return. */
struct cg_completion {
cgsem_t cgsem;
void (*fn)(void *fnarg);
void *fnarg;
};
void *completion_thread(void *arg)
{
struct cg_completion *cgc = (struct cg_completion *)arg;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
cgc->fn(cgc->fnarg);
cgsem_post(&cgc->cgsem);
return NULL;
}
bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
{
struct cg_completion *cgc;
pthread_t pthread;
bool ret = false;
cgc = (struct cg_completion *)malloc(sizeof(struct cg_completion));
if (unlikely(!cgc))
return ret;
cgsem_init(&cgc->cgsem);
#ifdef _MSC_VER
cgc->fn = (void(__cdecl *)(void *))fn;
#else
cgc->fn = fn;
#endif
cgc->fnarg = fnarg;
pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
ret = cgsem_mswait(&cgc->cgsem, timeout);
if (ret)
pthread_cancel(pthread);
pthread_join(pthread, NULL);
free(cgc);
return !ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2212_0 |
crossvul-cpp_data_good_3477_0 | /*
* security/tomoyo/mount.c
*
* Copyright (C) 2005-2010 NTT DATA CORPORATION
*/
#include <linux/slab.h>
#include "common.h"
/* Keywords for mount restrictions. */
/* Allow to call 'mount --bind /source_dir /dest_dir' */
#define TOMOYO_MOUNT_BIND_KEYWORD "--bind"
/* Allow to call 'mount --move /old_dir /new_dir ' */
#define TOMOYO_MOUNT_MOVE_KEYWORD "--move"
/* Allow to call 'mount -o remount /dir ' */
#define TOMOYO_MOUNT_REMOUNT_KEYWORD "--remount"
/* Allow to call 'mount --make-unbindable /dir' */
#define TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD "--make-unbindable"
/* Allow to call 'mount --make-private /dir' */
#define TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD "--make-private"
/* Allow to call 'mount --make-slave /dir' */
#define TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD "--make-slave"
/* Allow to call 'mount --make-shared /dir' */
#define TOMOYO_MOUNT_MAKE_SHARED_KEYWORD "--make-shared"
/**
* tomoyo_audit_mount_log - Audit mount log.
*
* @r: Pointer to "struct tomoyo_request_info".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_audit_mount_log(struct tomoyo_request_info *r)
{
const char *dev = r->param.mount.dev->name;
const char *dir = r->param.mount.dir->name;
const char *type = r->param.mount.type->name;
const unsigned long flags = r->param.mount.flags;
if (r->granted)
return 0;
if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD))
tomoyo_warn_log(r, "mount -o remount %s 0x%lX", dir, flags);
else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD)
|| !strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD))
tomoyo_warn_log(r, "mount %s %s %s 0x%lX", type, dev, dir,
flags);
else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD))
tomoyo_warn_log(r, "mount %s %s 0x%lX", type, dir, flags);
else
tomoyo_warn_log(r, "mount -t %s %s %s 0x%lX", type, dev, dir,
flags);
return tomoyo_supervisor(r,
TOMOYO_KEYWORD_ALLOW_MOUNT "%s %s %s 0x%lX\n",
tomoyo_pattern(r->param.mount.dev),
tomoyo_pattern(r->param.mount.dir), type,
flags);
}
static bool tomoyo_check_mount_acl(struct tomoyo_request_info *r,
const struct tomoyo_acl_info *ptr)
{
const struct tomoyo_mount_acl *acl =
container_of(ptr, typeof(*acl), head);
return tomoyo_compare_number_union(r->param.mount.flags, &acl->flags) &&
tomoyo_compare_name_union(r->param.mount.type, &acl->fs_type) &&
tomoyo_compare_name_union(r->param.mount.dir, &acl->dir_name) &&
(!r->param.mount.need_dev ||
tomoyo_compare_name_union(r->param.mount.dev, &acl->dev_name));
}
/**
* tomoyo_mount_acl - Check permission for mount() operation.
*
* @r: Pointer to "struct tomoyo_request_info".
* @dev_name: Name of device file.
* @dir: Pointer to "struct path".
* @type: Name of filesystem type.
* @flags: Mount options.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_mount_acl(struct tomoyo_request_info *r, char *dev_name,
struct path *dir, char *type, unsigned long flags)
{
struct path path;
struct file_system_type *fstype = NULL;
const char *requested_type = NULL;
const char *requested_dir_name = NULL;
const char *requested_dev_name = NULL;
struct tomoyo_path_info rtype;
struct tomoyo_path_info rdev;
struct tomoyo_path_info rdir;
int need_dev = 0;
int error = -ENOMEM;
/* Get fstype. */
requested_type = tomoyo_encode(type);
if (!requested_type)
goto out;
rtype.name = requested_type;
tomoyo_fill_path_info(&rtype);
/* Get mount point. */
requested_dir_name = tomoyo_realpath_from_path(dir);
if (!requested_dir_name) {
error = -ENOMEM;
goto out;
}
rdir.name = requested_dir_name;
tomoyo_fill_path_info(&rdir);
/* Compare fs name. */
if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD)) {
need_dev = -1; /* dev_name is a directory */
} else {
fstype = get_fs_type(type);
if (!fstype) {
error = -ENODEV;
goto out;
}
if (fstype->fs_flags & FS_REQUIRES_DEV)
/* dev_name is a block device file. */
need_dev = 1;
}
if (need_dev) {
/* Get mount point or device file. */
if (!dev_name || kern_path(dev_name, LOOKUP_FOLLOW, &path)) {
error = -ENOENT;
goto out;
}
requested_dev_name = tomoyo_realpath_from_path(&path);
path_put(&path);
if (!requested_dev_name) {
error = -ENOENT;
goto out;
}
} else {
/* Map dev_name to "<NULL>" if no dev_name given. */
if (!dev_name)
dev_name = "<NULL>";
requested_dev_name = tomoyo_encode(dev_name);
if (!requested_dev_name) {
error = -ENOMEM;
goto out;
}
}
rdev.name = requested_dev_name;
tomoyo_fill_path_info(&rdev);
r->param_type = TOMOYO_TYPE_MOUNT_ACL;
r->param.mount.need_dev = need_dev;
r->param.mount.dev = &rdev;
r->param.mount.dir = &rdir;
r->param.mount.type = &rtype;
r->param.mount.flags = flags;
do {
tomoyo_check_acl(r, tomoyo_check_mount_acl);
error = tomoyo_audit_mount_log(r);
} while (error == TOMOYO_RETRY_REQUEST);
out:
kfree(requested_dev_name);
kfree(requested_dir_name);
if (fstype)
put_filesystem(fstype);
kfree(requested_type);
return error;
}
/**
* tomoyo_mount_permission - Check permission for mount() operation.
*
* @dev_name: Name of device file.
* @path: Pointer to "struct path".
* @type: Name of filesystem type. May be NULL.
* @flags: Mount options.
* @data_page: Optional data. May be NULL.
*
* Returns 0 on success, negative value otherwise.
*/
int tomoyo_mount_permission(char *dev_name, struct path *path, char *type,
unsigned long flags, void *data_page)
{
struct tomoyo_request_info r;
int error;
int idx;
if (tomoyo_init_request_info(&r, NULL, TOMOYO_MAC_FILE_MOUNT)
== TOMOYO_CONFIG_DISABLED)
return 0;
if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
flags &= ~MS_MGC_MSK;
if (flags & MS_REMOUNT) {
type = TOMOYO_MOUNT_REMOUNT_KEYWORD;
flags &= ~MS_REMOUNT;
}
if (flags & MS_MOVE) {
type = TOMOYO_MOUNT_MOVE_KEYWORD;
flags &= ~MS_MOVE;
}
if (flags & MS_BIND) {
type = TOMOYO_MOUNT_BIND_KEYWORD;
flags &= ~MS_BIND;
}
if (flags & MS_UNBINDABLE) {
type = TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD;
flags &= ~MS_UNBINDABLE;
}
if (flags & MS_PRIVATE) {
type = TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD;
flags &= ~MS_PRIVATE;
}
if (flags & MS_SLAVE) {
type = TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD;
flags &= ~MS_SLAVE;
}
if (flags & MS_SHARED) {
type = TOMOYO_MOUNT_MAKE_SHARED_KEYWORD;
flags &= ~MS_SHARED;
}
if (!type)
type = "<NULL>";
idx = tomoyo_read_lock();
error = tomoyo_mount_acl(&r, dev_name, path, type, flags);
tomoyo_read_unlock(idx);
return error;
}
static bool tomoyo_same_mount_acl(const struct tomoyo_acl_info *a,
const struct tomoyo_acl_info *b)
{
const struct tomoyo_mount_acl *p1 = container_of(a, typeof(*p1), head);
const struct tomoyo_mount_acl *p2 = container_of(b, typeof(*p2), head);
return tomoyo_same_acl_head(&p1->head, &p2->head) &&
tomoyo_same_name_union(&p1->dev_name, &p2->dev_name) &&
tomoyo_same_name_union(&p1->dir_name, &p2->dir_name) &&
tomoyo_same_name_union(&p1->fs_type, &p2->fs_type) &&
tomoyo_same_number_union(&p1->flags, &p2->flags);
}
/**
* tomoyo_write_mount - Write "struct tomoyo_mount_acl" list.
*
* @data: String to parse.
* @domain: Pointer to "struct tomoyo_domain_info".
* @is_delete: True if it is a delete request.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_write_mount(char *data, struct tomoyo_domain_info *domain,
const bool is_delete)
{
struct tomoyo_mount_acl e = { .head.type = TOMOYO_TYPE_MOUNT_ACL };
int error = is_delete ? -ENOENT : -ENOMEM;
char *w[4];
if (!tomoyo_tokenize(data, w, sizeof(w)) || !w[3][0])
return -EINVAL;
if (!tomoyo_parse_name_union(w[0], &e.dev_name) ||
!tomoyo_parse_name_union(w[1], &e.dir_name) ||
!tomoyo_parse_name_union(w[2], &e.fs_type) ||
!tomoyo_parse_number_union(w[3], &e.flags))
goto out;
error = tomoyo_update_domain(&e.head, sizeof(e), is_delete, domain,
tomoyo_same_mount_acl, NULL);
out:
tomoyo_put_name_union(&e.dev_name);
tomoyo_put_name_union(&e.dir_name);
tomoyo_put_name_union(&e.fs_type);
tomoyo_put_number_union(&e.flags);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3477_0 |
crossvul-cpp_data_good_4829_0 | /*
* gd_gd2.c
*
* Implements the I/O and support for the GD2 format.
*
* Changing the definition of GD2_DBG (below) will cause copious messages
* to be displayed while it processes requests.
*
* Designed, Written & Copyright 1999, Philip Warner.
*
*/
/**
* File: GD2 IO
*
* Read and write GD2 images.
*
* The GD2 image format is a proprietary image format of libgd. *It has to be*
* *regarded as being obsolete, and should only be used for development and*
* *testing purposes.*
*
* Structure of a GD2 image file:
* - file header
* - chunk headers (only for compressed data)
* - color header (either truecolor or palette)
* - chunks of image data (chunk-row-major, top to bottom, left to right)
*
* All numbers are stored in big-endian format.
*
* File header structure:
* signature - 4 bytes (always "gd2\0")
* version - 1 word (e.g. "\0\002")
* width - 1 word
* height - 1 word
* chunk_size - 1 word
* format - 1 word
* x_chunk_count - 1 word
* y_chunk_count - 1 word
*
* Recognized formats:
* 1 - raw palette image data
* 2 - compressed palette image data
* 3 - raw truecolor image data
* 4 - compressed truecolor image data
*
* Chunk header:
* offset - 1 dword
* size - 1 dword
*
* There are x_chunk_count * y_chunk_count chunk headers.
*
* Truecolor image color header:
* truecolor - 1 byte (always "\001")
* transparent - 1 dword (ARGB color)
*
* Palette image color header:
* truecolor - 1 byte (always "\0")
* count - 1 word (the number of used palette colors)
* transparent - 1 dword (ARGB color)
* palette - 256 dwords (RGBA colors)
*
* Chunk structure:
* Sequential pixel data of a rectangular area (chunk_size x chunk_size),
* row-major from top to bottom, left to right:
* - 1 byte per pixel for palette images
* - 1 dword (ARGB) per pixel for truecolor images
*
* Depending on format, the chunk may be ZLIB compressed.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* 2.0.29: no more errno.h, makes windows happy */
#include <math.h>
#include <string.h>
#include "gd.h"
#include "gd_errors.h"
#include "gdhelpers.h"
/* 2.03: gd2 is no longer mandatory */
/* JCE - test after including gd.h so that HAVE_LIBZ can be set in
* a config.h file included by gd.h */
#ifdef HAVE_LIBZ
#include <zlib.h>
#define TRUE 1
#define FALSE 0
/* 2.11: not part of the API, as the save routine can figure it out
from im->trueColor, and the load routine doesn't need to tell
the end user the saved format. NOTE: adding 2 is assumed
to result in the correct format value for truecolor! */
#define GD2_FMT_TRUECOLOR_RAW 3
#define GD2_FMT_TRUECOLOR_COMPRESSED 4
#define gd2_compressed(fmt) (((fmt) == GD2_FMT_COMPRESSED) || \
((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
#define gd2_truecolor(fmt) (((fmt) == GD2_FMT_TRUECOLOR_RAW) || \
((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
/* Use this for commenting out debug-print statements. */
/* Just use the first '#define' to allow all the prints... */
/*#define GD2_DBG(s) (s) */
#define GD2_DBG(s)
typedef struct {
int offset;
int size;
}
t_chunk_info;
extern int _gdGetColors (gdIOCtx * in, gdImagePtr im, int gd2xFlag);
extern void _gdPutColors (gdImagePtr im, gdIOCtx * out);
/* */
/* Read the extra info in the gd2 header. */
/* */
static int
_gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
if (overflow2(sizeof(t_chunk_info), nc)) {
goto fail1;
}
sidx = sizeof (t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc (sidx, 1);
if (cidx == NULL) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
static gdImagePtr
_gd2CreateFromFile (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt,
int *ncx, int *ncy, t_chunk_info ** cidx)
{
gdImagePtr im;
if (_gd2GetHeader (in, sx, sy, cs, vers, fmt, ncx, ncy, cidx) != 1) {
GD2_DBG (printf ("Bad GD2 header\n"));
goto fail1;
}
if (gd2_truecolor (*fmt)) {
im = gdImageCreateTrueColor (*sx, *sy);
} else {
im = gdImageCreate (*sx, *sy);
}
if (im == NULL) {
GD2_DBG (printf ("Could not create gdImage\n"));
goto fail2;
};
if (!_gdGetColors (in, im, (*vers) == 2)) {
GD2_DBG (printf ("Could not read color palette\n"));
goto fail3;
}
GD2_DBG (printf ("Image palette completed: %d colours\n", im->colorsTotal));
return im;
fail3:
gdImageDestroy (im);
fail2:
gdFree(*cidx);
fail1:
return 0;
}
static int
_gd2ReadChunk (int offset, char *compBuf, int compSize, char *chunkBuf,
uLongf * chunkLen, gdIOCtx * in)
{
int zerr;
if (gdTell (in) != offset) {
GD2_DBG (printf ("Positioning in file to %d\n", offset));
gdSeek (in, offset);
} else {
GD2_DBG (printf ("Already Positioned in file to %d\n", offset));
};
/* Read and uncompress an entire chunk. */
GD2_DBG (printf ("Reading file\n"));
if (gdGetBuf (compBuf, compSize, in) != compSize) {
return FALSE;
};
GD2_DBG (printf
("Got %d bytes. Uncompressing into buffer of %d bytes\n", compSize,
*chunkLen));
zerr =
uncompress ((unsigned char *) chunkBuf, chunkLen,
(unsigned char *) compBuf, compSize);
if (zerr != Z_OK) {
GD2_DBG (printf ("Error %d from uncompress\n", zerr));
return FALSE;
};
GD2_DBG (printf ("Got chunk\n"));
return TRUE;
}
/*
Function: gdImageCreateFromGd2
<gdImageCreateFromGd2> is called to load images from gd2 format
files. Invoke <gdImageCreateFromGd2> with an already opened
pointer to a file containing the desired image in the gd2 file
format, which is specific to gd2 and intended for fast loading of
parts of large images. (It is a compressed format, but generally
not as good as maximum compression of the entire image would be.)
<gdImageCreateFromGd2> returns a <gdImagePtr> to the new image, or
NULL if unable to load the image (most often because the file is
corrupt or does not contain a gd format
image). <gdImageCreateFromGd2> does not close the file. You can
inspect the sx and sy members of the image to determine its
size. The image must eventually be destroyed using
<gdImageDestroy>.
Variants:
<gdImageCreateFromGd2Ptr> creates an image from GD data (i.e. the
contents of a GD2 file) already in memory.
<gdImageCreateFromGd2Ctx> reads in an image using the functions in
a <gdIOCtx> struct.
Parameters:
infile - The input FILE pointer
Returns:
A pointer to the new image or NULL if an error occurred.
Example:
> gdImagePtr im;
> FILE *in;
> in = fopen("mygd.gd2", "rb");
> im = gdImageCreateFromGd2(in);
> fclose(in);
> // ... Use the image ...
> gdImageDestroy(im);
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2 (FILE * inFile)
{
gdIOCtx *in = gdNewFileCtx (inFile);
gdImagePtr im;
if (in == NULL) return NULL;
im = gdImageCreateFromGd2Ctx (in);
in->gd_free (in);
return im;
}
/*
Function: gdImageCreateFromGd2Ptr
Parameters:
size - size of GD2 data in bytes.
data - GD2 data (i.e. contents of a GIF file).
See <gdImageCreateFromGd2>.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ptr (int size, void *data)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
if(!in)
return 0;
im = gdImageCreateFromGd2Ctx (in);
in->gd_free (in);
return im;
}
/*
Function: gdImageCreateFromGd2Ctx
Reads in a GD2 image via a <gdIOCtx> struct. See
<gdImageCreateFromGd2>.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
int sx, sy;
int i;
int ncx, ncy, nc, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int vers, fmt;
t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */
int chunkNum = 0;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax = 0;
int bytesPerPixel;
char *compBuf = NULL; /* So we can gdFree it with impunity. */
gdImagePtr im;
/* Get the header */
im =
_gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
&chunkIdx);
if (im == NULL) {
/* No need to free chunkIdx as _gd2CreateFromFile does it for us. */
return 0;
}
bytesPerPixel = im->trueColor ? 4 : 1;
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
/* Allocate buffers */
chunkMax = cs * bytesPerPixel * cs;
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail;
}
GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
};
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Read the data... */
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk %d (%d, %d), y from %d to %d\n",
chunkNum, cx, cy, ylo, yhi));
if (gd2_compressed (fmt)) {
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
GD2_DBG (printf ("Error reading comproessed chunk\n"));
goto fail;
};
chunkPos = 0;
};
for (y = ylo; (y < yhi); y++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
/*GD2_DBG(printf("y=%d: ",y)); */
if (!gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
if (!gdGetInt (&im->tpixels[y][x], in)) {
gd_error("gd2: EOF while reading\n");
gdImageDestroy(im);
return NULL;
}
} else {
int ch;
if (!gdGetByte (&ch, in)) {
gd_error("gd2: EOF while reading\n");
gdImageDestroy(im);
return NULL;
}
im->pixels[y][x] = ch;
}
}
} else {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
/* 2.0.1: work around a gcc bug by being verbose.
TBB */
int a = chunkBuf[chunkPos++] << 24;
int r = chunkBuf[chunkPos++] << 16;
int g = chunkBuf[chunkPos++] << 8;
int b = chunkBuf[chunkPos++];
/* 2.0.11: tpixels */
im->tpixels[y][x] = a + r + g + b;
} else {
im->pixels[y][x] = chunkBuf[chunkPos++];
}
};
};
/*GD2_DBG(printf("\n")); */
};
chunkNum++;
};
};
GD2_DBG (printf ("Freeing memory\n"));
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
GD2_DBG (printf ("Done\n"));
return im;
fail:
gdImageDestroy (im);
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
/*
Function: gdImageCreateFromGd2Part
<gdImageCreateFromGd2Part> is called to load parts of images from
gd2 format files. Invoked in the same way as <gdImageCreateFromGd2>,
but with extra parameters indicating the source (x, y) and
width/height of the desired image. <gdImageCreateFromGd2Part>
returns a <gdImagePtr> to the new image, or NULL if unable to load
the image. The image must eventually be destroyed using
<gdImageDestroy>.
Variants:
<gdImageCreateFromGd2PartPtr> creates an image from GD2 data
(i.e. the contents of a GD2 file) already in memory.
<gdImageCreateFromGd2Ctx> reads in an image using the functions in
a <gdIOCtx> struct.
Parameters:
infile - The input FILE pointer
srcx, srcy - The source X and Y coordinates
w, h - The resulting image's width and height
Returns:
A pointer to the new image or NULL if an error occurred.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Part (FILE * inFile, int srcx, int srcy, int w, int h)
{
gdImagePtr im;
gdIOCtx *in = gdNewFileCtx (inFile);
if (in == NULL) return NULL;
im = gdImageCreateFromGd2PartCtx (in, srcx, srcy, w, h);
in->gd_free (in);
return im;
}
/*
Function: gdImageCreateFromGd2PartPtr
Parameters:
size - size of GD data in bytes.
data - GD data (i.e. contents of a GIF file).
srcx, srcy - The source X and Y coordinates
w, h - The resulting image's width and height
Reads in part of a GD2 image file stored from memory. See
<gdImageCreateFromGd2Part>.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartPtr (int size, void *data, int srcx, int srcy, int w,
int h)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
if(!in)
return 0;
im = gdImageCreateFromGd2PartCtx (in, srcx, srcy, w, h);
in->gd_free (in);
return im;
}
/*
Function: gdImageCreateFromGd2PartCtx
Parameters:
in - The data source.
srcx, srcy - The source X and Y coordinates
w, h - The resulting image's width and height
Reads in part of a GD2 data image file via a <gdIOCtx> struct. See
<gdImageCreateFromGd2Part>.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
{
int scx, scy, ecx, ecy, fsx, fsy;
int nc, ncx, ncy, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int dstart, dpos;
int i;
/* 2.0.12: unsigned is correct; fixes problems with color munging.
Thanks to Steven Brown. */
unsigned int ch;
int vers, fmt;
t_chunk_info *chunkIdx = NULL;
unsigned char *chunkBuf = NULL;
int chunkNum;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax;
char *compBuf = NULL;
gdImagePtr im;
/* */
/* The next few lines are basically copied from gd2CreateFromFile */
/* - we change the file size, so don't want to use the code directly. */
/* but we do need to know the file size. */
/* */
if (_gd2GetHeader (in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx)
!= 1) {
goto fail1;
}
GD2_DBG (printf ("File size is %dx%d\n", fsx, fsy));
/* This is the difference - make a file based on size of chunks. */
if (gd2_truecolor (fmt)) {
im = gdImageCreateTrueColor (w, h);
} else {
im = gdImageCreate (w, h);
}
if (im == NULL) {
goto fail1;
};
if (!_gdGetColors (in, im, vers == 2)) {
goto fail2;
}
GD2_DBG (printf ("Image palette completed: %d colours\n", im->colorsTotal));
/* Process the header info */
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
if (im->trueColor) {
chunkMax = cs * cs * 4;
} else {
chunkMax = cs * cs;
}
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail2;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail2;
}
};
/* Don't bother with this... */
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Work out start/end chunks */
scx = srcx / cs;
scy = srcy / cs;
if (scx < 0) {
scx = 0;
};
if (scy < 0) {
scy = 0;
};
ecx = (srcx + w) / cs;
ecy = (srcy + h) / cs;
if (ecx >= ncx) {
ecx = ncx - 1;
};
if (ecy >= ncy) {
ecy = ncy - 1;
};
/* Remember file position of image data. */
dstart = gdTell (in);
GD2_DBG (printf ("Data starts at %d\n", dstart));
/* Loop through the chunks. */
for (cy = scy; (cy <= ecy); cy++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > fsy) {
yhi = fsy;
};
for (cx = scx; (cx <= ecx); cx++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > fsx) {
xhi = fsx;
};
GD2_DBG (printf
("Processing Chunk (%d, %d), from %d to %d\n", cx, cy, ylo,
yhi));
if (!gd2_compressed (fmt)) {
GD2_DBG (printf ("Using raw format data\n"));
if (im->trueColor) {
dpos =
(cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) +
dstart;
} else {
dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart;
}
/* gd 2.0.11: gdSeek returns TRUE on success, not 0.
Longstanding bug. 01/16/03 */
if (!gdSeek (in, dpos)) {
gd_error("Seek error\n");
goto fail2;
};
GD2_DBG (printf
("Reading (%d, %d) from position %d\n", cx, cy,
dpos - dstart));
} else {
chunkNum = cx + cy * ncx;
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
printf ("Error reading comproessed chunk\n");
goto fail2;
};
chunkPos = 0;
GD2_DBG (printf
("Reading (%d, %d) from chunk %d\n", cx, cy,
chunkNum));
};
GD2_DBG (printf
(" into (%d, %d) - (%d, %d)\n", xlo, ylo, xhi, yhi));
for (y = ylo; (y < yhi); y++) {
for (x = xlo; x < xhi; x++) {
if (!gd2_compressed (fmt)) {
if (im->trueColor) {
if (!gdGetInt ((int *) &ch, in)) {
ch = 0;
/*printf("EOF while reading file\n"); */
/*goto fail2; */
}
} else {
ch = gdGetC (in);
if ((int) ch == EOF) {
ch = 0;
/*printf("EOF while reading file\n"); */
/*goto fail2; */
}
}
} else {
if (im->trueColor) {
ch = chunkBuf[chunkPos++];
ch = (ch << 8) + chunkBuf[chunkPos++];
ch = (ch << 8) + chunkBuf[chunkPos++];
ch = (ch << 8) + chunkBuf[chunkPos++];
} else {
ch = chunkBuf[chunkPos++];
}
};
/* Only use a point that is in the image. */
if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0)
&& (y >= srcy) && (y < (srcy + h)) && (y < fsy)
&& (y >= 0)) {
/* 2.0.11: tpixels */
if (im->trueColor) {
im->tpixels[y - srcy][x - srcx] = ch;
} else {
im->pixels[y - srcy][x - srcx] = ch;
}
}
};
};
};
};
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
return im;
fail2:
gdImageDestroy (im);
fail1:
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
static void
_gd2PutHeader (gdImagePtr im, gdIOCtx * out, int cs, int fmt, int cx, int cy)
{
int i;
/* Send the gd2 id, to verify file format. */
for (i = 0; i < 4; i++) {
gdPutC ((unsigned char) (GD2_ID[i]), out);
};
/* */
/* We put the version info first, so future versions can easily change header info. */
/* */
gdPutWord (GD2_VERS, out);
gdPutWord (im->sx, out);
gdPutWord (im->sy, out);
gdPutWord (cs, out);
gdPutWord (fmt, out);
gdPutWord (cx, out);
gdPutWord (cy, out);
}
static void
_gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
{
int ncx, ncy, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int chunkLen;
int chunkNum = 0;
char *chunkData = NULL; /* So we can gdFree it with impunity. */
char *compData = NULL; /* So we can gdFree it with impunity. */
uLongf compLen;
int idxPos = 0;
int idxSize;
t_chunk_info *chunkIdx = NULL;
int posSave;
int bytesPerPixel = im->trueColor ? 4 : 1;
int compMax = 0;
/*printf("Trying to write GD2 file\n"); */
/* */
/* Force fmt to a valid value since we don't return anything. */
/* */
if ((fmt != GD2_FMT_RAW) && (fmt != GD2_FMT_COMPRESSED)) {
fmt = GD2_FMT_COMPRESSED;
};
if (im->trueColor) {
fmt += 2;
}
/* */
/* Make sure chunk size is valid. These are arbitrary values; 64 because it seems */
/* a little silly to expect performance improvements on a 64x64 bit scale, and */
/* 4096 because we buffer one chunk, and a 16MB buffer seems a little large - it may be */
/* OK for one user, but for another to read it, they require the buffer. */
/* */
if (cs == 0) {
cs = GD2_CHUNKSIZE;
} else if (cs < GD2_CHUNKSIZE_MIN) {
cs = GD2_CHUNKSIZE_MIN;
} else if (cs > GD2_CHUNKSIZE_MAX) {
cs = GD2_CHUNKSIZE_MAX;
};
/* Work out number of chunks. */
ncx = (im->sx + cs - 1) / cs;
ncy = (im->sy + cs - 1) / cs;
/* Write the standard header. */
_gd2PutHeader (im, out, cs, fmt, ncx, ncy);
if (gd2_compressed (fmt)) {
/* */
/* Work out size of buffer for compressed data, If CHUNKSIZE is large, */
/* then these will be large! */
/* */
/* The zlib notes say output buffer size should be (input size) * 1.01 * 12 */
/* - we'll use 1.02 to be paranoid. */
/* */
compMax = cs * bytesPerPixel * cs * 1.02 + 12;
/* */
/* Allocate the buffers. */
/* */
chunkData = gdCalloc (cs * bytesPerPixel * cs, 1);
if (!chunkData) {
goto fail;
}
compData = gdCalloc (compMax, 1);
if (!compData) {
goto fail;
}
/* */
/* Save the file position of chunk index, and allocate enough space for */
/* each chunk_info block . */
/* */
idxPos = gdTell (out);
idxSize = ncx * ncy * sizeof (t_chunk_info);
GD2_DBG (printf ("Index size is %d\n", idxSize));
gdSeek (out, idxPos + idxSize);
chunkIdx = gdCalloc (idxSize * sizeof (t_chunk_info), 1);
if (!chunkIdx) {
goto fail;
}
};
_gdPutColors (im, out);
GD2_DBG (printf ("Size: %dx%d\n", im->sx, im->sy));
GD2_DBG (printf ("Chunks: %dx%d\n", ncx, ncy));
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk (%dx%d), y from %d to %d\n", cx, cy,
ylo, yhi));
chunkLen = 0;
for (y = ylo; (y < yhi); y++) {
/*GD2_DBG(printf("y=%d: ",y)); */
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
if (gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
/* 2.0.11: use truecolor pixel array. TBB */
/*GD2_DBG(printf("%d...",x)); */
if (im->trueColor) {
int p = im->tpixels[y][x];
chunkData[chunkLen++] = gdTrueColorGetAlpha (p);
chunkData[chunkLen++] = gdTrueColorGetRed (p);
chunkData[chunkLen++] = gdTrueColorGetGreen (p);
chunkData[chunkLen++] = gdTrueColorGetBlue (p);
} else {
int p = im->pixels[y][x];
chunkData[chunkLen++] = p;
}
};
} else {
for (x = xlo; x < xhi; x++) {
/*GD2_DBG(printf("%d, ",x)); */
if (im->trueColor) {
gdPutInt (im->tpixels[y][x], out);
} else {
gdPutC ((unsigned char) im->pixels[y][x], out);
}
};
};
/*GD2_DBG(printf("y=%d done.\n",y)); */
};
if (gd2_compressed (fmt)) {
compLen = compMax;
if (compress ((unsigned char *)
&compData[0], &compLen,
(unsigned char *) &chunkData[0],
chunkLen) != Z_OK) {
printf ("Error from compressing\n");
} else {
chunkIdx[chunkNum].offset = gdTell (out);
chunkIdx[chunkNum++].size = compLen;
GD2_DBG (printf
("Chunk %d size %d offset %d\n", chunkNum,
chunkIdx[chunkNum - 1].size,
chunkIdx[chunkNum - 1].offset));
if (gdPutBuf (compData, compLen, out) <= 0) {
gd_error("gd write error\n");
};
};
};
};
};
if (gd2_compressed (fmt)) {
/* Save the position, write the index, restore position (paranoia). */
GD2_DBG (printf ("Seeking %d to write index\n", idxPos));
posSave = gdTell (out);
gdSeek (out, idxPos);
GD2_DBG (printf ("Writing index\n"));
for (x = 0; x < chunkNum; x++) {
GD2_DBG (printf
("Chunk %d size %d offset %d\n", x, chunkIdx[x].size,
chunkIdx[x].offset));
gdPutInt (chunkIdx[x].offset, out);
gdPutInt (chunkIdx[x].size, out);
};
/* We don't use fwrite for *endian reasons. */
/*fwrite(chunkIdx, sizeof(int)*2, chunkNum, out); */
gdSeek (out, posSave);
};
/*printf("Memory block size is %d\n",gdTell(out)); */
fail:
GD2_DBG (printf ("Freeing memory\n"));
if (chunkData) {
gdFree (chunkData);
}
if (compData) {
gdFree (compData);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
GD2_DBG (printf ("Done\n"));
}
/*
Function: gdImageGd2
*/
BGD_DECLARE(void) gdImageGd2 (gdImagePtr im, FILE * outFile, int cs, int fmt)
{
gdIOCtx *out = gdNewFileCtx (outFile);
if (out == NULL) return;
_gdImageGd2 (im, out, cs, fmt);
out->gd_free (out);
}
/*
Function: gdImageGd2Ptr
*/
BGD_DECLARE(void *) gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
if (out == NULL) return NULL;
_gdImageGd2 (im, out, cs, fmt);
rv = gdDPExtractData (out, size);
out->gd_free (out);
return rv;
}
#else /* no HAVE_LIBZ */
static void _noLibzError (void)
{
gd_error("GD2 support is not available - no libz\n");
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2 (FILE * inFile)
{
_noLibzError();
return NULL;
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
_noLibzError();
return NULL;
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Part (FILE * inFile, int srcx, int srcy, int w, int h)
{
_noLibzError();
return NULL;
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ptr (int size, void *data)
{
_noLibzError();
return NULL;
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
{
_noLibzError();
return NULL;
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartPtr (int size, void *data, int srcx, int srcy, int w,
int h)
{
_noLibzError();
return NULL;
}
BGD_DECLARE(void) gdImageGd2 (gdImagePtr im, FILE * outFile, int cs, int fmt)
{
_noLibzError();
}
BGD_DECLARE(void *) gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
{
_noLibzError();
return NULL;
}
#endif /* HAVE_LIBZ */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4829_0 |
crossvul-cpp_data_good_364_3 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP W W PPPP %
% P P W W P P %
% PPPP W W PPPP %
% P W W W P %
% P W W P %
% %
% %
% Read Seattle Film Works Image 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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/constitute.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/resource_.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P W P %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPWP() returns MagickTrue if the image format type, identified by the
% magick string, is PWP.
%
% The format of the IsPWP method is:
%
% MagickBooleanType IsPWP(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 IsPWP(const unsigned char *magick,const size_t length)
{
if (length < 5)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"SFW95",5) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P W P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPWPImage() reads a Seattle Film Works multi-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 ReadPWPImage method is:
%
% Image *ReadPWPImage(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 Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
FILE
*file;
Image
*image,
*next_image,
*pwp_image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register Image
*p;
register ssize_t
i;
size_t
filesize,
length;
ssize_t
count;
unsigned char
magick[MagickPathExtent];
/*
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=DestroyImage(image);
return((Image *) NULL);
}
pwp_image=image;
memset(magick,0,sizeof(magick));
count=ReadBlob(pwp_image,5,magick);
if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
read_info=CloneImageInfo(image_info);
(void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
(void *) NULL);
SetImageInfoBlob(read_info,(void *) NULL,0);
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s",
filename);
for ( ; ; )
{
(void) memset(magick,0,sizeof(magick));
for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
{
for (i=0; i < 17; i++)
magick[i]=magick[i+1];
magick[17]=(unsigned char) c;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
break;
}
if (c == EOF)
{
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
{
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Dump SFW image to a temporary file.
*/
file=(FILE *) NULL;
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=fwrite("SFW94A",1,6,file);
(void) length;
filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
for (i=0; i < (ssize_t) filesize; i++)
{
c=ReadBlobByte(pwp_image);
if (c == EOF)
break;
if (fputc(c,file) != c)
break;
}
(void) fclose(file);
if (c == EOF)
{
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
next_image=ReadImage(read_info,exception);
if (next_image == (Image *) NULL)
break;
(void) FormatLocaleString(next_image->filename,MagickPathExtent,
"slide_%02ld.sfw",(long) next_image->scene);
if (image == (Image *) NULL)
image=next_image;
else
{
/*
Link image into image list.
*/
for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
next_image->previous=p;
next_image->scene=p->scene+1;
p->next=next_image;
}
if (image_info->number_scenes != 0)
if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
GetBlobSize(pwp_image));
if (status == MagickFalse)
break;
}
if (unique_file != -1)
(void) close(unique_file);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
if (EOFBlob(image) != MagickFalse)
{
char
*message;
message=GetExceptionMessage(errno);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename,
message);
message=DestroyString(message);
}
(void) CloseBlob(image);
}
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P W P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPWPImage() adds attributes for the PWP 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 RegisterPWPImage method is:
%
% size_t RegisterPWPImage(void)
%
*/
ModuleExport size_t RegisterPWPImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PWP","PWP","Seattle Film Works");
entry->decoder=(DecodeImageHandler *) ReadPWPImage;
entry->magick=(IsImageFormatHandler *) IsPWP;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P W P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPWPImage() removes format registrations made by the
% PWP module from the list of supported formats.
%
% The format of the UnregisterPWPImage method is:
%
% UnregisterPWPImage(void)
%
*/
ModuleExport void UnregisterPWPImage(void)
{
(void) UnregisterMagickInfo("PWP");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_364_3 |
crossvul-cpp_data_bad_1658_2 | /* ntp_config.c
*
* This file contains the ntpd configuration code.
*
* Written By: Sachin Kamboj
* University of Delaware
* Newark, DE 19711
* Some parts borrowed from the older ntp_config.c
* Copyright (c) 2006
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef HAVE_NETINFO
# include <netinfo/ni.h>
#endif
#include <stdio.h>
#include <ctype.h>
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include <signal.h>
#ifndef SIGCHLD
# define SIGCHLD SIGCLD
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#include "ntp.h"
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_unixtime.h"
#include "ntp_refclock.h"
#include "ntp_filegen.h"
#include "ntp_stdlib.h"
#include "lib_strbuf.h"
#include "ntp_assert.h"
#include "ntpd-opts.h"
#include "ntp_random.h"
#include "ntp_workimpl.h"
#include <isc/net.h>
#include <isc/result.h>
/*
* [Bug 467]: Some linux headers collide with CONFIG_PHONE and CONFIG_KEYS
* so #include these later.
*/
#include "ntp_config.h"
#include "ntp_cmdargs.h"
#include "ntp_scanner.h"
#include "ntp_parser.h"
/* list of servers from command line for config_peers() */
int cmdline_server_count;
char ** cmdline_servers;
/*
* "logconfig" building blocks
*/
struct masks {
const char * name;
unsigned long mask;
};
static struct masks logcfg_class[] = {
{ "clock", NLOG_OCLOCK },
{ "peer", NLOG_OPEER },
{ "sync", NLOG_OSYNC },
{ "sys", NLOG_OSYS },
{ NULL, 0 }
};
static struct masks logcfg_item[] = {
{ "info", NLOG_INFO },
{ "allinfo", NLOG_SYSINFO|NLOG_PEERINFO|NLOG_CLOCKINFO|NLOG_SYNCINFO },
{ "events", NLOG_EVENT },
{ "allevents", NLOG_SYSEVENT|NLOG_PEEREVENT|NLOG_CLOCKEVENT|NLOG_SYNCEVENT },
{ "status", NLOG_STATUS },
{ "allstatus", NLOG_SYSSTATUS|NLOG_PEERSTATUS|NLOG_CLOCKSTATUS|NLOG_SYNCSTATUS },
{ "statistics", NLOG_STATIST },
{ "allstatistics", NLOG_SYSSTATIST|NLOG_PEERSTATIST|NLOG_CLOCKSTATIST|NLOG_SYNCSTATIST },
{ "allclock", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OCLOCK },
{ "allpeer", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OPEER },
{ "allsys", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OSYS },
{ "allsync", (NLOG_INFO|NLOG_STATIST|NLOG_EVENT|NLOG_STATUS)<<NLOG_OSYNC },
{ "all", NLOG_SYSMASK|NLOG_PEERMASK|NLOG_CLOCKMASK|NLOG_SYNCMASK },
{ NULL, 0 }
};
typedef struct peer_resolved_ctx_tag {
int flags;
int host_mode; /* T_* token identifier */
u_short family;
keyid_t keyid;
u_char hmode; /* MODE_* */
u_char version;
u_char minpoll;
u_char maxpoll;
u_char ttl;
const char * group;
} peer_resolved_ctx;
/* Limits */
#define MAXPHONE 10 /* maximum number of phone strings */
#define MAXPPS 20 /* maximum length of PPS device string */
/*
* Miscellaneous macros
*/
#define ISEOL(c) ((c) == '#' || (c) == '\n' || (c) == '\0')
#define ISSPACE(c) ((c) == ' ' || (c) == '\t')
/*
* Definitions of things either imported from or exported to outside
*/
extern int yydebug; /* ntp_parser.c (.y) */
int curr_include_level; /* The current include level */
struct FILE_INFO *fp[MAXINCLUDELEVEL+1];
config_tree cfgt; /* Parser output stored here */
struct config_tree_tag *cfg_tree_history; /* History of configs */
char *sys_phone[MAXPHONE] = {NULL}; /* ACTS phone numbers */
char default_keysdir[] = NTP_KEYSDIR;
char *keysdir = default_keysdir; /* crypto keys directory */
char * saveconfigdir;
#if defined(HAVE_SCHED_SETSCHEDULER)
int config_priority_override = 0;
int config_priority;
#endif
const char *config_file;
char default_ntp_signd_socket[] =
#ifdef NTP_SIGND_PATH
NTP_SIGND_PATH;
#else
"";
#endif
char *ntp_signd_socket = default_ntp_signd_socket;
#ifdef HAVE_NETINFO
struct netinfo_config_state *config_netinfo = NULL;
int check_netinfo = 1;
#endif /* HAVE_NETINFO */
#ifdef SYS_WINNT
char *alt_config_file;
LPTSTR temp;
char config_file_storage[MAX_PATH];
char alt_config_file_storage[MAX_PATH];
#endif /* SYS_WINNT */
#ifdef HAVE_NETINFO
/*
* NetInfo configuration state
*/
struct netinfo_config_state {
void *domain; /* domain with config */
ni_id config_dir; /* ID config dir */
int prop_index; /* current property */
int val_index; /* current value */
char **val_list; /* value list */
};
#endif
struct REMOTE_CONFIG_INFO remote_config; /* Remote configuration buffer and
pointer info */
int input_from_file = 1; /* A boolean flag, which when set, indicates that
the input is to be taken from the configuration
file, instead of the remote-configuration buffer
*/
int old_config_style = 1; /* A boolean flag, which when set,
* indicates that the old configuration
* format with a newline at the end of
* every command is being used
*/
int cryptosw; /* crypto command called */
extern int sys_maxclock;
extern char *stats_drift_file; /* name of the driftfile */
extern char *leapseconds_file_name; /*name of the leapseconds file */
#ifdef HAVE_IPTOS_SUPPORT
extern unsigned int qos; /* QoS setting */
#endif /* HAVE_IPTOS_SUPPORT */
#ifdef BC_LIST_FRAMEWORK_NOT_YET_USED
/*
* backwards compatibility flags
*/
bc_entry bc_list[] = {
{ T_Bc_bugXXXX, 1 } /* default enabled */
};
/*
* declare an int pointer for each flag for quick testing without
* walking bc_list. If the pointer is consumed by libntp rather
* than ntpd, declare it in a libntp source file pointing to storage
* initialized with the appropriate value for other libntp clients, and
* redirect it to point into bc_list during ntpd startup.
*/
int *p_bcXXXX_enabled = &bc_list[0].enabled;
#endif
/* FUNCTION PROTOTYPES */
static void init_syntax_tree(config_tree *);
static void apply_enable_disable(attr_val_fifo *q, int enable);
#ifdef FREE_CFG_T
static void free_auth_node(config_tree *);
static void free_config_other_modes(config_tree *);
static void free_config_auth(config_tree *);
static void free_config_tos(config_tree *);
static void free_config_monitor(config_tree *);
static void free_config_access(config_tree *);
static void free_config_tinker(config_tree *);
static void free_config_system_opts(config_tree *);
static void free_config_logconfig(config_tree *);
static void free_config_phone(config_tree *);
static void free_config_qos(config_tree *);
static void free_config_setvar(config_tree *);
static void free_config_ttl(config_tree *);
static void free_config_trap(config_tree *);
static void free_config_fudge(config_tree *);
static void free_config_vars(config_tree *);
static void free_config_peers(config_tree *);
static void free_config_unpeers(config_tree *);
static void free_config_nic_rules(config_tree *);
#ifdef SIM
static void free_config_sim(config_tree *);
#endif
static void destroy_address_fifo(address_fifo *);
#define FREE_ADDRESS_FIFO(pf) \
do { \
destroy_address_fifo(pf); \
(pf) = NULL; \
} while (0)
void free_all_config_trees(void); /* atexit() */
static void free_config_tree(config_tree *ptree);
#endif /* FREE_CFG_T */
static void destroy_restrict_node(restrict_node *my_node);
static int is_sane_resolved_address(sockaddr_u *peeraddr, int hmode);
static void save_and_apply_config_tree(void);
static void destroy_int_fifo(int_fifo *);
#define FREE_INT_FIFO(pf) \
do { \
destroy_int_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_string_fifo(string_fifo *);
#define FREE_STRING_FIFO(pf) \
do { \
destroy_string_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_attr_val_fifo(attr_val_fifo *);
#define FREE_ATTR_VAL_FIFO(pf) \
do { \
destroy_attr_val_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_filegen_fifo(filegen_fifo *);
#define FREE_FILEGEN_FIFO(pf) \
do { \
destroy_filegen_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_restrict_fifo(restrict_fifo *);
#define FREE_RESTRICT_FIFO(pf) \
do { \
destroy_restrict_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_setvar_fifo(setvar_fifo *);
#define FREE_SETVAR_FIFO(pf) \
do { \
destroy_setvar_fifo(pf); \
(pf) = NULL; \
} while (0)
static void destroy_addr_opts_fifo(addr_opts_fifo *);
#define FREE_ADDR_OPTS_FIFO(pf) \
do { \
destroy_addr_opts_fifo(pf); \
(pf) = NULL; \
} while (0)
static void config_tos(config_tree *);
static void config_monitor(config_tree *);
static void config_tinker(config_tree *);
static void config_system_opts(config_tree *);
static void config_logconfig(config_tree *);
static void config_vars(config_tree *);
#ifdef SIM
static sockaddr_u *get_next_address(address_node *addr);
static void config_sim(config_tree *);
static void config_ntpdsim(config_tree *);
#else /* !SIM follows */
static void config_ntpd(config_tree *);
static void config_other_modes(config_tree *);
static void config_auth(config_tree *);
static void config_access(config_tree *);
static void config_phone(config_tree *);
static void config_qos(config_tree *);
static void config_setvar(config_tree *);
static void config_ttl(config_tree *);
static void config_trap(config_tree *);
static void config_fudge(config_tree *);
static void config_peers(config_tree *);
static void config_unpeers(config_tree *);
static void config_nic_rules(config_tree *);
static u_char get_correct_host_mode(int token);
static int peerflag_bits(peer_node *);
#endif /* !SIM */
#ifdef WORKER
void peer_name_resolved(int, int, void *, const char *, const char *,
const struct addrinfo *,
const struct addrinfo *);
void unpeer_name_resolved(int, int, void *, const char *, const char *,
const struct addrinfo *,
const struct addrinfo *);
void trap_name_resolved(int, int, void *, const char *, const char *,
const struct addrinfo *,
const struct addrinfo *);
#endif
enum gnn_type {
t_UNK, /* Unknown */
t_REF, /* Refclock */
t_MSK /* Network Mask */
};
void ntpd_set_tod_using(const char *);
static char * normal_dtoa(double);
static unsigned long get_pfxmatch(char **s, struct masks *m);
static unsigned long get_match(char *s, struct masks *m);
static unsigned long get_logmask(char *s);
#ifndef SIM
static int getnetnum(const char *num, sockaddr_u *addr, int complain,
enum gnn_type a_type);
#endif
/* FUNCTIONS FOR INITIALIZATION
* ----------------------------
*/
#ifdef FREE_CFG_T
static void
free_auth_node(
config_tree *ptree
)
{
if (ptree->auth.keys) {
free(ptree->auth.keys);
ptree->auth.keys = NULL;
}
if (ptree->auth.keysdir) {
free(ptree->auth.keysdir);
ptree->auth.keysdir = NULL;
}
if (ptree->auth.ntp_signd_socket) {
free(ptree->auth.ntp_signd_socket);
ptree->auth.ntp_signd_socket = NULL;
}
}
#endif /* DEBUG */
static void
init_syntax_tree(
config_tree *ptree
)
{
memset(ptree, 0, sizeof(*ptree));
}
#ifdef FREE_CFG_T
void
free_all_config_trees(void)
{
config_tree *ptree;
config_tree *pnext;
ptree = cfg_tree_history;
while (ptree != NULL) {
pnext = ptree->link;
free_config_tree(ptree);
ptree = pnext;
}
}
static void
free_config_tree(
config_tree *ptree
)
{
#if defined(_MSC_VER) && defined (_DEBUG)
_CrtCheckMemory();
#endif
if (ptree->source.value.s != NULL)
free(ptree->source.value.s);
free_config_other_modes(ptree);
free_config_auth(ptree);
free_config_tos(ptree);
free_config_monitor(ptree);
free_config_access(ptree);
free_config_tinker(ptree);
free_config_system_opts(ptree);
free_config_logconfig(ptree);
free_config_phone(ptree);
free_config_qos(ptree);
free_config_setvar(ptree);
free_config_ttl(ptree);
free_config_trap(ptree);
free_config_fudge(ptree);
free_config_vars(ptree);
free_config_peers(ptree);
free_config_unpeers(ptree);
free_config_nic_rules(ptree);
#ifdef SIM
free_config_sim(ptree);
#endif
free_auth_node(ptree);
free(ptree);
#if defined(_MSC_VER) && defined (_DEBUG)
_CrtCheckMemory();
#endif
}
#endif /* FREE_CFG_T */
#ifdef SAVECONFIG
/* Dump all trees */
int
dump_all_config_trees(
FILE *df,
int comment
)
{
config_tree * cfg_ptr;
int return_value;
return_value = 0;
for (cfg_ptr = cfg_tree_history;
cfg_ptr != NULL;
cfg_ptr = cfg_ptr->link)
return_value |= dump_config_tree(cfg_ptr, df, comment);
return return_value;
}
/* The config dumper */
int
dump_config_tree(
config_tree *ptree,
FILE *df,
int comment
)
{
peer_node *peern;
unpeer_node *unpeern;
attr_val *atrv;
address_node *addr;
address_node *peer_addr;
address_node *fudge_addr;
filegen_node *fgen_node;
restrict_node *rest_node;
addr_opts_node *addr_opts;
setvar_node *setv_node;
nic_rule_node *rule_node;
int_node *i_n;
int_node *flags;
string_node *str_node;
const char *s;
char *s1;
char *s2;
char timestamp[80];
int enable;
DPRINTF(1, ("dump_config_tree(%p)\n", ptree));
if (comment) {
if (!strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S",
localtime(&ptree->timestamp)))
timestamp[0] = '\0';
fprintf(df, "# %s %s %s\n",
timestamp,
(CONF_SOURCE_NTPQ == ptree->source.attr)
? "ntpq remote config from"
: "startup configuration file",
ptree->source.value.s);
}
/* For options I didn't find documentation I'll just output its name and the cor. value */
atrv = HEAD_PFIFO(ptree->vars);
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->type) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown vars type %d (%s) for %s\n",
atrv->type, token_name(atrv->type),
token_name(atrv->attr));
break;
#endif
case T_Double:
fprintf(df, "%s %s\n", keyword(atrv->attr),
normal_dtoa(atrv->value.d));
break;
case T_Integer:
fprintf(df, "%s %d\n", keyword(atrv->attr),
atrv->value.i);
break;
case T_String:
fprintf(df, "%s \"%s\"", keyword(atrv->attr),
atrv->value.s);
if (T_Driftfile == atrv->attr &&
atrv->link != NULL &&
T_WanderThreshold == atrv->link->attr) {
atrv = atrv->link;
fprintf(df, " %s\n",
normal_dtoa(atrv->value.d));
} else {
fprintf(df, "\n");
}
break;
}
}
atrv = HEAD_PFIFO(ptree->logconfig);
if (atrv != NULL) {
fprintf(df, "logconfig");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %c%s", atrv->attr, atrv->value.s);
fprintf(df, "\n");
}
if (ptree->stats_dir)
fprintf(df, "statsdir \"%s\"\n", ptree->stats_dir);
i_n = HEAD_PFIFO(ptree->stats_list);
if (i_n != NULL) {
fprintf(df, "statistics");
for ( ; i_n != NULL; i_n = i_n->link)
fprintf(df, " %s", keyword(i_n->i));
fprintf(df, "\n");
}
fgen_node = HEAD_PFIFO(ptree->filegen_opts);
for ( ; fgen_node != NULL; fgen_node = fgen_node->link) {
atrv = HEAD_PFIFO(fgen_node->options);
if (atrv != NULL) {
fprintf(df, "filegen %s",
keyword(fgen_node->filegen_token));
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->attr) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown filegen option token %s\n"
"filegen %s",
token_name(atrv->attr),
keyword(fgen_node->filegen_token));
break;
#endif
case T_File:
fprintf(df, " file %s",
atrv->value.s);
break;
case T_Type:
fprintf(df, " type %s",
keyword(atrv->value.i));
break;
case T_Flag:
fprintf(df, " %s",
keyword(atrv->value.i));
break;
}
}
fprintf(df, "\n");
}
}
atrv = HEAD_PFIFO(ptree->auth.crypto_cmd_list);
if (atrv != NULL) {
fprintf(df, "crypto");
for ( ; atrv != NULL; atrv = atrv->link) {
fprintf(df, " %s %s", keyword(atrv->attr),
atrv->value.s);
}
fprintf(df, "\n");
}
if (ptree->auth.revoke != 0)
fprintf(df, "revoke %d\n", ptree->auth.revoke);
if (ptree->auth.keysdir != NULL)
fprintf(df, "keysdir \"%s\"\n", ptree->auth.keysdir);
if (ptree->auth.keys != NULL)
fprintf(df, "keys \"%s\"\n", ptree->auth.keys);
atrv = HEAD_PFIFO(ptree->auth.trusted_key_list);
if (atrv != NULL) {
fprintf(df, "trustedkey");
for ( ; atrv != NULL; atrv = atrv->link) {
if (T_Integer == atrv->type)
fprintf(df, " %d", atrv->value.i);
else if (T_Intrange == atrv->type)
fprintf(df, " (%d ... %d)",
atrv->value.r.first,
atrv->value.r.last);
#ifdef DEBUG
else
fprintf(df, "\n# dump error:\n"
"# unknown trustedkey attr type %d\n"
"trustedkey", atrv->type);
#endif
}
fprintf(df, "\n");
}
if (ptree->auth.control_key)
fprintf(df, "controlkey %d\n", ptree->auth.control_key);
if (ptree->auth.request_key)
fprintf(df, "requestkey %d\n", ptree->auth.request_key);
/* dump enable list, then disable list */
for (enable = 1; enable >= 0; enable--) {
atrv = (enable)
? HEAD_PFIFO(ptree->enable_opts)
: HEAD_PFIFO(ptree->disable_opts);
if (atrv != NULL) {
fprintf(df, (enable)
? "enable"
: "disable");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s",
keyword(atrv->value.i));
fprintf(df, "\n");
}
}
atrv = HEAD_PFIFO(ptree->orphan_cmds);
if (atrv != NULL) {
fprintf(df, "tos");
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->type) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown tos attr type %d %s\n"
"tos", atrv->type,
token_name(atrv->type));
break;
#endif
case T_Double:
fprintf(df, " %s %s",
keyword(atrv->attr),
normal_dtoa(atrv->value.d));
break;
}
}
fprintf(df, "\n");
}
atrv = HEAD_PFIFO(ptree->tinker);
if (atrv != NULL) {
fprintf(df, "tinker");
for ( ; atrv != NULL; atrv = atrv->link) {
NTP_INSIST(T_Double == atrv->type);
fprintf(df, " %s %s", keyword(atrv->attr),
normal_dtoa(atrv->value.d));
}
fprintf(df, "\n");
}
if (ptree->broadcastclient)
fprintf(df, "broadcastclient\n");
peern = HEAD_PFIFO(ptree->peers);
for ( ; peern != NULL; peern = peern->link) {
addr = peern->addr;
fprintf(df, "%s", keyword(peern->host_mode));
switch (addr->type) {
#ifdef DEBUG
default:
fprintf(df, "# dump error:\n"
"# unknown peer family %d for:\n"
"%s", addr->type,
keyword(peern->host_mode));
break;
#endif
case AF_UNSPEC:
break;
case AF_INET:
fprintf(df, " -4");
break;
case AF_INET6:
fprintf(df, " -6");
break;
}
fprintf(df, " %s", addr->address);
if (peern->minpoll != 0)
fprintf(df, " minpoll %u", peern->minpoll);
if (peern->maxpoll != 0)
fprintf(df, " maxpoll %u", peern->maxpoll);
if (peern->ttl != 0) {
if (strlen(addr->address) > 8
&& !memcmp(addr->address, "127.127.", 8))
fprintf(df, " mode %u", peern->ttl);
else
fprintf(df, " ttl %u", peern->ttl);
}
if (peern->peerversion != NTP_VERSION)
fprintf(df, " version %u", peern->peerversion);
if (peern->peerkey != 0)
fprintf(df, " key %u", peern->peerkey);
if (peern->group != NULL)
fprintf(df, " ident \"%s\"", peern->group);
atrv = HEAD_PFIFO(peern->peerflags);
for ( ; atrv != NULL; atrv = atrv->link) {
NTP_INSIST(T_Flag == atrv->attr);
NTP_INSIST(T_Integer == atrv->type);
fprintf(df, " %s", keyword(atrv->value.i));
}
fprintf(df, "\n");
addr_opts = HEAD_PFIFO(ptree->fudge);
for ( ; addr_opts != NULL; addr_opts = addr_opts->link) {
peer_addr = peern->addr;
fudge_addr = addr_opts->addr;
s1 = peer_addr->address;
s2 = fudge_addr->address;
if (strcmp(s1, s2))
continue;
fprintf(df, "fudge %s", s1);
for (atrv = HEAD_PFIFO(addr_opts->options);
atrv != NULL;
atrv = atrv->link) {
switch (atrv->type) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown fudge atrv->type %d\n"
"fudge %s", atrv->type,
s1);
break;
#endif
case T_Double:
fprintf(df, " %s %s",
keyword(atrv->attr),
normal_dtoa(atrv->value.d));
break;
case T_Integer:
fprintf(df, " %s %d",
keyword(atrv->attr),
atrv->value.i);
break;
case T_String:
fprintf(df, " %s %s",
keyword(atrv->attr),
atrv->value.s);
break;
}
}
fprintf(df, "\n");
}
}
addr = HEAD_PFIFO(ptree->manycastserver);
if (addr != NULL) {
fprintf(df, "manycastserver");
for ( ; addr != NULL; addr = addr->link)
fprintf(df, " %s", addr->address);
fprintf(df, "\n");
}
addr = HEAD_PFIFO(ptree->multicastclient);
if (addr != NULL) {
fprintf(df, "multicastclient");
for ( ; addr != NULL; addr = addr->link)
fprintf(df, " %s", addr->address);
fprintf(df, "\n");
}
for (unpeern = HEAD_PFIFO(ptree->unpeers);
unpeern != NULL;
unpeern = unpeern->link)
fprintf(df, "unpeer %s\n", unpeern->addr->address);
atrv = HEAD_PFIFO(ptree->mru_opts);
if (atrv != NULL) {
fprintf(df, "mru");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s %d", keyword(atrv->attr),
atrv->value.i);
fprintf(df, "\n");
}
atrv = HEAD_PFIFO(ptree->discard_opts);
if (atrv != NULL) {
fprintf(df, "discard");
for ( ; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s %d", keyword(atrv->attr),
atrv->value.i);
fprintf(df, "\n");
}
for (rest_node = HEAD_PFIFO(ptree->restrict_opts);
rest_node != NULL;
rest_node = rest_node->link) {
if (NULL == rest_node->addr) {
s = "default";
flags = HEAD_PFIFO(rest_node->flags);
for ( ; flags != NULL; flags = flags->link)
if (T_Source == flags->i) {
s = "source";
break;
}
} else {
s = rest_node->addr->address;
}
fprintf(df, "restrict %s", s);
if (rest_node->mask != NULL)
fprintf(df, " mask %s",
rest_node->mask->address);
flags = HEAD_PFIFO(rest_node->flags);
for ( ; flags != NULL; flags = flags->link)
if (T_Source != flags->i)
fprintf(df, " %s", keyword(flags->i));
fprintf(df, "\n");
}
rule_node = HEAD_PFIFO(ptree->nic_rules);
for ( ; rule_node != NULL; rule_node = rule_node->link) {
fprintf(df, "interface %s %s\n",
keyword(rule_node->action),
(rule_node->match_class)
? keyword(rule_node->match_class)
: rule_node->if_name);
}
str_node = HEAD_PFIFO(ptree->phone);
if (str_node != NULL) {
fprintf(df, "phone");
for ( ; str_node != NULL; str_node = str_node->link)
fprintf(df, " \"%s\"", str_node->s);
fprintf(df, "\n");
}
atrv = HEAD_PFIFO(ptree->qos);
if (atrv != NULL) {
fprintf(df, "qos");
for (; atrv != NULL; atrv = atrv->link)
fprintf(df, " %s", atrv->value.s);
fprintf(df, "\n");
}
setv_node = HEAD_PFIFO(ptree->setvar);
for ( ; setv_node != NULL; setv_node = setv_node->link) {
s1 = quote_if_needed(setv_node->var);
s2 = quote_if_needed(setv_node->val);
fprintf(df, "setvar %s = %s", s1, s2);
free(s1);
free(s2);
if (setv_node->isdefault)
fprintf(df, " default");
fprintf(df, "\n");
}
i_n = HEAD_PFIFO(ptree->ttl);
if (i_n != NULL) {
fprintf(df, "ttl");
for( ; i_n != NULL; i_n = i_n->link)
fprintf(df, " %d", i_n->i);
fprintf(df, "\n");
}
addr_opts = HEAD_PFIFO(ptree->trap);
for ( ; addr_opts != NULL; addr_opts = addr_opts->link) {
addr = addr_opts->addr;
fprintf(df, "trap %s", addr->address);
atrv = HEAD_PFIFO(addr_opts->options);
for ( ; atrv != NULL; atrv = atrv->link) {
switch (atrv->attr) {
#ifdef DEBUG
default:
fprintf(df, "\n# dump error:\n"
"# unknown trap token %d\n"
"trap %s", atrv->attr,
addr->address);
break;
#endif
case T_Port:
fprintf(df, " port %d", atrv->value.i);
break;
case T_Interface:
fprintf(df, " interface %s",
atrv->value.s);
break;
}
}
fprintf(df, "\n");
}
return 0;
}
#endif /* SAVECONFIG */
/* generic fifo routines for structs linked by 1st member */
void *
append_gen_fifo(
void *fifo,
void *entry
)
{
gen_fifo *pf;
gen_node *pe;
pf = fifo;
pe = entry;
if (NULL == pf)
pf = emalloc_zero(sizeof(*pf));
if (pe != NULL)
LINK_FIFO(*pf, pe, link);
return pf;
}
void *
concat_gen_fifos(
void *first,
void *second
)
{
gen_fifo *pf1;
gen_fifo *pf2;
pf1 = first;
pf2 = second;
if (NULL == pf1)
return pf2;
else if (NULL == pf2)
return pf1;
CONCAT_FIFO(*pf1, *pf2, link);
free(pf2);
return pf1;
}
/* FUNCTIONS FOR CREATING NODES ON THE SYNTAX TREE
* -----------------------------------------------
*/
attr_val *
create_attr_dval(
int attr,
double value
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
my_val->value.d = value;
my_val->type = T_Double;
return my_val;
}
attr_val *
create_attr_ival(
int attr,
int value
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
my_val->value.i = value;
my_val->type = T_Integer;
return my_val;
}
attr_val *
create_attr_rangeval(
int attr,
int first,
int last
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
my_val->value.r.first = first;
my_val->value.r.last = last;
my_val->type = T_Intrange;
return my_val;
}
attr_val *
create_attr_sval(
int attr,
char *s
)
{
attr_val *my_val;
my_val = emalloc_zero(sizeof(*my_val));
my_val->attr = attr;
if (NULL == s) /* free() hates NULL */
s = estrdup("");
my_val->value.s = s;
my_val->type = T_String;
return my_val;
}
int_node *
create_int_node(
int val
)
{
int_node *i_n;
i_n = emalloc_zero(sizeof(*i_n));
i_n->i = val;
return i_n;
}
string_node *
create_string_node(
char *str
)
{
string_node *sn;
sn = emalloc_zero(sizeof(*sn));
sn->s = str;
return sn;
}
address_node *
create_address_node(
char * addr,
int type
)
{
address_node *my_node;
NTP_REQUIRE(NULL != addr);
NTP_REQUIRE(AF_INET == type ||
AF_INET6 == type || AF_UNSPEC == type);
my_node = emalloc_zero(sizeof(*my_node));
my_node->address = addr;
my_node->type = (u_short)type;
return my_node;
}
void
destroy_address_node(
address_node *my_node
)
{
if (NULL == my_node)
return;
NTP_REQUIRE(NULL != my_node->address);
free(my_node->address);
free(my_node);
}
peer_node *
create_peer_node(
int hmode,
address_node * addr,
attr_val_fifo * options
)
{
peer_node *my_node;
attr_val *option;
int freenode;
int errflag = 0;
my_node = emalloc_zero(sizeof(*my_node));
/* Initialize node values to default */
my_node->peerversion = NTP_VERSION;
/* Now set the node to the read values */
my_node->host_mode = hmode;
my_node->addr = addr;
/*
* the options FIFO mixes items that will be saved in the
* peer_node as explicit members, such as minpoll, and
* those that are moved intact to the peer_node's peerflags
* FIFO. The options FIFO is consumed and reclaimed here.
*/
while (options != NULL) {
UNLINK_FIFO(option, *options, link);
if (NULL == option) {
free(options);
break;
}
freenode = 1;
/* Check the kind of option being set */
switch (option->attr) {
case T_Flag:
APPEND_G_FIFO(my_node->peerflags, option);
freenode = 0;
break;
case T_Minpoll:
if (option->value.i < NTP_MINPOLL ||
option->value.i > UCHAR_MAX) {
msyslog(LOG_INFO,
"minpoll: provided value (%d) is out of range [%d-%d])",
option->value.i, NTP_MINPOLL,
UCHAR_MAX);
my_node->minpoll = NTP_MINPOLL;
} else {
my_node->minpoll =
(u_char)option->value.u;
}
break;
case T_Maxpoll:
if (option->value.i < 0 ||
option->value.i > NTP_MAXPOLL) {
msyslog(LOG_INFO,
"maxpoll: provided value (%d) is out of range [0-%d])",
option->value.i, NTP_MAXPOLL);
my_node->maxpoll = NTP_MAXPOLL;
} else {
my_node->maxpoll =
(u_char)option->value.u;
}
break;
case T_Ttl:
if (option->value.u >= MAX_TTL) {
msyslog(LOG_ERR, "ttl: invalid argument");
errflag = 1;
} else {
my_node->ttl = (u_char)option->value.u;
}
break;
case T_Mode:
if (option->value.u >= UCHAR_MAX) {
msyslog(LOG_ERR, "mode: invalid argument");
errflag = 1;
} else {
my_node->ttl = (u_char)option->value.u;
}
break;
case T_Key:
if (option->value.u >= KEYID_T_MAX) {
msyslog(LOG_ERR, "key: invalid argument");
errflag = 1;
} else {
my_node->peerkey =
(keyid_t)option->value.u;
}
break;
case T_Version:
if (option->value.u >= UCHAR_MAX) {
msyslog(LOG_ERR, "version: invalid argument");
errflag = 1;
} else {
my_node->peerversion =
(u_char)option->value.u;
}
break;
case T_Ident:
my_node->group = option->value.s;
break;
default:
msyslog(LOG_ERR,
"Unknown peer/server option token %s",
token_name(option->attr));
errflag = 1;
}
if (freenode)
free(option);
}
/* Check if errors were reported. If yes, ignore the node */
if (errflag) {
free(my_node);
my_node = NULL;
}
return my_node;
}
unpeer_node *
create_unpeer_node(
address_node *addr
)
{
unpeer_node * my_node;
u_int u;
char * pch;
my_node = emalloc_zero(sizeof(*my_node));
/*
* From the parser's perspective an association ID fits into
* its generic T_String definition of a name/address "address".
* We treat all valid 16-bit numbers as association IDs.
*/
pch = addr->address;
while (*pch && isdigit(*pch))
pch++;
if (!*pch
&& 1 == sscanf(addr->address, "%u", &u)
&& u <= ASSOCID_MAX) {
my_node->assocID = (associd_t)u;
destroy_address_node(addr);
my_node->addr = NULL;
} else {
my_node->assocID = 0;
my_node->addr = addr;
}
return my_node;
}
filegen_node *
create_filegen_node(
int filegen_token,
attr_val_fifo * options
)
{
filegen_node *my_node;
my_node = emalloc_zero(sizeof(*my_node));
my_node->filegen_token = filegen_token;
my_node->options = options;
return my_node;
}
restrict_node *
create_restrict_node(
address_node * addr,
address_node * mask,
int_fifo * flags,
int line_no
)
{
restrict_node *my_node;
my_node = emalloc_zero(sizeof(*my_node));
my_node->addr = addr;
my_node->mask = mask;
my_node->flags = flags;
my_node->line_no = line_no;
return my_node;
}
static void
destroy_restrict_node(
restrict_node *my_node
)
{
/* With great care, free all the memory occupied by
* the restrict node
*/
destroy_address_node(my_node->addr);
destroy_address_node(my_node->mask);
destroy_int_fifo(my_node->flags);
free(my_node);
}
static void
destroy_int_fifo(
int_fifo * fifo
)
{
int_node * i_n;
if (fifo != NULL) {
do {
UNLINK_FIFO(i_n, *fifo, link);
if (i_n != NULL)
free(i_n);
} while (i_n != NULL);
free(fifo);
}
}
static void
destroy_string_fifo(
string_fifo * fifo
)
{
string_node * sn;
if (fifo != NULL) {
do {
UNLINK_FIFO(sn, *fifo, link);
if (sn != NULL) {
if (sn->s != NULL)
free(sn->s);
free(sn);
}
} while (sn != NULL);
free(fifo);
}
}
static void
destroy_attr_val_fifo(
attr_val_fifo * av_fifo
)
{
attr_val * av;
if (av_fifo != NULL) {
do {
UNLINK_FIFO(av, *av_fifo, link);
if (av != NULL) {
if (T_String == av->type)
free(av->value.s);
free(av);
}
} while (av != NULL);
free(av_fifo);
}
}
static void
destroy_filegen_fifo(
filegen_fifo * fifo
)
{
filegen_node * fg;
if (fifo != NULL) {
do {
UNLINK_FIFO(fg, *fifo, link);
if (fg != NULL) {
destroy_attr_val_fifo(fg->options);
free(fg);
}
} while (fg != NULL);
free(fifo);
}
}
static void
destroy_restrict_fifo(
restrict_fifo * fifo
)
{
restrict_node * rn;
if (fifo != NULL) {
do {
UNLINK_FIFO(rn, *fifo, link);
if (rn != NULL)
destroy_restrict_node(rn);
} while (rn != NULL);
free(fifo);
}
}
static void
destroy_setvar_fifo(
setvar_fifo * fifo
)
{
setvar_node * sv;
if (fifo != NULL) {
do {
UNLINK_FIFO(sv, *fifo, link);
if (sv != NULL) {
free(sv->var);
free(sv->val);
free(sv);
}
} while (sv != NULL);
free(fifo);
}
}
static void
destroy_addr_opts_fifo(
addr_opts_fifo * fifo
)
{
addr_opts_node * aon;
if (fifo != NULL) {
do {
UNLINK_FIFO(aon, *fifo, link);
if (aon != NULL) {
destroy_address_node(aon->addr);
destroy_attr_val_fifo(aon->options);
free(aon);
}
} while (aon != NULL);
free(fifo);
}
}
setvar_node *
create_setvar_node(
char * var,
char * val,
int isdefault
)
{
setvar_node * my_node;
char * pch;
/* do not allow = in the variable name */
pch = strchr(var, '=');
if (NULL != pch)
*pch = '\0';
/* Now store the string into a setvar_node */
my_node = emalloc_zero(sizeof(*my_node));
my_node->var = var;
my_node->val = val;
my_node->isdefault = isdefault;
return my_node;
}
nic_rule_node *
create_nic_rule_node(
int match_class,
char *if_name, /* interface name or numeric address */
int action
)
{
nic_rule_node *my_node;
NTP_REQUIRE(match_class != 0 || if_name != NULL);
my_node = emalloc_zero(sizeof(*my_node));
my_node->match_class = match_class;
my_node->if_name = if_name;
my_node->action = action;
return my_node;
}
addr_opts_node *
create_addr_opts_node(
address_node * addr,
attr_val_fifo * options
)
{
addr_opts_node *my_node;
my_node = emalloc_zero(sizeof(*my_node));
my_node->addr = addr;
my_node->options = options;
return my_node;
}
script_info *
create_sim_script_info(
double duration,
attr_val_fifo * script_queue
)
{
#ifndef SIM
return NULL;
#else /* SIM follows */
script_info *my_info;
attr_val *my_attr_val;
my_info = emalloc_zero(sizeof(*my_info));
/* Initialize Script Info with default values*/
my_info->duration = duration;
my_info->prop_delay = NET_DLY;
my_info->proc_delay = PROC_DLY;
/* Traverse the script_queue and fill out non-default values */
for (my_attr_val = HEAD_PFIFO(script_queue);
my_attr_val != NULL;
my_attr_val = my_attr_val->link) {
/* Set the desired value */
switch (my_attr_val->attr) {
case T_Freq_Offset:
my_info->freq_offset = my_attr_val->value.d;
break;
case T_Wander:
my_info->wander = my_attr_val->value.d;
break;
case T_Jitter:
my_info->jitter = my_attr_val->value.d;
break;
case T_Prop_Delay:
my_info->prop_delay = my_attr_val->value.d;
break;
case T_Proc_Delay:
my_info->proc_delay = my_attr_val->value.d;
break;
default:
msyslog(LOG_ERR, "Unknown script token %d",
my_attr_val->attr);
}
}
return my_info;
#endif /* SIM */
}
#ifdef SIM
static sockaddr_u *
get_next_address(
address_node *addr
)
{
const char addr_prefix[] = "192.168.0.";
static int curr_addr_num = 1;
#define ADDR_LENGTH 16 + 1 /* room for 192.168.1.255 */
char addr_string[ADDR_LENGTH];
sockaddr_u *final_addr;
struct addrinfo *ptr;
int gai_error;
final_addr = emalloc(sizeof(*final_addr));
if (addr->type == T_String) {
snprintf(addr_string, sizeof(addr_string), "%s%d",
addr_prefix, curr_addr_num++);
printf("Selecting ip address %s for hostname %s\n",
addr_string, addr->address);
gai_error = getaddrinfo(addr_string, "ntp", NULL, &ptr);
} else {
gai_error = getaddrinfo(addr->address, "ntp", NULL, &ptr);
}
if (gai_error) {
fprintf(stderr, "ERROR!! Could not get a new address\n");
exit(1);
}
memcpy(final_addr, ptr->ai_addr, ptr->ai_addrlen);
fprintf(stderr, "Successful in setting ip address of simulated server to: %s\n",
stoa(final_addr));
freeaddrinfo(ptr);
return final_addr;
}
#endif /* SIM */
server_info *
create_sim_server(
address_node * addr,
double server_offset,
script_info_fifo * script
)
{
#ifndef SIM
return NULL;
#else /* SIM follows */
server_info *my_info;
my_info = emalloc_zero(sizeof(*my_info));
my_info->server_time = server_offset;
my_info->addr = get_next_address(addr);
my_info->script = script;
UNLINK_FIFO(my_info->curr_script, *my_info->script, link);
return my_info;
#endif /* SIM */
}
sim_node *
create_sim_node(
attr_val_fifo * init_opts,
server_info_fifo * servers
)
{
sim_node *my_node;
my_node = emalloc(sizeof(*my_node));
my_node->init_opts = init_opts;
my_node->servers = servers;
return my_node;
}
/* FUNCTIONS FOR PERFORMING THE CONFIGURATION
* ------------------------------------------
*/
#ifndef SIM
static void
config_other_modes(
config_tree * ptree
)
{
sockaddr_u addr_sock;
address_node * addr_node;
if (ptree->broadcastclient)
proto_config(PROTO_BROADCLIENT, ptree->broadcastclient,
0., NULL);
addr_node = HEAD_PFIFO(ptree->manycastserver);
while (addr_node != NULL) {
ZERO_SOCK(&addr_sock);
AF(&addr_sock) = addr_node->type;
if (1 == getnetnum(addr_node->address, &addr_sock, 1,
t_UNK)) {
proto_config(PROTO_MULTICAST_ADD,
0, 0., &addr_sock);
sys_manycastserver = 1;
}
addr_node = addr_node->link;
}
/* Configure the multicast clients */
addr_node = HEAD_PFIFO(ptree->multicastclient);
if (addr_node != NULL) {
do {
ZERO_SOCK(&addr_sock);
AF(&addr_sock) = addr_node->type;
if (1 == getnetnum(addr_node->address,
&addr_sock, 1, t_UNK)) {
proto_config(PROTO_MULTICAST_ADD, 0, 0.,
&addr_sock);
}
addr_node = addr_node->link;
} while (addr_node != NULL);
proto_config(PROTO_MULTICAST_ADD, 1, 0., NULL);
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
destroy_address_fifo(
address_fifo * pfifo
)
{
address_node * addr_node;
if (pfifo != NULL) {
do {
UNLINK_FIFO(addr_node, *pfifo, link);
if (addr_node != NULL)
destroy_address_node(addr_node);
} while (addr_node != NULL);
free(pfifo);
}
}
static void
free_config_other_modes(
config_tree *ptree
)
{
FREE_ADDRESS_FIFO(ptree->manycastserver);
FREE_ADDRESS_FIFO(ptree->multicastclient);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_auth(
config_tree *ptree
)
{
attr_val * my_val;
int first;
int last;
int i;
#ifdef AUTOKEY
int item;
#endif
/* Crypto Command */
#ifdef AUTOKEY
item = -1; /* quiet warning */
my_val = HEAD_PFIFO(ptree->auth.crypto_cmd_list);
for (; my_val != NULL; my_val = my_val->link) {
switch (my_val->attr) {
default:
NTP_INSIST(0);
break;
case T_Host:
item = CRYPTO_CONF_PRIV;
break;
case T_Ident:
item = CRYPTO_CONF_IDENT;
break;
case T_Pw:
item = CRYPTO_CONF_PW;
break;
case T_Randfile:
item = CRYPTO_CONF_RAND;
break;
case T_Digest:
item = CRYPTO_CONF_NID;
break;
}
crypto_config(item, my_val->value.s);
}
#endif /* AUTOKEY */
/* Keysdir Command */
if (ptree->auth.keysdir) {
if (keysdir != default_keysdir)
free(keysdir);
keysdir = estrdup(ptree->auth.keysdir);
}
/* ntp_signd_socket Command */
if (ptree->auth.ntp_signd_socket) {
if (ntp_signd_socket != default_ntp_signd_socket)
free(ntp_signd_socket);
ntp_signd_socket = estrdup(ptree->auth.ntp_signd_socket);
}
#ifdef AUTOKEY
if (ptree->auth.cryptosw && !cryptosw) {
crypto_setup();
cryptosw = 1;
}
#endif /* AUTOKEY */
/* Keys Command */
if (ptree->auth.keys)
getauthkeys(ptree->auth.keys);
/* Control Key Command */
if (ptree->auth.control_key)
ctl_auth_keyid = (keyid_t)ptree->auth.control_key;
/* Requested Key Command */
if (ptree->auth.request_key) {
DPRINTF(4, ("set info_auth_keyid to %08lx\n",
(u_long) ptree->auth.request_key));
info_auth_keyid = (keyid_t)ptree->auth.request_key;
}
/* Trusted Key Command */
my_val = HEAD_PFIFO(ptree->auth.trusted_key_list);
for (; my_val != NULL; my_val = my_val->link) {
if (T_Integer == my_val->type)
authtrust(my_val->value.i, 1);
else if (T_Intrange == my_val->type) {
first = my_val->value.r.first;
last = my_val->value.r.last;
if (first > last || first < 1 || last > 65534)
msyslog(LOG_NOTICE,
"Ignoring invalid trustedkey range %d ... %d, min 1 max 65534.",
first, last);
else
for (i = first; i <= last; i++)
authtrust((keyid_t)i, 1);
}
}
#ifdef AUTOKEY
/* crypto revoke command */
if (ptree->auth.revoke)
sys_revoke = 1 << ptree->auth.revoke;
#endif /* AUTOKEY */
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_auth(
config_tree *ptree
)
{
destroy_attr_val_fifo(ptree->auth.crypto_cmd_list);
ptree->auth.crypto_cmd_list = NULL;
destroy_attr_val_fifo(ptree->auth.trusted_key_list);
ptree->auth.trusted_key_list = NULL;
}
#endif /* FREE_CFG_T */
static void
config_tos(
config_tree *ptree
)
{
attr_val *tos;
int item;
item = -1; /* quiet warning */
tos = HEAD_PFIFO(ptree->orphan_cmds);
for (; tos != NULL; tos = tos->link) {
switch(tos->attr) {
default:
NTP_INSIST(0);
break;
case T_Ceiling:
item = PROTO_CEILING;
break;
case T_Floor:
item = PROTO_FLOOR;
break;
case T_Cohort:
item = PROTO_COHORT;
break;
case T_Orphan:
item = PROTO_ORPHAN;
break;
case T_Orphanwait:
item = PROTO_ORPHWAIT;
break;
case T_Mindist:
item = PROTO_MINDISP;
break;
case T_Maxdist:
item = PROTO_MAXDIST;
break;
case T_Minclock:
item = PROTO_MINCLOCK;
break;
case T_Maxclock:
item = PROTO_MAXCLOCK;
break;
case T_Minsane:
item = PROTO_MINSANE;
break;
case T_Beacon:
item = PROTO_BEACON;
break;
}
proto_config(item, 0, tos->value.d, NULL);
}
}
#ifdef FREE_CFG_T
static void
free_config_tos(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->orphan_cmds);
}
#endif /* FREE_CFG_T */
static void
config_monitor(
config_tree *ptree
)
{
int_node *pfilegen_token;
const char *filegen_string;
const char *filegen_file;
FILEGEN *filegen;
filegen_node *my_node;
attr_val *my_opts;
int filegen_type;
int filegen_flag;
/* Set the statistics directory */
if (ptree->stats_dir)
stats_config(STATS_STATSDIR, ptree->stats_dir);
/* NOTE:
* Calling filegen_get is brain dead. Doing a string
* comparison to find the relavant filegen structure is
* expensive.
*
* Through the parser, we already know which filegen is
* being specified. Hence, we should either store a
* pointer to the specified structure in the syntax tree
* or an index into a filegen array.
*
* Need to change the filegen code to reflect the above.
*/
/* Turn on the specified statistics */
pfilegen_token = HEAD_PFIFO(ptree->stats_list);
for (; pfilegen_token != NULL; pfilegen_token = pfilegen_token->link) {
filegen_string = keyword(pfilegen_token->i);
filegen = filegen_get(filegen_string);
DPRINTF(4, ("enabling filegen for %s statistics '%s%s'\n",
filegen_string, filegen->prefix,
filegen->basename));
filegen->flag |= FGEN_FLAG_ENABLED;
}
/* Configure the statistics with the options */
my_node = HEAD_PFIFO(ptree->filegen_opts);
for (; my_node != NULL; my_node = my_node->link) {
filegen_file = keyword(my_node->filegen_token);
filegen = filegen_get(filegen_file);
/* Initialize the filegen variables to their pre-configuration states */
filegen_flag = filegen->flag;
filegen_type = filegen->type;
/* "filegen ... enabled" is the default (when filegen is used) */
filegen_flag |= FGEN_FLAG_ENABLED;
my_opts = HEAD_PFIFO(my_node->options);
for (; my_opts != NULL; my_opts = my_opts->link) {
switch (my_opts->attr) {
case T_File:
filegen_file = my_opts->value.s;
break;
case T_Type:
switch (my_opts->value.i) {
default:
NTP_INSIST(0);
break;
case T_None:
filegen_type = FILEGEN_NONE;
break;
case T_Pid:
filegen_type = FILEGEN_PID;
break;
case T_Day:
filegen_type = FILEGEN_DAY;
break;
case T_Week:
filegen_type = FILEGEN_WEEK;
break;
case T_Month:
filegen_type = FILEGEN_MONTH;
break;
case T_Year:
filegen_type = FILEGEN_YEAR;
break;
case T_Age:
filegen_type = FILEGEN_AGE;
break;
}
break;
case T_Flag:
switch (my_opts->value.i) {
case T_Link:
filegen_flag |= FGEN_FLAG_LINK;
break;
case T_Nolink:
filegen_flag &= ~FGEN_FLAG_LINK;
break;
case T_Enable:
filegen_flag |= FGEN_FLAG_ENABLED;
break;
case T_Disable:
filegen_flag &= ~FGEN_FLAG_ENABLED;
break;
default:
msyslog(LOG_ERR,
"Unknown filegen flag token %d",
my_opts->value.i);
exit(1);
}
break;
default:
msyslog(LOG_ERR,
"Unknown filegen option token %d",
my_opts->attr);
exit(1);
}
}
filegen_config(filegen, filegen_file, filegen_type,
filegen_flag);
}
}
#ifdef FREE_CFG_T
static void
free_config_monitor(
config_tree *ptree
)
{
if (ptree->stats_dir) {
free(ptree->stats_dir);
ptree->stats_dir = NULL;
}
FREE_INT_FIFO(ptree->stats_list);
FREE_FILEGEN_FIFO(ptree->filegen_opts);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_access(
config_tree *ptree
)
{
static int warned_signd;
attr_val * my_opt;
restrict_node * my_node;
int_node * curr_flag;
sockaddr_u addr;
sockaddr_u mask;
struct addrinfo hints;
struct addrinfo * ai_list;
struct addrinfo * pai;
int rc;
int restrict_default;
u_short flags;
u_short mflags;
int range_err;
const char * signd_warning =
#ifdef HAVE_NTP_SIGND
"MS-SNTP signd operations currently block ntpd degrading service to all clients.";
#else
"mssntp restrict bit ignored, this ntpd was configured without --enable-ntp-signd.";
#endif
/* Configure the mru options */
my_opt = HEAD_PFIFO(ptree->mru_opts);
for (; my_opt != NULL; my_opt = my_opt->link) {
range_err = FALSE;
switch (my_opt->attr) {
case T_Incalloc:
if (0 <= my_opt->value.i)
mru_incalloc = my_opt->value.u;
else
range_err = TRUE;
break;
case T_Incmem:
if (0 <= my_opt->value.i)
mru_incalloc = (my_opt->value.u * 1024)
/ sizeof(mon_entry);
else
range_err = TRUE;
break;
case T_Initalloc:
if (0 <= my_opt->value.i)
mru_initalloc = my_opt->value.u;
else
range_err = TRUE;
break;
case T_Initmem:
if (0 <= my_opt->value.i)
mru_initalloc = (my_opt->value.u * 1024)
/ sizeof(mon_entry);
else
range_err = TRUE;
break;
case T_Mindepth:
if (0 <= my_opt->value.i)
mru_mindepth = my_opt->value.u;
else
range_err = TRUE;
break;
case T_Maxage:
mru_maxage = my_opt->value.i;
break;
case T_Maxdepth:
if (0 <= my_opt->value.i)
mru_maxdepth = my_opt->value.u;
else
mru_maxdepth = UINT_MAX;
break;
case T_Maxmem:
if (0 <= my_opt->value.i)
mru_maxdepth = my_opt->value.u * 1024 /
sizeof(mon_entry);
else
mru_maxdepth = UINT_MAX;
break;
default:
msyslog(LOG_ERR,
"Unknown mru option %s (%d)",
keyword(my_opt->attr), my_opt->attr);
exit(1);
}
if (range_err)
msyslog(LOG_ERR,
"mru %s %d out of range, ignored.",
keyword(my_opt->attr), my_opt->value.i);
}
/* Configure the discard options */
my_opt = HEAD_PFIFO(ptree->discard_opts);
for (; my_opt != NULL; my_opt = my_opt->link) {
switch (my_opt->attr) {
case T_Average:
if (0 <= my_opt->value.i &&
my_opt->value.i <= UCHAR_MAX)
ntp_minpoll = (u_char)my_opt->value.u;
else
msyslog(LOG_ERR,
"discard average %d out of range, ignored.",
my_opt->value.i);
break;
case T_Minimum:
ntp_minpkt = my_opt->value.i;
break;
case T_Monitor:
mon_age = my_opt->value.i;
break;
default:
msyslog(LOG_ERR,
"Unknown discard option %s (%d)",
keyword(my_opt->attr), my_opt->attr);
exit(1);
}
}
/* Configure the restrict options */
my_node = HEAD_PFIFO(ptree->restrict_opts);
for (; my_node != NULL; my_node = my_node->link) {
/* Parse the flags */
flags = 0;
mflags = 0;
curr_flag = HEAD_PFIFO(my_node->flags);
for (; curr_flag != NULL; curr_flag = curr_flag->link) {
switch (curr_flag->i) {
default:
NTP_INSIST(0);
break;
case T_Ntpport:
mflags |= RESM_NTPONLY;
break;
case T_Source:
mflags |= RESM_SOURCE;
break;
case T_Flake:
flags |= RES_FLAKE;
break;
case T_Ignore:
flags |= RES_IGNORE;
break;
case T_Kod:
flags |= RES_KOD;
break;
case T_Mssntp:
flags |= RES_MSSNTP;
break;
case T_Limited:
flags |= RES_LIMITED;
break;
case T_Lowpriotrap:
flags |= RES_LPTRAP;
break;
case T_Nomodify:
flags |= RES_NOMODIFY;
break;
case T_Nopeer:
flags |= RES_NOPEER;
break;
case T_Noquery:
flags |= RES_NOQUERY;
break;
case T_Noserve:
flags |= RES_DONTSERVE;
break;
case T_Notrap:
flags |= RES_NOTRAP;
break;
case T_Notrust:
flags |= RES_DONTTRUST;
break;
case T_Version:
flags |= RES_VERSION;
break;
}
}
if ((RES_MSSNTP & flags) && !warned_signd) {
warned_signd = 1;
fprintf(stderr, "%s\n", signd_warning);
msyslog(LOG_WARNING, signd_warning);
}
ZERO_SOCK(&addr);
ai_list = NULL;
pai = NULL;
restrict_default = 0;
if (NULL == my_node->addr) {
ZERO_SOCK(&mask);
if (!(RESM_SOURCE & mflags)) {
/*
* The user specified a default rule
* without a -4 / -6 qualifier, add to
* both lists
*/
restrict_default = 1;
} else {
/* apply "restrict source ..." */
DPRINTF(1, ("restrict source template mflags %x flags %x\n",
mflags, flags));
hack_restrict(RESTRICT_FLAGS, NULL,
NULL, mflags, flags, 0);
continue;
}
} else {
/* Resolve the specified address */
AF(&addr) = (u_short)my_node->addr->type;
if (getnetnum(my_node->addr->address,
&addr, 1, t_UNK) != 1) {
/*
* Attempt a blocking lookup. This
* is in violation of the nonblocking
* design of ntpd's mainline code. The
* alternative of running without the
* restriction until the name resolved
* seems worse.
* Ideally some scheme could be used for
* restrict directives in the startup
* ntp.conf to delay starting up the
* protocol machinery until after all
* restrict hosts have been resolved.
*/
ai_list = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_protocol = IPPROTO_UDP;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = my_node->addr->type;
rc = getaddrinfo(my_node->addr->address,
"ntp", &hints,
&ai_list);
if (rc) {
msyslog(LOG_ERR,
"restrict: ignoring line %d, address/host '%s' unusable.",
my_node->line_no,
my_node->addr->address);
continue;
}
NTP_INSIST(ai_list != NULL);
pai = ai_list;
NTP_INSIST(pai->ai_addr != NULL);
NTP_INSIST(sizeof(addr) >=
pai->ai_addrlen);
memcpy(&addr, pai->ai_addr,
pai->ai_addrlen);
NTP_INSIST(AF_INET == AF(&addr) ||
AF_INET6 == AF(&addr));
}
SET_HOSTMASK(&mask, AF(&addr));
/* Resolve the mask */
if (my_node->mask) {
ZERO_SOCK(&mask);
AF(&mask) = my_node->mask->type;
if (getnetnum(my_node->mask->address,
&mask, 1, t_MSK) != 1) {
msyslog(LOG_ERR,
"restrict: ignoring line %d, mask '%s' unusable.",
my_node->line_no,
my_node->mask->address);
continue;
}
}
}
/* Set the flags */
if (restrict_default) {
AF(&addr) = AF_INET;
AF(&mask) = AF_INET;
hack_restrict(RESTRICT_FLAGS, &addr,
&mask, mflags, flags, 0);
AF(&addr) = AF_INET6;
AF(&mask) = AF_INET6;
}
do {
hack_restrict(RESTRICT_FLAGS, &addr,
&mask, mflags, flags, 0);
if (pai != NULL &&
NULL != (pai = pai->ai_next)) {
NTP_INSIST(pai->ai_addr != NULL);
NTP_INSIST(sizeof(addr) >=
pai->ai_addrlen);
ZERO_SOCK(&addr);
memcpy(&addr, pai->ai_addr,
pai->ai_addrlen);
NTP_INSIST(AF_INET == AF(&addr) ||
AF_INET6 == AF(&addr));
SET_HOSTMASK(&mask, AF(&addr));
}
} while (pai != NULL);
if (ai_list != NULL)
freeaddrinfo(ai_list);
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_access(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->mru_opts);
FREE_ATTR_VAL_FIFO(ptree->discard_opts);
FREE_RESTRICT_FIFO(ptree->restrict_opts);
}
#endif /* FREE_CFG_T */
static void
config_tinker(
config_tree *ptree
)
{
attr_val * tinker;
int item;
item = -1; /* quiet warning */
tinker = HEAD_PFIFO(ptree->tinker);
for (; tinker != NULL; tinker = tinker->link) {
switch (tinker->attr) {
default:
NTP_INSIST(0);
break;
case T_Allan:
item = LOOP_ALLAN;
break;
case T_Dispersion:
item = LOOP_PHI;
break;
case T_Freq:
item = LOOP_FREQ;
break;
case T_Huffpuff:
item = LOOP_HUFFPUFF;
break;
case T_Panic:
item = LOOP_PANIC;
break;
case T_Step:
item = LOOP_MAX;
break;
case T_Stepout:
item = LOOP_MINSTEP;
break;
}
loop_config(item, tinker->value.d);
}
}
#ifdef FREE_CFG_T
static void
free_config_tinker(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->tinker);
}
#endif /* FREE_CFG_T */
/*
* config_nic_rules - apply interface listen/ignore/drop items
*/
#ifndef SIM
void
config_nic_rules(
config_tree *ptree
)
{
nic_rule_node * curr_node;
sockaddr_u addr;
nic_rule_match match_type;
nic_rule_action action;
char * if_name;
char * pchSlash;
int prefixlen;
int addrbits;
curr_node = HEAD_PFIFO(ptree->nic_rules);
if (curr_node != NULL
&& (HAVE_OPT( NOVIRTUALIPS ) || HAVE_OPT( INTERFACE ))) {
msyslog(LOG_ERR,
"interface/nic rules are not allowed with --interface (-I) or --novirtualips (-L)%s",
(input_from_file) ? ", exiting" : "");
if (input_from_file)
exit(1);
else
return;
}
for (; curr_node != NULL; curr_node = curr_node->link) {
prefixlen = -1;
if_name = curr_node->if_name;
if (if_name != NULL)
if_name = estrdup(if_name);
switch (curr_node->match_class) {
default:
/*
* this assignment quiets a gcc "may be used
* uninitialized" warning and is here for no
* other reason.
*/
match_type = MATCH_ALL;
NTP_INSIST(0);
break;
case 0:
/*
* 0 is out of range for valid token T_...
* and in a nic_rules_node indicates the
* interface descriptor is either a name or
* address, stored in if_name in either case.
*/
NTP_INSIST(if_name != NULL);
pchSlash = strchr(if_name, '/');
if (pchSlash != NULL)
*pchSlash = '\0';
if (is_ip_address(if_name, AF_UNSPEC, &addr)) {
match_type = MATCH_IFADDR;
if (pchSlash != NULL) {
sscanf(pchSlash + 1, "%d",
&prefixlen);
addrbits = 8 *
SIZEOF_INADDR(AF(&addr));
prefixlen = max(-1, prefixlen);
prefixlen = min(prefixlen,
addrbits);
}
} else {
match_type = MATCH_IFNAME;
if (pchSlash != NULL)
*pchSlash = '/';
}
break;
case T_All:
match_type = MATCH_ALL;
break;
case T_Ipv4:
match_type = MATCH_IPV4;
break;
case T_Ipv6:
match_type = MATCH_IPV6;
break;
case T_Wildcard:
match_type = MATCH_WILDCARD;
break;
}
switch (curr_node->action) {
default:
/*
* this assignment quiets a gcc "may be used
* uninitialized" warning and is here for no
* other reason.
*/
action = ACTION_LISTEN;
NTP_INSIST(0);
break;
case T_Listen:
action = ACTION_LISTEN;
break;
case T_Ignore:
action = ACTION_IGNORE;
break;
case T_Drop:
action = ACTION_DROP;
break;
}
add_nic_rule(match_type, if_name, prefixlen,
action);
timer_interfacetimeout(current_time + 2);
if (if_name != NULL)
free(if_name);
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_nic_rules(
config_tree *ptree
)
{
nic_rule_node *curr_node;
if (ptree->nic_rules != NULL) {
while (1) {
UNLINK_FIFO(curr_node, *ptree->nic_rules, link);
if (NULL == curr_node)
break;
if (curr_node->if_name != NULL)
free(curr_node->if_name);
free(curr_node);
}
free(ptree->nic_rules);
ptree->nic_rules = NULL;
}
}
#endif /* FREE_CFG_T */
static void
apply_enable_disable(
attr_val_fifo * fifo,
int enable
)
{
attr_val *curr_flag;
int option;
#ifdef BC_LIST_FRAMEWORK_NOT_YET_USED
bc_entry *pentry;
#endif
for (curr_flag = HEAD_PFIFO(fifo);
curr_flag != NULL;
curr_flag = curr_flag->link) {
option = curr_flag->value.i;
switch (option) {
default:
msyslog(LOG_ERR,
"can not apply enable/disable token %d, unknown",
option);
break;
case T_Auth:
proto_config(PROTO_AUTHENTICATE, enable, 0., NULL);
break;
case T_Bclient:
proto_config(PROTO_BROADCLIENT, enable, 0., NULL);
break;
case T_Calibrate:
proto_config(PROTO_CAL, enable, 0., NULL);
break;
case T_Kernel:
proto_config(PROTO_KERNEL, enable, 0., NULL);
break;
case T_Monitor:
proto_config(PROTO_MONITOR, enable, 0., NULL);
break;
case T_Ntp:
proto_config(PROTO_NTP, enable, 0., NULL);
break;
case T_Stats:
proto_config(PROTO_FILEGEN, enable, 0., NULL);
break;
#ifdef BC_LIST_FRAMEWORK_NOT_YET_USED
case T_Bc_bugXXXX:
pentry = bc_list;
while (pentry->token) {
if (pentry->token == option)
break;
pentry++;
}
if (!pentry->token) {
msyslog(LOG_ERR,
"compat token %d not in bc_list[]",
option);
continue;
}
pentry->enabled = enable;
break;
#endif
}
}
}
static void
config_system_opts(
config_tree *ptree
)
{
apply_enable_disable(ptree->enable_opts, 1);
apply_enable_disable(ptree->disable_opts, 0);
}
#ifdef FREE_CFG_T
static void
free_config_system_opts(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->enable_opts);
FREE_ATTR_VAL_FIFO(ptree->disable_opts);
}
#endif /* FREE_CFG_T */
static void
config_logconfig(
config_tree *ptree
)
{
attr_val * my_lc;
my_lc = HEAD_PFIFO(ptree->logconfig);
for (; my_lc != NULL; my_lc = my_lc->link) {
switch (my_lc->attr) {
case '+':
ntp_syslogmask |= get_logmask(my_lc->value.s);
break;
case '-':
ntp_syslogmask &= ~get_logmask(my_lc->value.s);
break;
case '=':
ntp_syslogmask = get_logmask(my_lc->value.s);
break;
}
}
}
#ifdef FREE_CFG_T
static void
free_config_logconfig(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->logconfig);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_phone(
config_tree *ptree
)
{
int i;
string_node * sn;
i = 0;
sn = HEAD_PFIFO(ptree->phone);
for (; sn != NULL; sn = sn->link) {
/* need to leave array entry for NULL terminator */
if (i < COUNTOF(sys_phone) - 1) {
sys_phone[i++] = estrdup(sn->s);
sys_phone[i] = NULL;
} else {
msyslog(LOG_INFO,
"phone: Number of phone entries exceeds %lu. Ignoring phone %s...",
(u_long)(COUNTOF(sys_phone) - 1), sn->s);
}
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_phone(
config_tree *ptree
)
{
FREE_STRING_FIFO(ptree->phone);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_qos(
config_tree *ptree
)
{
attr_val * my_qc;
char * s;
#ifdef HAVE_IPTOS_SUPPORT
unsigned int qtos = 0;
#endif
my_qc = HEAD_PFIFO(ptree->qos);
for (; my_qc != NULL; my_qc = my_qc->link) {
s = my_qc->value.s;
#ifdef HAVE_IPTOS_SUPPORT
if (!strcmp(s, "lowdelay"))
qtos = CONF_QOS_LOWDELAY;
else if (!strcmp(s, "throughput"))
qtos = CONF_QOS_THROUGHPUT;
else if (!strcmp(s, "reliability"))
qtos = CONF_QOS_RELIABILITY;
else if (!strcmp(s, "mincost"))
qtos = CONF_QOS_MINCOST;
#ifdef IPTOS_PREC_INTERNETCONTROL
else if (!strcmp(s, "routine") || !strcmp(s, "cs0"))
qtos = CONF_QOS_CS0;
else if (!strcmp(s, "priority") || !strcmp(s, "cs1"))
qtos = CONF_QOS_CS1;
else if (!strcmp(s, "immediate") || !strcmp(s, "cs2"))
qtos = CONF_QOS_CS2;
else if (!strcmp(s, "flash") || !strcmp(s, "cs3"))
qtos = CONF_QOS_CS3; /* overlapping prefix on keyword */
if (!strcmp(s, "flashoverride") || !strcmp(s, "cs4"))
qtos = CONF_QOS_CS4;
else if (!strcmp(s, "critical") || !strcmp(s, "cs5"))
qtos = CONF_QOS_CS5;
else if(!strcmp(s, "internetcontrol") || !strcmp(s, "cs6"))
qtos = CONF_QOS_CS6;
else if (!strcmp(s, "netcontrol") || !strcmp(s, "cs7"))
qtos = CONF_QOS_CS7;
#endif /* IPTOS_PREC_INTERNETCONTROL */
if (qtos == 0)
msyslog(LOG_ERR, "parse error, qos %s not accepted\n", s);
else
qos = qtos;
#endif /* HAVE IPTOS_SUPPORT */
/*
* value is set, but not being effective. Need code to
* change the current connections to notice. Might
* also consider logging a message about the action.
* XXX msyslog(LOG_INFO, "QoS %s requested by config\n", s);
*/
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_qos(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->qos);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_setvar(
config_tree *ptree
)
{
setvar_node *my_node;
size_t varlen, vallen, octets;
char * str;
str = NULL;
my_node = HEAD_PFIFO(ptree->setvar);
for (; my_node != NULL; my_node = my_node->link) {
varlen = strlen(my_node->var);
vallen = strlen(my_node->val);
octets = varlen + vallen + 1 + 1;
str = erealloc(str, octets);
snprintf(str, octets, "%s=%s", my_node->var,
my_node->val);
set_sys_var(str, octets, (my_node->isdefault)
? DEF
: 0);
}
if (str != NULL)
free(str);
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_setvar(
config_tree *ptree
)
{
FREE_SETVAR_FIFO(ptree->setvar);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_ttl(
config_tree *ptree
)
{
int i = 0;
int_node *curr_ttl;
curr_ttl = HEAD_PFIFO(ptree->ttl);
for (; curr_ttl != NULL; curr_ttl = curr_ttl->link) {
if (i < COUNTOF(sys_ttl))
sys_ttl[i++] = (u_char)curr_ttl->i;
else
msyslog(LOG_INFO,
"ttl: Number of TTL entries exceeds %lu. Ignoring TTL %d...",
(u_long)COUNTOF(sys_ttl), curr_ttl->i);
}
sys_ttlmax = i - 1;
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_ttl(
config_tree *ptree
)
{
FREE_INT_FIFO(ptree->ttl);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_trap(
config_tree *ptree
)
{
addr_opts_node *curr_trap;
attr_val *curr_opt;
sockaddr_u addr_sock;
sockaddr_u peeraddr;
struct interface *localaddr;
struct addrinfo hints;
char port_text[8];
settrap_parms *pstp;
u_short port;
int err_flag;
int rc;
/* silence warning about addr_sock potentially uninitialized */
AF(&addr_sock) = AF_UNSPEC;
curr_trap = HEAD_PFIFO(ptree->trap);
for (; curr_trap != NULL; curr_trap = curr_trap->link) {
err_flag = 0;
port = 0;
localaddr = NULL;
curr_opt = HEAD_PFIFO(curr_trap->options);
for (; curr_opt != NULL; curr_opt = curr_opt->link) {
if (T_Port == curr_opt->attr) {
if (curr_opt->value.i < 1
|| curr_opt->value.i > USHRT_MAX) {
msyslog(LOG_ERR,
"invalid port number "
"%d, trap ignored",
curr_opt->value.i);
err_flag = 1;
}
port = (u_short)curr_opt->value.i;
}
else if (T_Interface == curr_opt->attr) {
/* Resolve the interface address */
ZERO_SOCK(&addr_sock);
if (getnetnum(curr_opt->value.s,
&addr_sock, 1, t_UNK) != 1) {
err_flag = 1;
break;
}
localaddr = findinterface(&addr_sock);
if (NULL == localaddr) {
msyslog(LOG_ERR,
"can't find interface with address %s",
stoa(&addr_sock));
err_flag = 1;
}
}
}
/* Now process the trap for the specified interface
* and port number
*/
if (!err_flag) {
if (!port)
port = TRAPPORT;
ZERO_SOCK(&peeraddr);
rc = getnetnum(curr_trap->addr->address,
&peeraddr, 1, t_UNK);
if (1 != rc) {
#ifndef WORKER
msyslog(LOG_ERR,
"trap: unable to use IP address %s.",
curr_trap->addr->address);
#else /* WORKER follows */
/*
* save context and hand it off
* for name resolution.
*/
memset(&hints, 0, sizeof(hints));
hints.ai_protocol = IPPROTO_UDP;
hints.ai_socktype = SOCK_DGRAM;
snprintf(port_text, sizeof(port_text),
"%u", port);
hints.ai_flags = Z_AI_NUMERICSERV;
pstp = emalloc_zero(sizeof(*pstp));
if (localaddr != NULL) {
hints.ai_family = localaddr->family;
pstp->ifaddr_nonnull = 1;
memcpy(&pstp->ifaddr,
&localaddr->sin,
sizeof(pstp->ifaddr));
}
rc = getaddrinfo_sometime(
curr_trap->addr->address,
port_text, &hints,
INITIAL_DNS_RETRY,
&trap_name_resolved,
pstp);
if (!rc)
msyslog(LOG_ERR,
"config_trap: getaddrinfo_sometime(%s,%s): %m",
curr_trap->addr->address,
port_text);
#endif /* WORKER */
continue;
}
/* port is at same location for v4 and v6 */
SET_PORT(&peeraddr, port);
if (NULL == localaddr)
localaddr = ANY_INTERFACE_CHOOSE(&peeraddr);
else
AF(&peeraddr) = AF(&addr_sock);
if (!ctlsettrap(&peeraddr, localaddr, 0,
NTP_VERSION))
msyslog(LOG_ERR,
"set trap %s -> %s failed.",
latoa(localaddr),
stoa(&peeraddr));
}
}
}
/*
* trap_name_resolved()
*
* Callback invoked when config_trap()'s DNS lookup completes.
*/
# ifdef WORKER
void
trap_name_resolved(
int rescode,
int gai_errno,
void * context,
const char * name,
const char * service,
const struct addrinfo * hints,
const struct addrinfo * res
)
{
settrap_parms *pstp;
struct interface *localaddr;
sockaddr_u peeraddr;
pstp = context;
if (rescode) {
msyslog(LOG_ERR,
"giving up resolving trap host %s: %s (%d)",
name, gai_strerror(rescode), rescode);
free(pstp);
return;
}
NTP_INSIST(sizeof(peeraddr) >= res->ai_addrlen);
memset(&peeraddr, 0, sizeof(peeraddr));
memcpy(&peeraddr, res->ai_addr, res->ai_addrlen);
localaddr = NULL;
if (pstp->ifaddr_nonnull)
localaddr = findinterface(&pstp->ifaddr);
if (NULL == localaddr)
localaddr = ANY_INTERFACE_CHOOSE(&peeraddr);
if (!ctlsettrap(&peeraddr, localaddr, 0, NTP_VERSION))
msyslog(LOG_ERR, "set trap %s -> %s failed.",
latoa(localaddr), stoa(&peeraddr));
free(pstp);
}
# endif /* WORKER */
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_trap(
config_tree *ptree
)
{
FREE_ADDR_OPTS_FIFO(ptree->trap);
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_fudge(
config_tree *ptree
)
{
addr_opts_node *curr_fudge;
attr_val *curr_opt;
sockaddr_u addr_sock;
address_node *addr_node;
struct refclockstat clock_stat;
int err_flag;
curr_fudge = HEAD_PFIFO(ptree->fudge);
for (; curr_fudge != NULL; curr_fudge = curr_fudge->link) {
err_flag = 0;
/* Get the reference clock address and
* ensure that it is sane
*/
addr_node = curr_fudge->addr;
ZERO_SOCK(&addr_sock);
if (getnetnum(addr_node->address, &addr_sock, 1, t_REF)
!= 1) {
err_flag = 1;
msyslog(LOG_ERR,
"unrecognized fudge reference clock address %s, line ignored",
stoa(&addr_sock));
}
if (!ISREFCLOCKADR(&addr_sock)) {
err_flag = 1;
msyslog(LOG_ERR,
"inappropriate address %s for the fudge command, line ignored",
stoa(&addr_sock));
}
/* Parse all the options to the fudge command */
memset(&clock_stat, 0, sizeof(clock_stat));
curr_opt = HEAD_PFIFO(curr_fudge->options);
for (; curr_opt != NULL; curr_opt = curr_opt->link) {
switch (curr_opt->attr) {
case T_Time1:
clock_stat.haveflags |= CLK_HAVETIME1;
clock_stat.fudgetime1 = curr_opt->value.d;
break;
case T_Time2:
clock_stat.haveflags |= CLK_HAVETIME2;
clock_stat.fudgetime2 = curr_opt->value.d;
break;
case T_Stratum:
clock_stat.haveflags |= CLK_HAVEVAL1;
clock_stat.fudgeval1 = curr_opt->value.i;
break;
case T_Refid:
clock_stat.haveflags |= CLK_HAVEVAL2;
clock_stat.fudgeval2 = 0;
memcpy(&clock_stat.fudgeval2,
curr_opt->value.s,
min(strlen(curr_opt->value.s), 4));
break;
case T_Flag1:
clock_stat.haveflags |= CLK_HAVEFLAG1;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG1;
else
clock_stat.flags &= ~CLK_FLAG1;
break;
case T_Flag2:
clock_stat.haveflags |= CLK_HAVEFLAG2;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG2;
else
clock_stat.flags &= ~CLK_FLAG2;
break;
case T_Flag3:
clock_stat.haveflags |= CLK_HAVEFLAG3;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG3;
else
clock_stat.flags &= ~CLK_FLAG3;
break;
case T_Flag4:
clock_stat.haveflags |= CLK_HAVEFLAG4;
if (curr_opt->value.i)
clock_stat.flags |= CLK_FLAG4;
else
clock_stat.flags &= ~CLK_FLAG4;
break;
default:
msyslog(LOG_ERR,
"Unexpected fudge flag %s (%d) for %s\n",
token_name(curr_opt->attr),
curr_opt->attr, stoa(&addr_sock));
exit(curr_opt->attr ? curr_opt->attr : 1);
}
}
# ifdef REFCLOCK
if (!err_flag)
refclock_control(&addr_sock, &clock_stat, NULL);
# endif
}
}
#endif /* !SIM */
#ifdef FREE_CFG_T
static void
free_config_fudge(
config_tree *ptree
)
{
FREE_ADDR_OPTS_FIFO(ptree->fudge);
}
#endif /* FREE_CFG_T */
static void
config_vars(
config_tree *ptree
)
{
attr_val *curr_var;
int len;
curr_var = HEAD_PFIFO(ptree->vars);
for (; curr_var != NULL; curr_var = curr_var->link) {
/* Determine which variable to set and set it */
switch (curr_var->attr) {
case T_Broadcastdelay:
proto_config(PROTO_BROADDELAY, 0, curr_var->value.d, NULL);
break;
case T_Tick:
proto_config(PROTO_ADJ, 0, curr_var->value.d, NULL);
break;
case T_Driftfile:
if ('\0' == curr_var->value.s[0]) {
stats_drift_file = 0;
msyslog(LOG_INFO, "config: driftfile disabled\n");
} else
stats_config(STATS_FREQ_FILE, curr_var->value.s);
break;
case T_Ident:
sys_ident = curr_var->value.s;
break;
case T_WanderThreshold: /* FALLTHROUGH */
case T_Nonvolatile:
wander_threshold = curr_var->value.d;
break;
case T_Leapfile:
stats_config(STATS_LEAP_FILE, curr_var->value.s);
break;
case T_Pidfile:
stats_config(STATS_PID_FILE, curr_var->value.s);
break;
case T_Logfile:
if (-1 == change_logfile(curr_var->value.s, 0))
msyslog(LOG_ERR,
"Cannot open logfile %s: %m",
curr_var->value.s);
break;
case T_Saveconfigdir:
if (saveconfigdir != NULL)
free(saveconfigdir);
len = strlen(curr_var->value.s);
if (0 == len) {
saveconfigdir = NULL;
} else if (DIR_SEP != curr_var->value.s[len - 1]
#ifdef SYS_WINNT /* slash is also a dir. sep. on Windows */
&& '/' != curr_var->value.s[len - 1]
#endif
) {
len++;
saveconfigdir = emalloc(len + 1);
snprintf(saveconfigdir, len + 1,
"%s%c",
curr_var->value.s,
DIR_SEP);
} else {
saveconfigdir = estrdup(
curr_var->value.s);
}
break;
case T_Automax:
#ifdef AUTOKEY
sys_automax = curr_var->value.i;
#endif
break;
default:
msyslog(LOG_ERR,
"config_vars(): unexpected token %d",
curr_var->attr);
}
}
}
#ifdef FREE_CFG_T
static void
free_config_vars(
config_tree *ptree
)
{
FREE_ATTR_VAL_FIFO(ptree->vars);
}
#endif /* FREE_CFG_T */
/* Define a function to check if a resolved address is sane.
* If yes, return 1, else return 0;
*/
static int
is_sane_resolved_address(
sockaddr_u * peeraddr,
int hmode
)
{
if (!ISREFCLOCKADR(peeraddr) && ISBADADR(peeraddr)) {
msyslog(LOG_ERR,
"attempt to configure invalid address %s",
stoa(peeraddr));
return 0;
}
/*
* Shouldn't be able to specify multicast
* address for server/peer!
* and unicast address for manycastclient!
*/
if ((T_Server == hmode || T_Peer == hmode || T_Pool == hmode)
&& IS_MCAST(peeraddr)) {
msyslog(LOG_ERR,
"attempt to configure invalid address %s",
stoa(peeraddr));
return 0;
}
if (T_Manycastclient == hmode && !IS_MCAST(peeraddr)) {
msyslog(LOG_ERR,
"attempt to configure invalid address %s",
stoa(peeraddr));
return 0;
}
if (IS_IPV6(peeraddr) && !ipv6_works)
return 0;
/* Ok, all tests succeeded, now we can return 1 */
return 1;
}
#ifndef SIM
static u_char
get_correct_host_mode(
int token
)
{
switch (token) {
case T_Server:
case T_Pool:
case T_Manycastclient:
return MODE_CLIENT;
case T_Peer:
return MODE_ACTIVE;
case T_Broadcast:
return MODE_BROADCAST;
default:
return 0;
}
}
/*
* peerflag_bits() get config_peers() peerflags value from a
* peer_node's queue of flag attr_val entries.
*/
static int
peerflag_bits(
peer_node *pn
)
{
int peerflags;
attr_val *option;
/* translate peerflags options to bits */
peerflags = 0;
option = HEAD_PFIFO(pn->peerflags);
for (; option != NULL; option = option->link) {
switch (option->value.i) {
default:
NTP_INSIST(0);
break;
case T_Autokey:
peerflags |= FLAG_SKEY;
break;
case T_Burst:
peerflags |= FLAG_BURST;
break;
case T_Iburst:
peerflags |= FLAG_IBURST;
break;
case T_Noselect:
peerflags |= FLAG_NOSELECT;
break;
case T_Preempt:
peerflags |= FLAG_PREEMPT;
break;
case T_Prefer:
peerflags |= FLAG_PREFER;
break;
case T_True:
peerflags |= FLAG_TRUE;
break;
case T_Xleave:
peerflags |= FLAG_XLEAVE;
break;
}
}
return peerflags;
}
static void
config_peers(
config_tree *ptree
)
{
sockaddr_u peeraddr;
struct addrinfo hints;
peer_node * curr_peer;
peer_resolved_ctx * ctx;
u_char hmode;
/* add servers named on the command line with iburst implied */
for (;
cmdline_server_count > 0;
cmdline_server_count--, cmdline_servers++) {
ZERO_SOCK(&peeraddr);
/*
* If we have a numeric address, we can safely
* proceed in the mainline with it. Otherwise, hand
* the hostname off to the blocking child.
*/
if (is_ip_address(*cmdline_servers, AF_UNSPEC,
&peeraddr)) {
SET_PORT(&peeraddr, NTP_PORT);
if (is_sane_resolved_address(&peeraddr,
T_Server))
peer_config(
&peeraddr,
NULL,
NULL,
MODE_CLIENT,
NTP_VERSION,
0,
0,
FLAG_IBURST,
0,
0,
NULL);
} else {
/* we have a hostname to resolve */
# ifdef WORKER
ctx = emalloc_zero(sizeof(*ctx));
ctx->family = AF_UNSPEC;
ctx->host_mode = T_Server;
ctx->hmode = MODE_CLIENT;
ctx->version = NTP_VERSION;
ctx->flags = FLAG_IBURST;
memset(&hints, 0, sizeof(hints));
hints.ai_family = (u_short)ctx->family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
getaddrinfo_sometime(*cmdline_servers,
"ntp", &hints,
INITIAL_DNS_RETRY,
&peer_name_resolved,
(void *)ctx);
# else /* !WORKER follows */
msyslog(LOG_ERR,
"hostname %s can not be used, please use IP address instead.\n",
curr_peer->addr->address);
# endif
}
}
/* add associations from the configuration file */
curr_peer = HEAD_PFIFO(ptree->peers);
for (; curr_peer != NULL; curr_peer = curr_peer->link) {
ZERO_SOCK(&peeraddr);
/* Find the correct host-mode */
hmode = get_correct_host_mode(curr_peer->host_mode);
NTP_INSIST(hmode != 0);
if (T_Pool == curr_peer->host_mode) {
AF(&peeraddr) = curr_peer->addr->type;
peer_config(
&peeraddr,
curr_peer->addr->address,
NULL,
hmode,
curr_peer->peerversion,
curr_peer->minpoll,
curr_peer->maxpoll,
peerflag_bits(curr_peer),
curr_peer->ttl,
curr_peer->peerkey,
curr_peer->group);
/*
* If we have a numeric address, we can safely
* proceed in the mainline with it. Otherwise, hand
* the hostname off to the blocking child.
*/
} else if (is_ip_address(curr_peer->addr->address,
curr_peer->addr->type, &peeraddr)) {
SET_PORT(&peeraddr, NTP_PORT);
if (is_sane_resolved_address(&peeraddr,
curr_peer->host_mode))
peer_config(
&peeraddr,
NULL,
NULL,
hmode,
curr_peer->peerversion,
curr_peer->minpoll,
curr_peer->maxpoll,
peerflag_bits(curr_peer),
curr_peer->ttl,
curr_peer->peerkey,
curr_peer->group);
} else {
/* we have a hostname to resolve */
# ifdef WORKER
ctx = emalloc_zero(sizeof(*ctx));
ctx->family = curr_peer->addr->type;
ctx->host_mode = curr_peer->host_mode;
ctx->hmode = hmode;
ctx->version = curr_peer->peerversion;
ctx->minpoll = curr_peer->minpoll;
ctx->maxpoll = curr_peer->maxpoll;
ctx->flags = peerflag_bits(curr_peer);
ctx->ttl = curr_peer->ttl;
ctx->keyid = curr_peer->peerkey;
ctx->group = curr_peer->group;
memset(&hints, 0, sizeof(hints));
hints.ai_family = ctx->family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
getaddrinfo_sometime(curr_peer->addr->address,
"ntp", &hints,
INITIAL_DNS_RETRY,
&peer_name_resolved, ctx);
# else /* !WORKER follows */
msyslog(LOG_ERR,
"hostname %s can not be used, please use IP address instead.\n",
curr_peer->addr->address);
# endif
}
}
}
#endif /* !SIM */
/*
* peer_name_resolved()
*
* Callback invoked when config_peers()'s DNS lookup completes.
*/
#ifdef WORKER
void
peer_name_resolved(
int rescode,
int gai_errno,
void * context,
const char * name,
const char * service,
const struct addrinfo * hints,
const struct addrinfo * res
)
{
sockaddr_u peeraddr;
peer_resolved_ctx * ctx;
u_short af;
const char * fam_spec;
ctx = context;
DPRINTF(1, ("peer_name_resolved(%s) rescode %d\n", name, rescode));
if (rescode) {
#ifndef IGNORE_DNS_ERRORS
free(ctx);
msyslog(LOG_ERR,
"giving up resolving host %s: %s (%d)",
name, gai_strerror(rescode), rescode);
#else /* IGNORE_DNS_ERRORS follows */
getaddrinfo_sometime(name, service, hints,
INITIAL_DNS_RETRY,
&peer_name_resolved, context);
#endif
return;
}
/* Loop to configure a single association */
for (; res != NULL; res = res->ai_next) {
memcpy(&peeraddr, res->ai_addr, res->ai_addrlen);
if (is_sane_resolved_address(&peeraddr,
ctx->host_mode)) {
NLOG(NLOG_SYSINFO) {
af = ctx->family;
fam_spec = (AF_INET6 == af)
? "(AAAA) "
: (AF_INET == af)
? "(A) "
: "";
msyslog(LOG_INFO, "DNS %s %s-> %s",
name, fam_spec,
stoa(&peeraddr));
}
peer_config(
&peeraddr,
NULL,
NULL,
ctx->hmode,
ctx->version,
ctx->minpoll,
ctx->maxpoll,
ctx->flags,
ctx->ttl,
ctx->keyid,
ctx->group);
break;
}
}
free(ctx);
}
#endif /* WORKER */
#ifdef FREE_CFG_T
static void
free_config_peers(
config_tree *ptree
)
{
peer_node *curr_peer;
if (ptree->peers != NULL) {
while (1) {
UNLINK_FIFO(curr_peer, *ptree->peers, link);
if (NULL == curr_peer)
break;
destroy_address_node(curr_peer->addr);
destroy_attr_val_fifo(curr_peer->peerflags);
free(curr_peer);
}
free(ptree->peers);
ptree->peers = NULL;
}
}
#endif /* FREE_CFG_T */
#ifndef SIM
static void
config_unpeers(
config_tree *ptree
)
{
sockaddr_u peeraddr;
struct addrinfo hints;
unpeer_node * curr_unpeer;
struct peer * p;
const char * name;
int rc;
curr_unpeer = HEAD_PFIFO(ptree->unpeers);
for (; curr_unpeer != NULL; curr_unpeer = curr_unpeer->link) {
/*
* Either AssocID will be zero, and we unpeer by name/
* address addr, or it is nonzero and addr NULL.
*/
if (curr_unpeer->assocID) {
p = findpeerbyassoc(curr_unpeer->assocID);
if (p != NULL) {
msyslog(LOG_NOTICE, "unpeered %s",
stoa(&p->srcadr));
peer_clear(p, "GONE");
unpeer(p);
}
continue;
}
memset(&peeraddr, 0, sizeof(peeraddr));
AF(&peeraddr) = curr_unpeer->addr->type;
name = curr_unpeer->addr->address;
rc = getnetnum(name, &peeraddr, 0, t_UNK);
/* Do we have a numeric address? */
if (rc > 0) {
DPRINTF(1, ("unpeer: searching for %s\n",
stoa(&peeraddr)));
p = findexistingpeer(&peeraddr, NULL, NULL, -1);
if (p != NULL) {
msyslog(LOG_NOTICE, "unpeered %s",
stoa(&peeraddr));
peer_clear(p, "GONE");
unpeer(p);
}
continue;
}
/*
* It's not a numeric IP address, it's a hostname.
* Check for associations with a matching hostname.
*/
for (p = peer_list; p != NULL; p = p->p_link)
if (p->hostname != NULL)
if (!strcasecmp(p->hostname, name))
break;
if (p != NULL) {
msyslog(LOG_NOTICE, "unpeered %s", name);
peer_clear(p, "GONE");
unpeer(p);
}
/* Resolve the hostname to address(es). */
# ifdef WORKER
memset(&hints, 0, sizeof(hints));
hints.ai_family = curr_unpeer->addr->type;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
getaddrinfo_sometime(name, "ntp", &hints,
INITIAL_DNS_RETRY,
&unpeer_name_resolved, NULL);
# else /* !WORKER follows */
msyslog(LOG_ERR,
"hostname %s can not be used, please use IP address instead.\n",
name);
# endif
}
}
#endif /* !SIM */
/*
* unpeer_name_resolved()
*
* Callback invoked when config_unpeers()'s DNS lookup completes.
*/
#ifdef WORKER
void
unpeer_name_resolved(
int rescode,
int gai_errno,
void * context,
const char * name,
const char * service,
const struct addrinfo * hints,
const struct addrinfo * res
)
{
sockaddr_u peeraddr;
struct peer * peer;
u_short af;
const char * fam_spec;
DPRINTF(1, ("unpeer_name_resolved(%s) rescode %d\n", name, rescode));
if (rescode) {
msyslog(LOG_ERR, "giving up resolving unpeer %s: %s (%d)",
name, gai_strerror(rescode), rescode);
return;
}
/*
* Loop through the addresses found
*/
for (; res != NULL; res = res->ai_next) {
NTP_INSIST(res->ai_addrlen <= sizeof(peeraddr));
memcpy(&peeraddr, res->ai_addr, res->ai_addrlen);
DPRINTF(1, ("unpeer: searching for peer %s\n",
stoa(&peeraddr)));
peer = findexistingpeer(&peeraddr, NULL, NULL, -1);
if (peer != NULL) {
af = AF(&peeraddr);
fam_spec = (AF_INET6 == af)
? "(AAAA) "
: (AF_INET == af)
? "(A) "
: "";
msyslog(LOG_NOTICE, "unpeered %s %s-> %s", name,
fam_spec, stoa(&peeraddr));
peer_clear(peer, "GONE");
unpeer(peer);
}
}
}
#endif /* WORKER */
#ifdef FREE_CFG_T
static void
free_config_unpeers(
config_tree *ptree
)
{
unpeer_node *curr_unpeer;
if (ptree->unpeers != NULL) {
while (1) {
UNLINK_FIFO(curr_unpeer, *ptree->unpeers, link);
if (NULL == curr_unpeer)
break;
destroy_address_node(curr_unpeer->addr);
free(curr_unpeer);
}
free(ptree->unpeers);
}
}
#endif /* FREE_CFG_T */
#ifdef SIM
static void
config_sim(
config_tree *ptree
)
{
int i;
server_info *serv_info;
attr_val *init_stmt;
sim_node *sim_n;
/* Check if a simulate block was found in the configuration code.
* If not, return an error and exit
*/
sim_n = HEAD_PFIFO(ptree->sim_details);
if (NULL == sim_n) {
fprintf(stderr, "ERROR!! I couldn't find a \"simulate\" block for configuring the simulator.\n");
fprintf(stderr, "\tCheck your configuration file.\n");
exit(1);
}
/* Process the initialization statements
* -------------------------------------
*/
init_stmt = HEAD_PFIFO(sim_n->init_opts);
for (; init_stmt != NULL; init_stmt = init_stmt->link) {
switch(init_stmt->attr) {
case T_Beep_Delay:
simulation.beep_delay = init_stmt->value.d;
break;
case T_Sim_Duration:
simulation.end_time = init_stmt->value.d;
break;
default:
fprintf(stderr,
"Unknown simulator init token %d\n",
init_stmt->attr);
exit(1);
}
}
/* Process the server list
* -----------------------
*/
simulation.num_of_servers = 0;
serv_info = HEAD_PFIFO(sim_n->servers);
for (; serv_info != NULL; serv_info = serv_info->link)
simulation.num_of_servers++;
simulation.servers = emalloc(simulation.num_of_servers *
sizeof(simulation.servers[0]));
i = 0;
serv_info = HEAD_PFIFO(sim_n->servers);
for (; serv_info != NULL; serv_info = serv_info->link) {
if (NULL == serv_info) {
fprintf(stderr, "Simulator server list is corrupt\n");
exit(1);
} else {
simulation.servers[i] = *serv_info;
simulation.servers[i].link = NULL;
i++;
}
}
printf("Creating server associations\n");
create_server_associations();
fprintf(stderr,"\tServer associations successfully created!!\n");
}
#ifdef FREE_CFG_T
static void
free_config_sim(
config_tree *ptree
)
{
sim_node *sim_n;
server_info *serv_n;
script_info *script_n;
if (NULL == ptree->sim_details)
return;
sim_n = HEAD_PFIFO(ptree->sim_details);
free(ptree->sim_details);
ptree->sim_details = NULL;
if (NULL == sim_n)
return;
FREE_ATTR_VAL_FIFO(sim_n->init_opts);
while (1) {
UNLINK_FIFO(serv_n, *sim_n->servers, link);
if (NULL == serv_n)
break;
script_n = serv_n->curr_script;
while (script_n != NULL) {
free(script_n);
if (serv_n->script != NULL)
UNLINK_FIFO(script_n, *serv_n->script,
link);
else
break;
}
if (serv_n->script != NULL)
free(serv_n->script);
free(serv_n);
}
free(sim_n);
}
#endif /* FREE_CFG_T */
#endif /* SIM */
/* Define two different config functions. One for the daemon and the other for
* the simulator. The simulator ignores a lot of the standard ntpd configuration
* options
*/
#ifndef SIM
static void
config_ntpd(
config_tree *ptree
)
{
config_nic_rules(ptree);
io_open_sockets();
config_monitor(ptree);
config_auth(ptree);
config_tos(ptree);
config_access(ptree);
config_tinker(ptree);
config_system_opts(ptree);
config_logconfig(ptree);
config_phone(ptree);
config_setvar(ptree);
config_ttl(ptree);
config_trap(ptree);
config_vars(ptree);
config_other_modes(ptree);
config_peers(ptree);
config_unpeers(ptree);
config_fudge(ptree);
config_qos(ptree);
#ifdef TEST_BLOCKING_WORKER
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo_sometime("www.cnn.com", "ntp", &hints,
INITIAL_DNS_RETRY,
gai_test_callback, (void *)1);
hints.ai_family = AF_INET6;
getaddrinfo_sometime("ipv6.google.com", "ntp", &hints,
INITIAL_DNS_RETRY,
gai_test_callback, (void *)0x600);
}
#endif
}
#endif /* !SIM */
#ifdef SIM
static void
config_ntpdsim(
config_tree *ptree
)
{
printf("Configuring Simulator...\n");
printf("Some ntpd-specific commands in the configuration file will be ignored.\n");
config_tos(ptree);
config_monitor(ptree);
config_tinker(ptree);
config_system_opts(ptree);
config_logconfig(ptree);
config_vars(ptree);
config_sim(ptree);
}
#endif /* SIM */
/*
* config_remotely() - implements ntpd side of ntpq :config
*/
void
config_remotely(
sockaddr_u * remote_addr
)
{
struct FILE_INFO remote_cuckoo;
char origin[128];
snprintf(origin, sizeof(origin), "remote config from %s",
stoa(remote_addr));
memset(&remote_cuckoo, 0, sizeof(remote_cuckoo));
remote_cuckoo.fname = origin;
remote_cuckoo.line_no = 1;
remote_cuckoo.col_no = 1;
ip_file = &remote_cuckoo;
input_from_file = 0;
init_syntax_tree(&cfgt);
yyparse();
cfgt.source.attr = CONF_SOURCE_NTPQ;
cfgt.timestamp = time(NULL);
cfgt.source.value.s = estrdup(stoa(remote_addr));
DPRINTF(1, ("Finished Parsing!!\n"));
save_and_apply_config_tree();
input_from_file = 1;
}
/*
* getconfig() - process startup configuration file e.g /etc/ntp.conf
*/
void
getconfig(
int argc,
char ** argv
)
{
char line[MAXLINE];
#ifdef DEBUG
atexit(free_all_config_trees);
#endif
#ifndef SYS_WINNT
config_file = CONFIG_FILE;
#else
temp = CONFIG_FILE;
if (!ExpandEnvironmentStrings((LPCTSTR)temp, (LPTSTR)config_file_storage, (DWORD)sizeof(config_file_storage))) {
msyslog(LOG_ERR, "ExpandEnvironmentStrings CONFIG_FILE failed: %m\n");
exit(1);
}
config_file = config_file_storage;
temp = ALT_CONFIG_FILE;
if (!ExpandEnvironmentStrings((LPCTSTR)temp, (LPTSTR)alt_config_file_storage, (DWORD)sizeof(alt_config_file_storage))) {
msyslog(LOG_ERR, "ExpandEnvironmentStrings ALT_CONFIG_FILE failed: %m\n");
exit(1);
}
alt_config_file = alt_config_file_storage;
#endif /* SYS_WINNT */
/*
* install a non default variable with this daemon version
*/
snprintf(line, sizeof(line), "daemon_version=\"%s\"", Version);
set_sys_var(line, strlen(line)+1, RO);
/*
* Set up for the first time step to install a variable showing
* which syscall is being used to step.
*/
set_tod_using = &ntpd_set_tod_using;
/*
* On Windows, the variable has already been set, on the rest,
* initialize it to "UNKNOWN".
*/
#ifndef SYS_WINNT
strncpy(line, "settimeofday=\"UNKNOWN\"", sizeof(line));
set_sys_var(line, strlen(line) + 1, RO);
#endif
getCmdOpts(argc, argv);
init_syntax_tree(&cfgt);
curr_include_level = 0;
if (
(fp[curr_include_level] = F_OPEN(FindConfig(config_file), "r")) == NULL
#ifdef HAVE_NETINFO
/* If there is no config_file, try NetInfo. */
&& check_netinfo && !(config_netinfo = get_netinfo_config())
#endif /* HAVE_NETINFO */
) {
msyslog(LOG_INFO, "getconfig: Couldn't open <%s>", FindConfig(config_file));
#ifndef SYS_WINNT
io_open_sockets();
return;
#else
/* Under WinNT try alternate_config_file name, first NTP.CONF, then NTP.INI */
if ((fp[curr_include_level] = F_OPEN(FindConfig(alt_config_file), "r")) == NULL) {
/*
* Broadcast clients can sometimes run without
* a configuration file.
*/
msyslog(LOG_INFO, "getconfig: Couldn't open <%s>", FindConfig(alt_config_file));
io_open_sockets();
return;
}
cfgt.source.value.s = estrdup(alt_config_file);
#endif /* SYS_WINNT */
} else
cfgt.source.value.s = estrdup(config_file);
/*** BULK OF THE PARSER ***/
#ifdef DEBUG
yydebug = !!(debug >= 5);
#endif
ip_file = fp[curr_include_level];
yyparse();
DPRINTF(1, ("Finished Parsing!!\n"));
cfgt.source.attr = CONF_SOURCE_FILE;
cfgt.timestamp = time(NULL);
save_and_apply_config_tree();
while (curr_include_level != -1)
FCLOSE(fp[curr_include_level--]);
#ifdef HAVE_NETINFO
if (config_netinfo)
free_netinfo_config(config_netinfo);
#endif /* HAVE_NETINFO */
}
void
save_and_apply_config_tree(void)
{
config_tree *ptree;
#ifndef SAVECONFIG
config_tree *punlinked;
#endif
/*
* Keep all the configuration trees applied since startup in
* a list that can be used to dump the configuration back to
* a text file.
*/
ptree = emalloc(sizeof(*ptree));
memcpy(ptree, &cfgt, sizeof(*ptree));
memset(&cfgt, 0, sizeof(cfgt));
LINK_TAIL_SLIST(cfg_tree_history, ptree, link, config_tree);
#ifdef SAVECONFIG
if (HAVE_OPT( SAVECONFIGQUIT )) {
FILE *dumpfile;
int err;
int dumpfailed;
dumpfile = fopen(OPT_ARG( SAVECONFIGQUIT ), "w");
if (NULL == dumpfile) {
err = errno;
fprintf(stderr,
"can not create save file %s, error %d %s\n",
OPT_ARG( SAVECONFIGQUIT ), err,
strerror(err));
exit(err);
}
dumpfailed = dump_all_config_trees(dumpfile, 0);
if (dumpfailed)
fprintf(stderr,
"--saveconfigquit %s error %d\n",
OPT_ARG( SAVECONFIGQUIT ),
dumpfailed);
else
fprintf(stderr,
"configuration saved to %s\n",
OPT_ARG( SAVECONFIGQUIT ));
exit(dumpfailed);
}
#endif /* SAVECONFIG */
/* The actual configuration done depends on whether we are configuring the
* simulator or the daemon. Perform a check and call the appropriate
* function as needed.
*/
#ifndef SIM
config_ntpd(ptree);
#else
config_ntpdsim(ptree);
#endif
/*
* With configure --disable-saveconfig, there's no use keeping
* the config tree around after application, so free it.
*/
#ifndef SAVECONFIG
UNLINK_SLIST(punlinked, cfg_tree_history, ptree, link,
config_tree);
NTP_INSIST(punlinked == ptree);
free_config_tree(ptree);
#endif
}
void
ntpd_set_tod_using(
const char *which
)
{
char line[128];
snprintf(line, sizeof(line), "settimeofday=\"%s\"", which);
set_sys_var(line, strlen(line) + 1, RO);
}
static char *
normal_dtoa(
double d
)
{
char * buf;
char * pch_e;
char * pch_nz;
LIB_GETBUF(buf);
snprintf(buf, LIB_BUFLENGTH, "%g", d);
/* use lowercase 'e', strip any leading zeroes in exponent */
pch_e = strchr(buf, 'e');
if (NULL == pch_e) {
pch_e = strchr(buf, 'E');
if (NULL == pch_e)
return buf;
*pch_e = 'e';
}
pch_e++;
if ('-' == *pch_e)
pch_e++;
pch_nz = pch_e;
while ('0' == *pch_nz)
pch_nz++;
if (pch_nz == pch_e)
return buf;
strncpy(pch_e, pch_nz, LIB_BUFLENGTH - (pch_e - buf));
return buf;
}
/* FUNCTIONS COPIED FROM THE OLDER ntp_config.c
* --------------------------------------------
*/
/*
* get_pfxmatch - find value for prefixmatch
* and update char * accordingly
*/
static unsigned long
get_pfxmatch(
char ** s,
struct masks *m
)
{
while (m->name) {
if (strncmp(*s, m->name, strlen(m->name)) == 0) {
*s += strlen(m->name);
return m->mask;
} else {
m++;
}
}
return 0;
}
/*
* get_match - find logmask value
*/
static unsigned long
get_match(
char *s,
struct masks *m
)
{
while (m->name) {
if (strcmp(s, m->name) == 0)
return m->mask;
else
m++;
}
return 0;
}
/*
* get_logmask - build bitmask for ntp_syslogmask
*/
static unsigned long
get_logmask(
char *s
)
{
char *t;
unsigned long offset;
unsigned long mask;
t = s;
offset = get_pfxmatch(&t, logcfg_class);
mask = get_match(t, logcfg_item);
if (mask)
return mask << offset;
else
msyslog(LOG_ERR, "logconfig: illegal argument %s - ignored", s);
return 0;
}
#ifdef HAVE_NETINFO
/*
* get_netinfo_config - find the nearest NetInfo domain with an ntp
* configuration and initialize the configuration state.
*/
static struct netinfo_config_state *
get_netinfo_config(void)
{
ni_status status;
void *domain;
ni_id config_dir;
struct netinfo_config_state *config;
if (ni_open(NULL, ".", &domain) != NI_OK) return NULL;
while ((status = ni_pathsearch(domain, &config_dir, NETINFO_CONFIG_DIR)) == NI_NODIR) {
void *next_domain;
if (ni_open(domain, "..", &next_domain) != NI_OK) {
ni_free(next_domain);
break;
}
ni_free(domain);
domain = next_domain;
}
if (status != NI_OK) {
ni_free(domain);
return NULL;
}
config = emalloc(sizeof(*config));
config->domain = domain;
config->config_dir = config_dir;
config->prop_index = 0;
config->val_index = 0;
config->val_list = NULL;
return config;
}
/*
* free_netinfo_config - release NetInfo configuration state
*/
static void
free_netinfo_config(
struct netinfo_config_state *config
)
{
ni_free(config->domain);
free(config);
}
/*
* gettokens_netinfo - return tokens from NetInfo
*/
static int
gettokens_netinfo (
struct netinfo_config_state *config,
char **tokenlist,
int *ntokens
)
{
int prop_index = config->prop_index;
int val_index = config->val_index;
char **val_list = config->val_list;
/*
* Iterate through each keyword and look for a property that matches it.
*/
again:
if (!val_list) {
for (; prop_index < COUNTOF(keywords); prop_index++)
{
ni_namelist namelist;
struct keyword current_prop = keywords[prop_index];
ni_index index;
/*
* For each value associated in the property, we're going to return
* a separate line. We squirrel away the values in the config state
* so the next time through, we don't need to do this lookup.
*/
NI_INIT(&namelist);
if (NI_OK == ni_lookupprop(config->domain,
&config->config_dir, current_prop.text,
&namelist)) {
/* Found the property, but it has no values */
if (namelist.ni_namelist_len == 0) continue;
config->val_list =
emalloc(sizeof(char*) *
(namelist.ni_namelist_len + 1));
val_list = config->val_list;
for (index = 0;
index < namelist.ni_namelist_len;
index++) {
char *value;
value = namelist.ni_namelist_val[index];
val_list[index] = estrdup(value);
}
val_list[index] = NULL;
break;
}
ni_namelist_free(&namelist);
}
config->prop_index = prop_index;
}
/* No list; we're done here. */
if (!val_list)
return CONFIG_UNKNOWN;
/*
* We have a list of values for the current property.
* Iterate through them and return each in order.
*/
if (val_list[val_index]) {
int ntok = 1;
int quoted = 0;
char *tokens = val_list[val_index];
msyslog(LOG_INFO, "%s %s", keywords[prop_index].text, val_list[val_index]);
(const char*)tokenlist[0] = keywords[prop_index].text;
for (ntok = 1; ntok < MAXTOKENS; ntok++) {
tokenlist[ntok] = tokens;
while (!ISEOL(*tokens) && (!ISSPACE(*tokens) || quoted))
quoted ^= (*tokens++ == '"');
if (ISEOL(*tokens)) {
*tokens = '\0';
break;
} else { /* must be space */
*tokens++ = '\0';
while (ISSPACE(*tokens))
tokens++;
if (ISEOL(*tokens))
break;
}
}
if (ntok == MAXTOKENS) {
/* HMS: chomp it to lose the EOL? */
msyslog(LOG_ERR,
"gettokens_netinfo: too many tokens. Ignoring: %s",
tokens);
} else {
*ntokens = ntok + 1;
}
config->val_index++; /* HMS: Should this be in the 'else'? */
return keywords[prop_index].keytype;
}
/* We're done with the current property. */
prop_index = ++config->prop_index;
/* Free val_list and reset counters. */
for (val_index = 0; val_list[val_index]; val_index++)
free(val_list[val_index]);
free(val_list);
val_list = config->val_list = NULL;
val_index = config->val_index = 0;
goto again;
}
#endif /* HAVE_NETINFO */
/*
* getnetnum - return a net number (this is crude, but careful)
*
* returns 1 for success, and mysteriously, 0 for most failures, and
* -1 if the address found is IPv6 and we believe IPv6 isn't working.
*/
#ifndef SIM
static int
getnetnum(
const char *num,
sockaddr_u *addr,
int complain,
enum gnn_type a_type /* ignored */
)
{
NTP_REQUIRE(AF_UNSPEC == AF(addr) ||
AF_INET == AF(addr) ||
AF_INET6 == AF(addr));
if (!is_ip_address(num, AF(addr), addr))
return 0;
if (IS_IPV6(addr) && !ipv6_works)
return -1;
# ifdef ISC_PLATFORM_HAVESALEN
addr->sa.sa_len = SIZEOF_SOCKADDR(AF(addr));
# endif
SET_PORT(addr, NTP_PORT);
DPRINTF(2, ("getnetnum given %s, got %s\n", num, stoa(addr)));
return 1;
}
#endif /* !SIM */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1658_2 |
crossvul-cpp_data_good_19_0 | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.memcached.org/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <mellon@pobox.com>
* Brad Fitzpatrick <brad@danga.com>
*/
#include "memcached.h"
#ifdef EXTSTORE
#include "storage.h"
#endif
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sysexits.h>
#include <stddef.h>
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#endif
/* FreeBSD 4.x doesn't have IOV_MAX exposed. */
#ifndef IOV_MAX
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__)
# define IOV_MAX 1024
/* GNU/Hurd don't set MAXPATHLEN
* http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */
#ifndef MAXPATHLEN
#define MAXPATHLEN 4096
#endif
#endif
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static int try_read_command(conn *c);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static void conn_set_state(conn *c, enum conn_states state);
static int start_conn_timeout_thread();
/* stats */
static void stats_init(void);
static void server_stats(ADD_STAT add_stats, conn *c);
static void process_stat_settings(ADD_STAT add_stats, void *c);
static void conn_to_str(const conn *c, char *buf);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void process_command(conn *c, char *command);
static void write_and_free(conn *c, char *buf, int bytes);
static int ensure_iov_space(conn *c);
static int add_iov(conn *c, const void *buf, int len);
static int add_chunked_item_iovs(conn *c, item *it, int len);
static int add_msghdr(conn *c);
static void write_bin_error(conn *c, protocol_binary_response_status err,
const char *errstr, int swallow);
static void write_bin_miss_response(conn *c, char *key, size_t nkey);
#ifdef EXTSTORE
static void _get_extstore_cb(void *e, obj_io *io, int ret);
static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt);
#endif
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct stats_state stats_state;
struct settings settings;
time_t process_started; /* when the process was started */
conn **conns;
struct slab_rebalance slab_rebal;
volatile int slab_rebalance_signal;
#ifdef EXTSTORE
/* hoping this is temporary; I'd prefer to cut globals, but will complete this
* battle another day.
*/
void *ext_storage;
#endif
/** file scope variables **/
static conn *listen_conn = NULL;
static int max_fds;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
static enum transmit_result transmit(conn *c);
/* This reduces the latency without adding lots of extra wiring to be able to
* notify the listener thread of when to listen again.
* Also, the clock timer could be broken out into its own thread and we
* can block the listener via a condition.
*/
static volatile bool allow_new_conns = true;
static struct event maxconnsevent;
static void maxconns_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 0, .tv_usec = 10000};
if (fd == -42 || allow_new_conns == false) {
/* reschedule in 10ms if we need to keep polling */
evtimer_set(&maxconnsevent, maxconns_handler, 0);
event_base_set(main_base, &maxconnsevent);
evtimer_add(&maxconnsevent, &t);
} else {
evtimer_del(&maxconnsevent);
accept_new_conns(true);
}
}
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
static rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
memset(&stats, 0, sizeof(struct stats));
memset(&stats_state, 0, sizeof(struct stats_state));
stats_state.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - ITEM_UPDATE_INTERVAL - 2;
stats_prefix_init();
}
static void stats_reset(void) {
STATS_LOCK();
memset(&stats, 0, sizeof(struct stats));
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 0;
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.oldest_cas = 0; /* supplements accuracy of oldest_live */
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.num_threads_per_udp = 0;
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */
settings.slab_chunk_size_max = settings.slab_page_size / 2;
settings.sasl = false;
settings.maxconns_fast = true;
settings.lru_crawler = false;
settings.lru_crawler_sleep = 100;
settings.lru_crawler_tocrawl = 0;
settings.lru_maintainer_thread = false;
settings.lru_segmented = true;
settings.hot_lru_pct = 20;
settings.warm_lru_pct = 40;
settings.hot_max_factor = 0.2;
settings.warm_max_factor = 2.0;
settings.inline_ascii_response = false;
settings.temp_lru = false;
settings.temporary_ttl = 61;
settings.idle_timeout = 0; /* disabled */
settings.hashpower_init = 0;
settings.slab_reassign = true;
settings.slab_automove = 1;
settings.slab_automove_ratio = 0.8;
settings.slab_automove_window = 30;
settings.shutdown_command = false;
settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT;
settings.flush_enabled = true;
settings.dump_enabled = true;
settings.crawls_persleep = 1000;
settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE;
settings.logger_buf_size = LOGGER_BUF_SIZE;
settings.drop_privileges = true;
#ifdef MEMCACHED_DEBUG
settings.relaxed_privileges = false;
#endif
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_msghdr(conn *c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (! msg) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
if (IS_UDP(c->transport) && c->request_addr_size > 0) {
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
}
c->msgbytes = 0;
c->msgused++;
if (IS_UDP(c->transport)) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE);
}
return 0;
}
extern pthread_mutex_t conn_lock;
/* Connection timeout thread bits */
static pthread_t conn_timeout_tid;
#define CONNS_PER_SLICE 100
#define TIMEOUT_MSG_SIZE (1 + sizeof(int))
static void *conn_timeout_thread(void *arg) {
int i;
conn *c;
char buf[TIMEOUT_MSG_SIZE];
rel_time_t oldest_last_cmd;
int sleep_time;
useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE);
while(1) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread at top of connection list\n");
oldest_last_cmd = current_time;
for (i = 0; i < max_fds; i++) {
if ((i % CONNS_PER_SLICE) == 0) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread sleeping for %ulus\n",
(unsigned int)timeslice);
usleep(timeslice);
}
if (!conns[i])
continue;
c = conns[i];
if (!IS_TCP(c->transport))
continue;
if (c->state != conn_new_cmd && c->state != conn_read)
continue;
if ((current_time - c->last_cmd_time) > settings.idle_timeout) {
buf[0] = 't';
memcpy(&buf[1], &i, sizeof(int));
if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE)
!= TIMEOUT_MSG_SIZE)
perror("Failed to write timeout to notify pipe");
} else {
if (c->last_cmd_time < oldest_last_cmd)
oldest_last_cmd = c->last_cmd_time;
}
}
/* This is the soonest we could have another connection time out */
sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1;
if (sleep_time <= 0)
sleep_time = 1;
if (settings.verbose > 2)
fprintf(stderr,
"idle timeout thread finished pass, sleeping for %ds\n",
sleep_time);
usleep((useconds_t) sleep_time * 1000000);
}
return NULL;
}
static int start_conn_timeout_thread() {
int ret;
if (settings.idle_timeout == 0)
return -1;
if ((ret = pthread_create(&conn_timeout_tid, NULL,
conn_timeout_thread, NULL)) != 0) {
fprintf(stderr, "Can't create idle connection timeout thread: %s\n",
strerror(ret));
return -1;
}
return 0;
}
/*
* Initializes the connections array. We don't actually allocate connection
* structures until they're needed, so as to avoid wasting memory when the
* maximum connection count is much higher than the actual number of
* connections.
*
* This does end up wasting a few pointers' worth of memory for FDs that are
* used for things other than connections, but that's worth it in exchange for
* being able to directly index the conns array by FD.
*/
static void conn_init(void) {
/* We're unlikely to see an FD much higher than maxconns. */
int next_fd = dup(1);
int headroom = 10; /* account for extra unexpected open FDs */
struct rlimit rl;
max_fds = settings.maxconns + headroom + next_fd;
/* But if possible, get the actual highest FD we can possibly ever see. */
if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
max_fds = rl.rlim_max;
} else {
fprintf(stderr, "Failed to query maximum file descriptor; "
"falling back to maxconns\n");
}
close(next_fd);
if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
/* This is unrecoverable so bail out early. */
exit(1);
}
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
}
return rv;
}
void conn_close_idle(conn *c) {
if (settings.idle_timeout > 0 &&
(current_time - c->last_cmd_time) > settings.idle_timeout) {
if (c->state != conn_new_cmd && c->state != conn_read) {
if (settings.verbose > 1)
fprintf(stderr,
"fd %d wants to timeout, but isn't in read state", c->sfd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, "Closing idle fd %d\n", c->sfd);
c->thread->stats.idle_kicks++;
conn_set_state(c, conn_closing);
drive_machine(c);
}
}
/* bring conn back from a sidethread. could have had its event base moved. */
void conn_worker_readd(conn *c) {
c->ev_flags = EV_READ | EV_PERSIST;
event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c);
event_base_set(c->thread->base, &c->event);
c->state = conn_new_cmd;
// TODO: call conn_cleanup/fail/etc
if (event_add(&c->event, 0) == -1) {
perror("event_add");
}
#ifdef EXTSTORE
// If we had IO objects, process
if (c->io_wraplist) {
//assert(c->io_wrapleft == 0); // assert no more to process
conn_set_state(c, conn_mwrite);
drive_machine(c);
}
#endif
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base) {
conn *c;
assert(sfd >= 0 && sfd < max_fds);
c = conns[sfd];
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate connection object\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->rbuf = c->wbuf = 0;
c->ilist = 0;
c->suffixlist = 0;
c->iov = 0;
c->msglist = 0;
c->hdrbuf = 0;
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->suffixsize = SUFFIX_LIST_INITIAL;
c->iovsize = IOV_LIST_INITIAL;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize);
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 ||
c->msglist == 0 || c->suffixlist == 0) {
conn_free(c);
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate buffers for connection\n");
return NULL;
}
STATS_LOCK();
stats_state.conn_structs++;
STATS_UNLOCK();
c->sfd = sfd;
conns[sfd] = c;
}
c->transport = transport;
c->protocol = settings.binding_protocol;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (transport == tcp_transport && init_state == conn_new_cmd) {
if (getpeername(sfd, (struct sockaddr *) &c->request_addr,
&c->request_addr_size)) {
perror("getpeername");
memset(&c->request_addr, 0, sizeof(c->request_addr));
}
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = c->wbytes = 0;
c->wcurr = c->wbuf;
c->rcurr = c->rbuf;
c->ritem = 0;
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
c->ileft = 0;
c->suffixleft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->authenticated = false;
c->last_cmd_time = current_time; /* initialize for idle kicker */
#ifdef EXTSTORE
c->io_wraplist = NULL;
c->io_wrapleft = 0;
#endif
c->write_and_go = init_state;
c->write_and_free = 0;
c->item = 0;
c->noreply = false;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
perror("event_add");
return NULL;
}
STATS_LOCK();
stats_state.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
#ifdef EXTSTORE
static void recache_or_free(conn *c, io_wrap *wrap) {
item *it;
it = (item *)wrap->io.buf;
bool do_free = true;
// If request was ultimately a miss, unlink the header.
if (wrap->miss) {
do_free = false;
size_t ntotal = ITEM_ntotal(wrap->hdr_it);
item_unlink(wrap->hdr_it);
slabs_free(it, ntotal, slabs_clsid(ntotal));
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.miss_from_extstore++;
if (wrap->badcrc)
c->thread->stats.badcrc_from_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
} else if (settings.ext_recache_rate) {
// hashvalue is cuddled during store
uint32_t hv = (uint32_t)it->time;
// opt to throw away rather than wait on a lock.
void *hold_lock = item_trylock(hv);
if (hold_lock != NULL) {
item *h_it = wrap->hdr_it;
uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE;
// Item must be recently hit at least twice to recache.
if (((h_it->it_flags & flags) == flags) &&
h_it->time > current_time - ITEM_UPDATE_INTERVAL &&
c->recache_counter++ % settings.ext_recache_rate == 0) {
do_free = false;
// In case it's been updated.
it->exptime = h_it->exptime;
it->it_flags &= ~ITEM_LINKED;
it->refcount = 0;
it->h_next = NULL; // might not be necessary.
STORAGE_delete(c->thread->storage, h_it);
item_replace(h_it, it, hv);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.recache_from_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
if (hold_lock)
item_trylock_unlock(hold_lock);
}
if (do_free)
slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it));
wrap->io.buf = NULL; // sanity.
wrap->io.next = NULL;
wrap->next = NULL;
wrap->active = false;
// TODO: reuse lock and/or hv.
item_remove(wrap->hdr_it);
}
#endif
static void conn_release_items(conn *c) {
assert(c != NULL);
if (c->item) {
item_remove(c->item);
c->item = 0;
}
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
if (c->suffixleft != 0) {
for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) {
do_cache_free(c->thread->suffix_cache, *(c->suffixcurr));
}
}
#ifdef EXTSTORE
if (c->io_wraplist) {
io_wrap *tmp = c->io_wraplist;
while (tmp) {
io_wrap *next = tmp->next;
recache_or_free(c, tmp);
do_cache_free(c->thread->io_cache, tmp); // lockless
tmp = next;
}
c->io_wraplist = NULL;
}
#endif
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
conn_release_items(c);
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
if (IS_UDP(c->transport)) {
conn_set_state(c, conn_read);
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
assert(c != NULL);
assert(c->sfd >= 0 && c->sfd < max_fds);
MEMCACHED_CONN_DESTROY(c);
conns[c->sfd] = NULL;
if (c->hdrbuf)
free(c->hdrbuf);
if (c->msglist)
free(c->msglist);
if (c->rbuf)
free(c->rbuf);
if (c->wbuf)
free(c->wbuf);
if (c->ilist)
free(c->ilist);
if (c->suffixlist)
free(c->suffixlist);
if (c->iov)
free(c->iov);
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
conn_cleanup(c);
MEMCACHED_CONN_RELEASE(c->sfd);
conn_set_state(c, conn_closed);
close(c->sfd);
pthread_mutex_lock(&conn_lock);
allow_new_conns = true;
pthread_mutex_unlock(&conn_lock);
STATS_LOCK();
stats_state.curr_conns--;
STATS_UNLOCK();
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
static void conn_shrink(conn *c) {
assert(c != NULL);
if (IS_UDP(c->transport))
return;
if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) {
char *newbuf;
if (c->rcurr != c->rbuf)
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
if (newbuf) {
c->rbuf = newbuf;
c->rsize = DATA_BUFFER_SIZE;
}
/* TODO check other branch... */
c->rcurr = c->rbuf;
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]));
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0]));
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->iovsize > IOV_LIST_HIGHWAT) {
struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0]));
if (newbuf) {
c->iov = newbuf;
c->iovsize = IOV_LIST_INITIAL;
}
/* TODO check return value */
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite",
"conn_closed",
"conn_watch" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);
if (state != c->state) {
if (settings.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state),
state_text(state));
}
if (state == conn_write || state == conn_mwrite) {
MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes);
}
c->state = state;
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov = (struct iovec *)realloc(c->iov,
(c->iovsize * 2) * sizeof(struct iovec));
if (! new_iov) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->iov = new_iov;
c->iovsize *= 2;
/* Point all the msghdr structures at the new list. */
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* Returns 0 on success, -1 on out-of-memory.
* Note: This is a hot path for at least ASCII protocol. While there is
* redundant code in splitting TCP/UDP handling, any reduction in steps has a
* large impact for TCP connections.
*/
static int add_iov(conn *c, const void *buf, int len) {
struct msghdr *m;
int leftover;
assert(c != NULL);
if (IS_UDP(c->transport)) {
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes.
*/
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
} else {
/* Optimized path for TCP connections */
m = &c->msglist[c->msgused - 1];
if (m->msg_iovlen == IOV_MAX) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
}
return 0;
}
static int add_chunked_item_iovs(conn *c, item *it, int len) {
assert(it->it_flags & ITEM_CHUNKED);
item_chunk *ch = (item_chunk *) ITEM_data(it);
while (ch) {
int todo = (len > ch->used) ? ch->used : len;
if (add_iov(c, ch->data, todo) != 0) {
return -1;
}
ch = ch->next;
len -= todo;
}
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
static int build_udp_headers(conn *c) {
int i;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf) {
new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE);
} else {
new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE);
}
if (! new_hdrbuf) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = (void*)hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = 0;
*hdr++ = 0;
assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn *c, const char *str) {
size_t len;
assert(c != NULL);
if (c->noreply) {
if (settings.verbose > 1)
fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str);
c->noreply = false;
conn_set_state(c, conn_new_cmd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
/* Nuke a partial output... */
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
add_msghdr(c);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
return;
}
/*
* Outputs a protocol-specific "out of memory" error. For ASCII clients,
* this is equivalent to out_string().
*/
static void out_of_memory(conn *c, char *ascii_error) {
const static char error_prefix[] = "SERVER_ERROR ";
const static int error_prefix_len = sizeof(error_prefix) - 1;
if (c->protocol == binary_prot) {
/* Strip off the generic error prefix; it's irrelevant in binary */
if (!strncmp(ascii_error, error_prefix, error_prefix_len)) {
ascii_error += error_prefix_len;
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0);
} else {
out_string(c, ascii_error);
}
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->cmd, and the item is ready in c->item.
*/
static void complete_nread_ascii(conn *c) {
assert(c != NULL);
item *it = c->item;
int comm = c->cmd;
enum store_item_type ret;
bool is_valid = false;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if ((it->it_flags & ITEM_CHUNKED) == 0) {
if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) {
is_valid = true;
}
} else {
char buf[2];
/* should point to the final item chunk */
item_chunk *ch = (item_chunk *) c->ritem;
assert(ch->used != 0);
/* :( We need to look at the last two bytes. This could span two
* chunks.
*/
if (ch->used > 1) {
buf[0] = ch->data[ch->used - 2];
buf[1] = ch->data[ch->used - 1];
} else {
assert(ch->prev);
assert(ch->used == 1);
buf[0] = ch->prev->data[ch->prev->used - 1];
buf[1] = ch->data[ch->used - 1];
}
if (strncmp(buf, "\r\n", 2) == 0) {
is_valid = true;
} else {
assert(1 == 0);
}
}
if (!is_valid) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
ret = store_item(it, comm, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_CAS:
MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes,
cas);
break;
}
#endif
switch (ret) {
case STORED:
out_string(c, "STORED");
break;
case EXISTS:
out_string(c, "EXISTS");
break;
case NOT_FOUND:
out_string(c, "NOT_FOUND");
break;
case NOT_STORED:
out_string(c, "NOT_STORED");
break;
default:
out_string(c, "SERVER_ERROR Unhandled storage type.");
}
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
/**
* get a pointer to the start of the request struct for the current command
*/
static void* binary_get_request(conn *c) {
char *ret = c->rcurr;
ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen +
c->binary_header.request.extlen);
assert(ret >= c->rbuf);
return ret;
}
/**
* get a pointer to the key in this request
*/
static char* binary_get_key(conn *c) {
return c->rcurr - (c->binary_header.request.keylen);
}
static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) {
protocol_binary_response_header* header;
assert(c);
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
/* This should never run out of memory because iov and msg lists
* have minimum sizes big enough to hold an error response.
*/
out_of_memory(c, "SERVER_ERROR out of memory adding binary header");
return;
}
header = (protocol_binary_response_header *)c->wbuf;
header->response.magic = (uint8_t)PROTOCOL_BINARY_RES;
header->response.opcode = c->binary_header.request.opcode;
header->response.keylen = (uint16_t)htons(key_len);
header->response.extlen = (uint8_t)hdr_len;
header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
header->response.status = (uint16_t)htons(err);
header->response.bodylen = htonl(body_len);
header->response.opaque = c->opaque;
header->response.cas = htonll(c->cas);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d Writing bin response:", c->sfd);
for (ii = 0; ii < sizeof(header->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n>%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", header->bytes[ii]);
}
fprintf(stderr, "\n");
}
add_iov(c, c->wbuf, sizeof(header->response));
}
/**
* Writes a binary error response. If errstr is supplied, it is used as the
* error text; otherwise a generic description of the error status code is
* included.
*/
static void write_bin_error(conn *c, protocol_binary_response_status err,
const char *errstr, int swallow) {
size_t len;
if (!errstr) {
switch (err) {
case PROTOCOL_BINARY_RESPONSE_ENOMEM:
errstr = "Out of memory";
break;
case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
errstr = "Unknown command";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
errstr = "Not found";
break;
case PROTOCOL_BINARY_RESPONSE_EINVAL:
errstr = "Invalid arguments";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
errstr = "Data exists for key.";
break;
case PROTOCOL_BINARY_RESPONSE_E2BIG:
errstr = "Too large.";
break;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL:
errstr = "Non-numeric server-side value for incr or decr";
break;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
errstr = "Not stored.";
break;
case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR:
errstr = "Auth failure.";
break;
default:
assert(false);
errstr = "UNHANDLED ERROR";
fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err);
}
}
if (settings.verbose > 1) {
fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr);
}
len = strlen(errstr);
add_bin_header(c, err, 0, 0, len);
if (len > 0) {
add_iov(c, errstr, len);
}
conn_set_state(c, conn_mwrite);
if(swallow > 0) {
c->sbytes = swallow;
c->write_and_go = conn_swallow;
} else {
c->write_and_go = conn_new_cmd;
}
}
/* Form and send a response to a command over the binary protocol */
static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) {
if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET ||
c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_bin_header(c, 0, hlen, keylen, dlen);
if(dlen > 0) {
add_iov(c, d, dlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
conn_set_state(c, conn_new_cmd);
}
}
static void complete_incr_bin(conn *c) {
item *it;
char *key;
size_t nkey;
/* Weird magic in add_delta forces me to pad here */
char tmpbuf[INCR_MAX_STORAGE_LEN];
uint64_t cas = 0;
protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf;
protocol_binary_request_incr* req = binary_get_request(c);
assert(c != NULL);
assert(c->wsize >= sizeof(*rsp));
/* fix byteorder in the request */
req->message.body.delta = ntohll(req->message.body.delta);
req->message.body.initial = ntohll(req->message.body.initial);
req->message.body.expiration = ntohl(req->message.body.expiration);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int i;
fprintf(stderr, "incr ");
for (i = 0; i < nkey; i++) {
fprintf(stderr, "%c", key[i]);
}
fprintf(stderr, " %lld, %llu, %d\n",
(long long)req->message.body.delta,
(long long)req->message.body.initial,
req->message.body.expiration);
}
if (c->binary_header.request.cas != 0) {
cas = c->binary_header.request.cas;
}
switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT,
req->message.body.delta, tmpbuf,
&cas)) {
case OK:
rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10));
if (cas) {
c->cas = cas;
}
write_bin_response(c, &rsp->message.body, 0, 0,
sizeof(rsp->message.body.value));
break;
case NON_NUMERIC:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0);
break;
case EOM:
out_of_memory(c, "SERVER_ERROR Out of memory incrementing value");
break;
case DELTA_ITEM_NOT_FOUND:
if (req->message.body.expiration != 0xffffffff) {
/* Save some room for the response */
rsp->message.body.value = htonll(req->message.body.initial);
snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu",
(unsigned long long)req->message.body.initial);
int res = strlen(tmpbuf);
it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration),
res + 2);
if (it != NULL) {
memcpy(ITEM_data(it), tmpbuf, res);
memcpy(ITEM_data(it) + res, "\r\n", 2);
if (store_item(it, NREAD_ADD, c)) {
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value));
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED,
NULL, 0);
}
item_remove(it); /* release our reference */
} else {
out_of_memory(c,
"SERVER_ERROR Out of memory allocating new item");
}
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
}
break;
case DELTA_ITEM_CAS_MISMATCH:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
break;
}
}
static void complete_update_bin(conn *c) {
protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL;
enum store_item_type ret = NOT_STORED;
assert(c != NULL);
item *it = c->item;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We don't actually receive the trailing two characters in the bin
* protocol, so we're going to just set them here */
if ((it->it_flags & ITEM_CHUNKED) == 0) {
*(ITEM_data(it) + it->nbytes - 2) = '\r';
*(ITEM_data(it) + it->nbytes - 1) = '\n';
} else {
assert(c->ritem);
item_chunk *ch = (item_chunk *) c->ritem;
if (ch->size == ch->used)
ch = ch->next;
assert(ch->size - ch->used >= 2);
ch->data[ch->used] = '\r';
ch->data[ch->used + 1] = '\n';
ch->used += 2;
}
ret = store_item(it, c->cmd, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
}
#endif
switch (ret) {
case STORED:
/* Stored */
write_bin_response(c, NULL, 0, 0, 0);
break;
case EXISTS:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
break;
case NOT_FOUND:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
break;
case NOT_STORED:
case TOO_LARGE:
case NO_MEMORY:
if (c->cmd == NREAD_ADD) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;
} else if(c->cmd == NREAD_REPLACE) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED;
}
write_bin_error(c, eno, NULL, 0);
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
static void write_bin_miss_response(conn *c, char *key, size_t nkey) {
if (nkey) {
char *ofs = c->wbuf + sizeof(protocol_binary_response_header);
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, nkey, nkey);
memcpy(ofs, key, nkey);
add_iov(c, ofs, nkey);
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
NULL, 0);
}
}
static void process_bin_get_or_touch(conn *c) {
item *it;
protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf;
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH ||
c->cmd == PROTOCOL_BINARY_CMD_GAT ||
c->cmd == PROTOCOL_BINARY_CMD_GATK);
int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK ||
c->cmd == PROTOCOL_BINARY_CMD_GATK);
int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH);
bool failed = false;
if (settings.verbose > 1) {
fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET");
if (fwrite(key, 1, nkey, stderr)) {}
fputc('\n', stderr);
}
if (should_touch) {
protocol_binary_request_touch *t = binary_get_request(c);
time_t exptime = ntohl(t->message.body.expiration);
it = item_touch(key, nkey, realtime(exptime), c);
} else {
it = item_get(key, nkey, c, DO_UPDATE);
}
if (it) {
/* the length has two unnecessary bytes ("\r\n") */
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2);
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
} else {
c->thread->stats.get_cmds++;
c->thread->stats.lru_hits[it->slabs_clsid]++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
if (should_touch) {
MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
} else {
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
}
if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) {
bodylen -= it->nbytes - 2;
} else if (should_return_key) {
bodylen += nkey;
keylen = nkey;
}
add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen);
rsp->message.header.response.cas = htonll(ITEM_get_cas(it));
// add the flags
if (settings.inline_ascii_response) {
rsp->message.body.flags = htonl(strtoul(ITEM_suffix(it), NULL, 10));
} else if (it->nsuffix > 0) {
rsp->message.body.flags = htonl(*((uint32_t *)ITEM_suffix(it)));
} else {
rsp->message.body.flags = 0;
}
add_iov(c, &rsp->message.body, sizeof(rsp->message.body));
if (should_return_key) {
add_iov(c, ITEM_key(it), nkey);
}
if (should_return_value) {
/* Add the data minus the CRLF */
#ifdef EXTSTORE
if (it->it_flags & ITEM_HDR) {
int iovcnt = 4;
int iovst = c->iovused - 3;
if (!should_return_key) {
iovcnt = 3;
iovst = c->iovused - 2;
}
// FIXME: this can return an error, but code flow doesn't
// allow bailing here.
if (_get_extstore(c, it, iovst, iovcnt) != 0)
failed = true;
} else if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes - 2);
} else {
add_chunked_item_iovs(c, it, it->nbytes - 2);
}
#else
if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes - 2);
} else {
add_chunked_item_iovs(c, it, it->nbytes - 2);
}
#endif
}
if (!failed) {
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
/* Remember this command so we can garbage collect it later */
#ifdef EXTSTORE
if ((it->it_flags & ITEM_HDR) == 0) {
c->item = it;
} else {
c->item = NULL;
}
#else
c->item = it;
#endif
} else {
item_remove(it);
}
} else {
failed = true;
}
if (failed) {
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
} else {
c->thread->stats.get_cmds++;
c->thread->stats.get_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
if (should_touch) {
MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0);
} else {
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
if (c->noreply) {
conn_set_state(c, conn_new_cmd);
} else {
if (should_return_key) {
write_bin_miss_response(c, key, nkey);
} else {
write_bin_miss_response(c, NULL, 0);
}
}
}
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
}
static void append_bin_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *buf = c->stats.buffer + c->stats.offset;
uint32_t bodylen = klen + vlen;
protocol_binary_response_header header = {
.response.magic = (uint8_t)PROTOCOL_BINARY_RES,
.response.opcode = PROTOCOL_BINARY_CMD_STAT,
.response.keylen = (uint16_t)htons(klen),
.response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES,
.response.bodylen = htonl(bodylen),
.response.opaque = c->opaque
};
memcpy(buf, header.bytes, sizeof(header.response));
buf += sizeof(header.response);
if (klen > 0) {
memcpy(buf, key, klen);
buf += klen;
if (vlen > 0) {
memcpy(buf, val, vlen);
}
}
c->stats.offset += sizeof(header.response) + bodylen;
}
static void append_ascii_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *pos = c->stats.buffer + c->stats.offset;
uint32_t nbytes = 0;
int remaining = c->stats.size - c->stats.offset;
int room = remaining - 1;
if (klen == 0 && vlen == 0) {
nbytes = snprintf(pos, room, "END\r\n");
} else if (vlen == 0) {
nbytes = snprintf(pos, room, "STAT %s\r\n", key);
} else {
nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val);
}
c->stats.offset += nbytes;
}
static bool grow_stats_buf(conn *c, size_t needed) {
size_t nsize = c->stats.size;
size_t available = nsize - c->stats.offset;
bool rv = true;
/* Special case: No buffer -- need to allocate fresh */
if (c->stats.buffer == NULL) {
nsize = 1024;
available = c->stats.size = c->stats.offset = 0;
}
while (needed > available) {
assert(nsize > 0);
nsize = nsize << 1;
available = nsize - c->stats.offset;
}
if (nsize != c->stats.size) {
char *ptr = realloc(c->stats.buffer, nsize);
if (ptr) {
c->stats.buffer = ptr;
c->stats.size = nsize;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
rv = false;
}
}
return rv;
}
static void append_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
const void *cookie)
{
/* value without a key is invalid */
if (klen == 0 && vlen > 0) {
return ;
}
conn *c = (conn*)cookie;
if (c->protocol == binary_prot) {
size_t needed = vlen + klen + sizeof(protocol_binary_response_header);
if (!grow_stats_buf(c, needed)) {
return ;
}
append_bin_stats(key, klen, val, vlen, c);
} else {
size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n"
if (!grow_stats_buf(c, needed)) {
return ;
}
append_ascii_stats(key, klen, val, vlen, c);
}
assert(c->stats.offset <= c->stats.size);
}
static void process_bin_stat(conn *c) {
char *subcommand = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d STATS ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", subcommand[ii]);
}
fprintf(stderr, "\n");
}
if (nkey == 0) {
/* request all statistics */
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strncmp(subcommand, "reset", 5) == 0) {
stats_reset();
} else if (strncmp(subcommand, "settings", 8) == 0) {
process_stat_settings(&append_stats, c);
} else if (strncmp(subcommand, "detail", 6) == 0) {
char *subcmd_pos = subcommand + 6;
if (strncmp(subcmd_pos, " dump", 5) == 0) {
int len;
char *dump_buf = stats_prefix_dump(&len);
if (dump_buf == NULL || len <= 0) {
out_of_memory(c, "SERVER_ERROR Out of memory generating stats");
if (dump_buf != NULL)
free(dump_buf);
return;
} else {
append_stats("detailed", strlen("detailed"), dump_buf, len, c);
free(dump_buf);
}
} else if (strncmp(subcmd_pos, " on", 3) == 0) {
settings.detail_enabled = 1;
} else if (strncmp(subcmd_pos, " off", 4) == 0) {
settings.detail_enabled = 0;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
return;
}
} else {
if (get_stats(subcommand, nkey, &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR Out of memory generating stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
}
return;
}
/* Append termination package and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) {
assert(c);
c->substate = next_substate;
c->rlbytes = c->keylen + extra;
/* Ok... do we have room for the extras and the key in the input buffer? */
ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf;
if (c->rlbytes > c->rsize - offset) {
size_t nsize = c->rsize;
size_t size = c->rlbytes + sizeof(protocol_binary_request_header);
while (size > nsize) {
nsize *= 2;
}
if (nsize != c->rsize) {
if (settings.verbose > 1) {
fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n",
c->sfd, (unsigned long)c->rsize, (unsigned long)nsize);
}
char *newm = realloc(c->rbuf, nsize);
if (newm == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
if (settings.verbose) {
fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n",
c->sfd);
}
conn_set_state(c, conn_closing);
return;
}
c->rbuf= newm;
/* rcurr should point to the same offset in the packet */
c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header);
c->rsize = nsize;
}
if (c->rbuf != c->rcurr) {
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Repack input buffer\n", c->sfd);
}
}
}
/* preserve the header in the buffer.. */
c->ritem = c->rcurr + sizeof(protocol_binary_request_header);
conn_set_state(c, conn_nread);
}
/* Just write an error message and disconnect the client */
static void handle_binary_protocol_error(conn *c) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0);
if (settings.verbose) {
fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n",
c->binary_header.request.opcode, c->sfd);
}
c->write_and_go = conn_closing;
}
static void init_sasl_conn(conn *c) {
assert(c);
/* should something else be returned? */
if (!settings.sasl)
return;
c->authenticated = false;
if (!c->sasl_conn) {
int result=sasl_server_new("memcached",
NULL,
my_sasl_hostname[0] ? my_sasl_hostname : NULL,
NULL, NULL,
NULL, 0, &c->sasl_conn);
if (result != SASL_OK) {
if (settings.verbose) {
fprintf(stderr, "Failed to initialize SASL conn.\n");
}
c->sasl_conn = NULL;
}
}
}
static void bin_list_sasl_mechs(conn *c) {
// Guard against a disabled SASL.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
init_sasl_conn(c);
const char *result_string = NULL;
unsigned int string_length = 0;
int result=sasl_listmech(c->sasl_conn, NULL,
"", /* What to prepend the string with */
" ", /* What to separate mechanisms with */
"", /* What to append to the string */
&result_string, &string_length,
NULL);
if (result != SASL_OK) {
/* Perhaps there's a better error for this... */
if (settings.verbose) {
fprintf(stderr, "Failed to list SASL mechanisms.\n");
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
return;
}
write_bin_response(c, (char*)result_string, 0, 0, string_length);
}
static void process_bin_sasl_auth(conn *c) {
// Guard for handling disabled SASL on the server.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
assert(c->binary_header.request.extlen == 0);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > MAX_SASL_MECH_LEN) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
return;
}
char *key = binary_get_key(c);
assert(key);
item *it = item_alloc(key, nkey, 0, 0, vlen+2);
/* Can't use a chunked item for SASL authentication. */
if (it == 0 || (it->it_flags & ITEM_CHUNKED)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen);
c->write_and_go = conn_swallow;
return;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_reading_sasl_auth_data;
}
static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > ((item*) c->item)->nkey) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
item_unlink(c->item);
return;
}
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
if (vlen > ((item*) c->item)->nbytes) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
item_unlink(c->item);
return;
}
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
c->authenticated = true;
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.auth_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.auth_cmds++;
c->thread->stats.auth_errors++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
static bool authenticated(conn *c) {
assert(settings.sasl);
bool rv = false;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */
rv = true;
break;
default:
rv = c->authenticated;
}
if (settings.verbose > 1) {
fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n",
c->cmd, rv ? "true" : "false");
}
return rv;
}
static void dispatch_bin_command(conn *c) {
int protocol_error = 0;
uint8_t extlen = c->binary_header.request.extlen;
uint16_t keylen = c->binary_header.request.keylen;
uint32_t bodylen = c->binary_header.request.bodylen;
if (keylen > bodylen || keylen + extlen > bodylen) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0);
c->write_and_go = conn_closing;
return;
}
if (settings.sasl && !authenticated(c)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
c->write_and_go = conn_closing;
return;
}
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
c->noreply = true;
/* binprot supports 16bit keys, but internals are still 8bit */
if (keylen > KEY_MAX_LENGTH) {
handle_binary_protocol_error(c);
return;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SETQ:
c->cmd = PROTOCOL_BINARY_CMD_SET;
break;
case PROTOCOL_BINARY_CMD_ADDQ:
c->cmd = PROTOCOL_BINARY_CMD_ADD;
break;
case PROTOCOL_BINARY_CMD_REPLACEQ:
c->cmd = PROTOCOL_BINARY_CMD_REPLACE;
break;
case PROTOCOL_BINARY_CMD_DELETEQ:
c->cmd = PROTOCOL_BINARY_CMD_DELETE;
break;
case PROTOCOL_BINARY_CMD_INCREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_INCREMENT;
break;
case PROTOCOL_BINARY_CMD_DECREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_DECREMENT;
break;
case PROTOCOL_BINARY_CMD_QUITQ:
c->cmd = PROTOCOL_BINARY_CMD_QUIT;
break;
case PROTOCOL_BINARY_CMD_FLUSHQ:
c->cmd = PROTOCOL_BINARY_CMD_FLUSH;
break;
case PROTOCOL_BINARY_CMD_APPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_PREPEND;
break;
case PROTOCOL_BINARY_CMD_GETQ:
c->cmd = PROTOCOL_BINARY_CMD_GET;
break;
case PROTOCOL_BINARY_CMD_GETKQ:
c->cmd = PROTOCOL_BINARY_CMD_GETK;
break;
case PROTOCOL_BINARY_CMD_GATQ:
c->cmd = PROTOCOL_BINARY_CMD_GAT;
break;
case PROTOCOL_BINARY_CMD_GATKQ:
c->cmd = PROTOCOL_BINARY_CMD_GATK;
break;
default:
c->noreply = false;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_VERSION:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, VERSION, 0, 0, strlen(VERSION));
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_FLUSH:
if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) {
bin_read_key(c, bin_read_flush_exptime, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_NOOP:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_REPLACE:
if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) {
bin_read_key(c, bin_reading_set_header, 8);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETK:
if (extlen == 0 && bodylen == keylen && keylen > 0) {
bin_read_key(c, bin_reading_get_key, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_DELETE:
if (keylen > 0 && extlen == 0 && bodylen == keylen) {
bin_read_key(c, bin_reading_del_header, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_INCREMENT:
case PROTOCOL_BINARY_CMD_DECREMENT:
if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) {
bin_read_key(c, bin_reading_incr_header, 20);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_APPEND:
case PROTOCOL_BINARY_CMD_PREPEND:
if (keylen > 0 && extlen == 0) {
bin_read_key(c, bin_reading_set_header, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_STAT:
if (extlen == 0) {
bin_read_key(c, bin_reading_stat, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_QUIT:
if (keylen == 0 && extlen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
c->write_and_go = conn_closing;
if (c->noreply) {
conn_set_state(c, conn_closing);
}
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
bin_list_sasl_mechs(c);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_AUTH:
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (extlen == 0 && keylen != 0) {
bin_read_key(c, bin_reading_sasl_auth, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_TOUCH:
case PROTOCOL_BINARY_CMD_GAT:
case PROTOCOL_BINARY_CMD_GATQ:
case PROTOCOL_BINARY_CMD_GATK:
case PROTOCOL_BINARY_CMD_GATKQ:
if (extlen == 4 && keylen != 0) {
bin_read_key(c, bin_reading_touch_key, 4);
} else {
protocol_error = 1;
}
break;
default:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
bodylen);
}
if (protocol_error)
handle_binary_protocol_error(c);
}
static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* This error generating method eats the swallow value. Add here. */
c->sbytes = vlen;
status = NO_MEMORY;
}
/* FIXME: losing c->cmd since it's translated below. refactor? */
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, 0, key, nkey, req->message.body.expiration,
ITEM_clsid(it));
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_append_prepend(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
vlen = c->binary_header.request.bodylen - nkey;
if (settings.verbose > 1) {
fprintf(stderr, "Value len is %d\n", vlen);
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, 0, 0, vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, 0, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* OOM calls eat the swallow value. Add here. */
c->sbytes = vlen;
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_APPEND:
c->cmd = NREAD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPEND:
c->cmd = NREAD_PREPEND;
break;
default:
assert(0);
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_flush(conn *c) {
time_t exptime = 0;
protocol_binary_request_flush* req = binary_get_request(c);
rel_time_t new_oldest = 0;
if (!settings.flush_enabled) {
// flush_all is not allowed but we log it on stats
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
return;
}
if (c->binary_header.request.extlen == sizeof(req->message.body)) {
exptime = ntohl(req->message.body.expiration);
}
if (exptime > 0) {
new_oldest = realtime(exptime);
} else {
new_oldest = current_time;
}
if (settings.use_cas) {
settings.oldest_live = new_oldest - 1;
if (settings.oldest_live <= current_time)
settings.oldest_cas = get_cas_id();
} else {
settings.oldest_live = new_oldest;
}
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_response(c, NULL, 0, 0, 0);
}
static void process_bin_delete(conn *c) {
item *it;
protocol_binary_request_delete* req = binary_get_request(c);
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
assert(c != NULL);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "Deleting ");
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
uint64_t cas = ntohll(req->message.header.request.cas);
if (cas == 0 || cas == ITEM_get_cas(it)) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
write_bin_response(c, NULL, 0, 0, 0);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
static void complete_nread_binary(conn *c) {
assert(c != NULL);
assert(c->cmd >= 0);
switch(c->substate) {
case bin_reading_set_header:
if (c->cmd == PROTOCOL_BINARY_CMD_APPEND ||
c->cmd == PROTOCOL_BINARY_CMD_PREPEND) {
process_bin_append_prepend(c);
} else {
process_bin_update(c);
}
break;
case bin_read_set_value:
complete_update_bin(c);
break;
case bin_reading_get_key:
case bin_reading_touch_key:
process_bin_get_or_touch(c);
break;
case bin_reading_stat:
process_bin_stat(c);
break;
case bin_reading_del_header:
process_bin_delete(c);
break;
case bin_reading_incr_header:
complete_incr_bin(c);
break;
case bin_read_flush_exptime:
process_bin_flush(c);
break;
case bin_reading_sasl_auth:
process_bin_sasl_auth(c);
break;
case bin_reading_sasl_auth_data:
process_bin_complete_sasl_auth(c);
break;
default:
fprintf(stderr, "Not handling substate %d\n", c->substate);
assert(0);
}
}
static void reset_cmd_handler(conn *c) {
c->cmd = -1;
c->substate = bin_no_state;
if(c->item != NULL) {
item_remove(c->item);
c->item = NULL;
}
conn_shrink(c);
if (c->rbytes > 0) {
conn_set_state(c, conn_parse_cmd);
} else {
conn_set_state(c, conn_waiting);
}
}
static void complete_nread(conn *c) {
assert(c != NULL);
assert(c->protocol == ascii_prot
|| c->protocol == binary_prot);
if (c->protocol == ascii_prot) {
complete_nread_ascii(c);
} else if (c->protocol == binary_prot) {
complete_nread_binary(c);
}
}
/* Destination must always be chunked */
/* This should be part of item.c */
static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) {
item_chunk *dch = (item_chunk *) ITEM_data(d_it);
/* Advance dch until we find free space */
while (dch->size == dch->used) {
if (dch->next) {
dch = dch->next;
} else {
break;
}
}
if (s_it->it_flags & ITEM_CHUNKED) {
int remain = len;
item_chunk *sch = (item_chunk *) ITEM_data(s_it);
int copied = 0;
/* Fills dch's to capacity, not straight copy sch in case data is
* being added or removed (ie append/prepend)
*/
while (sch && dch && remain) {
assert(dch->used <= dch->size);
int todo = (dch->size - dch->used < sch->used - copied)
? dch->size - dch->used : sch->used - copied;
if (remain < todo)
todo = remain;
memcpy(dch->data + dch->used, sch->data + copied, todo);
dch->used += todo;
copied += todo;
remain -= todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, remain);
if (tch) {
dch = tch;
} else {
return -1;
}
}
assert(copied <= sch->used);
if (copied == sch->used) {
copied = 0;
sch = sch->next;
}
}
/* assert that the destination had enough space for the source */
assert(remain == 0);
} else {
int done = 0;
/* Fill dch's via a non-chunked item. */
while (len > done && dch) {
int todo = (dch->size - dch->used < len - done)
? dch->size - dch->used : len - done;
//assert(dch->size - dch->used != 0);
memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo);
done += todo;
dch->used += todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, len - done);
if (tch) {
dch = tch;
} else {
return -1;
}
}
}
assert(len == done);
}
return 0;
}
static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) {
if (comm == NREAD_APPEND) {
if (new_it->it_flags & ITEM_CHUNKED) {
if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 ||
_store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) {
return -1;
}
} else {
memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes);
memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes);
}
} else {
/* NREAD_PREPEND */
if (new_it->it_flags & ITEM_CHUNKED) {
if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 ||
_store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) {
return -1;
}
} else {
memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes);
memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes);
}
}
return 0;
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns the state of storage.
*/
enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) {
char *key = ITEM_key(it);
item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE);
enum store_item_type stored = NOT_STORED;
item *new_it = NULL;
uint32_t flags;
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && (comm == NREAD_REPLACE
|| comm == NREAD_APPEND || comm == NREAD_PREPEND))
{
/* replace only replaces an existing value; don't store */
} else if (comm == NREAD_CAS) {
/* validate cas operation */
if(old_it == NULL) {
// LRU expired
stored = NOT_FOUND;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.cas_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) {
// cas validates
// it and old_it may belong to different classes.
// I'm updating the stats for the one that's getting pushed out
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
STORAGE_delete(c->thread->storage, old_it);
item_replace(old_it, it, hv);
stored = STORED;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(settings.verbose > 1) {
fprintf(stderr, "CAS: failure: expected %llu, got %llu\n",
(unsigned long long)ITEM_get_cas(old_it),
(unsigned long long)ITEM_get_cas(it));
}
stored = EXISTS;
}
} else {
int failed_alloc = 0;
/*
* Append - combine new and old record into single one. Here it's
* atomic and thread-safe.
*/
if (comm == NREAD_APPEND || comm == NREAD_PREPEND) {
/*
* Validate CAS
*/
if (ITEM_get_cas(it) != 0) {
// CAS much be equal
if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) {
stored = EXISTS;
}
}
#ifdef EXTSTORE
if ((old_it->it_flags & ITEM_HDR) != 0) {
/* block append/prepend from working with extstore-d items.
* also don't replace the header with the append chunk
* accidentally, so mark as a failed_alloc.
*/
failed_alloc = 1;
} else
#endif
if (stored == NOT_STORED) {
/* we have it and old_it here - alloc memory to hold both */
/* flags was already lost - so recover them from ITEM_suffix(it) */
if (settings.inline_ascii_response) {
flags = (uint32_t) strtoul(ITEM_suffix(old_it), (char **) NULL, 10);
} else if (old_it->nsuffix > 0) {
flags = *((uint32_t *)ITEM_suffix(old_it));
} else {
flags = 0;
}
new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */);
/* copy data from it and old_it to new_it */
if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) {
failed_alloc = 1;
stored = NOT_STORED;
// failed data copy, free up.
if (new_it != NULL)
item_remove(new_it);
} else {
it = new_it;
}
}
}
if (stored == NOT_STORED && failed_alloc == 0) {
if (old_it != NULL) {
STORAGE_delete(c->thread->storage, old_it);
item_replace(old_it, it, hv);
} else {
do_item_link(it, hv);
}
c->cas = ITEM_get_cas(it);
stored = STORED;
}
}
if (old_it != NULL)
do_item_remove(old_it); /* release our reference */
if (new_it != NULL)
do_item_remove(new_it);
if (stored == STORED) {
c->cas = ITEM_get_cas(it);
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL,
stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it));
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 8
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
size_t len = strlen(command);
unsigned int i = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
s = e = command;
for (i = 0; i < len; i++) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
if (ntokens == max_tokens - 1) {
e++;
s = e; /* so we don't add an extra token */
break;
}
}
s = e + 1;
}
e++;
}
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
/* set up a connection to write a buffer then free it, used for stats */
static void write_and_free(conn *c, char *buf, int bytes) {
if (buf) {
c->write_and_free = buf;
c->wcurr = buf;
c->wbytes = bytes;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
} else {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
}
}
static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens)
{
int noreply_index = ntokens - 2;
/*
NOTE: this function is not the first place where we are going to
send the reply. We could send it instead from process_command()
if the request line has wrong number of tokens. However parsing
malformed line for "noreply" option is not reliable anyway, so
it can't be helped.
*/
if (tokens[noreply_index].value
&& strcmp(tokens[noreply_index].value, "noreply") == 0) {
c->noreply = true;
}
return c->noreply;
}
void append_stat(const char *name, ADD_STAT add_stats, conn *c,
const char *fmt, ...) {
char val_str[STAT_VAL_LEN];
int vlen;
va_list ap;
assert(name);
assert(add_stats);
assert(c);
assert(fmt);
va_start(ap, fmt);
vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap);
va_end(ap);
add_stats(name, strlen(name), val_str, vlen, c);
}
inline static void process_stats_detail(conn *c, const char *command) {
assert(c != NULL);
if (strcmp(command, "on") == 0) {
settings.detail_enabled = 1;
out_string(c, "OK");
}
else if (strcmp(command, "off") == 0) {
settings.detail_enabled = 0;
out_string(c, "OK");
}
else if (strcmp(command, "dump") == 0) {
int len;
char *stats = stats_prefix_dump(&len);
write_and_free(c, stats, len);
}
else {
out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump");
}
}
/* return server specific stats only */
static void server_stats(ADD_STAT add_stats, conn *c) {
pid_t pid = getpid();
rel_time_t now = current_time;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(&thread_stats);
struct slab_stats slab_stats;
slab_stats_aggregate(&thread_stats, &slab_stats);
#ifdef EXTSTORE
struct extstore_stats st;
#endif
#ifndef WIN32
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
#endif /* !WIN32 */
STATS_LOCK();
APPEND_STAT("pid", "%lu", (long)pid);
APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL);
APPEND_STAT("time", "%ld", now + (long)process_started);
APPEND_STAT("version", "%s", VERSION);
APPEND_STAT("libevent", "%s", event_get_version());
APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *)));
#ifndef WIN32
append_stat("rusage_user", add_stats, c, "%ld.%06ld",
(long)usage.ru_utime.tv_sec,
(long)usage.ru_utime.tv_usec);
append_stat("rusage_system", add_stats, c, "%ld.%06ld",
(long)usage.ru_stime.tv_sec,
(long)usage.ru_stime.tv_usec);
#endif /* !WIN32 */
APPEND_STAT("max_connections", "%d", settings.maxconns);
APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1);
APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns);
if (settings.maxconns_fast) {
APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns);
}
APPEND_STAT("connection_structures", "%u", stats_state.conn_structs);
APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds);
APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds);
APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds);
APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds);
APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds);
APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits);
APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses);
APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired);
APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed);
#ifdef EXTSTORE
if (c->thread->storage) {
APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore);
APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore);
APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore);
APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore);
}
#endif
APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses);
APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits);
APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses);
APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits);
APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses);
APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits);
APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses);
APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits);
APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval);
APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits);
APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses);
APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds);
APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors);
if (settings.idle_timeout) {
APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks);
}
APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read);
APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written);
APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns);
APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num);
APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us);
APPEND_STAT("threads", "%d", settings.num_threads);
APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields);
APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level);
APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes);
APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding);
if (settings.slab_reassign) {
APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues);
APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues);
APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem);
APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim);
APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items);
APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes);
APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running);
APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved);
}
if (settings.lru_crawler) {
APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running);
APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts);
}
if (settings.lru_maintainer_thread) {
APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles);
}
APPEND_STAT("malloc_fails", "%llu",
(unsigned long long)stats.malloc_fails);
APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped);
APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written);
APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped);
APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent);
STATS_UNLOCK();
#ifdef EXTSTORE
if (c->thread->storage) {
STATS_LOCK();
APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost);
APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues);
APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped);
STATS_UNLOCK();
extstore_get_stats(c->thread->storage, &st);
APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs);
APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions);
APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims);
APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free);
APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used);
APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted);
APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read);
APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written);
APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used);
APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted);
APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written);
APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read);
APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used);
APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented);
APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size));
}
#endif
}
static void process_stat_settings(ADD_STAT add_stats, void *c) {
assert(add_stats);
APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("maxconns", "%d", settings.maxconns);
APPEND_STAT("tcpport", "%d", settings.port);
APPEND_STAT("udpport", "%d", settings.udpport);
APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL");
APPEND_STAT("verbosity", "%d", settings.verbose);
APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live);
APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off");
APPEND_STAT("domain_socket", "%s",
settings.socketpath ? settings.socketpath : "NULL");
APPEND_STAT("umask", "%o", settings.access);
APPEND_STAT("growth_factor", "%.2f", settings.factor);
APPEND_STAT("chunk_size", "%d", settings.chunk_size);
APPEND_STAT("num_threads", "%d", settings.num_threads);
APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp);
APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter);
APPEND_STAT("detail_enabled", "%s",
settings.detail_enabled ? "yes" : "no");
APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event);
APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no");
APPEND_STAT("tcp_backlog", "%d", settings.backlog);
APPEND_STAT("binding_protocol", "%s",
prot_text(settings.binding_protocol));
APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no");
APPEND_STAT("item_size_max", "%d", settings.item_size_max);
APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no");
APPEND_STAT("hashpower_init", "%d", settings.hashpower_init);
APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no");
APPEND_STAT("slab_automove", "%d", settings.slab_automove);
APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio);
APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window);
APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max);
APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no");
APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep);
APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl);
APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time);
APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no");
APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no");
APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm);
APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no");
APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no");
APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct);
APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct);
APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor);
APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor);
APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no");
APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl);
APPEND_STAT("idle_timeout", "%d", settings.idle_timeout);
APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size);
APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size);
APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no");
APPEND_STAT("inline_ascii_response", "%s", settings.inline_ascii_response ? "yes" : "no");
#ifdef EXTSTORE
APPEND_STAT("ext_item_size", "%u", settings.ext_item_size);
APPEND_STAT("ext_item_age", "%u", settings.ext_item_age);
APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl);
APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate);
APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size);
APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under);
APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under);
APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag);
APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio);
APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no");
#endif
}
static void conn_to_str(const conn *c, char *buf) {
char addr_text[MAXPATHLEN];
if (!c) {
strcpy(buf, "<null>");
} else if (c->state == conn_closed) {
strcpy(buf, "<closed>");
} else {
const char *protoname = "?";
struct sockaddr_in6 local_addr;
struct sockaddr *addr = (void *)&c->request_addr;
int af;
unsigned short port = 0;
/* For listen ports and idle UDP ports, show listen address */
if (c->state == conn_listening ||
(IS_UDP(c->transport) &&
c->state == conn_read)) {
socklen_t local_addr_len = sizeof(local_addr);
if (getsockname(c->sfd,
(struct sockaddr *)&local_addr,
&local_addr_len) == 0) {
addr = (struct sockaddr *)&local_addr;
}
}
af = addr->sa_family;
addr_text[0] = '\0';
switch (af) {
case AF_INET:
(void) inet_ntop(af,
&((struct sockaddr_in *)addr)->sin_addr,
addr_text,
sizeof(addr_text) - 1);
port = ntohs(((struct sockaddr_in *)addr)->sin_port);
protoname = IS_UDP(c->transport) ? "udp" : "tcp";
break;
case AF_INET6:
addr_text[0] = '[';
addr_text[1] = '\0';
if (inet_ntop(af,
&((struct sockaddr_in6 *)addr)->sin6_addr,
addr_text + 1,
sizeof(addr_text) - 2)) {
strcat(addr_text, "]");
}
port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
protoname = IS_UDP(c->transport) ? "udp6" : "tcp6";
break;
case AF_UNIX:
strncpy(addr_text,
((struct sockaddr_un *)addr)->sun_path,
sizeof(addr_text) - 1);
addr_text[sizeof(addr_text)-1] = '\0';
protoname = "unix";
break;
}
if (strlen(addr_text) < 2) {
/* Most likely this is a connected UNIX-domain client which
* has no peer socket address, but there's no portable way
* to tell for sure.
*/
sprintf(addr_text, "<AF %d>", af);
}
if (port) {
sprintf(buf, "%s:%s:%u", protoname, addr_text, port);
} else {
sprintf(buf, "%s:%s", protoname, addr_text);
}
}
}
static void process_stats_conns(ADD_STAT add_stats, void *c) {
int i;
char key_str[STAT_KEY_LEN];
char val_str[STAT_VAL_LEN];
char conn_name[MAXPATHLEN + sizeof("unix:") + sizeof("65535")];
int klen = 0, vlen = 0;
assert(add_stats);
for (i = 0; i < max_fds; i++) {
if (conns[i]) {
/* This is safe to do unlocked because conns are never freed; the
* worst that'll happen will be a minor inconsistency in the
* output -- not worth the complexity of the locking that'd be
* required to prevent it.
*/
if (conns[i]->state != conn_closed) {
conn_to_str(conns[i], conn_name);
APPEND_NUM_STAT(i, "addr", "%s", conn_name);
APPEND_NUM_STAT(i, "state", "%s",
state_text(conns[i]->state));
APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d",
current_time - conns[i]->last_cmd_time);
}
}
}
}
#ifdef EXTSTORE
static void process_extstore_stats(ADD_STAT add_stats, conn *c) {
int i;
char key_str[STAT_KEY_LEN];
char val_str[STAT_VAL_LEN];
int klen = 0, vlen = 0;
struct extstore_stats st;
assert(add_stats);
void *storage = c->thread->storage;
extstore_get_stats(storage, &st);
st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data));
extstore_get_page_data(storage, &st);
for (i = 0; i < st.page_count; i++) {
APPEND_NUM_STAT(i, "version", "%llu",
(unsigned long long) st.page_data[i].version);
APPEND_NUM_STAT(i, "bytes", "%llu",
(unsigned long long) st.page_data[i].bytes_used);
APPEND_NUM_STAT(i, "bucket", "%u",
st.page_data[i].bucket);
}
}
#endif
static void process_stat(conn *c, token_t *tokens, const size_t ntokens) {
const char *subcommand = tokens[SUBCOMMAND_TOKEN].value;
assert(c != NULL);
if (ntokens < 2) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (ntokens == 2) {
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strcmp(subcommand, "reset") == 0) {
stats_reset();
out_string(c, "RESET");
return ;
} else if (strcmp(subcommand, "detail") == 0) {
/* NOTE: how to tackle detail with binary? */
if (ntokens < 4)
process_stats_detail(c, ""); /* outputs the error message */
else
process_stats_detail(c, tokens[2].value);
/* Output already generated */
return ;
} else if (strcmp(subcommand, "settings") == 0) {
process_stat_settings(&append_stats, c);
} else if (strcmp(subcommand, "cachedump") == 0) {
char *buf;
unsigned int bytes, id, limit = 0;
if (!settings.dump_enabled) {
out_string(c, "CLIENT_ERROR stats cachedump not allowed");
return;
}
if (ntokens < 5) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (!safe_strtoul(tokens[2].value, &id) ||
!safe_strtoul(tokens[3].value, &limit)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (id >= MAX_NUMBER_OF_SLAB_CLASSES) {
out_string(c, "CLIENT_ERROR Illegal slab id");
return;
}
buf = item_cachedump(id, limit, &bytes);
write_and_free(c, buf, bytes);
return ;
} else if (strcmp(subcommand, "conns") == 0) {
process_stats_conns(&append_stats, c);
#ifdef EXTSTORE
} else if (strcmp(subcommand, "extstore") == 0) {
process_extstore_stats(&append_stats, c);
#endif
} else {
/* getting here means that the subcommand is either engine specific or
is invalid. query the engine and see. */
if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
out_string(c, "ERROR");
}
return ;
}
/* append terminator and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
/* nsuffix == 0 means use no storage for client flags */
static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) {
char *p = suffix;
if (!settings.inline_ascii_response) {
*p = ' ';
p++;
if (it->nsuffix == 0) {
*p = '0';
p++;
} else {
p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p);
}
*p = ' ';
p = itoa_u32(nbytes-2, p+1);
} else {
p = suffix;
}
if (return_cas) {
*p = ' ';
p = itoa_u64(ITEM_get_cas(it), p+1);
}
*p = '\r';
*(p+1) = '\n';
*(p+2) = '\0';
return (p - suffix) + 2;
}
#define IT_REFCOUNT_LIMIT 60000
static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) {
item *it;
if (should_touch) {
it = item_touch(key, nkey, exptime, c);
} else {
it = item_get(key, nkey, c, DO_UPDATE);
}
if (it && it->refcount > IT_REFCOUNT_LIMIT) {
item_remove(it);
it = NULL;
}
return it;
}
static inline int _ascii_get_expand_ilist(conn *c, int i) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
}
return 0;
}
static inline char *_ascii_get_suffix_buf(conn *c, int i) {
char *suffix;
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return NULL;
}
}
suffix = do_cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix");
return NULL;
}
*(c->suffixlist + i) = suffix;
return suffix;
}
#ifdef EXTSTORE
// FIXME: This runs in the IO thread. to get better IO performance this should
// simply mark the io wrapper with the return value and decrement wrapleft, if
// zero redispatching. Still a bit of work being done in the side thread but
// minimized at least.
static void _get_extstore_cb(void *e, obj_io *io, int ret) {
// FIXME: assumes success
io_wrap *wrap = (io_wrap *)io->data;
conn *c = wrap->c;
assert(wrap->active == true);
item *read_it = (item *)io->buf;
bool miss = false;
// TODO: How to do counters for hit/misses?
if (ret < 1) {
miss = true;
} else {
uint32_t crc2;
uint32_t crc = (uint32_t) read_it->exptime;
int x;
// item is chunked, crc the iov's
if (io->iov != NULL) {
// first iov is the header, which we don't use beyond crc
crc2 = crc32c(0, (char *)io->iov[0].iov_base+32, io->iov[0].iov_len-32);
// make sure it's not sent. hack :(
io->iov[0].iov_len = 0;
for (x = 1; x < io->iovcnt; x++) {
crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len);
}
} else {
crc2 = crc32c(0, (char *)read_it+32, io->len-32);
}
if (crc != crc2) {
miss = true;
wrap->badcrc = true;
}
}
if (miss) {
int i;
struct iovec *v;
// TODO: This should be movable to the worker thread.
if (c->protocol == binary_prot) {
protocol_binary_response_header *header =
(protocol_binary_response_header *)c->wbuf;
// this zeroes out the iovecs since binprot never stacks them.
if (header->response.keylen) {
write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey);
} else {
write_bin_miss_response(c, 0, 0);
}
} else {
for (i = 0; i < wrap->iovec_count; i++) {
v = &c->iov[wrap->iovec_start + i];
v->iov_len = 0;
v->iov_base = NULL;
}
}
wrap->miss = true;
} else {
assert(read_it->slabs_clsid != 0);
// kill \r\n for binprot
if (io->iov == NULL) {
c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it);
if (c->protocol == binary_prot)
c->iov[wrap->iovec_data].iov_len -= 2;
} else {
// FIXME: Might need to go back and ensure chunked binprots don't
// ever span two chunks for the final \r\n
if (c->protocol == binary_prot) {
if (io->iov[io->iovcnt-1].iov_len >= 2) {
io->iov[io->iovcnt-1].iov_len -= 2;
} else {
io->iov[io->iovcnt-1].iov_len = 0;
io->iov[io->iovcnt-2].iov_len -= 1;
}
}
}
// iov_len is already set
// TODO: Should do that here instead and cuddle in the wrap object
}
c->io_wrapleft--;
wrap->active = false;
//assert(c->io_wrapleft >= 0);
// All IO's have returned, lets re-attach this connection to our original
// thread.
if (c->io_wrapleft == 0) {
assert(c->io_queued == true);
c->io_queued = false;
redispatch_conn(c);
}
}
// FIXME: This completely breaks UDP support.
static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) {
item_hdr *hdr = (item_hdr *)ITEM_data(it);
size_t ntotal = ITEM_ntotal(it);
unsigned int clsid = slabs_clsid(ntotal);
item *new_it;
bool chunked = false;
if (ntotal > settings.slab_chunk_size_max) {
// Pull a chunked item header.
// FIXME: make a func. used in several places.
uint32_t flags;
if (settings.inline_ascii_response) {
flags = (uint32_t) strtoul(ITEM_suffix(it), (char **) NULL, 10);
} else if (it->nsuffix > 0) {
flags = *((uint32_t *)ITEM_suffix(it));
} else {
flags = 0;
}
new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes);
assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED));
chunked = true;
} else {
new_it = do_item_alloc_pull(ntotal, clsid);
}
if (new_it == NULL)
return -1;
assert(!c->io_queued); // FIXME: debugging.
// so we can free the chunk on a miss
new_it->slabs_clsid = clsid;
io_wrap *io = do_cache_alloc(c->thread->io_cache);
io->active = true;
io->miss = false;
io->badcrc = false;
// io_wrap owns the reference for this object now.
io->hdr_it = it;
// FIXME: error handling.
// The offsets we'll wipe on a miss.
io->iovec_start = iovst;
io->iovec_count = iovcnt;
// This is probably super dangerous. keep it at 0 and fill into wrap
// object?
if (chunked) {
unsigned int ciovcnt = 1;
size_t remain = new_it->nbytes;
item_chunk *chunk = (item_chunk *) ITEM_data(new_it);
io->io.iov = &c->iov[c->iovused];
// fill the header so we can get the full data + crc back.
add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes);
while (remain > 0) {
chunk = do_item_alloc_chunk(chunk, remain);
// TODO: counter bump
if (chunk == NULL) {
item_remove(new_it);
do_cache_free(c->thread->io_cache, io);
return -1;
}
add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size);
chunk->used = (remain < chunk->size) ? remain : chunk->size;
remain -= chunk->size;
ciovcnt++;
}
io->io.iovcnt = ciovcnt;
// header object was already accounted for, remove one from total
io->iovec_count += ciovcnt-1;
} else {
io->io.iov = NULL;
io->iovec_data = c->iovused;
add_iov(c, "", it->nbytes);
}
io->io.buf = (void *)new_it;
// The offset we'll fill in on a hit.
io->c = c;
// We need to stack the sub-struct IO's together as well.
if (c->io_wraplist) {
io->io.next = &c->io_wraplist->io;
} else {
io->io.next = NULL;
}
// IO queue for this connection.
io->next = c->io_wraplist;
c->io_wraplist = io;
assert(c->io_wrapleft >= 0);
c->io_wrapleft++;
// reference ourselves for the callback.
io->io.data = (void *)io;
// Now, fill in io->io based on what was in our header.
io->io.page_version = hdr->page_version;
io->io.page_id = hdr->page_id;
io->io.offset = hdr->offset;
io->io.len = ntotal;
io->io.mode = OBJ_IO_READ;
io->io.cb = _get_extstore_cb;
//fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data);
// FIXME: This stat needs to move to reflect # of flash hits vs misses
// for now it's a good gauge on how often we request out to flash at
// least.
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
return 0;
}
#endif
// FIXME: the 'breaks' around memory malloc's should break all the way down,
// fill ileft/suffixleft, then run conn_releaseitems()
/* ntokens is overwritten here... shrug.. */
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) {
char *key;
size_t nkey;
int i = 0;
int si = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
int32_t exptime_int = 0;
rel_time_t exptime = 0;
assert(c != NULL);
if (should_touch) {
// For get and touch commands, use first token as exptime
if (!safe_strtol(tokens[1].value, &exptime_int)) {
out_string(c, "CLIENT_ERROR invalid exptime argument");
return;
}
key_token++;
exptime = realtime(exptime_int);
}
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if (nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
while (i-- > 0) {
item_remove(*(c->ilist + i));
if (return_cas || !settings.inline_ascii_response) {
do_cache_free(c->thread->suffix_cache, *(c->suffixlist + i));
}
}
return;
}
it = limited_get(key, nkey, c, exptime, should_touch);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (_ascii_get_expand_ilist(c, i) != 0) {
item_remove(it);
break; // FIXME: Should bail down to error.
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas || !settings.inline_ascii_response)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
int nbytes;
suffix = _ascii_get_suffix_buf(c, si);
if (suffix == NULL) {
item_remove(it);
break;
}
si++;
nbytes = it->nbytes;
int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes);
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
(settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) ||
add_iov(c, suffix, suffix_len) != 0)
{
item_remove(it);
break;
}
#ifdef EXTSTORE
if (it->it_flags & ITEM_HDR) {
if (_get_extstore(c, it, c->iovused-3, 4) != 0) {
item_remove(it);
break;
}
} else if ((it->it_flags & ITEM_CHUNKED) == 0) {
#else
if ((it->it_flags & ITEM_CHUNKED) == 0) {
#endif
add_iov(c, ITEM_data(it), it->nbytes);
} else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0)
{
item_remove(it);
break;
}
if ((it->it_flags & ITEM_CHUNKED) == 0)
{
if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
} else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 ||
add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
break;
}
}
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d sending key ", c->sfd);
for (ii = 0; ii < it->nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
} else {
c->thread->stats.lru_hits[it->slabs_clsid]++;
c->thread->stats.get_cmds++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
#ifdef EXTSTORE
/* If ITEM_HDR, an io_wrap owns the reference. */
if ((it->it_flags & ITEM_HDR) == 0) {
*(c->ilist + i) = it;
i++;
}
#else
*(c->ilist + i) = it;
i++;
#endif
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
} else {
c->thread->stats.get_misses++;
c->thread->stats.get_cmds++;
}
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
pthread_mutex_unlock(&c->thread->stats.mutex);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas || !settings.inline_ascii_response) {
c->suffixcurr = c->suffixlist;
c->suffixleft = si;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_of_memory(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
}
static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
/* Negative exptimes can underflow and end up immortal. realtime() will
immediately expire values that are greater than REALTIME_MAXDELTA, but less
than process_started, so lets aim for that. */
if (exptime < 0)
exptime = REALTIME_MAXDELTA + 1;
// does cas value exist?
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
if (vlen < 0 || vlen > (INT_MAX - 2)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
vlen += 2;
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, flags, vlen)) {
out_string(c, "SERVER_ERROR object too large for cache");
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR out of memory storing object");
status = NO_MEMORY;
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, comm, key, nkey, 0, 0);
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
int32_t exptime_int = 0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtol(tokens[2].value, &exptime_int)) {
out_string(c, "CLIENT_ERROR invalid exptime argument");
return;
}
it = item_touch(key, nkey, realtime(exptime_int), c);
if (it) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "TOUCHED");
item_remove(it);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) {
char temp[INCR_MAX_STORAGE_LEN];
uint64_t delta;
char *key;
size_t nkey;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtoull(tokens[2].value, &delta)) {
out_string(c, "CLIENT_ERROR invalid numeric delta argument");
return;
}
switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) {
case OK:
out_string(c, temp);
break;
case NON_NUMERIC:
out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value");
break;
case EOM:
out_of_memory(c, "SERVER_ERROR out of memory");
break;
case DELTA_ITEM_NOT_FOUND:
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
break;
case DELTA_ITEM_CAS_MISMATCH:
break; /* Should never get here */
}
}
/*
* adds a delta value to a numeric item.
*
* c connection requesting the operation
* it item to adjust
* incr true to increment value, false to decrement
* delta amount to adjust value by
* buf buffer for response string
*
* returns a response string to send back to the client.
*/
enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey,
const bool incr, const int64_t delta,
char *buf, uint64_t *cas,
const uint32_t hv) {
char *ptr;
uint64_t value;
int res;
item *it;
it = do_item_get(key, nkey, hv, c, DONT_UPDATE);
if (!it) {
return DELTA_ITEM_NOT_FOUND;
}
/* Can't delta zero byte values. 2-byte are the "\r\n" */
/* Also can't delta for chunked items. Too large to be a number */
#ifdef EXTSTORE
if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) {
#else
if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) {
#endif
return NON_NUMERIC;
}
if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) {
do_item_remove(it);
return DELTA_ITEM_CAS_MISMATCH;
}
ptr = ITEM_data(it);
if (!safe_strtoull(ptr, &value)) {
do_item_remove(it);
return NON_NUMERIC;
}
if (incr) {
value += delta;
MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value);
} else {
if(delta > value) {
value = 0;
} else {
value -= delta;
}
MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value);
}
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++;
} else {
c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value);
res = strlen(buf);
/* refcount == 2 means we are the only ones holding the item, and it is
* linked. We hold the item's lock in this function, so refcount cannot
* increase. */
if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */
/* When changing the value without replacing the item, we
need to update the CAS on the existing item. */
/* We also need to fiddle it in the sizes tracker in case the tracking
* was enabled at runtime, since it relies on the CAS value to know
* whether to remove an item or not. */
item_stats_sizes_remove(it);
ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
item_stats_sizes_add(it);
memcpy(ITEM_data(it), buf, res);
memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2);
do_item_update(it);
} else if (it->refcount > 1) {
item *new_it;
uint32_t flags;
if (settings.inline_ascii_response) {
flags = (uint32_t) strtoul(ITEM_suffix(it), (char **) NULL, 10);
} else if (it->nsuffix > 0) {
flags = *((uint32_t *)ITEM_suffix(it));
} else {
flags = 0;
}
new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2);
if (new_it == 0) {
do_item_remove(it);
return EOM;
}
memcpy(ITEM_data(new_it), buf, res);
memcpy(ITEM_data(new_it) + res, "\r\n", 2);
item_replace(it, new_it, hv);
// Overwrite the older item's CAS with our new CAS since we're
// returning the CAS of the old item below.
ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0);
do_item_remove(new_it); /* release our reference */
} else {
/* Should never get here. This means we somehow fetched an unlinked
* item. TODO: Add a counter? */
if (settings.verbose) {
fprintf(stderr, "Tried to do incr/decr on invalid item\n");
}
if (it->refcount == 1)
do_item_remove(it);
return DELTA_ITEM_NOT_FOUND;
}
if (cas) {
*cas = ITEM_get_cas(it); /* swap the incoming CAS value */
}
do_item_remove(it); /* release our reference */
return OK;
}
static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
item *it;
assert(c != NULL);
if (ntokens > 3) {
bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0;
bool sets_noreply = set_noreply_maybe(c, tokens, ntokens);
bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply))
|| (ntokens == 5 && hold_is_zero && sets_noreply);
if (!valid) {
out_string(c, "CLIENT_ERROR bad command line format. "
"Usage: delete <key> [noreply]");
return;
}
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it); /* release our reference */
out_string(c, "DELETED");
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
level = strtoul(tokens[1].value, NULL, 10);
settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level;
out_string(c, "OK");
return;
}
#ifdef MEMCACHED_DEBUG
static void process_misbehave_command(conn *c) {
int allowed = 0;
// try opening new TCP socket
int i = socket(AF_INET, SOCK_STREAM, 0);
if (i != -1) {
allowed++;
close(i);
}
// try executing new commands
i = system("sleep 0");
if (i != -1) {
allowed++;
}
if (allowed) {
out_string(c, "ERROR");
} else {
out_string(c, "OK");
}
}
#endif
static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
double ratio;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (strcmp(tokens[2].value, "ratio") == 0) {
if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) {
out_string(c, "ERROR");
return;
}
settings.slab_automove_ratio = ratio;
} else {
level = strtoul(tokens[2].value, NULL, 10);
if (level == 0) {
settings.slab_automove = 0;
} else if (level == 1 || level == 2) {
settings.slab_automove = level;
} else {
out_string(c, "ERROR");
return;
}
}
out_string(c, "OK");
return;
}
/* TODO: decide on syntax for sampling? */
static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) {
uint16_t f = 0;
int x;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (ntokens > 2) {
for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) {
if ((strcmp(tokens[x].value, "rawcmds") == 0)) {
f |= LOG_RAWCMDS;
} else if ((strcmp(tokens[x].value, "evictions") == 0)) {
f |= LOG_EVICTIONS;
} else if ((strcmp(tokens[x].value, "fetchers") == 0)) {
f |= LOG_FETCHERS;
} else if ((strcmp(tokens[x].value, "mutations") == 0)) {
f |= LOG_MUTATIONS;
} else if ((strcmp(tokens[x].value, "sysevents") == 0)) {
f |= LOG_SYSEVENTS;
} else {
out_string(c, "ERROR");
return;
}
}
} else {
f |= LOG_FETCHERS;
}
switch(logger_add_watcher(c, c->sfd, f)) {
case LOGGER_ADD_WATCHER_TOO_MANY:
out_string(c, "WATCHER_TOO_MANY log watcher limit reached");
break;
case LOGGER_ADD_WATCHER_FAILED:
out_string(c, "WATCHER_FAILED failed to add log watcher");
break;
case LOGGER_ADD_WATCHER_OK:
conn_set_state(c, conn_watch);
event_del(&c->event);
break;
}
}
static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t memlimit;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (!safe_strtoul(tokens[1].value, &memlimit)) {
out_string(c, "ERROR");
} else {
if (memlimit < 8) {
out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m");
} else {
if (memlimit > 1000000000) {
out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes");
} else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) {
if (settings.verbose > 0) {
fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit);
}
out_string(c, "OK");
} else {
out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust");
}
}
}
}
static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t pct_hot;
uint32_t pct_warm;
double hot_factor;
int32_t ttl;
double factor;
set_noreply_maybe(c, tokens, ntokens);
if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) {
if (!safe_strtoul(tokens[2].value, &pct_hot) ||
!safe_strtoul(tokens[3].value, &pct_warm) ||
!safe_strtod(tokens[4].value, &hot_factor) ||
!safe_strtod(tokens[5].value, &factor)) {
out_string(c, "ERROR");
} else {
if (pct_hot + pct_warm > 80) {
out_string(c, "ERROR hot and warm pcts must not exceed 80");
} else if (factor <= 0 || hot_factor <= 0) {
out_string(c, "ERROR hot/warm age factors must be greater than 0");
} else {
settings.hot_lru_pct = pct_hot;
settings.warm_lru_pct = pct_warm;
settings.hot_max_factor = hot_factor;
settings.warm_max_factor = factor;
out_string(c, "OK");
}
}
} else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 3 &&
settings.lru_maintainer_thread) {
if (strcmp(tokens[2].value, "flat") == 0) {
settings.lru_segmented = false;
out_string(c, "OK");
} else if (strcmp(tokens[2].value, "segmented") == 0) {
settings.lru_segmented = true;
out_string(c, "OK");
} else {
out_string(c, "ERROR");
}
} else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 3 &&
settings.lru_maintainer_thread) {
if (!safe_strtol(tokens[2].value, &ttl)) {
out_string(c, "ERROR");
} else {
if (ttl < 0) {
settings.temp_lru = false;
} else {
settings.temp_lru = true;
settings.temporary_ttl = ttl;
}
out_string(c, "OK");
}
} else {
out_string(c, "ERROR");
}
}
#ifdef EXTSTORE
static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) {
set_noreply_maybe(c, tokens, ntokens);
bool ok = true;
if (ntokens < 4) {
ok = false;
} else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) {
/* per-slab-class free chunk setting. */
unsigned int clsid = 0;
unsigned int limit = 0;
if (!safe_strtoul(tokens[2].value, &clsid) ||
!safe_strtoul(tokens[3].value, &limit)) {
ok = false;
} else {
if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) {
settings.ext_free_memchunks[clsid] = limit;
} else {
ok = false;
}
}
} else if (strcmp(tokens[1].value, "item_size") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_item_size))
ok = false;
} else if (strcmp(tokens[1].value, "item_age") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_item_age))
ok = false;
} else if (strcmp(tokens[1].value, "low_ttl") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl))
ok = false;
} else if (strcmp(tokens[1].value, "recache_rate") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate))
ok = false;
} else if (strcmp(tokens[1].value, "compact_under") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under))
ok = false;
} else if (strcmp(tokens[1].value, "drop_under") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under))
ok = false;
} else if (strcmp(tokens[1].value, "max_frag") == 0) {
if (!safe_strtod(tokens[2].value, &settings.ext_max_frag))
ok = false;
} else if (strcmp(tokens[1].value, "drop_unread") == 0) {
unsigned int v;
if (!safe_strtoul(tokens[2].value, &v)) {
ok = false;
} else {
settings.ext_drop_unread = v == 0 ? false : true;
}
} else {
ok = false;
}
if (!ok) {
out_string(c, "ERROR");
} else {
out_string(c, "OK");
}
}
#endif
static void process_command(conn *c, char *command) {
token_t tokens[MAX_TOKENS];
size_t ntokens;
int comm;
assert(c != NULL);
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
if (settings.verbose > 1)
fprintf(stderr, "<%d %s\n", c->sfd, command);
/*
* for commands set/add/replace, we build an item and read the data
* directly into it, then continue in nread_complete().
*/
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_of_memory(c, "SERVER_ERROR out of memory preparing response");
return;
}
ntokens = tokenize_command(command, tokens, MAX_TOKENS);
if (ntokens >= 3 &&
((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) ||
(strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) {
process_get_command(c, tokens, ntokens, false, false);
} else if ((ntokens == 6 || ntokens == 7) &&
((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) {
process_update_command(c, tokens, ntokens, comm, false);
} else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) {
process_update_command(c, tokens, ntokens, comm, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 1);
} else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) {
process_get_command(c, tokens, ntokens, true, false);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 0);
} else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) {
process_delete_command(c, tokens, ntokens);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) {
process_touch_command(c, tokens, ntokens);
} else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) {
process_get_command(c, tokens, ntokens, false, true);
} else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) {
process_get_command(c, tokens, ntokens, true, true);
} else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) {
process_stat(c, tokens, ntokens);
} else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) {
time_t exptime = 0;
rel_time_t new_oldest = 0;
set_noreply_maybe(c, tokens, ntokens);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (!settings.flush_enabled) {
// flush_all is not allowed but we log it on stats
out_string(c, "CLIENT_ERROR flush_all not allowed");
return;
}
if (ntokens != (c->noreply ? 3 : 2)) {
exptime = strtol(tokens[1].value, NULL, 10);
if(errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
/*
If exptime is zero realtime() would return zero too, and
realtime(exptime) - 1 would overflow to the max unsigned
value. So we process exptime == 0 the same way we do when
no delay is given at all.
*/
if (exptime > 0) {
new_oldest = realtime(exptime);
} else { /* exptime == 0 */
new_oldest = current_time;
}
if (settings.use_cas) {
settings.oldest_live = new_oldest - 1;
if (settings.oldest_live <= current_time)
settings.oldest_cas = get_cas_id();
} else {
settings.oldest_live = new_oldest;
}
out_string(c, "OK");
return;
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) {
out_string(c, "VERSION " VERSION);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) {
conn_set_state(c, conn_closing);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) {
if (settings.shutdown_command) {
conn_set_state(c, conn_closing);
raise(SIGINT);
} else {
out_string(c, "ERROR: shutdown not enabled");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) {
if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) {
int src, dst, rv;
if (settings.slab_reassign == false) {
out_string(c, "CLIENT_ERROR slab reassignment disabled");
return;
}
src = strtol(tokens[2].value, NULL, 10);
dst = strtol(tokens[3].value, NULL, 10);
if (errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
rv = slabs_reassign(src, dst);
switch (rv) {
case REASSIGN_OK:
out_string(c, "OK");
break;
case REASSIGN_RUNNING:
out_string(c, "BUSY currently processing reassign request");
break;
case REASSIGN_BADCLASS:
out_string(c, "BADCLASS invalid src or dst class id");
break;
case REASSIGN_NOSPARE:
out_string(c, "NOSPARE source class has no spare pages");
break;
case REASSIGN_SRC_DST_SAME:
out_string(c, "SAME src and dst class are identical");
break;
}
return;
} else if (ntokens >= 4 &&
(strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) {
process_slabs_automove_command(c, tokens, ntokens);
} else {
out_string(c, "ERROR");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) {
if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) {
int rv;
if (settings.lru_crawler == false) {
out_string(c, "CLIENT_ERROR lru crawler disabled");
return;
}
rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0,
settings.lru_crawler_tocrawl);
switch(rv) {
case CRAWLER_OK:
out_string(c, "OK");
break;
case CRAWLER_RUNNING:
out_string(c, "BUSY currently processing crawler request");
break;
case CRAWLER_BADCLASS:
out_string(c, "BADCLASS invalid class id");
break;
case CRAWLER_NOTSTARTED:
out_string(c, "NOTSTARTED no items to crawl");
break;
case CRAWLER_ERROR:
out_string(c, "ERROR an unknown error happened");
break;
}
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) {
if (settings.lru_crawler == false) {
out_string(c, "CLIENT_ERROR lru crawler disabled");
return;
}
if (!settings.dump_enabled) {
out_string(c, "ERROR metadump not allowed");
return;
}
int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP,
c, c->sfd, LRU_CRAWLER_CAP_REMAINING);
switch(rv) {
case CRAWLER_OK:
out_string(c, "OK");
// TODO: Don't reuse conn_watch here.
conn_set_state(c, conn_watch);
event_del(&c->event);
break;
case CRAWLER_RUNNING:
out_string(c, "BUSY currently processing crawler request");
break;
case CRAWLER_BADCLASS:
out_string(c, "BADCLASS invalid class id");
break;
case CRAWLER_NOTSTARTED:
out_string(c, "NOTSTARTED no items to crawl");
break;
case CRAWLER_ERROR:
out_string(c, "ERROR an unknown error happened");
break;
}
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) {
uint32_t tocrawl;
if (!safe_strtoul(tokens[2].value, &tocrawl)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
settings.lru_crawler_tocrawl = tocrawl;
out_string(c, "OK");
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) {
uint32_t tosleep;
if (!safe_strtoul(tokens[2].value, &tosleep)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (tosleep > 1000000) {
out_string(c, "CLIENT_ERROR sleep must be one second or less");
return;
}
settings.lru_crawler_sleep = tosleep;
out_string(c, "OK");
return;
} else if (ntokens == 3) {
if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) {
if (start_item_crawler_thread() == 0) {
out_string(c, "OK");
} else {
out_string(c, "ERROR failed to start lru crawler thread");
}
} else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) {
if (stop_item_crawler_thread() == 0) {
out_string(c, "OK");
} else {
out_string(c, "ERROR failed to stop lru crawler thread");
}
} else {
out_string(c, "ERROR");
}
return;
} else {
out_string(c, "ERROR");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) {
process_watch_command(c, tokens, ntokens);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) {
process_memlimit_command(c, tokens, ntokens);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) {
process_verbosity_command(c, tokens, ntokens);
} else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) {
process_lru_command(c, tokens, ntokens);
#ifdef MEMCACHED_DEBUG
// commands which exist only for testing the memcached's security protection
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) {
process_misbehave_command(c);
#endif
#ifdef EXTSTORE
} else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) {
process_extstore_command(c, tokens, ntokens);
#endif
} else {
if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) {
conn_set_state(c, conn_closing);
} else {
out_string(c, "ERROR");
}
}
return;
}
/*
* if we have a complete line in the buffer, process it.
*/
static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_of_memory(c,
"SERVER_ERROR Out of memory allocating headers");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (ptr - c->rcurr > 100 ||
(strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
c->last_cmd_time = current_time;
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
/*
* read a UDP request.
*/
static enum try_read_result try_read_udp(conn *c) {
int res;
assert(c != NULL);
c->request_addr_size = sizeof(c->request_addr);
res = recvfrom(c->sfd, c->rbuf, c->rsize,
0, (struct sockaddr *)&c->request_addr,
&c->request_addr_size);
if (res > 8) {
unsigned char *buf = (unsigned char *)c->rbuf;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* Beginning of UDP packet is the request ID; save it. */
c->request_id = buf[0] * 256 + buf[1];
/* If this is a multi-packet request, drop it. */
if (buf[4] != 0 || buf[5] != 1) {
out_string(c, "SERVER_ERROR multi-packet request not supported");
return READ_NO_DATA_RECEIVED;
}
/* Don't care about any of the rest of the header. */
res -= 8;
memmove(c->rbuf, c->rbuf + 8, res);
c->rbytes = res;
c->rcurr = c->rbuf;
return READ_DATA_RECEIVED;
}
return READ_NO_DATA_RECEIVED;
}
/*
* read from network as much as we can, handle buffer overflow and connection
* close.
* before reading, move the remaining incomplete fragment of a command
* (if any) to the beginning of the buffer.
*
* To protect us from someone flooding a connection with bogus data causing
* the connection to eat up all available memory, break out and start looking
* at the data I've got after a number of reallocs...
*
* @return enum try_read_result
*/
static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
int num_allocs = 0;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
if (num_allocs == 4) {
return gotdata;
}
++num_allocs;
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
if (settings.verbose > 0) {
fprintf(stderr, "Couldn't realloc input buffer\n");
}
c->rbytes = 0; /* ignore what we read */
out_of_memory(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = read(c->sfd, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
static bool update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags)
return true;
if (event_del(&c->event) == -1) return false;
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) return false;
return true;
}
/*
* Sets whether we are listening for new connections or not.
*/
void do_accept_new_conns(const bool do_accept) {
conn *next;
for (next = listen_conn; next; next = next->next) {
if (do_accept) {
update_event(next, EV_READ | EV_PERSIST);
if (listen(next->sfd, settings.backlog) != 0) {
perror("listen");
}
}
else {
update_event(next, 0);
if (listen(next->sfd, 0) != 0) {
perror("listen");
}
}
}
if (do_accept) {
struct timeval maxconns_exited;
uint64_t elapsed_us;
gettimeofday(&maxconns_exited,NULL);
STATS_LOCK();
elapsed_us =
(maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000
+ (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec);
stats.time_in_listen_disabled_us += elapsed_us;
stats_state.accepting_conns = true;
STATS_UNLOCK();
} else {
STATS_LOCK();
stats_state.accepting_conns = false;
gettimeofday(&stats.maxconns_entered,NULL);
stats.listen_disabled_num++;
STATS_UNLOCK();
allow_new_conns = false;
maxconns_handler(-42, 0, 0);
}
}
/*
* Transmit the next chunk of data from our list of msgbuf structures.
*
* Returns:
* TRANSMIT_COMPLETE All done writing.
* TRANSMIT_INCOMPLETE More data remaining to write.
* TRANSMIT_SOFT_ERROR Can't write any more right now.
* TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
*/
static enum transmit_result transmit(conn *c) {
assert(c != NULL);
if (c->msgcurr < c->msgused &&
c->msglist[c->msgcurr].msg_iovlen == 0) {
/* Finished writing the current msg; advance to the next. */
c->msgcurr++;
}
if (c->msgcurr < c->msgused) {
ssize_t res;
struct msghdr *m = &c->msglist[c->msgcurr];
res = sendmsg(c->sfd, m, 0);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_written += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We've written some of the data. Remove the completed
iovec entries from the list of pending writes. */
while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) {
res -= m->msg_iov->iov_len;
m->msg_iovlen--;
m->msg_iov++;
}
/* Might have written just part of the last iovec entry;
adjust it so the next write will do the rest. */
if (res > 0) {
m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res;
m->msg_iov->iov_len -= res;
}
return TRANSMIT_INCOMPLETE;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
}
return TRANSMIT_SOFT_ERROR;
}
/* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK,
we have a real error, on which we close the connection */
if (settings.verbose > 0)
perror("Failed to write, and not due to blocking");
if (IS_UDP(c->transport))
conn_set_state(c, conn_read);
else
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
} else {
return TRANSMIT_COMPLETE;
}
}
/* Does a looped read to fill data chunks */
/* TODO: restrict number of times this can loop.
* Also, benchmark using readv's.
*/
static int read_into_chunked_item(conn *c) {
int total = 0;
int res;
assert(c->rcurr != c->ritem);
while (c->rlbytes > 0) {
item_chunk *ch = (item_chunk *)c->ritem;
assert(ch->used <= ch->size);
if (ch->size == ch->used) {
// FIXME: ch->next is currently always 0. remove this?
if (ch->next) {
c->ritem = (char *) ch->next;
} else {
/* Allocate next chunk. Binary protocol needs 2b for \r\n */
c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes +
((c->protocol == binary_prot) ? 2 : 0));
if (!c->ritem) {
// We failed an allocation. Let caller handle cleanup.
total = -2;
break;
}
// ritem has new chunk, restart the loop.
continue;
//assert(c->rlbytes == 0);
}
}
int unused = ch->size - ch->used;
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
total = 0;
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
tocopy = tocopy > unused ? unused : tocopy;
if (c->ritem != c->rcurr) {
memmove(ch->data + ch->used, c->rcurr, tocopy);
}
total += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
ch->used += tocopy;
if (c->rlbytes == 0) {
break;
}
} else {
/* now try reading from the socket */
res = read(c->sfd, ch->data + ch->used,
(unused > c->rlbytes ? c->rlbytes : unused));
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
ch->used += res;
total += res;
c->rlbytes -= res;
} else {
/* Reset total to the latest result so caller can handle it */
total = res;
break;
}
}
}
/* At some point I will be able to ditch the \r\n from item storage and
remove all of these kludges.
The above binprot check ensures inline space for \r\n, but if we do
exactly enough allocs there will be no additional chunk for \r\n.
*/
if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) {
item_chunk *ch = (item_chunk *)c->ritem;
if (ch->size - ch->used < 2) {
c->ritem = (char *) do_item_alloc_chunk(ch, 2);
if (!c->ritem) {
total = -2;
}
}
}
return total;
}
static void drive_machine(conn *c) {
bool stop = false;
int sfd;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
const char *str;
#ifdef HAVE_ACCEPT4
static int use_accept4 = 1;
#else
static int use_accept4 = 0;
#endif
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
#ifdef HAVE_ACCEPT4
if (use_accept4) {
sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK);
} else {
sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen);
}
#else
sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen);
#endif
if (sfd == -1) {
if (use_accept4 && errno == ENOSYS) {
use_accept4 = 0;
continue;
}
perror(use_accept4 ? "accept4()" : "accept()");
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if (!use_accept4) {
if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
}
if (settings.maxconns_fast &&
stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) {
str = "ERROR Too many open connections\r\n";
res = write(sfd, str, strlen(str));
close(sfd);
STATS_LOCK();
stats.rejected_conns++;
STATS_UNLOCK();
} else {
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, c->transport);
}
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* Check if rbytes < 0, to prevent crash */
if (c->rlbytes < 0) {
if (settings.verbose) {
fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes);
}
conn_set_state(c, conn_closing);
break;
}
if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) {
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = read(c->sfd, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
} else {
res = read_into_chunked_item(c);
if (res > 0)
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* Memory allocation failure */
if (res == -2) {
out_of_memory(c, "SERVER_ERROR Out of memory during read");
c->sbytes = c->rlbytes;
c->write_and_go = conn_swallow;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes <= 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
#ifdef EXTSTORE
/* have side IO's that must process before transmit() can run.
* remove the connection from the worker thread and dispatch the
* IO queue
*/
if (c->io_wrapleft) {
assert(c->io_queued == false);
assert(c->io_wraplist != NULL);
// TODO: create proper state for this condition
conn_set_state(c, conn_watch);
event_del(&c->event);
c->io_queued = true;
extstore_submit(c->thread->storage, &c->io_wraplist->io);
stop = true;
break;
}
#endif
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
conn_release_items(c);
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_closed:
/* This only happens if dormando is an idiot. */
abort();
break;
case conn_watch:
/* We handed off our connection to the logger thread. */
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
}
void event_handler(const int fd, const short which, void *arg) {
conn *c;
c = (conn *)arg;
assert(c != NULL);
c->which = which;
/* sanity */
if (fd != c->sfd) {
if (settings.verbose > 0)
fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n");
conn_close(c);
return;
}
drive_machine(c);
/* wait for next event */
return;
}
static int new_socket(struct addrinfo *ai) {
int sfd;
int flags;
if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
/*
* Sets a socket's send buffer size to the maximum allowed by the system.
*/
static void maximize_sndbuf(const int sfd) {
socklen_t intsize = sizeof(int);
int last_good = 0;
int min, max, avg;
int old_size;
/* Start with the default size. */
if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) {
if (settings.verbose > 0)
perror("getsockopt(SO_SNDBUF)");
return;
}
/* Binary-search for the real maximum. */
min = old_size;
max = MAX_SENDBUF_SIZE;
while (min <= max) {
avg = ((unsigned int)(min + max)) / 2;
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) {
last_good = avg;
min = avg + 1;
} else {
max = avg - 1;
}
}
if (settings.verbose > 1)
fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good);
}
/**
* Create a socket and bind it to a specific port number
* @param interface the interface to bind to
* @param port the port number to bind to
* @param transport the transport protocol (TCP / UDP)
* @param portnumber_file A filepointer to write the port numbers to
* when they are successfully added to the list of ports we
* listen on.
*/
static int server_socket(const char *interface,
int port,
enum network_transport transport,
FILE *portnumber_file) {
int sfd;
struct linger ling = {0, 0};
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = { .ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC };
char port_buf[NI_MAXSERV];
int error;
int success = 0;
int flags =1;
hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM;
if (port == -1) {
port = 0;
}
snprintf(port_buf, sizeof(port_buf), "%d", port);
error= getaddrinfo(interface, port_buf, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM)
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
else
perror("getaddrinfo()");
return 1;
}
for (next= ai; next; next= next->ai_next) {
conn *listen_conn_add;
if ((sfd = new_socket(next)) == -1) {
/* getaddrinfo can return "junk" addresses,
* we make sure at least one works before erroring.
*/
if (errno == EMFILE) {
/* ...unless we're out of fds */
perror("server_socket");
exit(EX_OSERR);
}
continue;
}
#ifdef IPV6_V6ONLY
if (next->ai_family == AF_INET6) {
error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags));
if (error != 0) {
perror("setsockopt");
close(sfd);
continue;
}
}
#endif
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
if (IS_UDP(transport)) {
maximize_sndbuf(sfd);
} else {
error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
}
if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
if (errno != EADDRINUSE) {
perror("bind()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
close(sfd);
continue;
} else {
success++;
if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
if (portnumber_file != NULL &&
(next->ai_addr->sa_family == AF_INET ||
next->ai_addr->sa_family == AF_INET6)) {
union {
struct sockaddr_in in;
struct sockaddr_in6 in6;
} my_sockaddr;
socklen_t len = sizeof(my_sockaddr);
if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
if (next->ai_addr->sa_family == AF_INET) {
fprintf(portnumber_file, "%s INET: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in.sin_port));
} else {
fprintf(portnumber_file, "%s INET6: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in6.sin6_port));
}
}
}
}
if (IS_UDP(transport)) {
int c;
for (c = 0; c < settings.num_threads_per_udp; c++) {
/* Allocate one UDP file descriptor per worker thread;
* this allows "stats conns" to separately list multiple
* parallel UDP requests in progress.
*
* The dispatch code round-robins new connection requests
* among threads, so this is guaranteed to assign one
* FD to each thread.
*/
int per_thread_fd = c ? dup(sfd) : sfd;
dispatch_conn_new(per_thread_fd, conn_read,
EV_READ | EV_PERSIST,
UDP_READ_BUFFER_SIZE, transport);
}
} else {
if (!(listen_conn_add = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
listen_conn_add->next = listen_conn;
listen_conn = listen_conn_add;
}
}
freeaddrinfo(ai);
/* Return zero iff we detected no errors in starting up connections */
return success == 0;
}
static int server_sockets(int port, enum network_transport transport,
FILE *portnumber_file) {
if (settings.inter == NULL) {
return server_socket(settings.inter, port, transport, portnumber_file);
} else {
// tokenize them and bind to each one of them..
char *b;
int ret = 0;
char *list = strdup(settings.inter);
if (list == NULL) {
fprintf(stderr, "Failed to allocate memory for parsing server interface string\n");
return 1;
}
for (char *p = strtok_r(list, ";,", &b);
p != NULL;
p = strtok_r(NULL, ";,", &b)) {
int the_port = port;
char *h = NULL;
if (*p == '[') {
// expecting it to be an IPv6 address enclosed in []
// i.e. RFC3986 style recommended by RFC5952
char *e = strchr(p, ']');
if (e == NULL) {
fprintf(stderr, "Invalid IPV6 address: \"%s\"", p);
free(list);
return 1;
}
h = ++p; // skip the opening '['
*e = '\0';
p = ++e; // skip the closing ']'
}
char *s = strchr(p, ':');
if (s != NULL) {
// If no more semicolons - attempt to treat as port number.
// Otherwise the only valid option is an unenclosed IPv6 without port, until
// of course there was an RFC3986 IPv6 address previously specified -
// in such a case there is no good option, will just send it to fail as port number.
if (strchr(s + 1, ':') == NULL || h != NULL) {
*s = '\0';
++s;
if (!safe_strtol(s, &the_port)) {
fprintf(stderr, "Invalid port number: \"%s\"", s);
free(list);
return 1;
}
}
}
if (h != NULL)
p = h;
if (strcmp(p, "*") == 0) {
p = NULL;
}
ret |= server_socket(p, the_port, transport, portnumber_file);
}
free(list);
return ret;
}
}
static int new_socket_unix(void) {
int sfd;
int flags;
if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket()");
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
static int server_socket_unix(const char *path, int access_mask) {
int sfd;
struct linger ling = {0, 0};
struct sockaddr_un addr;
struct stat tstat;
int flags =1;
int old_umask;
if (!path) {
return 1;
}
if ((sfd = new_socket_unix()) == -1) {
return 1;
}
/*
* Clean up a previous socket file if we left it around
*/
if (lstat(path, &tstat) == 0) {
if (S_ISSOCK(tstat.st_mode))
unlink(path);
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/*
* the memset call clears nonstandard fields in some implementations
* that otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
assert(strcmp(addr.sun_path, path) == 0);
old_umask = umask( ~(access_mask&0777));
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind()");
close(sfd);
umask(old_umask);
return 1;
}
umask(old_umask);
if (listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
return 1;
}
if (!(listen_conn = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
local_transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*
* We keep the current time of day in a global variable that's updated by a
* timer event. This saves us a bunch of time() system calls (we really only
* need to get the time once a second, whereas there can be tens of thousands
* of requests a second) and allows us to use server-start-relative timestamps
* rather than absolute UNIX timestamps, a space savings on systems where
* sizeof(time_t) > sizeof(unsigned int).
*/
volatile rel_time_t current_time;
static struct event clockevent;
/* libevent uses a monotonic clock when available for event scheduling. Aside
* from jitter, simply ticking our internal timer here is accurate enough.
* Note that users who are setting explicit dates for expiration times *must*
* ensure their clocks are correct before starting memcached. */
static void clock_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
static bool initialized = false;
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
static bool monotonic = false;
static time_t monotonic_start;
#endif
if (initialized) {
/* only delete the event if it's actually there. */
evtimer_del(&clockevent);
} else {
initialized = true;
/* process_started is initialized to time() - 2. We initialize to 1 so
* flush_all won't underflow during tests. */
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
monotonic = true;
monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2;
}
#endif
}
// While we're here, check for hash table expansion.
// This function should be quick to avoid delaying the timer.
assoc_start_expand(stats_state.curr_items);
evtimer_set(&clockevent, clock_handler, 0);
event_base_set(main_base, &clockevent);
evtimer_add(&clockevent, &t);
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
if (monotonic) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
return;
current_time = (rel_time_t) (ts.tv_sec - monotonic_start);
return;
}
#endif
{
struct timeval tv;
gettimeofday(&tv, NULL);
current_time = (rel_time_t) (tv.tv_sec - process_started);
}
}
static void usage(void) {
printf(PACKAGE " " VERSION "\n");
printf("-p, --port=<num> TCP port to listen on (default: 11211)\n"
"-U, --udp-port=<num> UDP port to listen on (default: 11211, 0 is off)\n"
"-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n"
"-A, --enable-shutdown enable ascii \"shutdown\" command\n"
"-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n"
"-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n"
"-d, --daemon run as a daemon\n"
"-r, --enable-coredumps maximize core file limit\n"
"-u, --user=<user> assume identity of <username> (only when run as root)\n"
"-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n"
"-M, --disable-evictions return error on memory exhausted instead of evicting\n"
"-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n"
"-k, --lock-memory lock down all paged memory\n"
"-v, --verbose verbose (print errors/warnings while in event loop)\n"
"-vv very verbose (also print client commands/responses)\n"
"-vvv extremely verbose (internal state transitions)\n"
"-h, --help print this help and exit\n"
"-i, --license print memcached and libevent license\n"
"-V, --version print version and exit\n"
"-P, --pidfile=<file> save PID in <file>, only used with -d option\n"
"-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n"
"-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n");
printf("-L, --enable-largepages try to use large memory pages (if available)\n");
printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n"
" This is used for per-prefix stats reporting. The default is\n"
" \":\" (colon). If this option is specified, stats collection\n"
" is turned on automatically; if not, then it may be turned on\n"
" by sending the \"stats detail on\" command to the server.\n");
printf("-t, --threads=<num> number of threads to use (default: 4)\n");
printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n"
" requests processed per connection to prevent \n"
" starvation (default: 20)\n");
printf("-C, --disable-cas disable use of CAS\n");
printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n");
printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n");
printf("-I, --max-item-size=<num> adjusts max item size\n"
" (default: 1mb, min: 1k, max: 128m)\n");
#ifdef ENABLE_SASL
printf("-S, --enable-sasl turn on Sasl authentication\n");
#endif
printf("-F, --disable-flush-all disable flush_all command\n");
printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n");
printf("-o, --extended comma separated list of extended options\n"
" most options have a 'no_' prefix to disable\n"
" - maxconns_fast: immediately close new connections after limit\n"
" - hashpower: an integer multiplier for how large the hash\n"
" table should be. normally grows at runtime.\n"
" set based on \"STAT hash_power_level\"\n"
" - tail_repair_time: time in seconds for how long to wait before\n"
" forcefully killing LRU tail item.\n"
" disabled by default; very dangerous option.\n"
" - hash_algorithm: the hash table algorithm\n"
" default is murmur3 hash. options: jenkins, murmur3\n"
" - lru_crawler: enable LRU Crawler background thread\n"
" - lru_crawler_sleep: microseconds to sleep between items\n"
" default is 100.\n"
" - lru_crawler_tocrawl: max items to crawl per slab per run\n"
" default is 0 (unlimited)\n"
" - lru_maintainer: enable new LRU system + background thread\n"
" - hot_lru_pct: pct of slab memory to reserve for hot lru.\n"
" (requires lru_maintainer)\n"
" - warm_lru_pct: pct of slab memory to reserve for warm lru.\n"
" (requires lru_maintainer)\n"
" - hot_max_factor: items idle > cold lru age * drop from hot lru.\n"
" - warm_max_factor: items idle > cold lru age * this drop from warm.\n"
" - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n"
" (requires lru_maintainer)\n"
" - idle_timeout: timeout for idle connections\n"
" - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n"
" - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n"
" - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n"
" read by background thread, then written to watchers.\n"
" - track_sizes: enable dynamic reports for 'stats sizes' command.\n"
" - no_inline_ascii_resp: save up to 24 bytes per item.\n"
" small perf hit in ASCII, no perf difference in\n"
" binary protocol. speeds up all sets.\n"
" - no_hashexpand: disables hash table expansion (dangerous)\n"
" - modern: enables options which will be default in future.\n"
" currently: nothing\n"
" - no_modern: uses defaults of previous major version (1.4.x)\n"
#ifdef HAVE_DROP_PRIVILEGES
" - no_drop_privileges: Disable drop_privileges in case it causes issues with\n"
" some customisation.\n"
#ifdef MEMCACHED_DEBUG
" - relaxed_privileges: Running tests requires extra privileges.\n"
#endif
#endif
#ifdef EXTSTORE
" - ext_path: file to write to for external storage.\n"
" - ext_page_size: size in megabytes of storage pages.\n"
" - ext_wbuf_size: size in megabytes of page write buffers.\n"
" - ext_threads: number of IO threads to run.\n"
" - ext_item_size: store items larger than this (bytes)\n"
" - ext_item_age: store items idle at least this long\n"
" - ext_low_ttl: consider TTLs lower than this specially\n"
" - ext_drop_unread: don't re-write unread values during compaction\n"
" - ext_recache_rate: recache an item every N accesses\n"
" - ext_compact_under: compact when fewer than this many free pages\n"
" - ext_drop_under: drop COLD items when fewer than this many free pages\n"
" - ext_max_frag: max page fragmentation to tolerage\n"
" (see doc/storage.txt for more info)\n"
#endif
);
return;
}
static void usage_license(void) {
printf(PACKAGE " " VERSION "\n\n");
printf(
"Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are\n"
"met:\n"
"\n"
" * Redistributions of source code must retain the above copyright\n"
"notice, this list of conditions and the following disclaimer.\n"
"\n"
" * Redistributions in binary form must reproduce the above\n"
"copyright notice, this list of conditions and the following disclaimer\n"
"in the documentation and/or other materials provided with the\n"
"distribution.\n"
"\n"
" * Neither the name of the Danga Interactive nor the names of its\n"
"contributors may be used to endorse or promote products derived from\n"
"this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"\n"
"\n"
"This product includes software developed by Niels Provos.\n"
"\n"
"[ libevent ]\n"
"\n"
"Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions\n"
"are met:\n"
"1. Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
"3. All advertising materials mentioning features or use of this software\n"
" must display the following acknowledgement:\n"
" This product includes software developed by Niels Provos.\n"
"4. The name of the author may not be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n"
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
);
return;
}
static void save_pid(const char *pid_file) {
FILE *fp;
if (access(pid_file, F_OK) == 0) {
if ((fp = fopen(pid_file, "r")) != NULL) {
char buffer[1024];
if (fgets(buffer, sizeof(buffer), fp) != NULL) {
unsigned int pid;
if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) {
fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid);
}
}
fclose(fp);
}
}
/* Create the pid file first with a temporary name, then
* atomically move the file to the real name to avoid a race with
* another process opening the file to read the pid, but finding
* it empty.
*/
char tmp_pid_file[1024];
snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file);
if ((fp = fopen(tmp_pid_file, "w")) == NULL) {
vperror("Could not open the pid file %s for writing", tmp_pid_file);
return;
}
fprintf(fp,"%ld\n", (long)getpid());
if (fclose(fp) == -1) {
vperror("Could not close the pid file %s", tmp_pid_file);
}
if (rename(tmp_pid_file, pid_file) != 0) {
vperror("Could not rename the pid file from %s to %s",
tmp_pid_file, pid_file);
}
}
static void remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
vperror("Could not remove the pid file %s", pid_file);
}
}
static void sig_handler(const int sig) {
printf("Signal handled: %s.\n", strsignal(sig));
exit(EXIT_SUCCESS);
}
#ifndef HAVE_SIGIGNORE
static int sigignore(int sig) {
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 };
if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) {
return -1;
}
return 0;
}
#endif
/*
* On systems that supports multiple page sizes we may reduce the
* number of TLB-misses by using the biggest available page size
*/
static int enable_large_pages(void) {
#if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL)
int ret = -1;
size_t sizes[32];
int avail = getpagesizes(sizes, 32);
if (avail != -1) {
size_t max = sizes[0];
struct memcntl_mha arg = {0};
int ii;
for (ii = 1; ii < avail; ++ii) {
if (max < sizes[ii]) {
max = sizes[ii];
}
}
arg.mha_flags = 0;
arg.mha_pagesize = max;
arg.mha_cmd = MHA_MAPSIZE_BSSBRK;
if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) {
fprintf(stderr, "Failed to set large pages: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
} else {
ret = 0;
}
} else {
fprintf(stderr, "Failed to get supported pagesizes: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
}
return ret;
#else
return -1;
#endif
}
/**
* Do basic sanity check of the runtime environment
* @return true if no errors found, false if we can't use this env
*/
static bool sanitycheck(void) {
/* One of our biggest problems is old and bogus libevents */
const char *ever = event_get_version();
if (ever != NULL) {
if (strncmp(ever, "1.", 2) == 0) {
/* Require at least 1.3 (that's still a couple of years old) */
if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) {
fprintf(stderr, "You are using libevent %s.\nPlease upgrade to"
" a more recent version (1.3 or newer)\n",
event_get_version());
return false;
}
}
}
return true;
}
static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) {
char *b = NULL;
uint32_t size = 0;
int i = 0;
uint32_t last_size = 0;
if (strlen(s) < 1)
return false;
for (char *p = strtok_r(s, "-", &b);
p != NULL;
p = strtok_r(NULL, "-", &b)) {
if (!safe_strtoul(p, &size) || size < settings.chunk_size
|| size > settings.slab_chunk_size_max) {
fprintf(stderr, "slab size %u is out of valid range\n", size);
return false;
}
if (last_size >= size) {
fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size);
return false;
}
if (size <= last_size + CHUNK_ALIGN_BYTES) {
fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n",
size, CHUNK_ALIGN_BYTES);
return false;
}
slab_sizes[i++] = size;
last_size = size;
if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) {
fprintf(stderr, "too many slab classes specified\n");
return false;
}
}
slab_sizes[i] = 0;
return true;
}
int main (int argc, char **argv) {
int c;
bool lock_memory = false;
bool do_daemonize = false;
bool preallocate = false;
int maxcore = 0;
char *username = NULL;
char *pid_file = NULL;
struct passwd *pw;
struct rlimit rlim;
char *buf;
char unit = '\0';
int size_max = 0;
int retval = EXIT_SUCCESS;
/* listening sockets */
static int *l_socket = NULL;
/* udp socket */
static int *u_socket = NULL;
bool protocol_specified = false;
bool tcp_specified = false;
bool udp_specified = false;
bool start_lru_maintainer = true;
bool start_lru_crawler = true;
bool start_assoc_maint = true;
enum hashfunc_type hash_type = MURMUR3_HASH;
uint32_t tocrawl;
uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES];
bool use_slab_sizes = false;
char *slab_sizes_unparsed = NULL;
bool slab_chunk_size_changed = false;
#ifdef EXTSTORE
void *storage = NULL;
char *storage_file = NULL;
struct extstore_conf ext_cf;
#endif
char *subopts, *subopts_orig;
char *subopts_value;
enum {
MAXCONNS_FAST = 0,
HASHPOWER_INIT,
NO_HASHEXPAND,
SLAB_REASSIGN,
SLAB_AUTOMOVE,
SLAB_AUTOMOVE_RATIO,
SLAB_AUTOMOVE_WINDOW,
TAIL_REPAIR_TIME,
HASH_ALGORITHM,
LRU_CRAWLER,
LRU_CRAWLER_SLEEP,
LRU_CRAWLER_TOCRAWL,
LRU_MAINTAINER,
HOT_LRU_PCT,
WARM_LRU_PCT,
HOT_MAX_FACTOR,
WARM_MAX_FACTOR,
TEMPORARY_TTL,
IDLE_TIMEOUT,
WATCHER_LOGBUF_SIZE,
WORKER_LOGBUF_SIZE,
SLAB_SIZES,
SLAB_CHUNK_MAX,
TRACK_SIZES,
NO_INLINE_ASCII_RESP,
MODERN,
NO_MODERN,
NO_CHUNKED_ITEMS,
NO_SLAB_REASSIGN,
NO_SLAB_AUTOMOVE,
NO_MAXCONNS_FAST,
INLINE_ASCII_RESP,
NO_LRU_CRAWLER,
NO_LRU_MAINTAINER,
NO_DROP_PRIVILEGES,
#ifdef MEMCACHED_DEBUG
RELAXED_PRIVILEGES,
#endif
#ifdef EXTSTORE
EXT_PAGE_SIZE,
EXT_PAGE_COUNT,
EXT_WBUF_SIZE,
EXT_THREADS,
EXT_IO_DEPTH,
EXT_PATH,
EXT_ITEM_SIZE,
EXT_ITEM_AGE,
EXT_LOW_TTL,
EXT_RECACHE_RATE,
EXT_COMPACT_UNDER,
EXT_DROP_UNDER,
EXT_MAX_FRAG,
EXT_DROP_UNREAD,
SLAB_AUTOMOVE_FREERATIO,
#endif
};
char *const subopts_tokens[] = {
[MAXCONNS_FAST] = "maxconns_fast",
[HASHPOWER_INIT] = "hashpower",
[NO_HASHEXPAND] = "no_hashexpand",
[SLAB_REASSIGN] = "slab_reassign",
[SLAB_AUTOMOVE] = "slab_automove",
[SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio",
[SLAB_AUTOMOVE_WINDOW] = "slab_automove_window",
[TAIL_REPAIR_TIME] = "tail_repair_time",
[HASH_ALGORITHM] = "hash_algorithm",
[LRU_CRAWLER] = "lru_crawler",
[LRU_CRAWLER_SLEEP] = "lru_crawler_sleep",
[LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl",
[LRU_MAINTAINER] = "lru_maintainer",
[HOT_LRU_PCT] = "hot_lru_pct",
[WARM_LRU_PCT] = "warm_lru_pct",
[HOT_MAX_FACTOR] = "hot_max_factor",
[WARM_MAX_FACTOR] = "warm_max_factor",
[TEMPORARY_TTL] = "temporary_ttl",
[IDLE_TIMEOUT] = "idle_timeout",
[WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size",
[WORKER_LOGBUF_SIZE] = "worker_logbuf_size",
[SLAB_SIZES] = "slab_sizes",
[SLAB_CHUNK_MAX] = "slab_chunk_max",
[TRACK_SIZES] = "track_sizes",
[NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp",
[MODERN] = "modern",
[NO_MODERN] = "no_modern",
[NO_CHUNKED_ITEMS] = "no_chunked_items",
[NO_SLAB_REASSIGN] = "no_slab_reassign",
[NO_SLAB_AUTOMOVE] = "no_slab_automove",
[NO_MAXCONNS_FAST] = "no_maxconns_fast",
[INLINE_ASCII_RESP] = "inline_ascii_resp",
[NO_LRU_CRAWLER] = "no_lru_crawler",
[NO_LRU_MAINTAINER] = "no_lru_maintainer",
[NO_DROP_PRIVILEGES] = "no_drop_privileges",
#ifdef MEMCACHED_DEBUG
[RELAXED_PRIVILEGES] = "relaxed_privileges",
#endif
#ifdef EXTSTORE
[EXT_PAGE_SIZE] = "ext_page_size",
[EXT_PAGE_COUNT] = "ext_page_count",
[EXT_WBUF_SIZE] = "ext_wbuf_size",
[EXT_THREADS] = "ext_threads",
[EXT_IO_DEPTH] = "ext_io_depth",
[EXT_PATH] = "ext_path",
[EXT_ITEM_SIZE] = "ext_item_size",
[EXT_ITEM_AGE] = "ext_item_age",
[EXT_LOW_TTL] = "ext_low_ttl",
[EXT_RECACHE_RATE] = "ext_recache_rate",
[EXT_COMPACT_UNDER] = "ext_compact_under",
[EXT_DROP_UNDER] = "ext_drop_under",
[EXT_MAX_FRAG] = "ext_max_frag",
[EXT_DROP_UNREAD] = "ext_drop_unread",
[SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio",
#endif
NULL
};
if (!sanitycheck()) {
return EX_OSERR;
}
/* handle SIGINT and SIGTERM */
signal(SIGINT, sig_handler);
signal(SIGTERM, sig_handler);
/* init settings */
settings_init();
#ifdef EXTSTORE
settings.ext_item_size = 512;
settings.ext_item_age = UINT_MAX;
settings.ext_low_ttl = 0;
settings.ext_recache_rate = 2000;
settings.ext_max_frag = 0.8;
settings.ext_drop_unread = false;
settings.ext_wbuf_size = 1024 * 1024 * 4;
settings.ext_compact_under = 0;
settings.ext_drop_under = 0;
settings.slab_automove_freeratio = 0.01;
ext_cf.page_size = 1024 * 1024 * 64;
ext_cf.page_count = 64;
ext_cf.wbuf_size = settings.ext_wbuf_size;
ext_cf.io_threadcount = 1;
ext_cf.io_depth = 1;
ext_cf.page_buckets = 4;
ext_cf.wbuf_count = ext_cf.page_buckets;
#endif
/* Run regardless of initializing it later */
init_lru_maintainer();
/* set stderr non-buffering (for running under, say, daemontools) */
setbuf(stderr, NULL);
char *shortopts =
"a:" /* access mask for unix socket */
"A" /* enable admin shutdown command */
"p:" /* TCP port number to listen on */
"s:" /* unix socket path to listen on */
"U:" /* UDP port number to listen on */
"m:" /* max memory to use for items in megabytes */
"M" /* return error on memory exhausted */
"c:" /* max simultaneous connections */
"k" /* lock down all paged memory */
"hiV" /* help, licence info, version */
"r" /* maximize core file limit */
"v" /* verbose */
"d" /* daemon mode */
"l:" /* interface to listen on */
"u:" /* user identity to run as */
"P:" /* save PID in file */
"f:" /* factor? */
"n:" /* minimum space allocated for key+value+flags */
"t:" /* threads */
"D:" /* prefix delimiter? */
"L" /* Large memory pages */
"R:" /* max requests per event */
"C" /* Disable use of CAS */
"b:" /* backlog queue limit */
"B:" /* Binding protocol */
"I:" /* Max item size */
"S" /* Sasl ON */
"F" /* Disable flush_all */
"X" /* Disable dump commands */
"o:" /* Extended generic options */
;
/* process arguments */
#ifdef HAVE_GETOPT_LONG
const struct option longopts[] = {
{"unix-mask", required_argument, 0, 'a'},
{"enable-shutdown", no_argument, 0, 'A'},
{"port", required_argument, 0, 'p'},
{"unix-socket", required_argument, 0, 's'},
{"udp-port", required_argument, 0, 'U'},
{"memory-limit", required_argument, 0, 'm'},
{"disable-evictions", no_argument, 0, 'M'},
{"conn-limit", required_argument, 0, 'c'},
{"lock-memory", no_argument, 0, 'k'},
{"help", no_argument, 0, 'h'},
{"license", no_argument, 0, 'i'},
{"version", no_argument, 0, 'V'},
{"enable-coredumps", no_argument, 0, 'r'},
{"verbose", optional_argument, 0, 'v'},
{"daemon", no_argument, 0, 'd'},
{"listen", required_argument, 0, 'l'},
{"user", required_argument, 0, 'u'},
{"pidfile", required_argument, 0, 'P'},
{"slab-growth-factor", required_argument, 0, 'f'},
{"slab-min-size", required_argument, 0, 'n'},
{"threads", required_argument, 0, 't'},
{"enable-largepages", no_argument, 0, 'L'},
{"max-reqs-per-event", required_argument, 0, 'R'},
{"disable-cas", no_argument, 0, 'C'},
{"listen-backlog", required_argument, 0, 'b'},
{"protocol", required_argument, 0, 'B'},
{"max-item-size", required_argument, 0, 'I'},
{"enable-sasl", no_argument, 0, 'S'},
{"disable-flush-all", no_argument, 0, 'F'},
{"disable-dumping", no_argument, 0, 'X'},
{"extended", required_argument, 0, 'o'},
{0, 0, 0, 0}
};
int optindex;
while (-1 != (c = getopt_long(argc, argv, shortopts,
longopts, &optindex))) {
#else
while (-1 != (c = getopt(argc, argv, shortopts))) {
#endif
switch (c) {
case 'A':
/* enables "shutdown" command */
settings.shutdown_command = true;
break;
case 'a':
/* access for unix domain socket, as octal mask (like chmod)*/
settings.access= strtol(optarg,NULL,8);
break;
case 'U':
settings.udpport = atoi(optarg);
udp_specified = true;
break;
case 'p':
settings.port = atoi(optarg);
tcp_specified = true;
break;
case 's':
settings.socketpath = optarg;
break;
case 'm':
settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
break;
case 'M':
settings.evict_to_free = 0;
break;
case 'c':
settings.maxconns = atoi(optarg);
if (settings.maxconns <= 0) {
fprintf(stderr, "Maximum connections must be greater than 0\n");
return 1;
}
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'i':
usage_license();
exit(EXIT_SUCCESS);
case 'V':
printf(PACKAGE " " VERSION "\n");
exit(EXIT_SUCCESS);
case 'k':
lock_memory = true;
break;
case 'v':
settings.verbose++;
break;
case 'l':
if (settings.inter != NULL) {
if (strstr(settings.inter, optarg) != NULL) {
break;
}
size_t len = strlen(settings.inter) + strlen(optarg) + 2;
char *p = malloc(len);
if (p == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
return 1;
}
snprintf(p, len, "%s,%s", settings.inter, optarg);
free(settings.inter);
settings.inter = p;
} else {
settings.inter= strdup(optarg);
}
break;
case 'd':
do_daemonize = true;
break;
case 'r':
maxcore = 1;
break;
case 'R':
settings.reqs_per_event = atoi(optarg);
if (settings.reqs_per_event == 0) {
fprintf(stderr, "Number of requests per event must be greater than 0\n");
return 1;
}
break;
case 'u':
username = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'f':
settings.factor = atof(optarg);
if (settings.factor <= 1.0) {
fprintf(stderr, "Factor must be greater than 1\n");
return 1;
}
break;
case 'n':
settings.chunk_size = atoi(optarg);
if (settings.chunk_size == 0) {
fprintf(stderr, "Chunk size must be greater than 0\n");
return 1;
}
break;
case 't':
settings.num_threads = atoi(optarg);
if (settings.num_threads <= 0) {
fprintf(stderr, "Number of threads must be greater than 0\n");
return 1;
}
/* There're other problems when you get above 64 threads.
* In the future we should portably detect # of cores for the
* default.
*/
if (settings.num_threads > 64) {
fprintf(stderr, "WARNING: Setting a high number of worker"
"threads is not recommended.\n"
" Set this value to the number of cores in"
" your machine or less.\n");
}
break;
case 'D':
if (! optarg || ! optarg[0]) {
fprintf(stderr, "No delimiter specified\n");
return 1;
}
settings.prefix_delimiter = optarg[0];
settings.detail_enabled = 1;
break;
case 'L' :
if (enable_large_pages() == 0) {
preallocate = true;
} else {
fprintf(stderr, "Cannot enable large pages on this system\n"
"(There is no Linux support as of this version)\n");
return 1;
}
break;
case 'C' :
settings.use_cas = false;
break;
case 'b' :
settings.backlog = atoi(optarg);
break;
case 'B':
protocol_specified = true;
if (strcmp(optarg, "auto") == 0) {
settings.binding_protocol = negotiating_prot;
} else if (strcmp(optarg, "binary") == 0) {
settings.binding_protocol = binary_prot;
} else if (strcmp(optarg, "ascii") == 0) {
settings.binding_protocol = ascii_prot;
} else {
fprintf(stderr, "Invalid value for binding protocol: %s\n"
" -- should be one of auto, binary, or ascii\n", optarg);
exit(EX_USAGE);
}
break;
case 'I':
buf = strdup(optarg);
unit = buf[strlen(buf)-1];
if (unit == 'k' || unit == 'm' ||
unit == 'K' || unit == 'M') {
buf[strlen(buf)-1] = '\0';
size_max = atoi(buf);
if (unit == 'k' || unit == 'K')
size_max *= 1024;
if (unit == 'm' || unit == 'M')
size_max *= 1024 * 1024;
settings.item_size_max = size_max;
} else {
settings.item_size_max = atoi(buf);
}
free(buf);
break;
case 'S': /* set Sasl authentication to true. Default is false */
#ifndef ENABLE_SASL
fprintf(stderr, "This server is not built with SASL support.\n");
exit(EX_USAGE);
#endif
settings.sasl = true;
break;
case 'F' :
settings.flush_enabled = false;
break;
case 'X' :
settings.dump_enabled = false;
break;
case 'o': /* It's sub-opts time! */
subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */
while (*subopts != '\0') {
switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) {
case MAXCONNS_FAST:
settings.maxconns_fast = true;
break;
case HASHPOWER_INIT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for hashpower\n");
return 1;
}
settings.hashpower_init = atoi(subopts_value);
if (settings.hashpower_init < 12) {
fprintf(stderr, "Initial hashtable multiplier of %d is too low\n",
settings.hashpower_init);
return 1;
} else if (settings.hashpower_init > 32) {
fprintf(stderr, "Initial hashtable multiplier of %d is too high\n"
"Choose a value based on \"STAT hash_power_level\" from a running instance\n",
settings.hashpower_init);
return 1;
}
break;
case NO_HASHEXPAND:
start_assoc_maint = false;
break;
case SLAB_REASSIGN:
settings.slab_reassign = true;
break;
case SLAB_AUTOMOVE:
if (subopts_value == NULL) {
settings.slab_automove = 1;
break;
}
settings.slab_automove = atoi(subopts_value);
if (settings.slab_automove < 0 || settings.slab_automove > 2) {
fprintf(stderr, "slab_automove must be between 0 and 2\n");
return 1;
}
break;
case SLAB_AUTOMOVE_RATIO:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_ratio argument\n");
return 1;
}
settings.slab_automove_ratio = atof(subopts_value);
if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) {
fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n");
return 1;
}
break;
case SLAB_AUTOMOVE_WINDOW:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_window argument\n");
return 1;
}
settings.slab_automove_window = atoi(subopts_value);
if (settings.slab_automove_window < 3) {
fprintf(stderr, "slab_automove_window must be > 2\n");
return 1;
}
break;
case TAIL_REPAIR_TIME:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for tail_repair_time\n");
return 1;
}
settings.tail_repair_time = atoi(subopts_value);
if (settings.tail_repair_time < 10) {
fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n");
return 1;
}
break;
case HASH_ALGORITHM:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hash_algorithm argument\n");
return 1;
};
if (strcmp(subopts_value, "jenkins") == 0) {
hash_type = JENKINS_HASH;
} else if (strcmp(subopts_value, "murmur3") == 0) {
hash_type = MURMUR3_HASH;
} else {
fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n");
return 1;
}
break;
case LRU_CRAWLER:
start_lru_crawler = true;
break;
case LRU_CRAWLER_SLEEP:
if (subopts_value == NULL) {
fprintf(stderr, "Missing lru_crawler_sleep value\n");
return 1;
}
settings.lru_crawler_sleep = atoi(subopts_value);
if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) {
fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n");
return 1;
}
break;
case LRU_CRAWLER_TOCRAWL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing lru_crawler_tocrawl value\n");
return 1;
}
if (!safe_strtoul(subopts_value, &tocrawl)) {
fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n");
return 1;
}
settings.lru_crawler_tocrawl = tocrawl;
break;
case LRU_MAINTAINER:
start_lru_maintainer = true;
settings.lru_segmented = true;
break;
case HOT_LRU_PCT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hot_lru_pct argument\n");
return 1;
}
settings.hot_lru_pct = atoi(subopts_value);
if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) {
fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n");
return 1;
}
break;
case WARM_LRU_PCT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing warm_lru_pct argument\n");
return 1;
}
settings.warm_lru_pct = atoi(subopts_value);
if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) {
fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n");
return 1;
}
break;
case HOT_MAX_FACTOR:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hot_max_factor argument\n");
return 1;
}
settings.hot_max_factor = atof(subopts_value);
if (settings.hot_max_factor <= 0) {
fprintf(stderr, "hot_max_factor must be > 0\n");
return 1;
}
break;
case WARM_MAX_FACTOR:
if (subopts_value == NULL) {
fprintf(stderr, "Missing warm_max_factor argument\n");
return 1;
}
settings.warm_max_factor = atof(subopts_value);
if (settings.warm_max_factor <= 0) {
fprintf(stderr, "warm_max_factor must be > 0\n");
return 1;
}
break;
case TEMPORARY_TTL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing temporary_ttl argument\n");
return 1;
}
settings.temp_lru = true;
settings.temporary_ttl = atoi(subopts_value);
break;
case IDLE_TIMEOUT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for idle_timeout\n");
return 1;
}
settings.idle_timeout = atoi(subopts_value);
break;
case WATCHER_LOGBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing watcher_logbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) {
fprintf(stderr, "could not parse argument to watcher_logbuf_size\n");
return 1;
}
settings.logger_watcher_buf_size *= 1024; /* kilobytes */
break;
case WORKER_LOGBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing worker_logbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) {
fprintf(stderr, "could not parse argument to worker_logbuf_size\n");
return 1;
}
settings.logger_buf_size *= 1024; /* kilobytes */
case SLAB_SIZES:
slab_sizes_unparsed = subopts_value;
break;
case SLAB_CHUNK_MAX:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_chunk_max argument\n");
}
if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) {
fprintf(stderr, "could not parse argument to slab_chunk_max\n");
}
slab_chunk_size_changed = true;
break;
case TRACK_SIZES:
item_stats_sizes_init();
break;
case NO_INLINE_ASCII_RESP:
settings.inline_ascii_response = false;
break;
case INLINE_ASCII_RESP:
settings.inline_ascii_response = true;
break;
case NO_CHUNKED_ITEMS:
settings.slab_chunk_size_max = settings.slab_page_size;
break;
case NO_SLAB_REASSIGN:
settings.slab_reassign = false;
break;
case NO_SLAB_AUTOMOVE:
settings.slab_automove = 0;
break;
case NO_MAXCONNS_FAST:
settings.maxconns_fast = false;
break;
case NO_LRU_CRAWLER:
settings.lru_crawler = false;
start_lru_crawler = false;
break;
case NO_LRU_MAINTAINER:
start_lru_maintainer = false;
settings.lru_segmented = false;
break;
#ifdef EXTSTORE
case EXT_PAGE_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_page_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.page_size)) {
fprintf(stderr, "could not parse argument to ext_page_size\n");
return 1;
}
ext_cf.page_size *= 1024 * 1024; /* megabytes */
break;
case EXT_PAGE_COUNT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_page_count argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.page_count)) {
fprintf(stderr, "could not parse argument to ext_page_count\n");
return 1;
}
break;
case EXT_WBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_wbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) {
fprintf(stderr, "could not parse argument to ext_wbuf_size\n");
return 1;
}
ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */
settings.ext_wbuf_size = ext_cf.wbuf_size;
break;
case EXT_THREADS:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_threads argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) {
fprintf(stderr, "could not parse argument to ext_threads\n");
return 1;
}
break;
case EXT_IO_DEPTH:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_io_depth argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) {
fprintf(stderr, "could not parse argument to ext_io_depth\n");
return 1;
}
break;
case EXT_ITEM_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_item_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_item_size)) {
fprintf(stderr, "could not parse argument to ext_item_size\n");
return 1;
}
break;
case EXT_ITEM_AGE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_item_age argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_item_age)) {
fprintf(stderr, "could not parse argument to ext_item_age\n");
return 1;
}
break;
case EXT_LOW_TTL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_low_ttl argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) {
fprintf(stderr, "could not parse argument to ext_low_ttl\n");
return 1;
}
break;
case EXT_RECACHE_RATE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_recache_rate argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) {
fprintf(stderr, "could not parse argument to ext_recache_rate\n");
return 1;
}
break;
case EXT_COMPACT_UNDER:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_compact_under argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) {
fprintf(stderr, "could not parse argument to ext_compact_under\n");
return 1;
}
break;
case EXT_DROP_UNDER:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_drop_under argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) {
fprintf(stderr, "could not parse argument to ext_drop_under\n");
return 1;
}
break;
case EXT_MAX_FRAG:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_max_frag argument\n");
return 1;
}
if (!safe_strtod(subopts_value, &settings.ext_max_frag)) {
fprintf(stderr, "could not parse argument to ext_max_frag\n");
return 1;
}
break;
case SLAB_AUTOMOVE_FREERATIO:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_freeratio argument\n");
return 1;
}
if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) {
fprintf(stderr, "could not parse argument to slab_automove_freeratio\n");
return 1;
}
break;
case EXT_DROP_UNREAD:
settings.ext_drop_unread = true;
break;
case EXT_PATH:
storage_file = strdup(subopts_value);
break;
#endif
case MODERN:
/* currently no new defaults */
break;
case NO_MODERN:
if (!slab_chunk_size_changed) {
settings.slab_chunk_size_max = settings.slab_page_size;
}
settings.slab_reassign = false;
settings.slab_automove = 0;
settings.maxconns_fast = false;
settings.inline_ascii_response = true;
settings.lru_segmented = false;
hash_type = JENKINS_HASH;
start_lru_crawler = false;
start_lru_maintainer = false;
break;
case NO_DROP_PRIVILEGES:
settings.drop_privileges = false;
break;
#ifdef MEMCACHED_DEBUG
case RELAXED_PRIVILEGES:
settings.relaxed_privileges = true;
break;
#endif
default:
printf("Illegal suboption \"%s\"\n", subopts_value);
return 1;
}
}
free(subopts_orig);
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
return 1;
}
}
if (settings.item_size_max < 1024) {
fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > (settings.maxbytes / 2)) {
fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > (1024 * 1024 * 1024)) {
fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > 1024 * 1024) {
if (!slab_chunk_size_changed) {
// Ideal new default is 16k, but needs stitching.
settings.slab_chunk_size_max = settings.slab_page_size / 2;
}
}
if (settings.slab_chunk_size_max > settings.item_size_max) {
fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n",
settings.slab_chunk_size_max, settings.item_size_max);
exit(EX_USAGE);
}
if (settings.item_size_max % settings.slab_chunk_size_max != 0) {
fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n",
settings.item_size_max, settings.slab_chunk_size_max);
exit(EX_USAGE);
}
if (settings.slab_page_size % settings.slab_chunk_size_max != 0) {
fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n",
settings.slab_chunk_size_max, settings.slab_page_size);
exit(EX_USAGE);
}
#ifdef EXTSTORE
if (storage_file) {
if (settings.item_size_max > ext_cf.wbuf_size) {
fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n",
settings.item_size_max, ext_cf.wbuf_size);
exit(EX_USAGE);
}
/* This is due to the suffix header being generated with the wrong length
* value for the ITEM_HDR replacement. The cuddled nbytes no longer
* matches, so we end up losing a few bytes on readback.
*/
if (settings.inline_ascii_response) {
fprintf(stderr, "Cannot use inline_ascii_response with extstore enabled\n");
exit(EX_USAGE);
}
if (settings.udpport) {
fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n");
exit(EX_USAGE);
}
}
#endif
// Reserve this for the new default. If factor size hasn't changed, use
// new default.
/*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) {
settings.factor = 1.08;
}*/
if (slab_sizes_unparsed != NULL) {
if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) {
use_slab_sizes = true;
} else {
exit(EX_USAGE);
}
}
if (settings.hot_lru_pct + settings.warm_lru_pct > 80) {
fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n");
exit(EX_USAGE);
}
if (settings.temp_lru && !start_lru_maintainer) {
fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n");
exit(EX_USAGE);
}
if (hash_init(hash_type) != 0) {
fprintf(stderr, "Failed to initialize hash_algorithm!\n");
exit(EX_USAGE);
}
/*
* Use one workerthread to serve each UDP port if the user specified
* multiple ports
*/
if (settings.inter != NULL && strchr(settings.inter, ',')) {
settings.num_threads_per_udp = 1;
} else {
settings.num_threads_per_udp = settings.num_threads;
}
if (settings.sasl) {
if (!protocol_specified) {
settings.binding_protocol = binary_prot;
} else {
if (settings.binding_protocol != binary_prot) {
fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n");
exit(EX_USAGE);
}
}
}
if (udp_specified && settings.udpport != 0 && !tcp_specified) {
settings.port = settings.udpport;
}
if (maxcore != 0) {
struct rlimit rlim_new;
/*
* First try raising to infinity; if that fails, try bringing
* the soft limit to the hard.
*/
if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) {
/* failed. try raising just to the old max */
rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
(void)setrlimit(RLIMIT_CORE, &rlim_new);
}
}
/*
* getrlimit again to see what we ended up with. Only fail if
* the soft limit ends up 0, because then no core files will be
* created at all.
*/
if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) {
fprintf(stderr, "failed to ensure corefile creation\n");
exit(EX_OSERR);
}
}
/*
* If needed, increase rlimits to allow as many connections
* as needed.
*/
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to getrlimit number of files\n");
exit(EX_OSERR);
} else {
rlim.rlim_cur = settings.maxconns;
rlim.rlim_max = settings.maxconns;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n");
exit(EX_OSERR);
}
}
/* lose root privileges if we have them */
if (getuid() == 0 || geteuid() == 0) {
if (username == 0 || *username == '\0') {
fprintf(stderr, "can't run as root without the -u switch\n");
exit(EX_USAGE);
}
if ((pw = getpwnam(username)) == 0) {
fprintf(stderr, "can't find the user %s to switch to\n", username);
exit(EX_NOUSER);
}
if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
fprintf(stderr, "failed to assume identity of user %s\n", username);
exit(EX_OSERR);
}
}
/* Initialize Sasl if -S was specified */
if (settings.sasl) {
init_sasl();
}
/* daemonize if requested */
/* if we want to ensure our ability to dump core, don't chdir to / */
if (do_daemonize) {
if (sigignore(SIGHUP) == -1) {
perror("Failed to ignore SIGHUP");
}
if (daemonize(maxcore, settings.verbose) == -1) {
fprintf(stderr, "failed to daemon() in order to daemonize\n");
exit(EXIT_FAILURE);
}
}
/* lock paged memory if needed */
if (lock_memory) {
#ifdef HAVE_MLOCKALL
int res = mlockall(MCL_CURRENT | MCL_FUTURE);
if (res != 0) {
fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n",
strerror(errno));
}
#else
fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n");
#endif
}
/* initialize main thread libevent instance */
#if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101
/* If libevent version is larger/equal to 2.0.2-alpha, use newer version */
struct event_config *ev_config;
ev_config = event_config_new();
event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK);
main_base = event_base_new_with_config(ev_config);
event_config_free(ev_config);
#else
/* Otherwise, use older API */
main_base = event_init();
#endif
/* initialize other stuff */
logger_init();
stats_init();
assoc_init(settings.hashpower_init);
conn_init();
slabs_init(settings.maxbytes, settings.factor, preallocate,
use_slab_sizes ? slab_sizes : NULL);
#ifdef EXTSTORE
if (storage_file) {
enum extstore_res eres;
if (settings.ext_compact_under == 0) {
settings.ext_compact_under = ext_cf.page_count / 4;
/* Only rescues non-COLD items if below this threshold */
settings.ext_drop_under = ext_cf.page_count / 4;
}
crc32c_init();
/* Init free chunks to zero. */
for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) {
settings.ext_free_memchunks[x] = 0;
}
storage = extstore_init(storage_file, &ext_cf, &eres);
if (storage == NULL) {
fprintf(stderr, "Failed to initialize external storage: %s\n",
extstore_err(eres));
if (eres == EXTSTORE_INIT_OPEN_FAIL) {
perror("extstore open");
}
exit(EXIT_FAILURE);
}
ext_storage = storage;
/* page mover algorithm for extstore needs memory prefilled */
slabs_prefill_global();
}
#endif
/*
* ignore SIGPIPE signals; we can use errno == EPIPE if we
* need that information
*/
if (sigignore(SIGPIPE) == -1) {
perror("failed to ignore SIGPIPE; sigaction");
exit(EX_OSERR);
}
/* start up worker threads if MT mode */
#ifdef EXTSTORE
slabs_set_storage(storage);
memcached_thread_init(settings.num_threads, storage);
init_lru_crawler(storage);
#else
memcached_thread_init(settings.num_threads, NULL);
init_lru_crawler(NULL);
#endif
if (start_assoc_maint && start_assoc_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (start_lru_crawler && start_item_crawler_thread() != 0) {
fprintf(stderr, "Failed to enable LRU crawler thread\n");
exit(EXIT_FAILURE);
}
#ifdef EXTSTORE
if (storage && start_storage_compact_thread(storage) != 0) {
fprintf(stderr, "Failed to start storage compaction thread\n");
exit(EXIT_FAILURE);
}
if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) {
#else
if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) {
#endif
fprintf(stderr, "Failed to enable LRU maintainer thread\n");
return 1;
}
if (settings.slab_reassign &&
start_slab_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (settings.idle_timeout && start_conn_timeout_thread() == -1) {
exit(EXIT_FAILURE);
}
/* initialise clock event */
clock_handler(0, 0, 0);
/* create unix mode sockets after dropping privileges */
if (settings.socketpath != NULL) {
errno = 0;
if (server_socket_unix(settings.socketpath,settings.access)) {
vperror("failed to listen on UNIX socket: %s", settings.socketpath);
exit(EX_OSERR);
}
}
/* create the listening socket, bind it, and init */
if (settings.socketpath == NULL) {
const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME");
char *temp_portnumber_filename = NULL;
size_t len;
FILE *portnumber_file = NULL;
if (portnumber_filename != NULL) {
len = strlen(portnumber_filename)+4+1;
temp_portnumber_filename = malloc(len);
snprintf(temp_portnumber_filename,
len,
"%s.lck", portnumber_filename);
portnumber_file = fopen(temp_portnumber_filename, "a");
if (portnumber_file == NULL) {
fprintf(stderr, "Failed to open \"%s\": %s\n",
temp_portnumber_filename, strerror(errno));
}
}
errno = 0;
if (settings.port && server_sockets(settings.port, tcp_transport,
portnumber_file)) {
vperror("failed to listen on TCP port %d", settings.port);
exit(EX_OSERR);
}
/*
* initialization order: first create the listening sockets
* (may need root on low ports), then drop root if needed,
* then daemonize if needed, then init libevent (in some cases
* descriptors created by libevent wouldn't survive forking).
*/
/* create the UDP listening socket and bind it */
errno = 0;
if (settings.udpport && server_sockets(settings.udpport, udp_transport,
portnumber_file)) {
vperror("failed to listen on UDP port %d", settings.udpport);
exit(EX_OSERR);
}
if (portnumber_file) {
fclose(portnumber_file);
rename(temp_portnumber_filename, portnumber_filename);
}
if (temp_portnumber_filename)
free(temp_portnumber_filename);
}
/* Give the sockets a moment to open. I know this is dumb, but the error
* is only an advisory.
*/
usleep(1000);
if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) {
fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n");
exit(EXIT_FAILURE);
}
if (pid_file != NULL) {
save_pid(pid_file);
}
/* Drop privileges no longer needed */
if (settings.drop_privileges) {
drop_privileges();
}
/* Initialize the uriencode lookup table. */
uriencode_init();
/* enter the event loop */
if (event_base_loop(main_base, 0) != 0) {
retval = EXIT_FAILURE;
}
stop_assoc_maintenance_thread();
/* remove the PID file if we're a daemon */
if (do_daemonize)
remove_pidfile(pid_file);
/* Clean up strdup() call for bind() address */
if (settings.inter)
free(settings.inter);
if (l_socket)
free(l_socket);
if (u_socket)
free(u_socket);
/* cleanup base */
event_base_free(main_base);
return retval;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_19_0 |
crossvul-cpp_data_good_4718_2 | /*
* verify.c:
*
* Author:
* Mono Project (http://www.mono-project.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*/
#include <config.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/verify.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/opcodes.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/reflection.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/security-manager.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/mono-basic-block.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/monobitset.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
static gboolean verify_all = FALSE;
/*
* Set the desired level of checks for the verfier.
*
*/
void
mono_verifier_set_mode (MiniVerifierMode mode)
{
verifier_mode = mode;
}
void
mono_verifier_enable_verify_all ()
{
verify_all = TRUE;
}
#ifndef DISABLE_VERIFIER
/*
* Pull the list of opcodes
*/
#define OPDEF(a,b,c,d,e,f,g,h,i,j) \
a = i,
enum {
#include "mono/cil/opcode.def"
LAST = 0xff
};
#undef OPDEF
#ifdef MONO_VERIFIER_DEBUG
#define VERIFIER_DEBUG(code) do { code } while (0)
#else
#define VERIFIER_DEBUG(code)
#endif
//////////////////////////////////////////////////////////////////
#define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
#define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
#define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
#define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
#define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
#define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = __status; \
vinfo->info.message = ( __msg ); \
vinfo->exception_type = (__exception); \
(__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
} while (0)
//TODO support MONO_VERIFY_REPORT_ALL_ERRORS
#define ADD_VERIFY_ERROR(__ctx, __msg) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE(__ctx, __msg) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
#define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
#if SIZEOF_VOID_P == 4
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
#else
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
#endif
#define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
#define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
/*Flags to be used with ILCodeDesc::flags */
enum {
/*Instruction has not been processed.*/
IL_CODE_FLAG_NOT_PROCESSED = 0,
/*Instruction was decoded by mono_method_verify loop.*/
IL_CODE_FLAG_SEEN = 1,
/*Instruction was target of a branch or is at a protected block boundary.*/
IL_CODE_FLAG_WAS_TARGET = 2,
/*Used by stack_init to avoid double initialize each entry.*/
IL_CODE_FLAG_STACK_INITED = 4,
/*Used by merge_stacks to decide if it should just copy the eval stack.*/
IL_CODE_STACK_MERGED = 8,
/*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
IL_CODE_DELEGATE_SEQUENCE = 0x10,
/*This is a delegate created from a ldftn to a non final virtual method*/
IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
/*This is a call to a non final virtual method*/
IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
};
typedef enum {
RESULT_VALID,
RESULT_UNVERIFIABLE,
RESULT_INVALID
} verify_result_t;
typedef struct {
MonoType *type;
int stype;
MonoMethod *method;
} ILStackDesc;
typedef struct {
ILStackDesc *stack;
guint16 size, max_size;
guint16 flags;
} ILCodeDesc;
typedef struct {
int max_args;
int max_stack;
int verifiable;
int valid;
int level;
int code_size;
ILCodeDesc *code;
ILCodeDesc eval;
MonoType **params;
GSList *list;
/*Allocated fnptr MonoType that should be freed by us.*/
GSList *funptrs;
/*Type dup'ed exception types from catch blocks.*/
GSList *exception_types;
int num_locals;
MonoType **locals;
/*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
int target;
guint32 ip_offset;
MonoMethodSignature *signature;
MonoMethodHeader *header;
MonoGenericContext *generic_context;
MonoImage *image;
MonoMethod *method;
/*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0"
*on a method that creates a delegate for a non-final virtual method using ldftn*/
gboolean has_this_store;
/*This flag is used to control if the contructor of the parent class has been called.
*If the this pointer is pushed on the eval stack and it's a reference type constructor and
* super_ctor_called is false, the uninitialized flag is set on the pushed value.
*
* Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
* the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
*/
gboolean super_ctor_called;
guint32 prefix_set;
gboolean has_flags;
MonoType *constrained_type;
} VerifyContext;
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
static int
get_stack_type (MonoType *type);
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
static MonoGenericParam*
verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type);
//////////////////////////////////////////////////////////////////
enum {
TYPE_INV = 0, /* leave at 0. */
TYPE_I4 = 1,
TYPE_I8 = 2,
TYPE_NATIVE_INT = 3,
TYPE_R8 = 4,
/* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
TYPE_PTR = 5,
/* value types and classes */
TYPE_COMPLEX = 6,
/* Number of types, used to define the size of the tables*/
TYPE_MAX = 6,
/* Used by tables to signal that a result is not verifiable*/
NON_VERIFIABLE_RESULT = 0x80,
/*Mask used to extract just the type, excluding flags */
TYPE_MASK = 0x0F,
/* The stack type is a managed pointer, unmask the value to res */
POINTER_MASK = 0x100,
/*Stack type with the pointer mask*/
RAW_TYPE_MASK = 0x10F,
/* Controlled Mutability Manager Pointer */
CMMP_MASK = 0x200,
/* The stack type is a null literal*/
NULL_LITERAL_MASK = 0x400,
/**Used by ldarg.0 and family to let delegate verification happens.*/
THIS_POINTER_MASK = 0x800,
/**Signals that this is a boxed value type*/
BOXED_MASK = 0x1000,
/*This is an unitialized this ref*/
UNINIT_THIS_MASK = 0x2000,
};
static const char* const
type_names [TYPE_MAX + 1] = {
"Invalid",
"Int32",
"Int64",
"Native Int",
"Float64",
"Native Pointer",
"Complex"
};
enum {
PREFIX_UNALIGNED = 1,
PREFIX_VOLATILE = 2,
PREFIX_TAIL = 4,
PREFIX_CONSTRAINED = 8,
PREFIX_READONLY = 16
};
//////////////////////////////////////////////////////////////////
#ifdef ENABLE_VERIFIER_STATS
#define MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
#define MEM_FREE(amt) do { working_set -= (amt); } while (0)
static int allocated_memory;
static int working_set;
static int max_allocated_memory;
static int max_working_set;
static int total_allocated_memory;
static void
finish_collect_stats (void)
{
max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
max_working_set = MAX (max_working_set, working_set);
total_allocated_memory += allocated_memory;
allocated_memory = working_set = 0;
}
static void
init_verifier_stats (void)
{
static gboolean inited;
if (!inited) {
inited = TRUE;
mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
}
}
#else
#define MEM_ALLOC(amt) do {} while (0)
#define MEM_FREE(amt) do { } while (0)
#define finish_collect_stats()
#define init_verifier_stats()
#endif
//////////////////////////////////////////////////////////////////
/*Token validation macros and functions */
#define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
#define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
#define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
#define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
#define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
#define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
#define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
#define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
#define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
#define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
/*
* Verify if @token refers to a valid row on int's table.
*/
static gboolean
token_bounds_check (MonoImage *image, guint32 token)
{
if (image->dynamic)
return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
}
static MonoType *
mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
{
MonoType *res = g_new0 (MonoType, 1);
MEM_ALLOC (sizeof (MonoType));
//FIXME use mono_method_get_signature_full
res->data.method = mono_method_signature (method);
res->type = MONO_TYPE_FNPTR;
ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
return res;
}
/*
* mono_type_is_enum_type:
*
* Returns TRUE if @type is an enum type.
*/
static gboolean
mono_type_is_enum_type (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return TRUE;
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return TRUE;
return FALSE;
}
/*
* mono_type_is_value_type:
*
* Returns TRUE if @type is named after @namespace.@name.
*
*/
static gboolean
mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
{
return type->type == MONO_TYPE_VALUETYPE &&
!strcmp (namespace, type->data.klass->name_space) &&
!strcmp (name, type->data.klass->name);
}
/*
* Returns TURE if @type is VAR or MVAR
*/
static gboolean
mono_type_is_generic_argument (MonoType *type)
{
return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
}
/*
* mono_type_get_underlying_type_any:
*
* This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
*
* Returns the underlying type of @type regardless if it is byref or not.
*/
static MonoType*
mono_type_get_underlying_type_any (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return mono_class_enum_basetype (type->data.klass);
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return mono_class_enum_basetype (type->data.generic_class->container_class);
return type;
}
static G_GNUC_UNUSED const char*
mono_type_get_stack_name (MonoType *type)
{
return type_names [get_stack_type (type) & TYPE_MASK];
}
#define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
#define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
static gboolean
mono_method_is_constructor (MonoMethod *method)
{
return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
!(method->flags & CTOR_INVALID_FLAGS) &&
!strcmp (".ctor", method->name));
}
static gboolean
mono_class_has_default_constructor (MonoClass *klass)
{
MonoMethod *method;
int i;
mono_class_setup_methods (klass);
if (klass->exception_type)
return FALSE;
for (i = 0; i < klass->method.count; ++i) {
method = klass->methods [i];
if (mono_method_is_constructor (method) &&
mono_method_signature (method) &&
mono_method_signature (method)->param_count == 0 &&
(method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
return TRUE;
}
return FALSE;
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
*/
static gboolean
mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
{
int i;
MonoGenericInst *inst;
switch (type->type) {
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
if (!context)
return FALSE;
inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
return FALSE;
break;
case MONO_TYPE_SZARRAY:
return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context);
case MONO_TYPE_ARRAY:
return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context);
case MONO_TYPE_PTR:
return mono_type_is_valid_type_in_context (type->data.type, context);
case MONO_TYPE_GENERICINST:
inst = type->data.generic_class->context.class_inst;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context))
return FALSE;
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE: {
MonoClass *klass = type->data.klass;
/*
* It's possible to encode generic'sh types in such a way that they disguise themselves as class or valuetype.
* Fixing the type decoding is really tricky since under some cases this behavior is needed, for example, to
* have a 'class' type pointing to a 'genericinst' class.
*
* For the runtime these non canonical (weird) encodings work fine, they worst they can cause is some
* reflection oddities which are harmless - to security at least.
*/
if (klass->byval_arg.type != type->type)
return mono_type_is_valid_type_in_context (&klass->byval_arg, context);
break;
}
}
return TRUE;
}
/*This function returns NULL if the type is not instantiatable*/
static MonoType*
verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
{
MonoError error;
MonoType *result;
result = mono_class_inflate_generic_type_checked (type, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return NULL;
}
return result;
}
static gboolean
is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
MonoError error;
int i;
if (ginst->type_argc != gc->type_argc)
return FALSE;
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass *paramClass;
MonoClass **constraints;
MonoType *param_type = ginst->type_argv [i];
/*it's not our job to validate type variables*/
if (mono_type_is_generic_argument (param_type))
continue;
paramClass = mono_class_from_mono_type (param_type);
if (paramClass->exception_type != MONO_EXCEPTION_NONE)
return FALSE;
/* A GTD can't be a generic argument.
*
* Due to how types are encoded we must check for the case of a genericinst MonoType and GTD MonoClass.
* This happens in cases such as: class Foo<T> { void X() { new Bar<T> (); } }
*
* Open instantiations can have GTDs as this happens when one type is instantiated with others params
* and the former has an expansion into the later. For example:
* class B<K> {}
* class A<T>: B<K> {}
* The type A <K> has a parent B<K>, that is inflated into the GTD B<>.
* Since A<K> is open, thus not instantiatable, this is valid.
*/
if (paramClass->generic_container && param_type->type != MONO_TYPE_GENERICINST && !ginst->is_open)
return FALSE;
/*it's not safe to call mono_class_init from here*/
if (paramClass->generic_class && !paramClass->inited) {
if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
return FALSE;
}
if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
continue;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
return FALSE;
if (!param_info->constraints)
continue;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *inflated;
inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return FALSE;
}
ctr = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (!mono_class_is_assignable_from_slow (ctr, paramClass))
return FALSE;
}
}
return TRUE;
}
/*
* Return true if @candidate is constraint compatible with @target.
*
* This means that @candidate constraints are a super set of @target constaints
*/
static gboolean
mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoClass *candidate_param_class, MonoGenericContext *context)
{
MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
if ((tmask & cmask) != tmask)
return FALSE;
if (tinfo->constraints) {
MonoClass **target_class, **candidate_class;
for (target_class = tinfo->constraints; *target_class; ++target_class) {
MonoClass *tc;
MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
if (!inflated)
return FALSE;
tc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
/*
* A constraint from @target might inflate into @candidate itself and in that case we don't need
* check it's constraints since it satisfy the constraint by itself.
*/
if (mono_metadata_type_equal (&tc->byval_arg, &candidate_param_class->byval_arg))
continue;
if (!cinfo->constraints)
return FALSE;
for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
MonoClass *cc;
inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
if (!inflated)
return FALSE;
cc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (mono_class_is_assignable_from (tc, cc))
break;
/*
* This happens when we have the following:
*
* Bar<K> where K : IFace
* Foo<T, U> where T : U where U : IFace
* ...
* Bar<T> <- T here satisfy K constraint transitively through to U's constraint
*
*/
if (mono_type_is_generic_argument (&cc->byval_arg)) {
MonoGenericParam *other_candidate = verifier_get_generic_param_from_type (ctx, &cc->byval_arg);
if (mono_generic_param_is_constraint_compatible (ctx, target, other_candidate, cc, context)) {
break;
}
}
}
if (!*candidate_class)
return FALSE;
}
}
return TRUE;
}
static MonoGenericParam*
verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
{
MonoGenericContainer *gc;
MonoMethod *method = ctx->method;
int num;
num = mono_type_get_generic_param_num (type);
if (type->type == MONO_TYPE_VAR) {
MonoClass *gtd = method->klass;
if (gtd->generic_class)
gtd = gtd->generic_class->container_class;
gc = gtd->generic_container;
} else { //MVAR
MonoMethod *gmd = method;
if (method->is_inflated)
gmd = ((MonoMethodInflated*)method)->declaring;
gc = mono_method_get_generic_container (gmd);
}
if (!gc)
return NULL;
return mono_generic_container_get_param (gc, num);
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
* This means that it either
*/
static gboolean
is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
{
return mono_type_is_valid_type_in_context (type, ctx->generic_context);
}
static gboolean
is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
if (!is_valid_type_in_context (ctx, type))
return FALSE;
}
return TRUE;
}
static gboolean
generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
MonoGenericParam *target = mono_generic_container_get_param (gc, i);
MonoGenericParam *candidate;
MonoClass *candidate_class;
if (!mono_type_is_generic_argument (type))
continue;
if (!is_valid_type_in_context (ctx, type))
return FALSE;
candidate = verifier_get_generic_param_from_type (ctx, type);
candidate_class = mono_class_from_mono_type (type);
if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, candidate_class, context))
return FALSE;
}
return TRUE;
}
static gboolean
mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
}
static gboolean
mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = klass->generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = gklass->container_class->generic_container;
return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
}
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
if (!gc) /*non-generic inflated method - it's part of a generic type */
return TRUE;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
return FALSE;
return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
}
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = klass->generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = gklass->container_class->generic_container;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
return FALSE;
return is_valid_generic_instantiation (gc, &gklass->context, ginst);
}
static gboolean
mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
{
MonoClass *klass;
if (type == NULL) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return FALSE;
}
if (!is_valid_type_in_context (ctx, type)) {
char *str = mono_type_full_name (type);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
type->type == MONO_TYPE_VAR ? "!" : "!!",
str,
type->type == MONO_TYPE_VAR ? "class" : "method",
ctx->ip_offset),
MONO_EXCEPTION_BAD_IMAGE);
g_free (str);
return FALSE;
}
klass = mono_class_from_mono_type (type);
mono_class_init (klass);
if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
else
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
mono_loader_clear_error ();
return FALSE;
}
if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!klass->generic_class)
return TRUE;
if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!mono_class_repect_method_constraints (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s (generic args don't respect target's constraints) at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
return TRUE;
}
static verify_result_t
mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
{
if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
return RESULT_INVALID;
if (!method->is_inflated)
return RESULT_VALID;
if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset), MONO_EXCEPTION_UNVERIFIABLE_IL);
return RESULT_INVALID;
}
if (!mono_method_repect_method_constraints (ctx, method)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s (generic args don't respect target's constraints) at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset));
return RESULT_UNVERIFIABLE;
}
return RESULT_VALID;
}
static MonoClassField*
verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
MonoClassField *field;
MonoClass *klass = NULL;
if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
if (!field || !field->parent || !klass || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load field from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
return NULL;
if (mono_field_get_flags (field) & FIELD_ATTRIBUTE_LITERAL) {
char *type_name = mono_type_get_full_name (field->parent);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot reference literal field %s::%s at 0x%04x", type_name, field->name, ctx->ip_offset));
g_free (type_name);
return NULL;
}
*out_klass = klass;
return field;
}
static MonoMethod*
verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
MonoMethod* method;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid method token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
if (!method || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load method from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
return NULL;
return method;
}
static MonoType*
verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
MonoType* type;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
type = mono_type_get_full (ctx->image, token, ctx->generic_context);
if (!type || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load type from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, type))
return NULL;
return type;
}
/* stack_slot_get_type:
*
* Returns the stack type of @value. This value includes POINTER_MASK.
*
* Use this function to checks that account for a managed pointer.
*/
static gint32
stack_slot_get_type (ILStackDesc *value)
{
return value->stype & RAW_TYPE_MASK;
}
/* stack_slot_get_underlying_type:
*
* Returns the stack type of @value. This value does not include POINTER_MASK.
*
* Use this function is cases where the fact that the value could be a managed pointer is
* irrelevant. For example, field load doesn't care about this fact of type on stack.
*/
static gint32
stack_slot_get_underlying_type (ILStackDesc *value)
{
return value->stype & TYPE_MASK;
}
/* stack_slot_is_managed_pointer:
*
* Returns TRUE is @value is a managed pointer.
*/
static gboolean
stack_slot_is_managed_pointer (ILStackDesc *value)
{
return (value->stype & POINTER_MASK) == POINTER_MASK;
}
/* stack_slot_is_managed_mutability_pointer:
*
* Returns TRUE is @value is a managed mutability pointer.
*/
static G_GNUC_UNUSED gboolean
stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
{
return (value->stype & CMMP_MASK) == CMMP_MASK;
}
/* stack_slot_is_null_literal:
*
* Returns TRUE is @value is the null literal.
*/
static gboolean
stack_slot_is_null_literal (ILStackDesc *value)
{
return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
}
/* stack_slot_is_this_pointer:
*
* Returns TRUE is @value is the this literal
*/
static gboolean
stack_slot_is_this_pointer (ILStackDesc *value)
{
return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
}
/* stack_slot_is_boxed_value:
*
* Returns TRUE is @value is a boxed value
*/
static gboolean
stack_slot_is_boxed_value (ILStackDesc *value)
{
return (value->stype & BOXED_MASK) == BOXED_MASK;
}
static const char *
stack_slot_get_name (ILStackDesc *value)
{
return type_names [value->stype & TYPE_MASK];
}
#define APPEND_WITH_PREDICATE(PRED,NAME) do {\
if (PRED (value)) { \
if (!first) \
g_string_append (str, ", "); \
g_string_append (str, NAME); \
first = FALSE; \
} } while (0)
static char*
stack_slot_stack_type_full_name (ILStackDesc *value)
{
GString *str = g_string_new ("");
char *result;
gboolean has_pred = FALSE, first = TRUE;
if ((value->stype & TYPE_MASK) != value->stype) {
g_string_append(str, "[");
APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
has_pred = TRUE;
}
if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
if (!has_pred)
g_string_append(str, "[");
if (!first)
g_string_append (str, ", ");
g_string_append (str, "unboxed");
has_pred = TRUE;
}
if (has_pred)
g_string_append(str, "] ");
g_string_append (str, stack_slot_get_name (value));
result = str->str;
g_string_free (str, FALSE);
return result;
}
static char*
stack_slot_full_name (ILStackDesc *value)
{
char *type_name = mono_type_full_name (value->type);
char *stack_name = stack_slot_stack_type_full_name (value);
char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
g_free (type_name);
g_free (stack_name);
return res;
}
//////////////////////////////////////////////////////////////////
void
mono_free_verify_list (GSList *list)
{
MonoVerifyInfoExtended *info;
GSList *tmp;
for (tmp = list; tmp; tmp = tmp->next) {
info = tmp->data;
g_free (info->info.message);
g_free (info);
}
g_slist_free (list);
}
#define ADD_ERROR(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = MONO_VERIFY_ERROR; \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_WARN(list,code,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = (code); \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_INVALID(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->status = MONO_VERIFY_ERROR; \
vinfo->message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
/*G_BREAKPOINT ();*/ \
goto invalid_cil; \
} while (0)
#define CHECK_STACK_UNDERFLOW(num) \
do { \
if (cur_stack < (num)) \
ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
} while (0)
#define CHECK_STACK_OVERFLOW() \
do { \
if (cur_stack >= max_stack) \
ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
} while (0)
static int
in_any_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* in_any_exception_block:
*
* Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
*/
static gboolean
in_any_exception_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return TRUE;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return TRUE;
}
return FALSE;
}
/*
* is_valid_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with br and brtrue/false.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
* The major diferent from other similiar functions is that branching into a
* finally/fault block is invalid instead of just unverifiable.
*/
static int
is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching into a finally block is invalid*/
if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
!MONO_OFFSET_IN_HANDLER (clause, offset) &&
MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 1;
}
return 0;
}
/*
* is_valid_cmp_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with binary comparison branching instruction, like beq, bge and similars.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
*
* The major diferences from other similar functions are that most errors lead to invalid
* code and only branching out of finally, filter or fault clauses is unverifiable.
*/
static int
is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching out of a handler or finally*/
if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
MONO_OFFSET_IN_HANDLER (clause, offset) &&
!MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 2;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 2;
}
return 0;
}
/*
* A leave can't escape a finally block
*/
static int
is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
return 0;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 0;
}
return 1;
}
/*
* A rethrow can't happen outside of a catch handler.
*/
static int
is_correct_rethrow (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* An endfinally can't happen outside of a finally/fault handler.
*/
static int
is_correct_endfinally (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
return 1;
}
return 0;
}
/*
* An endfilter can only happens inside a filter clause.
* In non-strict mode filter is allowed inside the handler clause too
*/
static MonoExceptionClause *
is_correct_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
continue;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return clause;
if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
return clause;
}
return NULL;
}
/*
* Non-strict endfilter can happens inside a try block or any handler block
*/
static int
is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
}
return 0;
}
static gboolean
is_valid_bool_arg (ILStackDesc *arg)
{
if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
return TRUE;
switch (stack_slot_get_underlying_type (arg)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_PTR:
return TRUE;
case TYPE_COMPLEX:
g_assert (arg->type);
switch (arg->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
return TRUE;
case MONO_TYPE_GENERICINST:
/*We need to check if the container class
* of the generic type is a valuetype, iow:
* is it a "class Foo<T>" or a "struct Foo<T>"?
*/
return !arg->type->data.generic_class->container_class->valuetype;
}
default:
return FALSE;
}
}
/*Type manipulation helper*/
/*Returns the byref version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byref (MonoType *type)
{
if (type->byref)
return type;
return &mono_class_from_mono_type (type)->this_arg;
}
/*Returns the byval version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byval (MonoType *type)
{
if (!type->byref)
return type;
return &mono_class_from_mono_type (type)->byval_arg;
}
static MonoType*
mono_type_from_stack_slot (ILStackDesc *slot)
{
if (stack_slot_is_managed_pointer (slot))
return mono_type_get_type_byref (slot->type);
return slot->type;
}
/*Stack manipulation code*/
static void
ensure_stack_size (ILCodeDesc *stack, int required)
{
int new_size = 8;
ILStackDesc *tmp;
if (required < stack->max_size)
return;
/* We don't have to worry about the exponential growth since stack_copy prune unused space */
new_size = MAX (8, MAX (required, stack->max_size * 2));
g_assert (new_size >= stack->size);
g_assert (new_size >= required);
tmp = g_new0 (ILStackDesc, new_size);
MEM_ALLOC (sizeof (ILStackDesc) * new_size);
if (stack->stack) {
if (stack->size)
memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
g_free (stack->stack);
MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
}
stack->stack = tmp;
stack->max_size = new_size;
}
static void
stack_init (VerifyContext *ctx, ILCodeDesc *state)
{
if (state->flags & IL_CODE_FLAG_STACK_INITED)
return;
state->size = state->max_size = 0;
state->flags |= IL_CODE_FLAG_STACK_INITED;
}
static void
stack_copy (ILCodeDesc *to, ILCodeDesc *from)
{
ensure_stack_size (to, from->size);
to->size = from->size;
/*stack copy happens at merge points, which have small stacks*/
if (from->size)
memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
}
static void
copy_stack_value (ILStackDesc *to, ILStackDesc *from)
{
to->stype = from->stype;
to->type = from->type;
to->method = from->method;
}
static int
check_underflow (VerifyContext *ctx, int size)
{
if (ctx->eval.size < size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
return 0;
}
return 1;
}
static int
check_overflow (VerifyContext *ctx)
{
if (ctx->eval.size >= ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
return 0;
}
return 1;
}
/*This reject out PTR, FNPTR and TYPEDBYREF*/
static gboolean
check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
{
if (stack_slot_get_type (value) == TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
/*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
static gboolean
check_unverifiable_type (VerifyContext *ctx, MonoType *type)
{
if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
static ILStackDesc *
stack_push (VerifyContext *ctx)
{
g_assert (ctx->eval.size < ctx->max_stack);
g_assert (ctx->eval.size <= ctx->eval.max_size);
ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
return & ctx->eval.stack [ctx->eval.size++];
}
static ILStackDesc *
stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
{
ILStackDesc *top = stack_push (ctx);
top->stype = stype;
top->type = type;
return top;
}
static ILStackDesc *
stack_pop (VerifyContext *ctx)
{
ILStackDesc *ret;
g_assert (ctx->eval.size > 0);
ret = ctx->eval.stack + --ctx->eval.size;
if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
return ret;
}
/* This function allows to safely pop an unititialized this ptr from
* the eval stack without marking the method as unverifiable.
*/
static ILStackDesc *
stack_pop_safe (VerifyContext *ctx)
{
g_assert (ctx->eval.size > 0);
return ctx->eval.stack + --ctx->eval.size;
}
/*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
static ILStackDesc*
stack_peek (VerifyContext *ctx, int distance)
{
g_assert (ctx->eval.size - distance > 0);
return ctx->eval.stack + (ctx->eval.size - 1 - distance);
}
static ILStackDesc *
stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
{
ILStackDesc *top = stack_push (ctx);
copy_stack_value (top, value);
return top;
}
/* Returns the MonoType associated with the token, or NULL if it is invalid.
*
* A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
* */
static MonoType*
get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
{
MonoType *type;
MonoClass *class;
if (!(type = verifier_load_type (ctx, token, opcode)))
return NULL;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_TYPEDBYREF)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
if (!(class = mono_class_from_mono_type (type)))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset));
check_unverifiable_type (ctx, type);
return type;
}
/*operation result tables */
static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
};
static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
#ifdef MONO_VERIFIER_DEBUG
/*debug helpers */
static void
dump_stack_value (ILStackDesc *value)
{
printf ("[(%x)(%x)", value->type->type, value->stype);
if (stack_slot_is_this_pointer (value))
printf ("[this] ");
if (stack_slot_is_boxed_value (value))
printf ("[boxed] ");
if (stack_slot_is_null_literal (value))
printf ("[null] ");
if (stack_slot_is_managed_mutability_pointer (value))
printf ("Controled Mutability MP: ");
if (stack_slot_is_managed_pointer (value))
printf ("Managed Pointer to: ");
switch (stack_slot_get_underlying_type (value)) {
case TYPE_INV:
printf ("invalid type]");
return;
case TYPE_I4:
printf ("int32]");
return;
case TYPE_I8:
printf ("int64]");
return;
case TYPE_NATIVE_INT:
printf ("native int]");
return;
case TYPE_R8:
printf ("float64]");
return;
case TYPE_PTR:
printf ("unmanaged pointer]");
return;
case TYPE_COMPLEX:
switch (value->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE:
printf ("complex] (%s)", value->type->data.klass->name);
return;
case MONO_TYPE_STRING:
printf ("complex] (string)");
return;
case MONO_TYPE_OBJECT:
printf ("complex] (object)");
return;
case MONO_TYPE_SZARRAY:
printf ("complex] (%s [])", value->type->data.klass->name);
return;
case MONO_TYPE_ARRAY:
printf ("complex] (%s [%d %d %d])",
value->type->data.array->eklass->name,
value->type->data.array->rank,
value->type->data.array->numsizes,
value->type->data.array->numlobounds);
return;
case MONO_TYPE_GENERICINST:
printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
return;
case MONO_TYPE_VAR:
printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
case MONO_TYPE_MVAR:
printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
default: {
//should be a boxed value
char * name = mono_type_full_name (value->type);
printf ("complex] %s", name);
g_free (name);
return;
}
}
default:
printf ("unknown stack %x type]\n", value->stype);
g_assert_not_reached ();
}
}
static void
dump_stack_state (ILCodeDesc *state)
{
int i;
printf ("(%d) ", state->size);
for (i = 0; i < state->size; ++i)
dump_stack_value (state->stack + i);
printf ("\n");
}
#endif
/*Returns TRUE if candidate array type can be assigned to target.
*Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
*/
static gboolean
is_array_type_compatible (MonoType *target, MonoType *candidate)
{
MonoArrayType *left = target->data.array;
MonoArrayType *right = candidate->data.array;
g_assert (target->type == MONO_TYPE_ARRAY);
g_assert (candidate->type == MONO_TYPE_ARRAY);
if (left->rank != right->rank)
return FALSE;
return mono_class_is_assignable_from (left->eklass, right->eklass);
}
static int
get_stack_type (MonoType *type)
{
int mask = 0;
int type_kind = type->type;
if (type->byref)
mask = POINTER_MASK;
/*TODO handle CMMP_MASK */
handle_enum:
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
return TYPE_I4 | mask;
case MONO_TYPE_I:
case MONO_TYPE_U:
return TYPE_NATIVE_INT | mask;
/* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
return TYPE_PTR | mask;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
return TYPE_COMPLEX | mask;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return TYPE_I8 | mask;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
return TYPE_R8 | mask;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
type = mono_type_get_underlying_type_any (type);
if (!type)
return FALSE;
type_kind = type->type;
goto handle_enum;
} else {
return TYPE_COMPLEX | mask;
}
default:
return TYPE_INV;
}
}
/* convert MonoType to ILStackDesc format (stype) */
static gboolean
set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
{
int mask = 0;
int type_kind = type->type;
if (type->byref || take_addr)
mask = POINTER_MASK;
/* TODO handle CMMP_MASK */
handle_enum:
stack->type = type;
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
stack->stype = TYPE_I4 | mask;
break;
case MONO_TYPE_I:
case MONO_TYPE_U:
stack->stype = TYPE_NATIVE_INT | mask;
break;
/*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
stack->stype = TYPE_PTR | mask;
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
stack->stype = TYPE_COMPLEX | mask;
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
stack->stype = TYPE_I8 | mask;
break;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
stack->stype = TYPE_R8 | mask;
break;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
MonoType *utype = mono_type_get_underlying_type_any (type);
if (!utype) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
return FALSE;
}
type = utype;
type_kind = type->type;
goto handle_enum;
} else {
stack->stype = TYPE_COMPLEX | mask;
break;
}
default:
VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
return FALSE;
}
return TRUE;
}
/*
* init_stack_with_value_at_exception_boundary:
*
* Initialize the stack and push a given type.
* The instruction is marked as been on the exception boundary.
*/
static void
init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
{
MonoError error;
MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_get_full_name (klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
g_free (name);
mono_error_cleanup (&error);
return;
}
if (!ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
return;
}
stack_init (ctx, code);
ensure_stack_size (code, 1);
set_stack_value (ctx, code->stack, type, FALSE);
ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
code->size = 1;
code->flags |= IL_CODE_FLAG_WAS_TARGET;
if (mono_type_is_generic_argument (type))
code->stack->stype |= BOXED_MASK;
}
/*Verify if type 'candidate' can be stored in type 'target'.
*
* If strict, check for the underlying type and not the verification stack types
*/
static gboolean
verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
{
#define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
MonoType *original_candidate = candidate;
VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
/*only one is byref */
if (candidate->byref ^ target->byref) {
/* converting from native int to byref*/
if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
return TRUE;
}
return FALSE;
}
strict |= target->byref;
/*From now on we don't care about byref anymore, so it's ok to discard it here*/
candidate = mono_type_get_underlying_type_any (candidate);
handle_enum:
switch (target->type) {
case MONO_TYPE_VOID:
return candidate->type == MONO_TYPE_VOID;
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
case MONO_TYPE_I4:
case MONO_TYPE_U4: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
case MONO_TYPE_R4:
case MONO_TYPE_R8:
if (strict)
return candidate->type == target->type;
return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
case MONO_TYPE_I:
case MONO_TYPE_U: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_PTR:
if (candidate->type != MONO_TYPE_PTR)
return FALSE;
/* check the underlying type */
return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
case MONO_TYPE_FNPTR: {
MonoMethodSignature *left, *right;
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
left = mono_type_get_signature (target);
right = mono_type_get_signature (candidate);
return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
}
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (mono_class_is_nullable (target_klass)) {
if (!mono_class_is_nullable (candidate_klass))
return FALSE;
return target_klass == candidate_klass;
}
return mono_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_STRING:
return candidate->type == MONO_TYPE_STRING;
case MONO_TYPE_CLASS:
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
if (candidate->type == MONO_TYPE_VALUETYPE)
return FALSE;
/* If candidate is an enum it should return true for System.Enum and supertypes.
* That's why here we use the original type and not the underlying type.
*/
return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_SZARRAY: {
MonoClass *left;
MonoClass *right;
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
left = mono_class_from_mono_type (target);
right = mono_class_from_mono_type (candidate);
return mono_class_is_assignable_from (left, right);
}
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_TYPEDBYREF:
return candidate->type == MONO_TYPE_TYPEDBYREF;
case MONO_TYPE_VALUETYPE: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (candidate->type == MONO_TYPE_CLASS)
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (target_klass == candidate_klass)
return TRUE;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
return FALSE;
}
case MONO_TYPE_VAR:
if (candidate->type != MONO_TYPE_VAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
case MONO_TYPE_MVAR:
if (candidate->type != MONO_TYPE_MVAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
default:
VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
return 1;
#undef IS_ONE_OF3
#undef IS_ONE_OF2
}
static gboolean
verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
{
return verify_type_compatibility_full (ctx, target, candidate, FALSE);
}
/*
* Returns the generic param bound to the context been verified.
*
*/
static MonoGenericParam*
get_generic_param (VerifyContext *ctx, MonoType *param)
{
guint16 param_num = mono_type_get_generic_param_num (param);
if (param->type == MONO_TYPE_VAR) {
if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
return NULL;
}
return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
}
/*param must be a MVAR */
if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
return NULL;
}
return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
}
static gboolean
recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
{
MonoType *constraint_type = &constraint_class->byval_arg;
if (recursion_level <= 0)
return FALSE;
if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
return TRUE;
if (mono_type_is_generic_argument (constraint_type)) {
MonoGenericParam *param = get_generic_param (ctx, constraint_type);
MonoClass **class;
if (!param)
return FALSE;
for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1))
return TRUE;
}
}
return FALSE;
}
/*
* is_compatible_boxed_valuetype:
*
* Returns TRUE if @candidate / @stack is a valid boxed valuetype.
*
* @type The source type. It it tested to be of the proper type.
* @candidate type of the boxed valuetype.
* @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
* @strict if TRUE candidate must be boxed compatible to the target type
*
*/
static gboolean
is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
{
if (!stack_slot_is_boxed_value (stack))
return FALSE;
if (type->byref || candidate->byref)
return FALSE;
if (mono_type_is_generic_argument (candidate)) {
MonoGenericParam *param = get_generic_param (ctx, candidate);
MonoClass **class;
if (!param)
return FALSE;
for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
/*256 should be enough since there can't be more than 255 generic arguments.*/
if (recursive_boxed_constraint_type_check (ctx, type, *class, 256))
return TRUE;
}
}
if (mono_type_is_generic_argument (type))
return FALSE;
if (!strict)
return TRUE;
return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
}
static int
verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
{
MonoType *candidate = mono_type_from_stack_slot (stack);
if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
return TRUE;
if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
return TRUE;
if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
return FALSE;
if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
return FALSE;
if (drop_byref)
return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
return verify_type_compatibility_full (ctx, type, candidate, FALSE);
}
static int
verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
{
return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
}
static gboolean
mono_delegate_type_equal (MonoType *target, MonoType *candidate)
{
if (candidate->byref ^ target->byref)
return FALSE;
switch (target->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_TYPEDBYREF:
return candidate->type == target->type;
case MONO_TYPE_PTR:
return mono_delegate_type_equal (target->data.type, candidate->data.type);
case MONO_TYPE_FNPTR:
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
/*FIXME handle nullables and enum*/
return mono_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_CLASS:
return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
case MONO_TYPE_SZARRAY:
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_VALUETYPE:
/*FIXME handle nullables and enum*/
return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
case MONO_TYPE_VAR:
return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
case MONO_TYPE_MVAR:
return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
default:
VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
}
static gboolean
mono_delegate_param_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (method, delegate);
}
static gboolean
mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (delegate, method);
}
/*
* mono_delegate_signature_equal:
*
* Compare two signatures in the way expected by delegates.
*
* This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
*
* FIXME can this function be eliminated and proper metadata functionality be used?
*/
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
{
int i;
int method_offset = is_static_ldftn ? 1 : 0;
if (delegate_sig->param_count + method_offset != method_sig->param_count)
return FALSE;
if (delegate_sig->call_convention != method_sig->call_convention)
return FALSE;
for (i = 0; i < delegate_sig->param_count; i++) {
MonoType *p1 = delegate_sig->params [i];
MonoType *p2 = method_sig->params [i + method_offset];
if (!mono_delegate_param_equal (p1, p2))
return FALSE;
}
if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
return FALSE;
return TRUE;
}
gboolean
mono_verifier_is_signature_compatible (MonoMethodSignature *target, MonoMethodSignature *candidate)
{
return mono_delegate_signature_equal (target, candidate, FALSE);
}
/*
* verify_ldftn_delegate:
*
* Verify properties of ldftn based delegates.
*/
static void
verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
MonoMethod *method = funptr->method;
/*ldftn non-final virtuals only allowed if method is not static,
* the object is a this arg (comes from a ldarg.0), and there is no starg.0.
* This rules doesn't apply if the object on stack is a boxed valuetype.
*/
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
/*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
/*current method must not be static*/
if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
/*value is the this pointer, loaded using ldarg.0 */
if (!stack_slot_is_this_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at 0x%04x", ctx->ip_offset));
ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
}
}
/*
* verify_delegate_compatibility:
*
* Verify delegate creation sequence.
*
*/
static void
verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
#define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
#define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
MonoMethod *invoke, *method;
const guint8 *ip = ctx->header->code;
guint32 ip_offset = ctx->ip_offset;
gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
invoke = mono_get_delegate_invoke (delegate);
method = funptr->method;
if (!method || !mono_method_signature (method)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
if (!invoke || !mono_method_signature (invoke)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
if (is_static_ldftn)
is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer signature '%s' doesn't match delegate's signature '%s' at 0x%04x", fun_sig, invoke_sig, ctx->ip_offset));
g_free (fun_sig);
g_free (invoke_sig);
}
/*
* Delegate code sequences:
* [-6] ldftn token
* newobj ...
*
*
* [-7] dup
* [-6] ldvirtftn token
* newobj ...
*
* ldftn sequence:*/
if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
verify_ldftn_delegate (ctx, delegate, value, funptr);
} else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
}else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
}
ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
//general tests
if (is_first_arg_bound) {
if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_STATIC) {
if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
}
}
if (stack_slot_get_type (value) != TYPE_COMPLEX)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
#undef IS_VALID_OPCODE
#undef IS_LOAD_FUN_PTR
}
/* implement the opcode checks*/
static void
push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
{
ILStackDesc *top;
if (arg >= ctx->max_args) {
if (take_addr)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->params [arg]);
if (ctx->params [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
top = stack_push (ctx);
if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
return;
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
if (take_addr)
ctx->has_this_store = TRUE;
else
top->stype |= THIS_POINTER_MASK;
if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
top->stype |= UNINIT_THIS_MASK;
}
}
}
static void
push_local (VerifyContext *ctx, guint32 arg, int take_addr)
{
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->locals [arg]);
if (ctx->locals [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
}
}
static void
store_arg (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->max_args) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
if (check_underflow (ctx, 1))
stack_pop (ctx);
return;
}
if (check_underflow (ctx, 1)) {
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
}
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
ctx->has_this_store = 1;
}
static void
store_local (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
return;
}
/*TODO verify definite assigment */
if (check_underflow (ctx, 1)) {
value = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
char *expected = mono_type_full_name (ctx->locals [arg]);
char *found = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
found,
arg,
expected,
ctx->ip_offset));
g_free (expected);
g_free (found);
}
}
}
/*FIXME add and sub needs special care here*/
static void
do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b, *top;
int idxa, idxb, complexMerge = 0;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a)) {
idxa = TYPE_PTR;
complexMerge = 1;
}
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b)) {
idxb = TYPE_PTR;
complexMerge = 2;
}
--idxa;
--idxb;
res = table [idxa][idxb];
VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
top = stack_push (ctx);
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
copy_stack_value (top, a);
return;
}
if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
res = res & ~NON_VERIFIABLE_RESULT;
}
if (complexMerge && res == TYPE_PTR) {
if (complexMerge == 1)
copy_stack_value (top, a);
else if (complexMerge == 2)
copy_stack_value (top, b);
/*
* There is no need to merge the type of two pointers.
* The only valid operation is subtraction, that returns a native
* int as result and can be used with any 2 pointer kinds.
* This is valid acording to Patition III 1.1.4
*/
} else
top->stype = res;
}
static void
do_boolean_branch_op (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
ILStackDesc *top;
VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (!is_valid_bool_arg (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
check_unmanaged_pointer (ctx, top);
}
static gboolean
stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
{
return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
}
static void
do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
int target = ctx->ip_offset + delta;
VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1: /*FIXME use constants and not magic numbers.*/
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx,
g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
}
static void
do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
if (opcode == CEE_CGT_UN) {
if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
return;
}
}
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
if(res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
static void
do_ret (VerifyContext *ctx)
{
MonoType *ret = ctx->signature->ret;
VERIFIER_DEBUG ( printf ("checking ret\n"); );
if (ret->type != MONO_TYPE_VOID) {
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
return;
}
if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
}
if (ctx->eval.size > 0) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
}
if (in_any_block (ctx->header, ctx->ip_offset))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
}
/*
* FIXME we need to fix the case of a non-virtual instance method defined in the parent but call using a token pointing to a subclass.
* This is illegal but mono_get_method_full decoded it.
* TODO handle calling .ctor outside one or calling the .ctor for other class but super
*/
static void
do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
{
int param_count, i;
MonoMethodSignature *sig;
ILStackDesc *value;
MonoMethod *method;
gboolean virt_check_this = FALSE;
gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
return;
if (virtual) {
CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
if (method->klass->valuetype) // && !constrained ???
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_STATIC))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
virt_check_this = TRUE;
ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
}
}
if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
sig = mono_method_get_signature (method, ctx->image, method_token);
if (!sig) {
char *name = mono_type_get_full_name (method->klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
g_free (name);
return;
}
param_count = sig->param_count + sig->hasthis;
if (!check_underflow (ctx, param_count))
return;
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset));
if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot pass a byref argument to a tail %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset));
return;
}
}
if (sig->hasthis) {
MonoType *type = &method->klass->byval_arg;
ILStackDesc copy;
if (mono_method_is_constructor (method) && !method->klass->valuetype) {
if (!mono_method_is_constructor (ctx->method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor to a type diferent that this or super at 0x%04x", ctx->ip_offset));
ctx->super_ctor_called = TRUE;
value = stack_pop_safe (ctx);
if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
} else {
value = stack_pop (ctx);
}
copy_stack_value (©, value);
//TODO we should extract this to a 'drop_byref_argument' and use everywhere
//Other parts of the code suffer from the same issue of
copy.type = mono_type_get_type_byval (copy.type);
copy.stype &= ~POINTER_MASK;
if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset));
if (constrained && virtual) {
if (!stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
copy.stype |= BOXED_MASK;
} else {
if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset));
if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset));
}
if (!verify_stack_type_compatibility (ctx, type, ©)) {
char *expected = mono_type_full_name (type);
char *effective = stack_slot_full_name (©);
char *method_name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x",
expected, effective, method_name, ctx->ip_offset));
g_free (method_name);
g_free (effective);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
} else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
if (sig->ret->type != MONO_TYPE_VOID) {
if (!mono_type_is_valid_in_context (ctx, sig->ret))
return;
if (check_overflow (ctx)) {
value = stack_push (ctx);
set_stack_value (ctx, value, sig->ret, FALSE);
if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
ctx->prefix_set &= ~PREFIX_READONLY;
value->stype |= CMMP_MASK;
}
}
}
if ((ctx->prefix_set & PREFIX_TAIL)) {
if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
}
}
static void
do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
{
MonoClassField *field;
MonoClass *klass;
if (!check_overflow (ctx))
return;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
return;
}
/*taking the address of initonly field only works from the static constructor */
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
}
static void
do_store_static_field (VerifyContext *ctx, int token) {
MonoClassField *field;
MonoClass *klass;
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
return;
}
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
return;
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
if (!verify_stack_type_compatibility (ctx, field->type, value)) {
char *stack_name = stack_slot_full_name (value);
char *field_name = mono_type_full_name (field->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type in static field store expected '%s' but found '%s' at 0x%04x",
field_name, stack_name, ctx->ip_offset));
g_free (field_name);
g_free (stack_name);
}
}
static gboolean
check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
{
MonoClassField *field;
MonoClass *klass;
gboolean is_pointer;
/*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
return FALSE;
*ret_field = field;
//the value on stack is going to be used as a pointer
is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
return FALSE;
}
g_assert (obj->type);
/*The value on the stack must be a subclass of the defining type of the field*/
/* we need to check if we can load the field from the stack value*/
if (is_pointer) {
if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
} else {
if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a managed pointer to a reference type and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
/*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
char *found = stack_slot_full_name (obj);
char *expected = mono_type_full_name (&field->parent->byval_arg);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
g_free (found);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
}
check_unmanaged_pointer (ctx, obj);
return TRUE;
}
static void
do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
{
ILStackDesc *obj;
MonoClassField *field;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
return;
if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
}
static void
do_store_field (VerifyContext *ctx, int token)
{
ILStackDesc *value, *obj;
MonoClassField *field;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
value = stack_pop (ctx);
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
return;
if (!verify_stack_type_compatibility (ctx, field->type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
/*TODO proper handle for Nullable<T>*/
static void
do_box_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
MonoClass *klass;
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*box is a nop for reference types*/
if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
return;
}
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
klass = mono_class_from_mono_type (type);
if (mono_class_is_nullable (klass))
type = &mono_class_get_nullable_param (klass)->byval_arg;
stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
}
static void
do_unbox_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
if (!mono_class_from_mono_type (type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
value->stype |= CMMP_MASK;
}
static void
do_unbox_any (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_unary_math_op (VerifyContext *ctx, int op)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
break;
case TYPE_R8:
if (op == CEE_NEG)
break;
case TYPE_COMPLEX: /*only enums are ok*/
if (mono_type_is_enum_type (value->type))
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
}
stack_push_stack_val (ctx, value);
}
static void
do_conversion (VerifyContext *ctx, int kind)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_R8:
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation. Numeric type expected at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
switch (kind) {
case TYPE_I4:
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
break;
case TYPE_I8:
stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
break;
case TYPE_R8:
stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
break;
case TYPE_NATIVE_INT:
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
break;
default:
g_error ("unknown type %02x in conversion", kind);
}
}
static void
do_load_token (VerifyContext *ctx, int token)
{
gpointer handle;
MonoClass *handle_class;
if (!check_overflow (ctx))
return;
switch (token & 0xff000000) {
case MONO_TOKEN_TYPE_DEF:
case MONO_TOKEN_TYPE_REF:
case MONO_TOKEN_TYPE_SPEC:
case MONO_TOKEN_FIELD_DEF:
case MONO_TOKEN_METHOD_DEF:
case MONO_TOKEN_METHOD_SPEC:
case MONO_TOKEN_MEMBER_REF:
if (!token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Table index out of range 0x%x for token %x for ldtoken at 0x%04x", mono_metadata_token_index (token), token, ctx->ip_offset));
return;
}
break;
default:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid table 0x%x for token 0x%x for ldtoken at 0x%04x", mono_metadata_token_table (token), token, ctx->ip_offset));
return;
}
handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
if (!handle) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
return;
}
if (handle_class == mono_defaults.typehandle_class) {
mono_type_is_valid_in_context (ctx, (MonoType*)handle);
} else if (handle_class == mono_defaults.methodhandle_class) {
mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
} else if (handle_class == mono_defaults.fieldhandle_class) {
mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
} else {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
}
stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
}
static void
do_ldobj_value (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)
&& stack_slot_get_type (value) != TYPE_NATIVE_INT
&& !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
return;
}
if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
/*We have a byval on the stack, but the comparison must be strict. */
if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_stobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, type, src)) {
char *type_name = mono_type_full_name (type);
char *src_name = stack_slot_full_name (src);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token '%s' and source '%s' of stobj don't match ' at 0x%04x", type_name, src_name, ctx->ip_offset));
g_free (type_name);
g_free (src_name);
}
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_cpobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (src))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_initobj (VerifyContext *ctx, int token)
{
ILStackDesc *obj;
MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
obj = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
stack = mono_type_get_type_byval (obj->type);
if (MONO_TYPE_IS_REFERENCE (stack)) {
if (!verify_type_compatibility (ctx, stack, type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility (ctx, stack, type)) {
char *expected_name = mono_type_full_name (type);
char *stack_name = mono_type_full_name (stack);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Initobj %s not compatible with value on stack %s at 0x%04x", expected_name, stack_name, ctx->ip_offset));
g_free (expected_name);
g_free (stack_name);
}
}
static void
do_newobj (VerifyContext *ctx, int token)
{
ILStackDesc *value;
int i;
MonoMethodSignature *sig;
MonoMethod *method;
gboolean is_delegate = FALSE;
if (!(method = verifier_load_method (ctx, token, "newobj")))
return;
if (!mono_method_is_constructor (method)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
return;
}
if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *from = mono_method_full_name (ctx->method, TRUE);
char *to = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor %s not visible from %s at 0x%04x", to, from, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (from);
g_free (to);
}
//FIXME use mono_method_get_signature_full
sig = mono_method_signature (method);
if (!sig) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
return;
}
if (!sig->hasthis) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature missing hasthis at 0x%04x", ctx->ip_offset));
return;
}
if (!check_underflow (ctx, sig->param_count))
return;
is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
if (is_delegate) {
ILStackDesc *funptr;
//first arg is object, second arg is fun ptr
if (sig->param_count != 2) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
funptr = stack_pop (ctx);
value = stack_pop (ctx);
verify_delegate_compatibility (ctx, method->klass, value, funptr);
} else {
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with constructor signature: %s X %s at 0x%04x", sig_name, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
}
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
}
static void
do_cast (VerifyContext *ctx, int token, const char *opcode) {
ILStackDesc *value;
MonoType *type;
gboolean is_boxed;
gboolean do_box;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, opcode)))
return;
if (type->byref) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
return;
}
value = stack_pop (ctx);
is_boxed = stack_slot_is_boxed_value (value);
if (stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
char *name = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset));
g_free (name);
}
switch (value->type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
}
do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
}
static MonoType *
mono_type_from_opcode (int opcode) {
switch (opcode) {
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_STIND_I1:
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_STELEM_I1:
return &mono_defaults.sbyte_class->byval_arg;
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_STIND_I2:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_STELEM_I2:
return &mono_defaults.int16_class->byval_arg;
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_STIND_I4:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_STELEM_I4:
return &mono_defaults.int32_class->byval_arg;
case CEE_LDIND_I8:
case CEE_STIND_I8:
case CEE_LDELEM_I8:
case CEE_STELEM_I8:
return &mono_defaults.int64_class->byval_arg;
case CEE_LDIND_R4:
case CEE_STIND_R4:
case CEE_LDELEM_R4:
case CEE_STELEM_R4:
return &mono_defaults.single_class->byval_arg;
case CEE_LDIND_R8:
case CEE_STIND_R8:
case CEE_LDELEM_R8:
case CEE_STELEM_R8:
return &mono_defaults.double_class->byval_arg;
case CEE_LDIND_I:
case CEE_STIND_I:
case CEE_LDELEM_I:
case CEE_STELEM_I:
return &mono_defaults.int_class->byval_arg;
case CEE_LDIND_REF:
case CEE_STIND_REF:
case CEE_LDELEM_REF:
case CEE_STELEM_REF:
return &mono_defaults.object_class->byval_arg;
default:
g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
return NULL;
}
}
static void
do_load_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
return;
}
if (opcode == CEE_LDIND_REF) {
if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
} else {
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
}
}
static void
do_store_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *addr, *val;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
val = stack_pop (ctx);
addr = stack_pop (ctx);
check_unmanaged_pointer (ctx, addr);
if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
return;
}
if (stack_slot_is_managed_mutability_pointer (addr)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
return;
}
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
}
static void
do_newarr (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
}
/*FIXME handle arrays that are not 0-indexed*/
static void
do_ldlen (VerifyContext *ctx)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
}
/*FIXME handle arrays that are not 0-indexed*/
/*FIXME handle readonly prefix and CMMP*/
static void
do_ldelema (VerifyContext *ctx, int klass_token)
{
ILStackDesc *index, *array, *res;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
gboolean valid;
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
} else {
valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
}
if (!valid)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
}
}
res = stack_push (ctx);
set_stack_value (ctx, res, type, TRUE);
if (ctx->prefix_set & PREFIX_READONLY) {
ctx->prefix_set &= ~PREFIX_READONLY;
res->stype |= CMMP_MASK;
}
}
/*
* FIXME handle arrays that are not 0-indexed
* FIXME handle readonly prefix and CMMP
*/
static void
do_ldelem (VerifyContext *ctx, int opcode, int token)
{
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
ILStackDesc *index, *array;
MonoType *type;
if (!check_underflow (ctx, 2))
return;
if (opcode == CEE_LDELEM) {
if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (opcode == CEE_LDELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
type = &array->type->data.klass->byval_arg;
} else {
MonoType *candidate = &array->type->data.klass->byval_arg;
if (IS_STRICT_MODE (ctx)) {
MonoType *underlying_type = mono_type_get_underlying_type_any (type);
MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) ||
(IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
}
}
set_stack_value (ctx, stack_push (ctx), type, FALSE);
#undef IS_ONE_OF2
}
/*
* FIXME handle arrays that are not 0-indexed
*/
static void
do_stelem (VerifyContext *ctx, int opcode, int token)
{
ILStackDesc *index, *array, *value;
MonoType *type;
if (!check_underflow (ctx, 3))
return;
if (opcode == CEE_STELEM) {
if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
value = stack_pop (ctx);
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
} else {
if (opcode == CEE_STELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
}
}
}
if (opcode == CEE_STELEM_REF) {
if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (opcode != CEE_STELEM_REF) {
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
}
}
static void
do_throw (VerifyContext *ctx)
{
ILStackDesc *exception;
if (!check_underflow (ctx, 1))
return;
exception = stack_pop (ctx);
if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
char *name = mono_type_full_name (exception->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type but found unboxed %s at 0x%04x ", name, ctx->ip_offset));
g_free (name);
}
/*The stack is left empty after a throw*/
ctx->eval.size = 0;
}
static void
do_endfilter (VerifyContext *ctx)
{
MonoExceptionClause *clause;
if (IS_STRICT_MODE (ctx)) {
if (ctx->eval.size != 1)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
}
if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
if (IS_STRICT_MODE (ctx)) {
if (ctx->ip_offset != clause->handler_offset - 2)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
} else {
if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
}
} else {
if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
else
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
}
ctx->eval.size = 0;
}
static void
do_leave (VerifyContext *ctx, int delta)
{
int target = ((gint32)ctx->ip_offset) + delta;
if (target >= ctx->code_size || target < 0)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
ctx->eval.size = 0;
ctx->target = target;
}
/*
* do_static_branch:
*
* Verify br and br.s opcodes.
*/
static void
do_static_branch (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
}
ctx->target = target;
}
static void
do_switch (VerifyContext *ctx, int count, const unsigned char *data)
{
int i, base = ctx->ip_offset + 5 + count * 4;
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
for (i = 0; i < count; ++i) {
int target = base + read32 (data + i * 4);
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
return;
}
merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
}
}
static void
do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
{
ILStackDesc *top;
MonoMethod *method;
if (virtual && !check_underflow (ctx, 1))
return;
if (!virtual && !check_overflow (ctx))
return;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
return;
if (mono_method_is_constructor (method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
if (virtual) {
ILStackDesc *top = stack_pop (ctx);
if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
if (method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
}
if (!mono_method_can_access_method_full (ctx->method, method, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/ldvirtftn at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
top->method = method;
}
static void
do_sizeof (VerifyContext *ctx, int token)
{
MonoType *type;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(type = verifier_load_type (ctx, token, "sizeof")))
return;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
return;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
return;
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
}
/* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
static void
do_localloc (VerifyContext *ctx)
{
ILStackDesc *top;
if (ctx->eval.size != 1) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
/*TODO verify top type*/
top = stack_pop (ctx);
set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
}
static void
do_ldstr (VerifyContext *ctx, guint32 token)
{
GSList *error = NULL;
if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
if (error)
ctx->list = g_slist_concat (ctx->list, error);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (check_overflow (ctx))
stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
}
static void
do_refanyval (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanyval, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, TRUE);
}
static void
do_refanytype (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
}
static void
do_mkrefany (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a managed pointer for mkrefany, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
}else {
MonoType *stack_type = mono_type_get_type_byval (top->type);
if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
}
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
}
static void
do_ckfinite (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (stack_slot_get_underlying_type (top) != TYPE_R8)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected float32 or float64 on stack for ckfinit but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
stack_push_stack_val (ctx, top);
}
/*
* merge_stacks:
* Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
*
* @from holds new values for a given control path
* @to holds the current values of a given control path
*
* TODO we can eliminate the from argument as all callers pass &ctx->eval
*/
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
{
MonoError error;
int i, j, k;
stack_init (ctx, to);
if (start) {
if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
from->size = 0;
else
stack_copy (&ctx->eval, to);
goto end_verify;
} else if (!(to->flags & IL_CODE_STACK_MERGED)) {
stack_copy (to, &ctx->eval);
goto end_verify;
}
VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
if (from->size != to->size) {
VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset));
goto end_verify;
}
//FIXME we need to preserve CMMP attributes
//FIXME we must take null literals into consideration.
for (i = 0; i < from->size; ++i) {
ILStackDesc *new_slot = from->stack + i;
ILStackDesc *old_slot = to->stack + i;
MonoType *new_type = mono_type_from_stack_slot (new_slot);
MonoType *old_type = mono_type_from_stack_slot (old_slot);
MonoClass *old_class = mono_class_from_mono_type (old_type);
MonoClass *new_class = mono_class_from_mono_type (new_type);
MonoClass *match_class = NULL;
// S := T then U = S (new value is compatible with current value, keep current)
if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
copy_stack_value (new_slot, old_slot);
continue;
}
// T := S then U = T (old value is compatible with current value, use new)
if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
copy_stack_value (old_slot, new_slot);
continue;
}
if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
goto end_verify;
}
//both are reference types, use closest common super type
if (!mono_class_from_mono_type (old_type)->valuetype
&& !mono_class_from_mono_type (new_type)->valuetype
&& !stack_slot_is_managed_pointer (old_slot)
&& !stack_slot_is_managed_pointer (new_slot)) {
for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
match_class = old_class->supertypes [j];
goto match_found;
}
}
mono_class_setup_interfaces (old_class, &error);
if (!mono_error_ok (&error)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
mono_error_cleanup (&error);
goto end_verify;
}
for (j = 0; j < old_class->interface_count; ++j) {
for (k = 0; k < new_class->interface_count; ++k) {
if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
match_class = old_class->interfaces [j];
goto match_found;
}
}
}
//No decent super type found, use object
match_class = mono_defaults.object_class;
goto match_found;
} else if (is_compatible_boxed_valuetype (ctx,old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (ctx, new_type, old_type, old_slot, FALSE)) {
match_class = mono_defaults.object_class;
goto match_found;
}
{
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
}
set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
goto end_verify;
match_found:
g_assert (match_class);
set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
continue;
}
end_verify:
if (external)
to->flags |= IL_CODE_FLAG_WAS_TARGET;
to->flags |= IL_CODE_STACK_MERGED;
}
#define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
#define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
/*
* is_clause_in_range :
*
* Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
*/
static gboolean
is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset >= start && clause->try_offset < end)
return TRUE;
if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
return TRUE;
return FALSE;
}
/*
* is_clause_inside_range :
*
* Returns TRUE if @clause lies completely inside the @start - @end range.
*/
static gboolean
is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
return FALSE;
if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
return FALSE;
return TRUE;
}
/*
* is_clause_nested :
*
* Returns TRUE if @nested is nested in @clause.
*/
static gboolean
is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
{
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
return TRUE;
return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
}
/* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
* the each pair of exception must have the following properties:
* - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
* - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
* - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
*/
static void
verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
{
/*clause is nested*/
if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
return;
}
/*wrong nesting order.*/
if (is_clause_nested (clause, to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
return;
}
/*mutual protection*/
if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
/*handlers are not disjoint*/
if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
return;
}
/* handlers are not catch or filter */
if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
return;
}
/*OK*/
return;
}
/*not completelly disjoint*/
if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
}
#define code_bounds_check(size) \
if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
break; \
} \
static gboolean
mono_opcode_is_prefix (int op)
{
switch (op) {
case MONO_CEE_UNALIGNED_:
case MONO_CEE_VOLATILE_:
case MONO_CEE_TAIL_:
case MONO_CEE_CONSTRAINED_:
case MONO_CEE_READONLY_:
return TRUE;
}
return FALSE;
}
/*
* FIXME: need to distinguish between valid and verifiable.
* Need to keep track of types on the stack.
* Verify types for opcodes.
*/
GSList*
mono_method_verify (MonoMethod *method, int level)
{
MonoError error;
const unsigned char *ip, *code_start;
const unsigned char *end;
MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
int i, n, need_merge = 0, start = 0;
guint token, ip_offset = 0, prefix = 0;
MonoGenericContext *generic_context = NULL;
MonoImage *image;
VerifyContext ctx;
GSList *tmp;
VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
init_verifier_stats ();
if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
return NULL;
}
memset (&ctx, 0, sizeof (VerifyContext));
//FIXME use mono_method_get_signature_full
ctx.signature = mono_method_signature (method);
if (!ctx.signature) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
finish_collect_stats ();
return ctx.list;
}
ctx.header = mono_method_get_header (method);
if (!ctx.header) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
finish_collect_stats ();
return ctx.list;
}
ctx.method = method;
code_start = ip = ctx.header->code;
end = ip + ctx.header->code_size;
ctx.image = image = method->klass->image;
ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
ctx.max_stack = ctx.header->max_stack;
ctx.verifiable = ctx.valid = 1;
ctx.level = level;
ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
ctx.code_size = ctx.header->code_size;
MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
ctx.num_locals = ctx.header->num_locals;
ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
if (ctx.num_locals > 0 && !ctx.header->init_locals)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
ctx.params = g_new (MonoType*, ctx.max_args);
MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
if (ctx.signature->hasthis)
ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
if (ctx.signature->is_inflated)
ctx.generic_context = generic_context = mono_method_get_context (method);
if (!generic_context && (method->klass->generic_container || method->is_generic)) {
if (method->is_generic)
ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
else
ctx.generic_context = generic_context = &method->klass->generic_container->context;
}
for (i = 0; i < ctx.num_locals; ++i) {
MonoType *uninflated = ctx.locals [i];
ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.num_locals = i;
ctx.max_args = 0;
goto cleanup;
}
}
for (i = 0; i < ctx.max_args; ++i) {
MonoType *uninflated = ctx.params [i];
ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.max_args = i;
goto cleanup;
}
}
stack_init (&ctx, &ctx.eval);
for (i = 0; i < ctx.num_locals; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
break;
if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.locals [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
g_free (name);
break;
}
}
for (i = 0; i < ctx.max_args; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
break;
if (get_stack_type (ctx.params [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.params [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
g_free (name);
break;
}
}
if (!ctx.valid)
goto cleanup;
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
VERIFIER_DEBUG (printf ("clause try %x len %x filter at %x handler at %x len %x\n", clause->try_offset, clause->try_len, clause->data.filter_offset, clause->handler_offset, clause->handler_len); );
if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
if (clause->try_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
if (clause->handler_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
if (clause->data.filter_offset > ctx.code_size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
if (clause->data.filter_offset >= clause->handler_offset)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
}
for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
if (!ctx.valid)
break;
ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->try_offset + clause->try_len < ctx.code_size)
ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->handler_offset + clause->handler_len < ctx.code_size)
ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
if (!clause->data.catch_class) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
break;
}
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
}
else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
}
}
original_bb = bb = mono_basic_block_split (method, &error);
if (!mono_error_ok (&error)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
mono_error_cleanup (&error);
goto cleanup;
}
g_assert (bb);
while (ip < end && ctx.valid) {
int op_size;
ip_offset = ip - code_start;
{
const unsigned char *ip_copy = ip;
int op;
if (ip_offset > bb->end) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
goto cleanup;
}
if (ip_offset == bb->end)
bb = bb->next;
op_size = mono_opcode_value_and_size (&ip_copy, end, &op);
if (op_size == -1) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
goto cleanup;
}
if (ADD_IS_GREATER_OR_OVF (ip_offset, op_size, bb->end)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
goto cleanup;
}
/*Last Instruction*/
if (ip_offset + op_size == bb->end && mono_opcode_is_prefix (op)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset));
goto cleanup;
}
}
ctx.ip_offset = ip_offset = ip - code_start;
/*We need to check against fallthrou in and out of protected blocks.
* For fallout we check the once a protected block ends, if the start flag is not set.
* Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
* TODO convert these checks to be done using flags and not this loop
*/
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
start = 1;
}
if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
start = 1;
}
if (clause->handler_offset == ip_offset && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
start = 1;
}
}
/*This must be done after fallthru detection otherwise it won't happen.*/
if (bb->dead) {
/*FIXME remove this once we move all bad branch checking code to use BB only*/
ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
ip += op_size;
continue;
}
if (!ctx.valid)
break;
if (need_merge) {
VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
need_merge = 0;
}
merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
start = 0;
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
#ifdef MONO_VERIFIER_DEBUG
{
char *discode;
discode = mono_disasm_code_one (NULL, method, ip, NULL);
discode [strlen (discode) - 1] = 0; /* no \n */
g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
g_free (discode);
}
dump_stack_state (&ctx.code [ip_offset]);
dump_stack_state (&ctx.eval);
#endif
switch (*ip) {
case CEE_NOP:
case CEE_BREAK:
++ip;
break;
case CEE_LDARG_0:
case CEE_LDARG_1:
case CEE_LDARG_2:
case CEE_LDARG_3:
push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
++ip;
break;
case CEE_LDARG_S:
case CEE_LDARGA_S:
code_bounds_check (2);
push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
ip += 2;
break;
case CEE_ADD_OVF_UN:
do_binop (&ctx, *ip, add_ovf_un_table);
++ip;
break;
case CEE_SUB_OVF_UN:
do_binop (&ctx, *ip, sub_ovf_un_table);
++ip;
break;
case CEE_ADD_OVF:
case CEE_SUB_OVF:
case CEE_MUL_OVF:
case CEE_MUL_OVF_UN:
do_binop (&ctx, *ip, bin_ovf_table);
++ip;
break;
case CEE_ADD:
do_binop (&ctx, *ip, add_table);
++ip;
break;
case CEE_SUB:
do_binop (&ctx, *ip, sub_table);
++ip;
break;
case CEE_MUL:
case CEE_DIV:
case CEE_REM:
do_binop (&ctx, *ip, bin_op_table);
++ip;
break;
case CEE_AND:
case CEE_DIV_UN:
case CEE_OR:
case CEE_REM_UN:
case CEE_XOR:
do_binop (&ctx, *ip, int_bin_op_table);
++ip;
break;
case CEE_SHL:
case CEE_SHR:
case CEE_SHR_UN:
do_binop (&ctx, *ip, shift_op_table);
++ip;
break;
case CEE_POP:
if (!check_underflow (&ctx, 1))
break;
stack_pop_safe (&ctx);
++ip;
break;
case CEE_RET:
do_ret (&ctx);
++ip;
start = 1;
break;
case CEE_LDLOC_0:
case CEE_LDLOC_1:
case CEE_LDLOC_2:
case CEE_LDLOC_3:
/*TODO support definite assignment verification? */
push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
++ip;
break;
case CEE_STLOC_0:
case CEE_STLOC_1:
case CEE_STLOC_2:
case CEE_STLOC_3:
store_local (&ctx, *ip - CEE_STLOC_0);
++ip;
break;
case CEE_STLOC_S:
code_bounds_check (2);
store_local (&ctx, ip [1]);
ip += 2;
break;
case CEE_STARG_S:
code_bounds_check (2);
store_arg (&ctx, ip [1]);
ip += 2;
break;
case CEE_LDC_I4_M1:
case CEE_LDC_I4_0:
case CEE_LDC_I4_1:
case CEE_LDC_I4_2:
case CEE_LDC_I4_3:
case CEE_LDC_I4_4:
case CEE_LDC_I4_5:
case CEE_LDC_I4_6:
case CEE_LDC_I4_7:
case CEE_LDC_I4_8:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
++ip;
break;
case CEE_LDC_I4_S:
code_bounds_check (2);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 2;
break;
case CEE_LDC_I4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 5;
break;
case CEE_LDC_I8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
ip += 9;
break;
case CEE_LDC_R4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 5;
break;
case CEE_LDC_R8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 9;
break;
case CEE_LDNULL:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
++ip;
break;
case CEE_BEQ_S:
case CEE_BNE_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
ip += 2;
need_merge = 1;
break;
case CEE_BGE_S:
case CEE_BGT_S:
case CEE_BLE_S:
case CEE_BLT_S:
case CEE_BGE_UN_S:
case CEE_BGT_UN_S:
case CEE_BLE_UN_S:
case CEE_BLT_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
ip += 2;
need_merge = 1;
break;
case CEE_BEQ:
case CEE_BNE_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
ip += 5;
need_merge = 1;
break;
case CEE_BGE:
case CEE_BGT:
case CEE_BLE:
case CEE_BLT:
case CEE_BGE_UN:
case CEE_BGT_UN:
case CEE_BLE_UN:
case CEE_BLT_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
ip += 5;
need_merge = 1;
break;
case CEE_LDLOC_S:
case CEE_LDLOCA_S:
code_bounds_check (2);
push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
ip += 2;
break;
case CEE_UNUSED99:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_DUP: {
ILStackDesc *top;
if (!check_underflow (&ctx, 1))
break;
if (!check_overflow (&ctx))
break;
top = stack_push (&ctx);
copy_stack_value (top, stack_peek (&ctx, 1));
++ip;
break;
}
case CEE_JMP:
code_bounds_check (5);
if (ctx.eval.size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
token = read32 (ip + 1);
if (in_any_block (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
/*
* FIXME: check signature, retval, arguments etc.
*/
ip += 5;
break;
case CEE_CALL:
case CEE_CALLVIRT:
code_bounds_check (5);
do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
ip += 5;
break;
case CEE_CALLI:
code_bounds_check (5);
token = read32 (ip + 1);
/*
* FIXME: check signature, retval, arguments etc.
* FIXME: check requirements for tail call
*/
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
ip += 5;
break;
case CEE_BR_S:
code_bounds_check (2);
do_static_branch (&ctx, (signed char)ip [1] + 2);
need_merge = 1;
ip += 2;
start = 1;
break;
case CEE_BRFALSE_S:
case CEE_BRTRUE_S:
code_bounds_check (2);
do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
ip += 2;
need_merge = 1;
break;
case CEE_BR:
code_bounds_check (5);
do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
need_merge = 1;
ip += 5;
start = 1;
break;
case CEE_BRFALSE:
case CEE_BRTRUE:
code_bounds_check (5);
do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
ip += 5;
need_merge = 1;
break;
case CEE_SWITCH: {
guint32 entries;
code_bounds_check (5);
entries = read32 (ip + 1);
if (entries > 0xFFFFFFFFU / sizeof (guint32))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
ip += 5;
code_bounds_check (sizeof (guint32) * entries);
do_switch (&ctx, entries, ip);
ip += sizeof (guint32) * entries;
break;
}
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_LDIND_I8:
case CEE_LDIND_I:
case CEE_LDIND_R4:
case CEE_LDIND_R8:
case CEE_LDIND_REF:
do_load_indirect (&ctx, *ip);
++ip;
break;
case CEE_STIND_REF:
case CEE_STIND_I1:
case CEE_STIND_I2:
case CEE_STIND_I4:
case CEE_STIND_I8:
case CEE_STIND_R4:
case CEE_STIND_R8:
case CEE_STIND_I:
do_store_indirect (&ctx, *ip);
++ip;
break;
case CEE_NOT:
case CEE_NEG:
do_unary_math_op (&ctx, *ip);
++ip;
break;
case CEE_CONV_I1:
case CEE_CONV_I2:
case CEE_CONV_I4:
case CEE_CONV_U1:
case CEE_CONV_U2:
case CEE_CONV_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_I8:
case CEE_CONV_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_R4:
case CEE_CONV_R8:
case CEE_CONV_R_UN:
do_conversion (&ctx, TYPE_R8);
++ip;
break;
case CEE_CONV_I:
case CEE_CONV_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_CPOBJ:
code_bounds_check (5);
do_cpobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDOBJ:
code_bounds_check (5);
do_ldobj_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDSTR:
code_bounds_check (5);
do_ldstr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWOBJ:
code_bounds_check (5);
do_newobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CASTCLASS:
case CEE_ISINST:
code_bounds_check (5);
do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
ip += 5;
break;
case CEE_UNUSED58:
case CEE_UNUSED1:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_UNBOX:
code_bounds_check (5);
do_unbox_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_THROW:
do_throw (&ctx);
start = 1;
++ip;
break;
case CEE_LDFLD:
case CEE_LDFLDA:
code_bounds_check (5);
do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
ip += 5;
break;
case CEE_LDSFLD:
case CEE_LDSFLDA:
code_bounds_check (5);
do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
ip += 5;
break;
case CEE_STFLD:
code_bounds_check (5);
do_store_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STSFLD:
code_bounds_check (5);
do_store_static_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STOBJ:
code_bounds_check (5);
do_stobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1_UN:
case CEE_CONV_OVF_I2_UN:
case CEE_CONV_OVF_I4_UN:
case CEE_CONV_OVF_U1_UN:
case CEE_CONV_OVF_U2_UN:
case CEE_CONV_OVF_U4_UN:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8_UN:
case CEE_CONV_OVF_U8_UN:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I_UN:
case CEE_CONV_OVF_U_UN:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_BOX:
code_bounds_check (5);
do_box_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWARR:
code_bounds_check (5);
do_newarr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDLEN:
do_ldlen (&ctx);
++ip;
break;
case CEE_LDELEMA:
code_bounds_check (5);
do_ldelema (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_LDELEM_I8:
case CEE_LDELEM_I:
case CEE_LDELEM_R4:
case CEE_LDELEM_R8:
case CEE_LDELEM_REF:
do_ldelem (&ctx, *ip, 0);
++ip;
break;
case CEE_STELEM_I:
case CEE_STELEM_I1:
case CEE_STELEM_I2:
case CEE_STELEM_I4:
case CEE_STELEM_I8:
case CEE_STELEM_R4:
case CEE_STELEM_R8:
case CEE_STELEM_REF:
do_stelem (&ctx, *ip, 0);
++ip;
break;
case CEE_LDELEM:
code_bounds_check (5);
do_ldelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_STELEM:
code_bounds_check (5);
do_stelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_UNBOX_ANY:
code_bounds_check (5);
do_unbox_any (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1:
case CEE_CONV_OVF_U1:
case CEE_CONV_OVF_I2:
case CEE_CONV_OVF_U2:
case CEE_CONV_OVF_I4:
case CEE_CONV_OVF_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8:
case CEE_CONV_OVF_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I:
case CEE_CONV_OVF_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_REFANYVAL:
code_bounds_check (5);
do_refanyval (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CKFINITE:
do_ckfinite (&ctx);
++ip;
break;
case CEE_MKREFANY:
code_bounds_check (5);
do_mkrefany (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDTOKEN:
code_bounds_check (5);
do_load_token (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_ENDFINALLY:
if (!is_correct_endfinally (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_LEAVE:
code_bounds_check (5);
do_leave (&ctx, read32 (ip + 1) + 5);
ip += 5;
start = 1;
need_merge = 1;
break;
case CEE_LEAVE_S:
code_bounds_check (2);
do_leave (&ctx, (signed char)ip [1] + 2);
ip += 2;
start = 1;
need_merge = 1;
break;
case CEE_PREFIX1:
code_bounds_check (2);
++ip;
switch (*ip) {
case CEE_STLOC:
code_bounds_check (3);
store_local (&ctx, read16 (ip + 1));
ip += 3;
break;
case CEE_CEQ:
do_cmp_op (&ctx, cmp_br_eq_op, *ip);
++ip;
break;
case CEE_CGT:
case CEE_CGT_UN:
case CEE_CLT:
case CEE_CLT_UN:
do_cmp_op (&ctx, cmp_br_op, *ip);
++ip;
break;
case CEE_STARG:
code_bounds_check (3);
store_arg (&ctx, read16 (ip + 1) );
ip += 3;
break;
case CEE_ARGLIST:
if (!check_overflow (&ctx))
break;
if (ctx.signature->call_convention != MONO_CALL_VARARG)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
++ip;
break;
case CEE_LDFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
ip += 5;
break;
case CEE_LDVIRTFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
ip += 5;
break;
case CEE_LDARG:
case CEE_LDARGA:
code_bounds_check (3);
push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
ip += 3;
break;
case CEE_LDLOC:
case CEE_LDLOCA:
code_bounds_check (3);
push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
ip += 3;
break;
case CEE_LOCALLOC:
do_localloc (&ctx);
++ip;
break;
case CEE_UNUSED56:
case CEE_UNUSED57:
case CEE_UNUSED70:
case CEE_UNUSED:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_ENDFILTER:
do_endfilter (&ctx);
start = 1;
++ip;
break;
case CEE_UNALIGNED_:
code_bounds_check (2);
prefix |= PREFIX_UNALIGNED;
ip += 2;
break;
case CEE_VOLATILE_:
prefix |= PREFIX_VOLATILE;
++ip;
break;
case CEE_TAIL_:
prefix |= PREFIX_TAIL;
++ip;
if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
break;
case CEE_INITOBJ:
code_bounds_check (5);
do_initobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONSTRAINED_:
code_bounds_check (5);
ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
prefix |= PREFIX_CONSTRAINED;
ip += 5;
break;
case CEE_READONLY_:
prefix |= PREFIX_READONLY;
ip++;
break;
case CEE_CPBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_INITBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_NO_:
ip += 2;
break;
case CEE_RETHROW:
if (!is_correct_rethrow (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_SIZEOF:
code_bounds_check (5);
do_sizeof (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_REFANYTYPE:
do_refanytype (&ctx);
++ip;
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
if (prefix) {
if (!ctx.prefix_set) //first prefix
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
ctx.prefix_set |= prefix;
ctx.has_flags = TRUE;
prefix = 0;
} else {
if (!ctx.has_flags)
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
if (ctx.prefix_set & PREFIX_CONSTRAINED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_READONLY)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_VOLATILE)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_UNALIGNED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
ctx.prefix_set = prefix = 0;
ctx.has_flags = FALSE;
}
}
/*
* if ip != end we overflowed: mark as error.
*/
if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
}
/*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
}
if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid call to a non-final virtual function in method with stdarg.0 or ldarga.0 at 0x%04x", i));
}
if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
char *method_name = mono_method_full_name (ctx.method, TRUE);
char *type = mono_type_get_full_name (ctx.method->klass);
if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor due to a TypeLoadException on base type.", method_name, type));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
g_free (method_name);
g_free (type);
}
cleanup:
if (ctx.code) {
for (i = 0; i < ctx.header->code_size; ++i) {
if (ctx.code [i].stack)
g_free (ctx.code [i].stack);
}
}
for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
g_free (tmp->data);
g_slist_free (ctx.funptrs);
for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
mono_metadata_free_type (tmp->data);
g_slist_free (ctx.exception_types);
for (i = 0; i < ctx.num_locals; ++i) {
if (ctx.locals [i])
mono_metadata_free_type (ctx.locals [i]);
}
for (i = 0; i < ctx.max_args; ++i) {
if (ctx.params [i])
mono_metadata_free_type (ctx.params [i]);
}
if (ctx.eval.stack)
g_free (ctx.eval.stack);
if (ctx.code)
g_free (ctx.code);
g_free (ctx.locals);
g_free (ctx.params);
mono_basic_block_free (original_bb);
mono_metadata_free_mh (ctx.header);
finish_collect_stats ();
return ctx.list;
}
char*
mono_verify_corlib ()
{
/* This is a public API function so cannot be removed */
return NULL;
}
/*
* Returns true if @method needs to be verified.
*
*/
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
}
/*
* Returns true if @klass need to be verified.
*
*/
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
return mono_verifier_is_class_full_trust (method->klass);
}
/*
* Returns if @klass is under full trust or not.
*
* TODO This code doesn't take CAS into account.
*
* Under verify_all all user code must be verifiable if no security option was set
*
*/
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
(klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
return trusted_location || klass->image == mono_defaults.corlib;
return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
{
return mono_method_verify (method,
(verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
| (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
| (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
}
static int
get_field_end (MonoClassField *field)
{
int align;
int size = mono_type_size (field->type, &align);
if (size == 0)
size = 4; /*FIXME Is this a safe bet?*/
return size + field->offset;
}
static gboolean
verify_class_for_overlapping_reference_fields (MonoClass *class)
{
int i = 0, j;
gpointer iter = NULL;
MonoClassField *field;
gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
/*We can't skip types with !has_references since this is calculated after we have run.*/
if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
return TRUE;
/*We must check for stuff overlapping reference fields.
The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
*/
while ((field = mono_class_get_fields (class, &iter))) {
int fieldEnd = get_field_end (field);
gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
++i;
if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
for (j = i; j < class->field.count; ++j) {
MonoClassField *other = &class->fields [j];
int otherEnd = get_field_end (other);
if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
continue;
if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
return FALSE;
}
}
return TRUE;
}
static guint
field_hash (gconstpointer key)
{
const MonoClassField *field = key;
return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
}
static gboolean
field_equals (gconstpointer _a, gconstpointer _b)
{
const MonoClassField *a = _a;
const MonoClassField *b = _b;
return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
}
static gboolean
verify_class_fields (MonoClass *class)
{
gpointer iter = NULL;
MonoClassField *field;
MonoGenericContext *context = mono_class_get_context (class);
GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
if (class->generic_container)
context = &class->generic_container->context;
while ((field = mono_class_get_fields (class, &iter)) != NULL) {
if (!mono_type_is_valid_type_in_context (field->type, context)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
if (g_hash_table_lookup (unique_fields, field)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
g_hash_table_insert (unique_fields, field, field);
}
g_hash_table_destroy (unique_fields);
return TRUE;
}
static gboolean
verify_interfaces (MonoClass *class)
{
int i;
for (i = 0; i < class->interface_count; ++i) {
MonoClass *iface = class->interfaces [i];
if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
{
int type;
gpointer iter = NULL;
MonoClassField *field;
MonoClass *field_class;
if (!class->valuetype)
return TRUE;
type = class->byval_arg.type;
/*primitive type fields are not properly decoded*/
if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
return TRUE;
while ((field = mono_class_get_fields (class, &iter)) != NULL) {
if (!field->type)
return FALSE;
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout (MonoClass *class)
{
gboolean res;
res = verify_valuetype_layout_with_target (class, class);
return res;
}
static gboolean
recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
{
int idx;
MonoClass **constraints;
MonoGenericParamInfo *param_info;
g_assert (mono_type_is_generic_argument (type));
idx = mono_type_get_generic_param_num (type);
if (mono_bitset_test_fast (used_args, idx))
return FALSE;
mono_bitset_set_fast (used_args, idx);
param_info = mono_generic_container_get_param_info (gc, idx);
if (!param_info->constraints)
return TRUE;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
return FALSE;
}
return TRUE;
}
static gboolean
verify_generic_parameters (MonoClass *class)
{
int i;
MonoGenericContainer *gc = class->generic_container;
MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass **constraints;
if (!param_info->constraints)
continue;
mono_bitset_clear_all (used_args);
mono_bitset_set_fast (used_args, i);
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
goto fail;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
goto fail;
if (ctr->generic_class && !mono_class_is_valid_generic_instantiation (NULL, ctr))
goto fail;
}
}
mono_bitset_free (used_args);
return TRUE;
fail:
mono_bitset_free (used_args);
return FALSE;
}
/*
* Check if the class is verifiable.
*
* Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
* field and invalid generic instantiation are fatal errors.
*
* This method must be safe to be called from mono_class_init and all code must be carefull about that.
*
*/
gboolean
mono_verifier_verify_class (MonoClass *class)
{
/*Neither <Module>, object or ifaces have parent.*/
if (!class->parent &&
class != mono_defaults.object_class &&
!MONO_CLASS_IS_INTERFACE (class) &&
(!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
return FALSE;
if (class->parent) {
if (MONO_CLASS_IS_INTERFACE (class->parent))
return FALSE;
if (!class->generic_class && class->parent->generic_container)
return FALSE;
}
if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
return FALSE;
if (class->generic_container && !verify_generic_parameters (class))
return FALSE;
if (!verify_class_for_overlapping_reference_fields (class))
return FALSE;
if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
return FALSE;
if (class->generic_class == NULL && !verify_class_fields (class))
return FALSE;
if (class->valuetype && !verify_valuetype_layout (class))
return FALSE;
if (!verify_interfaces (class))
return FALSE;
return TRUE;
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
{
return mono_class_is_valid_generic_instantiation (NULL, class);
}
gboolean
mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
{
if (!method->is_inflated)
return TRUE;
return mono_method_is_valid_generic_instantiation (NULL, method);
}
#else
gboolean
mono_verifier_verify_class (MonoClass *class)
{
/* The verifier was disabled at compile time */
return TRUE;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
{
/* The verifier was disabled at compile time */
return NULL;
}
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return FALSE;
}
GSList*
mono_method_verify (MonoMethod *method, int level)
{
/* The verifier was disabled at compile time */
return NULL;
}
void
mono_free_verify_list (GSList *list)
{
/* The verifier was disabled at compile time */
/* will always be null if verifier is disabled */
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
{
return TRUE;
}
gboolean
mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
{
return TRUE;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4718_2 |
crossvul-cpp_data_good_5845_26 | /*
* 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(¬ifier->n_list, ©);
count++;
}
spin_unlock_irqrestore(&rs->rs_lock, flags);
if (!count)
return 0;
while (!list_empty(©)) {
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(¬ifier->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(©)) {
spin_lock_irqsave(&rs->rs_lock, flags);
list_splice(©, &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), ¬ify);
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));
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-20/c/good_5845_26 |
crossvul-cpp_data_good_2137_0 | /*-
* Copyright (c) 2008 Christos Zoulas
* 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*
* Parse Composite Document Files, the format used in Microsoft Office
* document files before they switched to zipped XML.
* Info from: http://sc.openoffice.org/compdocfileformat.pdf
*
* N.B. This is the "Composite Document File" format, and not the
* "Compound Document Format", nor the "Channel Definition Format".
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: cdf.c,v 1.60 2014/05/21 13:04:38 christos Exp $")
#endif
#include <assert.h>
#ifdef CDF_DEBUG
#include <err.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifndef EFTYPE
#define EFTYPE EINVAL
#endif
#include "cdf.h"
#ifdef CDF_DEBUG
#define DPRINTF(a) printf a, fflush(stdout)
#else
#define DPRINTF(a)
#endif
static union {
char s[4];
uint32_t u;
} cdf_bo;
#define NEED_SWAP (cdf_bo.u == (uint32_t)0x01020304)
#define CDF_TOLE8(x) ((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x)))
#define CDF_TOLE4(x) ((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x)))
#define CDF_TOLE2(x) ((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x)))
#define CDF_GETUINT32(x, y) cdf_getuint32(x, y)
/*
* swap a short
*/
static uint16_t
_cdf_tole2(uint16_t sv)
{
uint16_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[1];
d[1] = s[0];
return rv;
}
/*
* swap an int
*/
static uint32_t
_cdf_tole4(uint32_t sv)
{
uint32_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[3];
d[1] = s[2];
d[2] = s[1];
d[3] = s[0];
return rv;
}
/*
* swap a quad
*/
static uint64_t
_cdf_tole8(uint64_t sv)
{
uint64_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[7];
d[1] = s[6];
d[2] = s[5];
d[3] = s[4];
d[4] = s[3];
d[5] = s[2];
d[6] = s[1];
d[7] = s[0];
return rv;
}
/*
* grab a uint32_t from a possibly unaligned address, and return it in
* the native host order.
*/
static uint32_t
cdf_getuint32(const uint8_t *p, size_t offs)
{
uint32_t rv;
(void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv));
return CDF_TOLE4(rv);
}
#define CDF_UNPACK(a) \
(void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a)
#define CDF_UNPACKA(a) \
(void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a)
uint16_t
cdf_tole2(uint16_t sv)
{
return CDF_TOLE2(sv);
}
uint32_t
cdf_tole4(uint32_t sv)
{
return CDF_TOLE4(sv);
}
uint64_t
cdf_tole8(uint64_t sv)
{
return CDF_TOLE8(sv);
}
void
cdf_swap_header(cdf_header_t *h)
{
size_t i;
h->h_magic = CDF_TOLE8(h->h_magic);
h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]);
h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]);
h->h_revision = CDF_TOLE2(h->h_revision);
h->h_version = CDF_TOLE2(h->h_version);
h->h_byte_order = CDF_TOLE2(h->h_byte_order);
h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2);
h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2);
h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat);
h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory);
h->h_min_size_standard_stream =
CDF_TOLE4(h->h_min_size_standard_stream);
h->h_secid_first_sector_in_short_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat);
h->h_num_sectors_in_short_sat =
CDF_TOLE4(h->h_num_sectors_in_short_sat);
h->h_secid_first_sector_in_master_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat);
h->h_num_sectors_in_master_sat =
CDF_TOLE4(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]);
}
void
cdf_unpack_header(cdf_header_t *h, char *buf)
{
size_t i;
size_t len = 0;
CDF_UNPACK(h->h_magic);
CDF_UNPACKA(h->h_uuid);
CDF_UNPACK(h->h_revision);
CDF_UNPACK(h->h_version);
CDF_UNPACK(h->h_byte_order);
CDF_UNPACK(h->h_sec_size_p2);
CDF_UNPACK(h->h_short_sec_size_p2);
CDF_UNPACKA(h->h_unused0);
CDF_UNPACK(h->h_num_sectors_in_sat);
CDF_UNPACK(h->h_secid_first_directory);
CDF_UNPACKA(h->h_unused1);
CDF_UNPACK(h->h_min_size_standard_stream);
CDF_UNPACK(h->h_secid_first_sector_in_short_sat);
CDF_UNPACK(h->h_num_sectors_in_short_sat);
CDF_UNPACK(h->h_secid_first_sector_in_master_sat);
CDF_UNPACK(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
CDF_UNPACK(h->h_master_sat[i]);
}
void
cdf_swap_dir(cdf_directory_t *d)
{
d->d_namelen = CDF_TOLE2(d->d_namelen);
d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child);
d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child);
d->d_storage = CDF_TOLE4((uint32_t)d->d_storage);
d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]);
d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]);
d->d_flags = CDF_TOLE4(d->d_flags);
d->d_created = CDF_TOLE8((uint64_t)d->d_created);
d->d_modified = CDF_TOLE8((uint64_t)d->d_modified);
d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector);
d->d_size = CDF_TOLE4(d->d_size);
}
void
cdf_swap_class(cdf_classid_t *d)
{
d->cl_dword = CDF_TOLE4(d->cl_dword);
d->cl_word[0] = CDF_TOLE2(d->cl_word[0]);
d->cl_word[1] = CDF_TOLE2(d->cl_word[1]);
}
void
cdf_unpack_dir(cdf_directory_t *d, char *buf)
{
size_t len = 0;
CDF_UNPACKA(d->d_name);
CDF_UNPACK(d->d_namelen);
CDF_UNPACK(d->d_type);
CDF_UNPACK(d->d_color);
CDF_UNPACK(d->d_left_child);
CDF_UNPACK(d->d_right_child);
CDF_UNPACK(d->d_storage);
CDF_UNPACKA(d->d_storage_uuid);
CDF_UNPACK(d->d_flags);
CDF_UNPACK(d->d_created);
CDF_UNPACK(d->d_modified);
CDF_UNPACK(d->d_stream_first_sector);
CDF_UNPACK(d->d_size);
CDF_UNPACK(d->d_unused0);
}
static int
cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
(void)&line;
if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len));
errno = EFTYPE;
return -1;
}
static ssize_t
cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len)
{
size_t siz = (size_t)off + len;
if ((off_t)(off + len) != (off_t)siz) {
errno = EINVAL;
return -1;
}
if (info->i_buf != NULL && info->i_len >= siz) {
(void)memcpy(buf, &info->i_buf[off], len);
return (ssize_t)len;
}
if (info->i_fd == -1)
return -1;
if (pread(info->i_fd, buf, len, off) != (ssize_t)len)
return -1;
return (ssize_t)len;
}
int
cdf_read_header(const cdf_info_t *info, cdf_header_t *h)
{
char buf[512];
(void)memcpy(cdf_bo.s, "\01\02\03\04", 4);
if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1)
return -1;
cdf_unpack_header(h, buf);
cdf_swap_header(h);
if (h->h_magic != CDF_MAGIC) {
DPRINTF(("Bad magic 0x%" INT64_T_FORMAT "x != 0x%"
INT64_T_FORMAT "x\n",
(unsigned long long)h->h_magic,
(unsigned long long)CDF_MAGIC));
goto out;
}
if (h->h_sec_size_p2 > 20) {
DPRINTF(("Bad sector size 0x%u\n", h->h_sec_size_p2));
goto out;
}
if (h->h_short_sec_size_p2 > 20) {
DPRINTF(("Bad short sector size 0x%u\n",
h->h_short_sec_size_p2));
goto out;
}
return 0;
out:
errno = EFTYPE;
return -1;
}
ssize_t
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SEC_SIZE(h);
size_t pos = CDF_SEC_POS(h, id);
assert(ss == len);
return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len);
}
ssize_t
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
size_t len, const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SHORT_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos + len, CDF_SEC_SIZE(h) * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
/*
* Read the sector allocation table.
*/
int
cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat)
{
size_t i, j, k;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t *msa, mid, sec;
size_t nsatpersec = (ss / sizeof(mid)) - 1;
for (i = 0; i < __arraycount(h->h_master_sat); i++)
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
#define CDF_SEC_LIMIT (UINT32_MAX / (4 * ss))
if ((nsatpersec > 0 &&
h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) ||
i > CDF_SEC_LIMIT) {
DPRINTF(("Number of sectors in master SAT too big %u %"
SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i));
errno = EFTYPE;
return -1;
}
sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i;
DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n",
sat->sat_len, ss));
if ((sat->sat_tab = CAST(cdf_secid_t *, calloc(sat->sat_len, ss)))
== NULL)
return -1;
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] < 0)
break;
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
h->h_master_sat[i]) != (ssize_t)ss) {
DPRINTF(("Reading sector %d", h->h_master_sat[i]));
goto out1;
}
}
if ((msa = CAST(cdf_secid_t *, calloc(1, ss))) == NULL)
goto out1;
mid = h->h_secid_first_sector_in_master_sat;
for (j = 0; j < h->h_num_sectors_in_master_sat; j++) {
if (mid < 0)
goto out;
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Reading master sector loop limit"));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) {
DPRINTF(("Reading master sector %d", mid));
goto out2;
}
for (k = 0; k < nsatpersec; k++, i++) {
sec = CDF_TOLE4((uint32_t)msa[k]);
if (sec < 0)
goto out;
if (i >= sat->sat_len) {
DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT
"u >= %" SIZE_T_FORMAT "u", i, sat->sat_len));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
sec) != (ssize_t)ss) {
DPRINTF(("Reading sector %d",
CDF_TOLE4(msa[k])));
goto out2;
}
}
mid = CDF_TOLE4((uint32_t)msa[nsatpersec]);
}
out:
sat->sat_len = i;
free(msa);
return 0;
out2:
free(msa);
out1:
free(sat->sat_tab);
return -1;
}
size_t
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
{
size_t i, j;
cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size)
/ sizeof(maxsector));
DPRINTF(("Chain:"));
for (j = i = 0; sid >= 0; i++, j++) {
DPRINTF((" %d", sid));
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Counting chain loop limit"));
errno = EFTYPE;
return (size_t)-1;
}
if (sid >= maxsector) {
DPRINTF(("Sector %d >= %d\n", sid, maxsector));
errno = EFTYPE;
return (size_t)-1;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (i == 0) {
DPRINTF((" none, sid: %d\n", sid));
return (size_t)-1;
}
DPRINTF(("\n"));
return i;
}
int
cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
ssize_t nr;
scn->sst_len = cdf_count_chain(sat, sid, ss);
scn->sst_dirlen = len;
if (scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read long sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading long sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
scn->sst_len));
errno = EFTYPE;
goto out;
}
if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h,
sid)) != (ssize_t)ss) {
if (i == scn->sst_len - 1 && nr > 0) {
/* Last sector might be truncated */
return 0;
}
DPRINTF(("Reading long sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL)
return cdf_read_short_sector_chain(h, ssat, sst, sid, len,
scn);
else
return cdf_read_long_sector_chain(info, h, sat, sid, len, scn);
}
int
cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_dir_t *dir)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h), ns, nd;
char *buf;
cdf_secid_t sid = h->h_secid_first_directory;
ns = cdf_count_chain(sat, sid, ss);
if (ns == (size_t)-1)
return -1;
nd = ss / CDF_DIRECTORY_SIZE;
dir->dir_len = ns * nd;
dir->dir_tab = CAST(cdf_directory_t *,
calloc(dir->dir_len, sizeof(dir->dir_tab[0])));
if (dir->dir_tab == NULL)
return -1;
if ((buf = CAST(char *, malloc(ss))) == NULL) {
free(dir->dir_tab);
return -1;
}
for (j = i = 0; i < ns; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read dir loop limit"));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) {
DPRINTF(("Reading directory sector %d", sid));
goto out;
}
for (j = 0; j < nd; j++) {
cdf_unpack_dir(&dir->dir_tab[i * nd + j],
&buf[j * CDF_DIRECTORY_SIZE]);
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (NEED_SWAP)
for (i = 0; i < dir->dir_len; i++)
cdf_swap_dir(&dir->dir_tab[i]);
free(buf);
return 0;
out:
free(dir->dir_tab);
free(buf);
return -1;
}
int
cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_sat_t *ssat)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t sid = h->h_secid_first_sector_in_short_sat;
ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h));
if (ssat->sat_len == (size_t)-1)
return -1;
ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss));
if (ssat->sat_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sat sector loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= ssat->sat_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
ssat->sat_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) !=
(ssize_t)ss) {
DPRINTF(("Reading short sat sector %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(ssat->sat_tab);
return -1;
}
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
*root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
/* If the it is not there, just fake it; some docs don't have it */
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
*root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0)
goto out;
return cdf_read_long_sector_chain(info, h, sat,
d->d_stream_first_sector, d->d_size, scn);
out:
scn->sst_tab = NULL;
scn->sst_len = 0;
scn->sst_dirlen = 0;
return 0;
}
static int
cdf_namecmp(const char *d, const uint16_t *s, size_t l)
{
for (; l--; d++, s++)
if (*d != CDF_TOLE2(*s))
return (unsigned char)*d - CDF_TOLE2(*s);
return 0;
}
int
cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, cdf_stream_t *scn)
{
return cdf_read_user_stream(info, h, sat, ssat, sst, dir,
"\05SummaryInformation", scn);
}
int
cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, const char *name, cdf_stream_t *scn)
{
size_t i;
const cdf_directory_t *d;
size_t name_len = strlen(name) + 1;
for (i = dir->dir_len; i > 0; i--)
if (dir->dir_tab[i - 1].d_type == CDF_DIR_TYPE_USER_STREAM &&
cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len)
== 0)
break;
if (i == 0) {
DPRINTF(("Cannot find user stream `%s'\n", name));
errno = ESRCH;
return -1;
}
d = &dir->dir_tab[i - 1];
return cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, scn);
}
int
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
int
cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
{
size_t maxcount;
const cdf_summary_info_header_t *si =
CAST(const cdf_summary_info_header_t *, sst->sst_tab);
const cdf_section_declaration_t *sd =
CAST(const cdf_section_declaration_t *, (const void *)
((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
return -1;
ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
ssi->si_os_version = CDF_TOLE2(si->si_os_version);
ssi->si_os = CDF_TOLE2(si->si_os);
ssi->si_class = si->si_class;
cdf_swap_class(&ssi->si_class);
ssi->si_count = CDF_TOLE4(si->si_count);
*count = 0;
maxcount = 0;
*info = NULL;
if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,
count, &maxcount) == -1)
return -1;
return 0;
}
int
cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id)
{
return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-"
"%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0],
id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0],
id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4],
id->cl_six[5]);
}
static const struct {
uint32_t v;
const char *n;
} vn[] = {
{ CDF_PROPERTY_CODE_PAGE, "Code page" },
{ CDF_PROPERTY_TITLE, "Title" },
{ CDF_PROPERTY_SUBJECT, "Subject" },
{ CDF_PROPERTY_AUTHOR, "Author" },
{ CDF_PROPERTY_KEYWORDS, "Keywords" },
{ CDF_PROPERTY_COMMENTS, "Comments" },
{ CDF_PROPERTY_TEMPLATE, "Template" },
{ CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" },
{ CDF_PROPERTY_REVISION_NUMBER, "Revision Number" },
{ CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" },
{ CDF_PROPERTY_LAST_PRINTED, "Last Printed" },
{ CDF_PROPERTY_CREATE_TIME, "Create Time/Date" },
{ CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" },
{ CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" },
{ CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" },
{ CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" },
{ CDF_PROPERTY_THUMBNAIL, "Thumbnail" },
{ CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" },
{ CDF_PROPERTY_SECURITY, "Security" },
{ CDF_PROPERTY_LOCALE_ID, "Locale ID" },
};
int
cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p)
{
size_t i;
for (i = 0; i < __arraycount(vn); i++)
if (vn[i].v == p)
return snprintf(buf, bufsiz, "%s", vn[i].n);
return snprintf(buf, bufsiz, "0x%x", p);
}
int
cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts)
{
int len = 0;
int days, hours, mins, secs;
ts /= CDF_TIME_PREC;
secs = (int)(ts % 60);
ts /= 60;
mins = (int)(ts % 60);
ts /= 60;
hours = (int)(ts % 24);
ts /= 24;
days = (int)ts;
if (days) {
len += snprintf(buf + len, bufsiz - len, "%dd+", days);
if ((size_t)len >= bufsiz)
return len;
}
if (days || hours) {
len += snprintf(buf + len, bufsiz - len, "%.2d:", hours);
if ((size_t)len >= bufsiz)
return len;
}
len += snprintf(buf + len, bufsiz - len, "%.2d:", mins);
if ((size_t)len >= bufsiz)
return len;
len += snprintf(buf + len, bufsiz - len, "%.2d", secs);
return len;
}
#ifdef CDF_DEBUG
void
cdf_dump_header(const cdf_header_t *h)
{
size_t i;
#define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b)
#define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \
h->h_ ## b, 1 << h->h_ ## b)
DUMP("%d", revision);
DUMP("%d", version);
DUMP("0x%x", byte_order);
DUMP2("%d", sec_size_p2);
DUMP2("%d", short_sec_size_p2);
DUMP("%d", num_sectors_in_sat);
DUMP("%d", secid_first_directory);
DUMP("%d", min_size_standard_stream);
DUMP("%d", secid_first_sector_in_short_sat);
DUMP("%d", num_sectors_in_short_sat);
DUMP("%d", secid_first_sector_in_master_sat);
DUMP("%d", num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
(void)fprintf(stderr, "%35.35s[%.3zu] = %d\n",
"master_sat", i, h->h_master_sat[i]);
}
}
void
cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size)
{
size_t i, j, s = size / sizeof(cdf_secid_t);
for (i = 0; i < sat->sat_len; i++) {
(void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6"
SIZE_T_FORMAT "u: ", prefix, i, i * s);
for (j = 0; j < s; j++) {
(void)fprintf(stderr, "%5d, ",
CDF_TOLE4(sat->sat_tab[s * i + j]));
if ((j + 1) % 10 == 0)
(void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT
"u: ", i * s + j + 1);
}
(void)fprintf(stderr, "\n");
}
}
void
cdf_dump(void *v, size_t len)
{
size_t i, j;
unsigned char *p = v;
char abuf[16];
(void)fprintf(stderr, "%.4x: ", 0);
for (i = 0, j = 0; i < len; i++, p++) {
(void)fprintf(stderr, "%.2x ", *p);
abuf[j++] = isprint(*p) ? *p : '.';
if (j == 16) {
j = 0;
abuf[15] = '\0';
(void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ",
abuf, i + 1);
}
}
(void)fprintf(stderr, "\n");
}
void
cdf_dump_stream(const cdf_header_t *h, const cdf_stream_t *sst)
{
size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
cdf_dump(sst->sst_tab, ss * sst->sst_len);
}
void
cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir)
{
size_t i, j;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
cdf_stream_t scn;
struct timespec ts;
static const char *types[] = { "empty", "user storage",
"user stream", "lockbytes", "property", "root storage" };
for (i = 0; i < dir->dir_len; i++) {
char buf[26];
d = &dir->dir_tab[i];
for (j = 0; j < sizeof(name); j++)
name[j] = (char)CDF_TOLE2(d->d_name[j]);
(void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n",
i, name);
if (d->d_type < __arraycount(types))
(void)fprintf(stderr, "Type: %s\n", types[d->d_type]);
else
(void)fprintf(stderr, "Type: %d\n", d->d_type);
(void)fprintf(stderr, "Color: %s\n",
d->d_color ? "black" : "red");
(void)fprintf(stderr, "Left child: %d\n", d->d_left_child);
(void)fprintf(stderr, "Right child: %d\n", d->d_right_child);
(void)fprintf(stderr, "Flags: 0x%x\n", d->d_flags);
cdf_timestamp_to_timespec(&ts, d->d_created);
(void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf));
cdf_timestamp_to_timespec(&ts, d->d_modified);
(void)fprintf(stderr, "Modified %s",
cdf_ctime(&ts.tv_sec, buf));
(void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector);
(void)fprintf(stderr, "Size %d\n", d->d_size);
switch (d->d_type) {
case CDF_DIR_TYPE_USER_STORAGE:
(void)fprintf(stderr, "Storage: %d\n", d->d_storage);
break;
case CDF_DIR_TYPE_USER_STREAM:
if (sst == NULL)
break;
if (cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, &scn) == -1) {
warn("Can't read stream for %s at %d len %d",
name, d->d_stream_first_sector, d->d_size);
break;
}
cdf_dump_stream(h, &scn);
free(scn.sst_tab);
break;
default:
break;
}
}
}
void
cdf_dump_property_info(const cdf_property_info_t *info, size_t count)
{
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
size_t i, j;
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
(void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
(void)fprintf(stderr, "signed 16 [%hd]\n",
info[i].pi_s16);
break;
case CDF_SIGNED32:
(void)fprintf(stderr, "signed 32 [%d]\n",
info[i].pi_s32);
break;
case CDF_UNSIGNED32:
(void)fprintf(stderr, "unsigned 32 [%u]\n",
info[i].pi_u32);
break;
case CDF_FLOAT:
(void)fprintf(stderr, "float [%g]\n",
info[i].pi_f);
break;
case CDF_DOUBLE:
(void)fprintf(stderr, "double [%g]\n",
info[i].pi_d);
break;
case CDF_LENGTH32_STRING:
(void)fprintf(stderr, "string %u [%.*s]\n",
info[i].pi_str.s_len,
info[i].pi_str.s_len, info[i].pi_str.s_buf);
break;
case CDF_LENGTH32_WSTRING:
(void)fprintf(stderr, "string %u [",
info[i].pi_str.s_len);
for (j = 0; j < info[i].pi_str.s_len - 1; j++)
(void)fputc(info[i].pi_str.s_buf[j << 1], stderr);
(void)fprintf(stderr, "]\n");
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(buf, sizeof(buf), tp);
(void)fprintf(stderr, "timestamp %s\n", buf);
} else {
char buf[26];
cdf_timestamp_to_timespec(&ts, tp);
(void)fprintf(stderr, "timestamp %s",
cdf_ctime(&ts.tv_sec, buf));
}
break;
case CDF_CLIPBOARD:
(void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32);
break;
default:
DPRINTF(("Don't know how to deal with %x\n",
info[i].pi_type));
break;
}
}
}
void
cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst)
{
char buf[128];
cdf_summary_info_header_t ssi;
cdf_property_info_t *info;
size_t count;
(void)&h;
if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1)
return;
(void)fprintf(stderr, "Endian: %x\n", ssi.si_byte_order);
(void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff,
ssi.si_os_version >> 8);
(void)fprintf(stderr, "Os %d\n", ssi.si_os);
cdf_print_classid(buf, sizeof(buf), &ssi.si_class);
(void)fprintf(stderr, "Class %s\n", buf);
(void)fprintf(stderr, "Count %d\n", ssi.si_count);
cdf_dump_property_info(info, count);
free(info);
}
#endif
#ifdef TEST
int
main(int argc, char *argv[])
{
int i;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
cdf_info_t info;
if (argc < 2) {
(void)fprintf(stderr, "Usage: %s <filename>\n", getprogname());
return -1;
}
info.i_buf = NULL;
info.i_len = 0;
for (i = 1; i < argc; i++) {
if ((info.i_fd = open(argv[1], O_RDONLY)) == -1)
err(1, "Cannot open `%s'", argv[1]);
if (cdf_read_header(&info, &h) == -1)
err(1, "Cannot read header");
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if (cdf_read_sat(&info, &h, &sat) == -1)
err(1, "Cannot read sat");
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1)
err(1, "Cannot read ssat");
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if (cdf_read_dir(&info, &h, &sat, &dir) == -1)
err(1, "Cannot read dir");
if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst) == -1)
err(1, "Cannot read short stream");
#ifdef CDF_DEBUG
cdf_dump_stream(&h, &sst);
#endif
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn) == -1)
err(1, "Cannot read summary info");
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
(void)close(info.i_fd);
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2137_0 |
crossvul-cpp_data_bad_5418_5 | /*
* Copyright (c) 2002-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") 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, 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:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "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 HOLDERS 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. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
#include <jasper/jas_config.h>
#include <jasper/jas_types.h>
uchar jas_iccprofdata_srgb[] =
{
0x00, 0x00, 0x0c, 0x48, 0x4c, 0x69, 0x6e, 0x6f,
0x02, 0x10, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72,
0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xce, 0x00, 0x02, 0x00, 0x09, 0x00, 0x06,
0x00, 0x31, 0x00, 0x00, 0x61, 0x63, 0x73, 0x70,
0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d,
0x48, 0x50, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x11, 0x63, 0x70, 0x72, 0x74,
0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x33,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x84,
0x00, 0x00, 0x00, 0x6c, 0x77, 0x74, 0x70, 0x74,
0x00, 0x00, 0x01, 0xf0, 0x00, 0x00, 0x00, 0x14,
0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x02, 0x04,
0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a,
0x00, 0x00, 0x02, 0x18, 0x00, 0x00, 0x00, 0x14,
0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x2c,
0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a,
0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x14,
0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54,
0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64,
0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x4c,
0x00, 0x00, 0x00, 0x86, 0x76, 0x69, 0x65, 0x77,
0x00, 0x00, 0x03, 0xd4, 0x00, 0x00, 0x00, 0x24,
0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xf8,
0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x04, 0x0c, 0x00, 0x00, 0x00, 0x24,
0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x04, 0x30,
0x00, 0x00, 0x00, 0x0c, 0x72, 0x54, 0x52, 0x43,
0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c,
0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x3c,
0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43,
0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c,
0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00,
0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68,
0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x31, 0x39,
0x39, 0x38, 0x20, 0x48, 0x65, 0x77, 0x6c, 0x65,
0x74, 0x74, 0x2d, 0x50, 0x61, 0x63, 0x6b, 0x61,
0x72, 0x64, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x61,
0x6e, 0x79, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43,
0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x12, 0x73, 0x52, 0x47,
0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39,
0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x6f, 0xa2, 0x00, 0x00, 0x38, 0xf5,
0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x99,
0x00, 0x00, 0xb7, 0x85, 0x00, 0x00, 0x18, 0xda,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 0xa0, 0x00, 0x00, 0x0f, 0x84,
0x00, 0x00, 0xb6, 0xcf, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70,
0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e,
0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36,
0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65,
0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72,
0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d,
0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39,
0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52,
0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75,
0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c,
0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63,
0x65, 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e,
0x67, 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49,
0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d,
0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x52,
0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65,
0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67,
0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45,
0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32,
0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77,
0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0xfe,
0x00, 0x14, 0x5f, 0x2e, 0x00, 0x10, 0xcf, 0x14,
0x00, 0x03, 0xed, 0xcc, 0x00, 0x04, 0x13, 0x0b,
0x00, 0x03, 0x5c, 0x9e, 0x00, 0x00, 0x00, 0x01,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x4c, 0x09, 0x56, 0x00, 0x50, 0x00, 0x00,
0x00, 0x57, 0x1f, 0xe7, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02,
0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
0x43, 0x52, 0x54, 0x20, 0x63, 0x75, 0x72, 0x76,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f,
0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23,
0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a,
0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e,
0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86,
0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a,
0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1,
0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5,
0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01,
0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19,
0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c,
0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67,
0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1,
0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1,
0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03,
0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26,
0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71,
0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98,
0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb,
0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16,
0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72,
0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2,
0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06,
0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b,
0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8,
0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1,
0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58,
0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96,
0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16,
0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59,
0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3,
0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b,
0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf,
0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b,
0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa,
0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb,
0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4,
0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb,
0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae,
0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b,
0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8,
0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a,
0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3,
0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a,
0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e,
0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b,
0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a,
0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec,
0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7,
0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f,
0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45,
0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3,
0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5,
0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49,
0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56,
0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0,
0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa,
0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89,
0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf,
0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45,
0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77,
0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14,
0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52,
0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5,
0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40,
0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9,
0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41,
0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0,
0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55,
0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a,
0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c,
0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38,
0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7,
0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a,
0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06,
0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0,
0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69,
0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39,
0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1,
0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7,
0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c,
0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a,
0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d,
0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1,
0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2,
0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae,
0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c,
0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f,
0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b,
0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65,
0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60,
0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61,
0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a,
0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72,
0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a,
0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a,
0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0,
0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7,
0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c,
0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a,
0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e,
0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93,
0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6,
0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13,
0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75,
0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9,
0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a,
0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56,
0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6,
0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a,
0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa,
0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5,
0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94,
0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7,
0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96,
0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1,
0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf,
0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12,
0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0,
0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b,
0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28,
0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b,
0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89,
0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04,
0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01,
0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84,
0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92,
0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d,
0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b,
0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce,
0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc,
0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98,
0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6,
0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a,
0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9,
0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75,
0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5,
0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89,
0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa,
0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6,
0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38,
0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd,
0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f,
0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c,
0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00,
0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6,
0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a,
0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68,
0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e,
0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15,
0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec,
0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb,
0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3,
0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc,
0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5,
0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6,
0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1,
0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb,
0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8,
0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb,
0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29,
0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44,
0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84,
0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9,
0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb,
0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28,
0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c,
0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2,
0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38,
0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77,
0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
};
int jas_iccprofdata_srgblen = sizeof(jas_iccprofdata_srgb);
uchar jas_iccprofdata_sgray[] = {
0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x00, 0x00,
0x02, 0x20, 0x00, 0x00, 0x73, 0x63, 0x6e, 0x72,
0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xd3, 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0d,
0x00, 0x35, 0x00, 0x21, 0x61, 0x63, 0x73, 0x70,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x4b, 0x4f, 0x44, 0x41, 0x73, 0x47, 0x72, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d,
0x4a, 0x50, 0x45, 0x47, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x04, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x86,
0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x3c,
0x00, 0x00, 0x00, 0x2b, 0x77, 0x74, 0x70, 0x74,
0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x14,
0x6b, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x7c,
0x00, 0x00, 0x00, 0x0e, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c,
0x52, 0x65, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74,
0x65, 0x64, 0x20, 0x49, 0x43, 0x43, 0x20, 0x70,
0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x69, 0x6e,
0x67, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d, 0x67,
0x72, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74,
0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79,
0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x32, 0x30,
0x30, 0x33, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d,
0x67, 0x72, 0x65, 0x79, 0x20, 0x52, 0x65, 0x66,
0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xf3, 0x54, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcf, 0x63, 0x75, 0x72, 0x76,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x01, 0xcd
};
int jas_iccprofdata_sgraylen = sizeof(jas_iccprofdata_sgray);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5418_5 |
crossvul-cpp_data_good_5415_0 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2002 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") 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, 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:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "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 HOLDERS 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. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* JPEG-2000 Code Stream Library
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "jpc_cs.h"
/******************************************************************************\
* Types.
\******************************************************************************/
/* Marker segment table entry. */
typedef struct {
int id;
char *name;
jpc_msops_t ops;
} jpc_mstabent_t;
/******************************************************************************\
* Local prototypes.
\******************************************************************************/
static jpc_mstabent_t *jpc_mstab_lookup(int id);
static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static void jpc_poc_destroyparms(jpc_ms_t *ms);
static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out);
static void jpc_siz_destroyparms(jpc_ms_t *ms);
static void jpc_qcd_destroyparms(jpc_ms_t *ms);
static void jpc_qcc_destroyparms(jpc_ms_t *ms);
static void jpc_cod_destroyparms(jpc_ms_t *ms);
static void jpc_coc_destroyparms(jpc_ms_t *ms);
static void jpc_unk_destroyparms(jpc_ms_t *ms);
static void jpc_ppm_destroyparms(jpc_ms_t *ms);
static void jpc_ppt_destroyparms(jpc_ms_t *ms);
static void jpc_crg_destroyparms(jpc_ms_t *ms);
static void jpc_com_destroyparms(jpc_ms_t *ms);
static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms);
static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *in, uint_fast16_t len);
static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *out);
static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms);
static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms);
static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms);
/******************************************************************************\
* Global data.
\******************************************************************************/
static jpc_mstabent_t jpc_mstab[] = {
{JPC_MS_SOC, "SOC", {0, 0, 0, 0}},
{JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms,
jpc_sot_dumpparms}},
{JPC_MS_SOD, "SOD", {0, 0, 0, 0}},
{JPC_MS_EOC, "EOC", {0, 0, 0, 0}},
{JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms,
jpc_siz_putparms, jpc_siz_dumpparms}},
{JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms,
jpc_cod_putparms, jpc_cod_dumpparms}},
{JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms,
jpc_coc_putparms, jpc_coc_dumpparms}},
{JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms,
jpc_rgn_dumpparms}},
{JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms,
jpc_qcd_putparms, jpc_qcd_dumpparms}},
{JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms,
jpc_qcc_putparms, jpc_qcc_dumpparms}},
{JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms,
jpc_poc_putparms, jpc_poc_dumpparms}},
{JPC_MS_TLM, "TLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}},
{JPC_MS_PLM, "PLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}},
{JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms,
jpc_ppm_putparms, jpc_ppm_dumpparms}},
{JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms,
jpc_ppt_putparms, jpc_ppt_dumpparms}},
{JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms,
jpc_sop_dumpparms}},
{JPC_MS_EPH, "EPH", {0, 0, 0, 0}},
{JPC_MS_CRG, "CRG", {jpc_crg_destroyparms, jpc_crg_getparms,
jpc_crg_putparms, jpc_crg_dumpparms}},
{JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms,
jpc_com_putparms, jpc_com_dumpparms}},
{-1, "UNKNOWN", {jpc_unk_destroyparms, jpc_unk_getparms,
jpc_unk_putparms, jpc_unk_dumpparms}}
};
/******************************************************************************\
* Code stream manipulation functions.
\******************************************************************************/
/* Create a code stream state object. */
jpc_cstate_t *jpc_cstate_create()
{
jpc_cstate_t *cstate;
if (!(cstate = jas_malloc(sizeof(jpc_cstate_t)))) {
return 0;
}
cstate->numcomps = 0;
return cstate;
}
/* Destroy a code stream state object. */
void jpc_cstate_destroy(jpc_cstate_t *cstate)
{
jas_free(cstate);
}
/* Read a marker segment from a stream. */
jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate)
{
jpc_ms_t *ms;
jpc_mstabent_t *mstabent;
jas_stream_t *tmpstream;
if (!(ms = jpc_ms_create(0))) {
return 0;
}
/* Get the marker type. */
if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN ||
ms->id > JPC_MS_MAX) {
jpc_ms_destroy(ms);
return 0;
}
mstabent = jpc_mstab_lookup(ms->id);
ms->ops = &mstabent->ops;
/* Get the marker segment length and parameters if present. */
/* Note: It is tacitly assumed that a marker segment cannot have
parameters unless it has a length field. That is, there cannot
be a parameters field without a length field and vice versa. */
if (JPC_MS_HASPARMS(ms->id)) {
/* Get the length of the marker segment. */
if (jpc_getuint16(in, &ms->len) || ms->len < 3) {
jpc_ms_destroy(ms);
return 0;
}
/* Calculate the length of the marker segment parameters. */
ms->len -= 2;
/* Create and prepare a temporary memory stream from which to
read the marker segment parameters. */
/* Note: This approach provides a simple way of ensuring that
we never read beyond the end of the marker segment (even if
the marker segment length is errantly set too small). */
if (!(tmpstream = jas_stream_memopen(0, 0))) {
jpc_ms_destroy(ms);
return 0;
}
if (jas_stream_copy(tmpstream, in, ms->len) ||
jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {
jas_stream_close(tmpstream);
jpc_ms_destroy(ms);
return 0;
}
/* Get the marker segment parameters. */
if ((*ms->ops->getparms)(ms, cstate, tmpstream)) {
ms->ops = 0;
jpc_ms_destroy(ms);
jas_stream_close(tmpstream);
return 0;
}
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) {
jas_eprintf("warning: trailing garbage in marker segment (%ld bytes)\n",
ms->len - jas_stream_tell(tmpstream));
}
/* Close the temporary stream. */
jas_stream_close(tmpstream);
} else {
/* There are no marker segment parameters. */
ms->len = 0;
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
}
/* Update the code stream state information based on the type of
marker segment read. */
/* Note: This is a bit of a hack, but I'm not going to define another
type of virtual function for this one special case. */
if (ms->id == JPC_MS_SIZ) {
cstate->numcomps = ms->parms.siz.numcomps;
}
return ms;
}
/* Write a marker segment to a stream. */
int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms)
{
jas_stream_t *tmpstream;
int len;
/* Output the marker segment type. */
if (jpc_putuint16(out, ms->id)) {
return -1;
}
/* Output the marker segment length and parameters if necessary. */
if (ms->ops->putparms) {
/* Create a temporary stream in which to buffer the
parameter data. */
if (!(tmpstream = jas_stream_memopen(0, 0))) {
return -1;
}
if ((*ms->ops->putparms)(ms, cstate, tmpstream)) {
jas_stream_close(tmpstream);
return -1;
}
/* Get the number of bytes of parameter data written. */
if ((len = jas_stream_tell(tmpstream)) < 0) {
jas_stream_close(tmpstream);
return -1;
}
ms->len = len;
/* Write the marker segment length and parameter data to
the output stream. */
if (jas_stream_seek(tmpstream, 0, SEEK_SET) < 0 ||
jpc_putuint16(out, ms->len + 2) ||
jas_stream_copy(out, tmpstream, ms->len) < 0) {
jas_stream_close(tmpstream);
return -1;
}
/* Close the temporary stream. */
jas_stream_close(tmpstream);
}
/* This is a bit of a hack, but I'm not going to define another
type of virtual function for this one special case. */
if (ms->id == JPC_MS_SIZ) {
cstate->numcomps = ms->parms.siz.numcomps;
}
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
return 0;
}
/******************************************************************************\
* Marker segment operations.
\******************************************************************************/
/* Create a marker segment of the specified type. */
jpc_ms_t *jpc_ms_create(int type)
{
jpc_ms_t *ms;
jpc_mstabent_t *mstabent;
if (!(ms = jas_malloc(sizeof(jpc_ms_t)))) {
return 0;
}
ms->id = type;
ms->len = 0;
mstabent = jpc_mstab_lookup(ms->id);
ms->ops = &mstabent->ops;
memset(&ms->parms, 0, sizeof(jpc_msparms_t));
return ms;
}
/* Destroy a marker segment. */
void jpc_ms_destroy(jpc_ms_t *ms)
{
if (ms->ops && ms->ops->destroyparms) {
(*ms->ops->destroyparms)(ms);
}
jas_free(ms);
}
/* Dump a marker segment to a stream for debugging. */
void jpc_ms_dump(jpc_ms_t *ms, FILE *out)
{
jpc_mstabent_t *mstabent;
mstabent = jpc_mstab_lookup(ms->id);
fprintf(out, "type = 0x%04"PRIxFAST16" (%s);", ms->id, mstabent->name);
if (JPC_MS_HASPARMS(ms->id)) {
fprintf(out, " len = %"PRIuFAST16";", ms->len + 2);
if (ms->ops->dumpparms) {
(*ms->ops->dumpparms)(ms, out);
} else {
fprintf(out, "\n");
}
} else {
fprintf(out, "\n");
}
}
/******************************************************************************\
* SOT marker segment operations.
\******************************************************************************/
static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_sot_t *sot = &ms->parms.sot;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &sot->tileno) ||
jpc_getuint32(in, &sot->len) ||
jpc_getuint8(in, &sot->partno) ||
jpc_getuint8(in, &sot->numparts)) {
return -1;
}
if (sot->tileno > 65534 || sot->len < 12 || sot->partno > 254 ||
sot->numparts < 1 || sot->numparts > 255) {
return -1;
}
if (jas_stream_eof(in)) {
return -1;
}
return 0;
}
static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_sot_t *sot = &ms->parms.sot;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_putuint16(out, sot->tileno) ||
jpc_putuint32(out, sot->len) ||
jpc_putuint8(out, sot->partno) ||
jpc_putuint8(out, sot->numparts)) {
return -1;
}
return 0;
}
static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_sot_t *sot = &ms->parms.sot;
fprintf(out,
"tileno = %"PRIuFAST16"; len = %"PRIuFAST32"; partno = %d; numparts = %d\n",
sot->tileno, sot->len, sot->partno, sot->numparts);
return 0;
}
/******************************************************************************\
* SIZ marker segment operations.
\******************************************************************************/
static void jpc_siz_destroyparms(jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
if (siz->comps) {
jas_free(siz->comps);
}
}
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {
return -1;
}
if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {
jas_eprintf("all tiles are outside the image area\n");
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
assert(siz->width && siz->height && siz->tilewidth &&
siz->tileheight && siz->numcomps);
if (jpc_putuint16(out, siz->caps) ||
jpc_putuint32(out, siz->width) ||
jpc_putuint32(out, siz->height) ||
jpc_putuint32(out, siz->xoff) ||
jpc_putuint32(out, siz->yoff) ||
jpc_putuint32(out, siz->tilewidth) ||
jpc_putuint32(out, siz->tileheight) ||
jpc_putuint32(out, siz->tilexoff) ||
jpc_putuint32(out, siz->tileyoff) ||
jpc_putuint16(out, siz->numcomps)) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_putuint8(out, ((siz->comps[i].sgnd & 1) << 7) |
((siz->comps[i].prec - 1) & 0x7f)) ||
jpc_putuint8(out, siz->comps[i].hsamp) ||
jpc_putuint8(out, siz->comps[i].vsamp)) {
return -1;
}
}
return 0;
}
static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
fprintf(out, "caps = 0x%02"PRIxFAST16";\n", siz->caps);
fprintf(out, "width = %"PRIuFAST32"; height = %"PRIuFAST32"; xoff = %"PRIuFAST32"; yoff = %" PRIuFAST32 ";\n",
siz->width, siz->height, siz->xoff, siz->yoff);
fprintf(out, "tilewidth = %"PRIuFAST32"; tileheight = %"PRIuFAST32"; "
"tilexoff = %"PRIuFAST32"; tileyoff = %" PRIuFAST32 ";\n",
siz->tilewidth, siz->tileheight, siz->tilexoff, siz->tileyoff);
fprintf(out, "numcomps = %"PRIuFAST16";\n", siz->numcomps);
for (i = 0; i < siz->numcomps; ++i) {
fprintf(out, "prec[%d] = %d; sgnd[%d] = %d; hsamp[%d] = %d; "
"vsamp[%d] = %d\n", i, siz->comps[i].prec, i,
siz->comps[i].sgnd, i, siz->comps[i].hsamp, i,
siz->comps[i].vsamp);
}
return 0;
}
/******************************************************************************\
* COD marker segment operations.
\******************************************************************************/
static void jpc_cod_destroyparms(jpc_ms_t *ms)
{
jpc_cod_t *cod = &ms->parms.cod;
jpc_cox_destroycompparms(&cod->compparms);
}
static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_cod_t *cod = &ms->parms.cod;
if (jpc_getuint8(in, &cod->csty)) {
return -1;
}
if (jpc_getuint8(in, &cod->prg) ||
jpc_getuint16(in, &cod->numlyrs) ||
jpc_getuint8(in, &cod->mctrans)) {
return -1;
}
if (cod->numlyrs < 1 || cod->numlyrs > 65535) {
return -1;
}
if (jpc_cox_getcompparms(ms, cstate, in,
(cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
return -1;
}
if (jas_stream_eof(in)) {
jpc_cod_destroyparms(ms);
return -1;
}
return 0;
}
static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_cod_t *cod = &ms->parms.cod;
assert(cod->numlyrs > 0 && cod->compparms.numdlvls <= 32);
assert(cod->compparms.numdlvls == cod->compparms.numrlvls - 1);
if (jpc_putuint8(out, cod->compparms.csty) ||
jpc_putuint8(out, cod->prg) ||
jpc_putuint16(out, cod->numlyrs) ||
jpc_putuint8(out, cod->mctrans)) {
return -1;
}
if (jpc_cox_putcompparms(ms, cstate, out,
(cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
return -1;
}
return 0;
}
static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_cod_t *cod = &ms->parms.cod;
int i;
fprintf(out, "csty = 0x%02x;\n", cod->compparms.csty);
fprintf(out, "numdlvls = %d; qmfbid = %d; mctrans = %d\n",
cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans);
fprintf(out, "prg = %d; numlyrs = %"PRIuFAST16";\n",
cod->prg, cod->numlyrs);
fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
"cblksty = 0x%02x;\n", cod->compparms.cblkwidthval, cod->compparms.cblkheightval,
cod->compparms.cblksty);
if (cod->csty & JPC_COX_PRT) {
for (i = 0; i < cod->compparms.numrlvls; ++i) {
jas_eprintf("prcwidth[%d] = %d, prcheight[%d] = %d\n",
i, cod->compparms.rlvls[i].parwidthval,
i, cod->compparms.rlvls[i].parheightval);
}
}
return 0;
}
/******************************************************************************\
* COC marker segment operations.
\******************************************************************************/
static void jpc_coc_destroyparms(jpc_ms_t *ms)
{
jpc_coc_t *coc = &ms->parms.coc;
jpc_cox_destroycompparms(&coc->compparms);
}
static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_coc_t *coc = &ms->parms.coc;
uint_fast8_t tmp;
if (cstate->numcomps <= 256) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
coc->compno = tmp;
} else {
if (jpc_getuint16(in, &coc->compno)) {
return -1;
}
}
if (jpc_getuint8(in, &coc->compparms.csty)) {
return -1;
}
if (jpc_cox_getcompparms(ms, cstate, in,
(coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
return -1;
}
if (jas_stream_eof(in)) {
return -1;
}
return 0;
}
static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_coc_t *coc = &ms->parms.coc;
assert(coc->compparms.numdlvls <= 32);
if (cstate->numcomps <= 256) {
if (jpc_putuint8(out, coc->compno)) {
return -1;
}
} else {
if (jpc_putuint16(out, coc->compno)) {
return -1;
}
}
if (jpc_putuint8(out, coc->compparms.csty)) {
return -1;
}
if (jpc_cox_putcompparms(ms, cstate, out,
(coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
return -1;
}
return 0;
}
static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_coc_t *coc = &ms->parms.coc;
fprintf(out, "compno = %"PRIuFAST16"; csty = 0x%02x; numdlvls = %d;\n",
coc->compno, coc->compparms.csty, coc->compparms.numdlvls);
fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
"cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval,
coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid);
return 0;
}
/******************************************************************************\
* COD/COC marker segment operation helper functions.
\******************************************************************************/
static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms)
{
/* Eliminate compiler warning about unused variables. */
compparms = 0;
}
static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms)
{
uint_fast8_t tmp;
int i;
/* Eliminate compiler warning about unused variables. */
ms = 0;
cstate = 0;
if (jpc_getuint8(in, &compparms->numdlvls) ||
jpc_getuint8(in, &compparms->cblkwidthval) ||
jpc_getuint8(in, &compparms->cblkheightval) ||
jpc_getuint8(in, &compparms->cblksty) ||
jpc_getuint8(in, &compparms->qmfbid)) {
return -1;
}
if (compparms->numdlvls > 32) {
goto error;
}
compparms->numrlvls = compparms->numdlvls + 1;
if (compparms->numrlvls > JPC_MAXRLVLS) {
goto error;
}
if (prtflag) {
for (i = 0; i < compparms->numrlvls; ++i) {
if (jpc_getuint8(in, &tmp)) {
goto error;
}
compparms->rlvls[i].parwidthval = tmp & 0xf;
compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf;
}
/* Sigh.
This bit should be in the same field in both COC and COD mrk segs. */
compparms->csty |= JPC_COX_PRT;
}
if (jas_stream_eof(in)) {
goto error;
}
return 0;
error:
if (compparms) {
jpc_cox_destroycompparms(compparms);
}
return -1;
}
static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms)
{
int i;
assert(compparms->numdlvls <= 32);
/* Eliminate compiler warning about unused variables. */
ms = 0;
cstate = 0;
if (jpc_putuint8(out, compparms->numdlvls) ||
jpc_putuint8(out, compparms->cblkwidthval) ||
jpc_putuint8(out, compparms->cblkheightval) ||
jpc_putuint8(out, compparms->cblksty) ||
jpc_putuint8(out, compparms->qmfbid)) {
return -1;
}
if (prtflag) {
for (i = 0; i < compparms->numrlvls; ++i) {
if (jpc_putuint8(out,
((compparms->rlvls[i].parheightval & 0xf) << 4) |
(compparms->rlvls[i].parwidthval & 0xf))) {
return -1;
}
}
}
return 0;
}
/******************************************************************************\
* RGN marker segment operations.
\******************************************************************************/
static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
uint_fast8_t tmp;
if (cstate->numcomps <= 256) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
rgn->compno = tmp;
} else {
if (jpc_getuint16(in, &rgn->compno)) {
return -1;
}
}
if (jpc_getuint8(in, &rgn->roisty) ||
jpc_getuint8(in, &rgn->roishift)) {
return -1;
}
return 0;
}
static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
if (cstate->numcomps <= 256) {
if (jpc_putuint8(out, rgn->compno)) {
return -1;
}
} else {
if (jpc_putuint16(out, rgn->compno)) {
return -1;
}
}
if (jpc_putuint8(out, rgn->roisty) ||
jpc_putuint8(out, rgn->roishift)) {
return -1;
}
return 0;
}
static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
fprintf(out, "compno = %"PRIuFAST16"; roisty = %d; roishift = %d\n",
rgn->compno, rgn->roisty, rgn->roishift);
return 0;
}
/******************************************************************************\
* QCD marker segment operations.
\******************************************************************************/
static void jpc_qcd_destroyparms(jpc_ms_t *ms)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
jpc_qcx_destroycompparms(&qcd->compparms);
}
static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
return jpc_qcx_getcompparms(compparms, cstate, in, ms->len);
}
static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
return jpc_qcx_putcompparms(compparms, cstate, out);
}
static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, JAS_CAST(unsigned, JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i])),
i, JAS_CAST(unsigned, JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])));
}
return 0;
}
/******************************************************************************\
* QCC marker segment operations.
\******************************************************************************/
static void jpc_qcc_destroyparms(jpc_ms_t *ms)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
jpc_qcx_destroycompparms(&qcc->compparms);
}
static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
uint_fast8_t tmp;
int len;
len = ms->len;
if (cstate->numcomps <= 256) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
qcc->compno = tmp;
--len;
} else {
if (jpc_getuint16(in, &qcc->compno)) {
return -1;
}
len -= 2;
}
if (jpc_qcx_getcompparms(&qcc->compparms, cstate, in, len)) {
return -1;
}
if (jas_stream_eof(in)) {
jpc_qcc_destroyparms(ms);
return -1;
}
return 0;
}
static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
if (cstate->numcomps <= 256) {
if (jpc_putuint8(out, qcc->compno)) {
return -1;
}
} else {
if (jpc_putuint16(out, qcc->compno)) {
return -1;
}
}
if (jpc_qcx_putcompparms(&qcc->compparms, cstate, out)) {
return -1;
}
return 0;
}
static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
int i;
fprintf(out, "compno = %"PRIuFAST16"; qntsty = %d; numguard = %d; "
"numstepsizes = %d\n", qcc->compno, qcc->compparms.qntsty, qcc->compparms.numguard,
qcc->compparms.numstepsizes);
for (i = 0; i < qcc->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, (unsigned) JPC_QCX_GETEXPN(qcc->compparms.stepsizes[i]),
i, (unsigned) JPC_QCX_GETMANT(qcc->compparms.stepsizes[i]));
}
return 0;
}
/******************************************************************************\
* QCD/QCC marker segment helper functions.
\******************************************************************************/
static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms)
{
if (compparms->stepsizes) {
jas_free(compparms->stepsizes);
}
}
static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *in, uint_fast16_t len)
{
uint_fast8_t tmp;
int n;
int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
n = 0;
if (jpc_getuint8(in, &tmp)) {
return -1;
}
++n;
compparms->qntsty = tmp & 0x1f;
compparms->numguard = (tmp >> 5) & 7;
switch (compparms->qntsty) {
case JPC_QCX_SIQNT:
compparms->numstepsizes = 1;
break;
case JPC_QCX_NOQNT:
compparms->numstepsizes = (len - n);
break;
case JPC_QCX_SEQNT:
/* XXX - this is a hack */
compparms->numstepsizes = (len - n) / 2;
break;
}
/* Ensure that the step size array is sufficiently large. */
if (compparms->numstepsizes > 3 * JPC_MAXRLVLS + 1) {
jpc_qcx_destroycompparms(compparms);
return -1;
}
if (compparms->numstepsizes > 0) {
if (!(compparms->stepsizes = jas_alloc2(compparms->numstepsizes,
sizeof(uint_fast16_t)))) {
abort();
}
for (i = 0; i < compparms->numstepsizes; ++i) {
if (compparms->qntsty == JPC_QCX_NOQNT) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3);
} else {
if (jpc_getuint16(in, &compparms->stepsizes[i])) {
return -1;
}
}
}
} else {
compparms->stepsizes = 0;
}
if (jas_stream_error(in) || jas_stream_eof(in)) {
jpc_qcx_destroycompparms(compparms);
return -1;
}
return 0;
}
static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *out)
{
int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty);
for (i = 0; i < compparms->numstepsizes; ++i) {
if (compparms->qntsty == JPC_QCX_NOQNT) {
if (jpc_putuint8(out, JPC_QCX_GETEXPN(
compparms->stepsizes[i]) << 3)) {
return -1;
}
} else {
if (jpc_putuint16(out, compparms->stepsizes[i])) {
return -1;
}
}
}
return 0;
}
/******************************************************************************\
* SOP marker segment operations.
\******************************************************************************/
static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_sop_t *sop = &ms->parms.sop;
/* Eliminate compiler warning about unused variable. */
cstate = 0;
if (jpc_getuint16(in, &sop->seqno)) {
return -1;
}
return 0;
}
static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_sop_t *sop = &ms->parms.sop;
/* Eliminate compiler warning about unused variable. */
cstate = 0;
if (jpc_putuint16(out, sop->seqno)) {
return -1;
}
return 0;
}
static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_sop_t *sop = &ms->parms.sop;
fprintf(out, "seqno = %"PRIuFAST16";\n", sop->seqno);
return 0;
}
/******************************************************************************\
* PPM marker segment operations.
\******************************************************************************/
static void jpc_ppm_destroyparms(jpc_ms_t *ms)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
if (ppm->data) {
jas_free(ppm->data);
}
}
static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
ppm->data = 0;
if (ms->len < 1) {
goto error;
}
if (jpc_getuint8(in, &ppm->ind)) {
goto error;
}
ppm->len = ms->len - 1;
if (ppm->len > 0) {
if (!(ppm->data = jas_malloc(ppm->len))) {
goto error;
}
if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) {
goto error;
}
} else {
ppm->data = 0;
}
return 0;
error:
jpc_ppm_destroyparms(ms);
return -1;
}
static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
return -1;
}
return 0;
}
static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
fprintf(out, "ind=%d; len = %"PRIuFAST16";\n", ppm->ind, ppm->len);
if (ppm->len > 0) {
fprintf(out, "data =\n");
jas_memdump(out, ppm->data, ppm->len);
}
return 0;
}
/******************************************************************************\
* PPT marker segment operations.
\******************************************************************************/
static void jpc_ppt_destroyparms(jpc_ms_t *ms)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
if (ppt->data) {
jas_free(ppt->data);
}
}
static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
ppt->data = 0;
if (ms->len < 1) {
goto error;
}
if (jpc_getuint8(in, &ppt->ind)) {
goto error;
}
ppt->len = ms->len - 1;
if (ppt->len > 0) {
if (!(ppt->data = jas_malloc(ppt->len))) {
goto error;
}
if (jas_stream_read(in, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) {
goto error;
}
} else {
ppt->data = 0;
}
return 0;
error:
jpc_ppt_destroyparms(ms);
return -1;
}
static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
/* Eliminate compiler warning about unused variable. */
cstate = 0;
if (jpc_putuint8(out, ppt->ind)) {
return -1;
}
if (jas_stream_write(out, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) {
return -1;
}
return 0;
}
static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
fprintf(out, "ind=%d; len = %"PRIuFAST32";\n", ppt->ind, ppt->len);
if (ppt->len > 0) {
fprintf(out, "data =\n");
jas_memdump(out, ppt->data, ppt->len);
}
return 0;
}
/******************************************************************************\
* POC marker segment operations.
\******************************************************************************/
static void jpc_poc_destroyparms(jpc_ms_t *ms)
{
jpc_poc_t *poc = &ms->parms.poc;
if (poc->pchgs) {
jas_free(poc->pchgs);
}
}
static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
uint_fast8_t tmp;
poc->numpchgs = (cstate->numcomps > 256) ? (ms->len / 9) :
(ms->len / 7);
if (!(poc->pchgs = jas_alloc2(poc->numpchgs, sizeof(jpc_pocpchg_t)))) {
goto error;
}
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
++pchg) {
if (jpc_getuint8(in, &pchg->rlvlnostart)) {
goto error;
}
if (cstate->numcomps > 256) {
if (jpc_getuint16(in, &pchg->compnostart)) {
goto error;
}
} else {
if (jpc_getuint8(in, &tmp)) {
goto error;
};
pchg->compnostart = tmp;
}
if (jpc_getuint16(in, &pchg->lyrnoend) ||
jpc_getuint8(in, &pchg->rlvlnoend)) {
goto error;
}
if (cstate->numcomps > 256) {
if (jpc_getuint16(in, &pchg->compnoend)) {
goto error;
}
} else {
if (jpc_getuint8(in, &tmp)) {
goto error;
}
pchg->compnoend = tmp;
}
if (jpc_getuint8(in, &pchg->prgord)) {
goto error;
}
if (pchg->rlvlnostart > pchg->rlvlnoend ||
pchg->compnostart > pchg->compnoend) {
goto error;
}
}
return 0;
error:
jpc_poc_destroyparms(ms);
return -1;
}
static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
++pchg) {
if (jpc_putuint8(out, pchg->rlvlnostart) ||
((cstate->numcomps > 256) ?
jpc_putuint16(out, pchg->compnostart) :
jpc_putuint8(out, pchg->compnostart)) ||
jpc_putuint16(out, pchg->lyrnoend) ||
jpc_putuint8(out, pchg->rlvlnoend) ||
((cstate->numcomps > 256) ?
jpc_putuint16(out, pchg->compnoend) :
jpc_putuint8(out, pchg->compnoend)) ||
jpc_putuint8(out, pchg->prgord)) {
return -1;
}
}
return 0;
}
static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs;
++pchgno, ++pchg) {
fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord);
fprintf(out, "cs[%d] = %"PRIuFAST16"; ce[%d] = %"PRIuFAST16"; ",
pchgno, pchg->compnostart, pchgno, pchg->compnoend);
fprintf(out, "rs[%d] = %d; re[%d] = %d; ",
pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend);
fprintf(out, "le[%d] = %"PRIuFAST16"\n", pchgno, pchg->lyrnoend);
}
return 0;
}
/******************************************************************************\
* CRG marker segment operations.
\******************************************************************************/
static void jpc_crg_destroyparms(jpc_ms_t *ms)
{
jpc_crg_t *crg = &ms->parms.crg;
if (crg->comps) {
jas_free(crg->comps);
}
}
static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_crg_t *crg = &ms->parms.crg;
jpc_crgcomp_t *comp;
uint_fast16_t compno;
crg->numcomps = cstate->numcomps;
if (!(crg->comps = jas_alloc2(cstate->numcomps, sizeof(jpc_crgcomp_t)))) {
return -1;
}
for (compno = 0, comp = crg->comps; compno < cstate->numcomps;
++compno, ++comp) {
if (jpc_getuint16(in, &comp->hoff) ||
jpc_getuint16(in, &comp->voff)) {
jpc_crg_destroyparms(ms);
return -1;
}
}
return 0;
}
static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_crg_t *crg = &ms->parms.crg;
int compno;
jpc_crgcomp_t *comp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
++comp) {
if (jpc_putuint16(out, comp->hoff) ||
jpc_putuint16(out, comp->voff)) {
return -1;
}
}
return 0;
}
static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_crg_t *crg = &ms->parms.crg;
int compno;
jpc_crgcomp_t *comp;
for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
++comp) {
fprintf(out, "hoff[%d] = %"PRIuFAST16"; voff[%d] = %"PRIuFAST16"\n",
compno, comp->hoff, compno, comp->voff);
}
return 0;
}
/******************************************************************************\
* Operations for COM marker segment.
\******************************************************************************/
static void jpc_com_destroyparms(jpc_ms_t *ms)
{
jpc_com_t *com = &ms->parms.com;
if (com->data) {
jas_free(com->data);
}
}
static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_com_t *com = &ms->parms.com;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &com->regid)) {
return -1;
}
com->len = ms->len - 2;
if (com->len > 0) {
if (!(com->data = jas_malloc(com->len))) {
return -1;
}
if (jas_stream_read(in, com->data, com->len) != JAS_CAST(int, com->len)) {
return -1;
}
} else {
com->data = 0;
}
return 0;
}
static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_com_t *com = &ms->parms.com;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_putuint16(out, com->regid)) {
return -1;
}
if (jas_stream_write(out, com->data, com->len) != JAS_CAST(int, com->len)) {
return -1;
}
return 0;
}
static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_com_t *com = &ms->parms.com;
unsigned int i;
int printable;
fprintf(out, "regid = %"PRIuFAST16";\n", com->regid);
printable = 1;
for (i = 0; i < com->len; ++i) {
if (!isprint(com->data[i])) {
printable = 0;
break;
}
}
if (printable) {
fprintf(out, "data = ");
fwrite(com->data, sizeof(char), com->len, out);
fprintf(out, "\n");
}
return 0;
}
/******************************************************************************\
* Operations for unknown types of marker segments.
\******************************************************************************/
static void jpc_unk_destroyparms(jpc_ms_t *ms)
{
jpc_unk_t *unk = &ms->parms.unk;
if (unk->data) {
jas_free(unk->data);
}
}
static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_unk_t *unk = &ms->parms.unk;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (ms->len > 0) {
if (!(unk->data = jas_alloc2(ms->len, sizeof(unsigned char)))) {
return -1;
}
if (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) {
jas_free(unk->data);
return -1;
}
unk->len = ms->len;
} else {
unk->data = 0;
unk->len = 0;
}
return 0;
}
static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
/* Eliminate compiler warning about unused variables. */
cstate = 0;
ms = 0;
out = 0;
/* If this function is called, we are trying to write an unsupported
type of marker segment. Return with an error indication. */
return -1;
}
static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out)
{
unsigned int i;
jpc_unk_t *unk = &ms->parms.unk;
for (i = 0; i < unk->len; ++i) {
fprintf(out, "%02x ", unk->data[i]);
}
return 0;
}
/******************************************************************************\
* Primitive I/O operations.
\******************************************************************************/
int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val)
{
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
if (val) {
*val = c;
}
return 0;
}
int jpc_putuint8(jas_stream_t *out, uint_fast8_t val)
{
if (jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val)
{
uint_fast16_t v;
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if (val) {
*val = v;
}
return 0;
}
int jpc_putuint16(jas_stream_t *out, uint_fast16_t val)
{
if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val)
{
uint_fast32_t v;
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if (val) {
*val = v;
}
return 0;
}
int jpc_putuint32(jas_stream_t *out, uint_fast32_t val)
{
if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
/******************************************************************************\
* Miscellany
\******************************************************************************/
static jpc_mstabent_t *jpc_mstab_lookup(int id)
{
jpc_mstabent_t *mstabent;
for (mstabent = jpc_mstab;; ++mstabent) {
if (mstabent->id == id || mstabent->id < 0) {
return mstabent;
}
}
assert(0);
return 0;
}
int jpc_validate(jas_stream_t *in)
{
int n;
int i;
unsigned char buf[2];
assert(JAS_STREAM_MAXPUTBACK >= 2);
if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
return -1;
}
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
if (n < 2) {
return -1;
}
if (buf[0] == (JPC_MS_SOC >> 8) && buf[1] == (JPC_MS_SOC & 0xff)) {
return 0;
}
return -1;
}
int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len)
{
return jas_stream_copy(out, in, len);
}
int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long len)
{
return jas_stream_copy(out, in, len);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5415_0 |
crossvul-cpp_data_good_3195_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT GGGG AAA %
% T G A A %
% T G GG AAAAA %
% T G G A A %
% T GGG A A %
% %
% %
% Read/Write Truevision Targa Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://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 "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Enumerated declaractions.
*/
typedef enum
{
TGAColormap = 1,
TGARGB = 2,
TGAMonochrome = 3,
TGARLEColormap = 9,
TGARLERGB = 10,
TGARLEMonochrome = 11
} TGAImageType;
/*
Typedef declaractions.
*/
typedef struct _TGAInfo
{
TGAImageType
image_type;
unsigned char
id_length,
colormap_type;
unsigned short
colormap_index,
colormap_length;
unsigned char
colormap_size;
unsigned short
x_origin,
y_origin,
width,
height;
unsigned char
bits_per_pixel,
attributes;
} TGAInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteTGAImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T G A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTGAImage() reads a Truevision TGA 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 ReadTGAImage method is:
%
% Image *ReadTGAImage(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 Image *ReadTGAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PixelPacket
pixel;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
size_t
base,
flag,
offset,
real,
skip;
ssize_t
count,
y;
TGAInfo
tga_info;
unsigned char
j,
k,
pixels[4],
runlength;
unsigned int
alpha_bits;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read TGA header information.
*/
count=ReadBlob(image,1,&tga_info.id_length);
tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
tga_info.image_type=(TGAImageType) ReadBlobByte(image);
if ((count != 1) ||
((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARGB) &&
(tga_info.image_type != TGAMonochrome) &&
(tga_info.image_type != TGARLEColormap) &&
(tga_info.image_type != TGARLERGB) &&
(tga_info.image_type != TGARLEMonochrome)) ||
(((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGARLEColormap)) &&
(tga_info.colormap_type == 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
tga_info.colormap_index=ReadBlobLSBShort(image);
tga_info.colormap_length=ReadBlobLSBShort(image);
tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
tga_info.x_origin=ReadBlobLSBShort(image);
tga_info.y_origin=ReadBlobLSBShort(image);
tga_info.width=(unsigned short) ReadBlobLSBShort(image);
tga_info.height=(unsigned short) ReadBlobLSBShort(image);
tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
tga_info.attributes=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
(tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image structure.
*/
image->columns=tga_info.width;
image->rows=tga_info.height;
alpha_bits=(tga_info.attributes & 0x0FU);
image->matte=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||
(tga_info.colormap_size == 32) ? MagickTrue : MagickFalse;
if ((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARLEColormap))
image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
(tga_info.bits_per_pixel <= 16) ? 5 : 8);
else
image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
(tga_info.colormap_size <= 16) ? 5 : 8);
if ((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGAMonochrome) ||
(tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->storage_class=PseudoClass;
image->compression=NoCompression;
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome) ||
(tga_info.image_type == TGARLERGB))
image->compression=RLECompression;
if (image->storage_class == PseudoClass)
{
if (tga_info.colormap_type != 0)
image->colors=tga_info.colormap_index+tga_info.colormap_length;
else
{
size_t
one;
one=1;
image->colors=one << tga_info.bits_per_pixel;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (tga_info.id_length != 0)
{
char
*comment;
size_t
length;
/*
TGA image comment.
*/
length=(size_t) tga_info.id_length;
comment=(char *) NULL;
if (~length >= (MaxTextExtent-1))
comment=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,tga_info.id_length,(unsigned char *) comment);
comment[tga_info.id_length]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
if (tga_info.attributes & (1UL << 4))
{
if (tga_info.attributes & (1UL << 5))
SetImageArtifact(image,"tga:image-origin","TopRight");
else
SetImageArtifact(image,"tga:image-origin","BottomRight");
}
else
{
if (tga_info.attributes & (1UL << 5))
SetImageArtifact(image,"tga:image-origin","TopLeft");
else
SetImageArtifact(image,"tga:image-origin","BottomLeft");
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
pixel.opacity=(Quantum) OpaqueOpacity;
if (tga_info.colormap_type != 0)
{
/*
Read TGA raster colormap.
*/
if (image->colors < tga_info.colormap_index)
image->colors=tga_info.colormap_index;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) tga_info.colormap_index; i++)
image->colormap[i]=pixel;
for ( ; i < (ssize_t) image->colors; i++)
{
switch (tga_info.colormap_size)
{
case 8:
default:
{
/*
Gray scale.
*/
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=pixel.red;
pixel.blue=pixel.red;
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of red green and blue.
*/
j=(unsigned char) ReadBlobByte(image);
k=(unsigned char) ReadBlobByte(image);
range=GetQuantumRange(5UL);
pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range);
pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+
(1UL*(j & 0xe0) >> 5),range);
pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range);
break;
}
case 24:
{
/*
8 bits each of blue, green and red.
*/
pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
break;
}
case 32:
{
/*
8 bits each of blue, green, red, and alpha.
*/
pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image)));
break;
}
}
image->colormap[i]=pixel;
}
}
/*
Convert TGA pixels to pixel packets.
*/
base=0;
flag=0;
skip=MagickFalse;
real=0;
index=(IndexPacket) 0;
runlength=0;
offset=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
real=offset;
if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
real=image->rows-real-1;
q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLERGB) ||
(tga_info.image_type == TGARLEMonochrome))
{
if (runlength != 0)
{
runlength--;
skip=flag != 0;
}
else
{
count=ReadBlob(image,1,&runlength);
if (count != 1)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
flag=runlength & 0x80;
if (flag != 0)
runlength-=128;
skip=MagickFalse;
}
}
if (skip == MagickFalse)
switch (tga_info.bits_per_pixel)
{
case 8:
default:
{
/*
Gray scale.
*/
index=(IndexPacket) ReadBlobByte(image);
if (tga_info.colormap_type != 0)
pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
1UL*index)];
else
{
pixel.red=ScaleCharToQuantum((unsigned char) index);
pixel.green=ScaleCharToQuantum((unsigned char) index);
pixel.blue=ScaleCharToQuantum((unsigned char) index);
}
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of RGB;
*/
if (ReadBlob(image,2,pixels) != 2)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
j=pixels[0];
k=pixels[1];
range=GetQuantumRange(5UL);
pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range);
pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+
(1UL*(j & 0xe0) >> 5),range);
pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range);
if (image->matte != MagickFalse)
pixel.opacity=(k & 0x80) == 0 ? (Quantum) TransparentOpacity :
(Quantum) OpaqueOpacity;
if (image->storage_class == PseudoClass)
index=ConstrainColormapIndex(image,((size_t) k << 8)+j);
break;
}
case 24:
{
/*
BGR pixels.
*/
if (ReadBlob(image,3,pixels) != 3)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=ScaleCharToQuantum(pixels[0]);
pixel.green=ScaleCharToQuantum(pixels[1]);
pixel.red=ScaleCharToQuantum(pixels[2]);
break;
}
case 32:
{
/*
BGRA pixels.
*/
if (ReadBlob(image,4,pixels) != 4)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=ScaleCharToQuantum(pixels[0]);
pixel.green=ScaleCharToQuantum(pixels[1]);
pixel.red=ScaleCharToQuantum(pixels[2]);
pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
pixels[3]));
break;
}
}
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,index);
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->matte != MagickFalse)
SetPixelOpacity(q,pixel.opacity);
q++;
}
/*
if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)
offset+=4;
else
*/
if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)
offset+=2;
else
offset++;
if (offset >= image->rows)
{
base++;
offset=base;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T G A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTGAImage() adds properties for the TGA 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 RegisterTGAImage method is:
%
% size_t RegisterTGAImage(void)
%
*/
ModuleExport size_t RegisterTGAImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("ICB");
entry->decoder=(DecodeImageHandler *) ReadTGAImage;
entry->encoder=(EncodeImageHandler *) WriteTGAImage;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Truevision Targa image");
entry->module=ConstantString("TGA");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TGA");
entry->decoder=(DecodeImageHandler *) ReadTGAImage;
entry->encoder=(EncodeImageHandler *) WriteTGAImage;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Truevision Targa image");
entry->module=ConstantString("TGA");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("VDA");
entry->decoder=(DecodeImageHandler *) ReadTGAImage;
entry->encoder=(EncodeImageHandler *) WriteTGAImage;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Truevision Targa image");
entry->module=ConstantString("TGA");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("VST");
entry->decoder=(DecodeImageHandler *) ReadTGAImage;
entry->encoder=(EncodeImageHandler *) WriteTGAImage;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Truevision Targa image");
entry->module=ConstantString("TGA");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T G A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTGAImage() removes format registrations made by the
% TGA module from the list of supported formats.
%
% The format of the UnregisterTGAImage method is:
%
% UnregisterTGAImage(void)
%
*/
ModuleExport void UnregisterTGAImage(void)
{
(void) UnregisterMagickInfo("ICB");
(void) UnregisterMagickInfo("TGA");
(void) UnregisterMagickInfo("VDA");
(void) UnregisterMagickInfo("VST");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T G A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTGAImage() writes a image in the Truevision Targa rasterfile
% format.
%
% The format of the WriteTGAImage method is:
%
% MagickBooleanType WriteTGAImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static inline void WriteTGAPixel(Image *image,TGAImageType image_type,
const IndexPacket *indexes,const PixelPacket *p,const QuantumAny range,
const double midpoint)
{
if (image_type == TGAColormap || image_type == TGARLEColormap)
(void) WriteBlobByte(image,(unsigned char) GetPixelIndex(indexes));
else
{
if (image_type == TGAMonochrome || image_type == TGARLEMonochrome)
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p))));
else
if (image->depth == 5)
{
unsigned char
green,
value;
green=(unsigned char) ScaleQuantumToAny(GetPixelGreen(p),range);
value=((unsigned char) ScaleQuantumToAny(GetPixelBlue(p),range)) |
((green & 0x07) << 5);
(void) WriteBlobByte(image,value);
value=(unsigned char) ((((image->matte != MagickFalse) &&
((double) GetPixelOpacity(p) < midpoint)) ? 0x80 : 0) |
((unsigned char) ScaleQuantumToAny(GetPixelRed(p),range) << 2) |
((green & 0x18) >> 3));
(void) WriteBlobByte(image,value);
}
else
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte != MagickFalse)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
}
}
}
static MagickBooleanType WriteTGAImage(const ImageInfo *image_info,Image *image)
{
CompressionType
compression;
const char
*comment,
*value;
const double
midpoint = QuantumRange/2.0;
MagickBooleanType
status;
QuantumAny
range;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
register ssize_t
i;
register unsigned char
*q;
ssize_t
count,
y;
TGAInfo
tga_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Initialize TGA raster file header.
*/
if ((image->columns > 65535L) || (image->rows > 65535L))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TransformImageColorspace(image,sRGBColorspace);
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
range=GetQuantumRange(5UL);
tga_info.id_length=0;
comment=GetImageProperty(image,"comment");
if (comment != (const char *) NULL)
tga_info.id_length=(unsigned char) MagickMin(strlen(comment),255);
tga_info.colormap_type=0;
tga_info.colormap_index=0;
tga_info.colormap_length=0;
tga_info.colormap_size=0;
tga_info.x_origin=0;
tga_info.y_origin=0;
tga_info.width=(unsigned short) image->columns;
tga_info.height=(unsigned short) image->rows;
tga_info.bits_per_pixel=8;
tga_info.attributes=0;
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType) &&
(image_info->type != PaletteType) &&
(image->matte == MagickFalse) &&
(SetImageGray(image,&image->exception) != MagickFalse))
tga_info.image_type=compression == RLECompression ? TGARLEMonochrome :
TGAMonochrome;
else
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
/*
Full color TGA raster.
*/
tga_info.image_type=compression == RLECompression ? TGARLERGB : TGARGB;
if (image_info->depth == 5)
{
tga_info.bits_per_pixel=16;
if (image->matte != MagickFalse)
tga_info.attributes=1; /* # of alpha bits */
}
else
{
tga_info.bits_per_pixel=24;
if (image->matte != MagickFalse)
{
tga_info.bits_per_pixel=32;
tga_info.attributes=8; /* # of alpha bits */
}
}
}
else
{
/*
Colormapped TGA raster.
*/
tga_info.image_type=compression == RLECompression ? TGARLEColormap :
TGAColormap;
tga_info.colormap_type=1;
tga_info.colormap_length=(unsigned short) image->colors;
if (image_info->depth == 5)
tga_info.colormap_size=16;
else
tga_info.colormap_size=24;
}
value=GetImageArtifact(image,"tga:image-origin");
if (value != (const char *) NULL)
{
OrientationType
origin;
origin=(OrientationType) ParseCommandOption(MagickOrientationOptions,
MagickFalse,value);
if (origin == BottomRightOrientation || origin == TopRightOrientation)
tga_info.attributes|=(1UL << 4);
if (origin == TopLeftOrientation || origin == TopRightOrientation)
tga_info.attributes|=(1UL << 5);
}
/*
Write TGA header.
*/
(void) WriteBlobByte(image,tga_info.id_length);
(void) WriteBlobByte(image,tga_info.colormap_type);
(void) WriteBlobByte(image,(unsigned char) tga_info.image_type);
(void) WriteBlobLSBShort(image,tga_info.colormap_index);
(void) WriteBlobLSBShort(image,tga_info.colormap_length);
(void) WriteBlobByte(image,tga_info.colormap_size);
(void) WriteBlobLSBShort(image,tga_info.x_origin);
(void) WriteBlobLSBShort(image,tga_info.y_origin);
(void) WriteBlobLSBShort(image,tga_info.width);
(void) WriteBlobLSBShort(image,tga_info.height);
(void) WriteBlobByte(image,tga_info.bits_per_pixel);
(void) WriteBlobByte(image,tga_info.attributes);
if (tga_info.id_length != 0)
(void) WriteBlob(image,tga_info.id_length,(unsigned char *) comment);
if (tga_info.colormap_type != 0)
{
unsigned char
green,
*targa_colormap;
/*
Dump colormap to file (blue, green, red byte order).
*/
targa_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
tga_info.colormap_length,(tga_info.colormap_size/8)*sizeof(
*targa_colormap));
if (targa_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
q=targa_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
if (image_info->depth == 5)
{
green=(unsigned char) ScaleQuantumToAny(image->colormap[i].green,
range);
*q++=((unsigned char) ScaleQuantumToAny(image->colormap[i].blue,
range)) | ((green & 0x07) << 5);
*q++=(((image->matte != MagickFalse) && (
(double) image->colormap[i].opacity < midpoint)) ? 0x80 : 0) |
((unsigned char) ScaleQuantumToAny(image->colormap[i].red,
range) << 2) | ((green & 0x18) >> 3);
}
else
{
*q++=ScaleQuantumToChar(image->colormap[i].blue);
*q++=ScaleQuantumToChar(image->colormap[i].green);
*q++=ScaleQuantumToChar(image->colormap[i].red);
}
}
(void) WriteBlob(image,(size_t) ((tga_info.colormap_size/8)*
tga_info.colormap_length),targa_colormap);
targa_colormap=(unsigned char *) RelinquishMagickMemory(targa_colormap);
}
/*
Convert MIFF to TGA raster pixels.
*/
for (y=(ssize_t) (image->rows-1); y >= 0; y--)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
if (compression == RLECompression)
{
x=0;
count=0;
while (x < (ssize_t) image->columns)
{
i=1;
while ((i < 128) && (count + i < 128) &&
((x + i) < (ssize_t) image->columns))
{
if (tga_info.image_type == TGARLEColormap)
{
if (GetPixelIndex(indexes+i) != GetPixelIndex(indexes+(i-1)))
break;
}
else
if (tga_info.image_type == TGARLEMonochrome)
{
if (GetPixelLuma(image,p+i) != GetPixelLuma(image,p+(i-1)))
break;
}
else
{
if ((GetPixelBlue(p+i) != GetPixelBlue(p+(i-1))) ||
(GetPixelGreen(p+i) != GetPixelGreen(p+(i-1))) ||
(GetPixelRed(p+i) != GetPixelRed(p+(i-1))))
break;
if ((image->matte != MagickFalse) &&
(GetPixelAlpha(p+i) != GetPixelAlpha(p+(i-1))))
break;
}
i++;
}
if (i < 3)
{
count+=i;
p+=i;
indexes+=i;
}
if ((i >= 3) || (count == 128) ||
((x + i) == (ssize_t) image->columns))
{
if (count > 0)
{
(void) WriteBlobByte(image,(unsigned char) (--count));
while (count >= 0)
{
WriteTGAPixel(image,tga_info.image_type,indexes-(count+1),
p-(count+1),range,midpoint);
count--;
}
count=0;
}
}
if (i >= 3)
{
(void) WriteBlobByte(image,(unsigned char) ((i-1) | 0x80));
WriteTGAPixel(image,tga_info.image_type,indexes,p,range,midpoint);
p+=i;
indexes+=i;
}
x+=i;
}
}
else
{
for (x=0; x < (ssize_t) image->columns; x++)
WriteTGAPixel(image,tga_info.image_type,indexes+x,p++,range,midpoint);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3195_0 |
crossvul-cpp_data_bad_5562_0 | /*
* SUCS NET3:
*
* Generic datagram handling routines. These are generic for all
* protocols. Possibly a generic IP version on top of these would
* make sense. Not tonight however 8-).
* This is used because UDP, RAW, PACKET, DDP, IPX, AX.25 and
* NetROM layer all have identical poll code and mostly
* identical recvmsg() code. So we share it here. The poll was
* shared before but buried in udp.c so I moved it.
*
* Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>. (datagram_poll() from old
* udp.c code)
*
* Fixes:
* Alan Cox : NULL return from skb_peek_copy()
* understood
* Alan Cox : Rewrote skb_read_datagram to avoid the
* skb_peek_copy stuff.
* Alan Cox : Added support for SOCK_SEQPACKET.
* IPX can no longer use the SO_TYPE hack
* but AX.25 now works right, and SPX is
* feasible.
* Alan Cox : Fixed write poll of non IP protocol
* crash.
* Florian La Roche: Changed for my new skbuff handling.
* Darryl Miles : Fixed non-blocking SOCK_SEQPACKET.
* Linus Torvalds : BSD semantic fixes.
* Alan Cox : Datagram iovec handling
* Darryl Miles : Fixed non-blocking SOCK_STREAM.
* Alan Cox : POSIXisms
* Pete Wyckoff : Unconnected accept() fix.
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <asm/uaccess.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/poll.h>
#include <linux/highmem.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/checksum.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <trace/events/skb.h>
/*
* Is a socket 'connection oriented' ?
*/
static inline int connection_based(struct sock *sk)
{
return sk->sk_type == SOCK_SEQPACKET || sk->sk_type == SOCK_STREAM;
}
static int receiver_wake_function(wait_queue_t *wait, unsigned int mode, int sync,
void *key)
{
unsigned long bits = (unsigned long)key;
/*
* Avoid a wakeup if event not interesting for us
*/
if (bits && !(bits & (POLLIN | POLLERR)))
return 0;
return autoremove_wake_function(wait, mode, sync, key);
}
/*
* Wait for a packet..
*/
static int wait_for_packet(struct sock *sk, int *err, long *timeo_p)
{
int error;
DEFINE_WAIT_FUNC(wait, receiver_wake_function);
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/* Socket errors? */
error = sock_error(sk);
if (error)
goto out_err;
if (!skb_queue_empty(&sk->sk_receive_queue))
goto out;
/* Socket shut down? */
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto out_noerr;
/* Sequenced packets can come disconnected.
* If so we report the problem
*/
error = -ENOTCONN;
if (connection_based(sk) &&
!(sk->sk_state == TCP_ESTABLISHED || sk->sk_state == TCP_LISTEN))
goto out_err;
/* handle signals */
if (signal_pending(current))
goto interrupted;
error = 0;
*timeo_p = schedule_timeout(*timeo_p);
out:
finish_wait(sk_sleep(sk), &wait);
return error;
interrupted:
error = sock_intr_errno(*timeo_p);
out_err:
*err = error;
goto out;
out_noerr:
*err = 0;
error = 1;
goto out;
}
/**
* __skb_recv_datagram - Receive a datagram skbuff
* @sk: socket
* @flags: MSG_ flags
* @off: an offset in bytes to peek skb from. Returns an offset
* within an skb where data actually starts
* @peeked: returns non-zero if this packet has been seen before
* @err: error code returned
*
* Get a datagram skbuff, understands the peeking, nonblocking wakeups
* and possible races. This replaces identical code in packet, raw and
* udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
* the long standing peek and read race for datagram sockets. If you
* alter this routine remember it must be re-entrant.
*
* This function will lock the socket if a skb is returned, so the caller
* needs to unlock the socket in that case (usually by calling
* skb_free_datagram)
*
* * It does not lock socket since today. This function is
* * free of race conditions. This measure should/can improve
* * significantly datagram socket latencies at high loads,
* * when data copying to user space takes lots of time.
* * (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
* * 8) Great win.)
* * --ANK (980729)
*
* The order of the tests when we find no data waiting are specified
* quite explicitly by POSIX 1003.1g, don't change them without having
* the standard around please.
*/
struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
int *peeked, int *off, int *err)
{
struct sk_buff *skb;
long timeo;
/*
* Caller is allowed not to check sk->sk_err before skb_recv_datagram()
*/
int error = sock_error(sk);
if (error)
goto no_packet;
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
/* Again only user level code calls this function, so nothing
* interrupt level will suddenly eat the receive_queue.
*
* Look at current nfs client by the way...
* However, this function was correct in any case. 8)
*/
unsigned long cpu_flags;
struct sk_buff_head *queue = &sk->sk_receive_queue;
spin_lock_irqsave(&queue->lock, cpu_flags);
skb_queue_walk(queue, skb) {
*peeked = skb->peeked;
if (flags & MSG_PEEK) {
if (*off >= skb->len) {
*off -= skb->len;
continue;
}
skb->peeked = 1;
atomic_inc(&skb->users);
} else
__skb_unlink(skb, queue);
spin_unlock_irqrestore(&queue->lock, cpu_flags);
return skb;
}
spin_unlock_irqrestore(&queue->lock, cpu_flags);
/* User doesn't want to wait */
error = -EAGAIN;
if (!timeo)
goto no_packet;
} while (!wait_for_packet(sk, err, &timeo));
return NULL;
no_packet:
*err = error;
return NULL;
}
EXPORT_SYMBOL(__skb_recv_datagram);
struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
int noblock, int *err)
{
int peeked, off = 0;
return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, err);
}
EXPORT_SYMBOL(skb_recv_datagram);
void skb_free_datagram(struct sock *sk, struct sk_buff *skb)
{
consume_skb(skb);
sk_mem_reclaim_partial(sk);
}
EXPORT_SYMBOL(skb_free_datagram);
void skb_free_datagram_locked(struct sock *sk, struct sk_buff *skb)
{
bool slow;
if (likely(atomic_read(&skb->users) == 1))
smp_rmb();
else if (likely(!atomic_dec_and_test(&skb->users)))
return;
slow = lock_sock_fast(sk);
skb_orphan(skb);
sk_mem_reclaim_partial(sk);
unlock_sock_fast(sk, slow);
/* skb is now orphaned, can be freed outside of locked section */
__kfree_skb(skb);
}
EXPORT_SYMBOL(skb_free_datagram_locked);
/**
* skb_kill_datagram - Free a datagram skbuff forcibly
* @sk: socket
* @skb: datagram skbuff
* @flags: MSG_ flags
*
* This function frees a datagram skbuff that was received by
* skb_recv_datagram. The flags argument must match the one
* used for skb_recv_datagram.
*
* If the MSG_PEEK flag is set, and the packet is still on the
* receive queue of the socket, it will be taken off the queue
* before it is freed.
*
* This function currently only disables BH when acquiring the
* sk_receive_queue lock. Therefore it must not be used in a
* context where that lock is acquired in an IRQ context.
*
* It returns 0 if the packet was removed by us.
*/
int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
{
int err = 0;
if (flags & MSG_PEEK) {
err = -ENOENT;
spin_lock_bh(&sk->sk_receive_queue.lock);
if (skb == skb_peek(&sk->sk_receive_queue)) {
__skb_unlink(skb, &sk->sk_receive_queue);
atomic_dec(&skb->users);
err = 0;
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
}
kfree_skb(skb);
atomic_inc(&sk->sk_drops);
sk_mem_reclaim_partial(sk);
return err;
}
EXPORT_SYMBOL(skb_kill_datagram);
/**
* skb_copy_datagram_iovec - Copy a datagram to an iovec.
* @skb: buffer to copy
* @offset: offset in the buffer to start copying from
* @to: io vector to copy to
* @len: amount of data to copy from buffer to iovec
*
* Note: the iovec is modified during the copy.
*/
int skb_copy_datagram_iovec(const struct sk_buff *skb, int offset,
struct iovec *to, int len)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
trace_skb_copy_datagram_iovec(skb, len);
/* Copy header. */
if (copy > 0) {
if (copy > len)
copy = len;
if (memcpy_toiovec(to, skb->data + offset, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
}
/* Copy paged appendix. Hmm... why does this look so complicated? */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
int err;
u8 *vaddr;
struct page *page = skb_frag_page(frag);
if (copy > len)
copy = len;
vaddr = kmap(page);
err = memcpy_toiovec(to, vaddr + frag->page_offset +
offset - start, copy);
kunmap(page);
if (err)
goto fault;
if (!(len -= copy))
return 0;
offset += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_copy_datagram_iovec(frag_iter,
offset - start,
to, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_copy_datagram_iovec);
/**
* skb_copy_datagram_const_iovec - Copy a datagram to an iovec.
* @skb: buffer to copy
* @offset: offset in the buffer to start copying from
* @to: io vector to copy to
* @to_offset: offset in the io vector to start copying to
* @len: amount of data to copy from buffer to iovec
*
* Returns 0 or -EFAULT.
* Note: the iovec is not modified during the copy.
*/
int skb_copy_datagram_const_iovec(const struct sk_buff *skb, int offset,
const struct iovec *to, int to_offset,
int len)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
/* Copy header. */
if (copy > 0) {
if (copy > len)
copy = len;
if (memcpy_toiovecend(to, skb->data + offset, to_offset, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
to_offset += copy;
}
/* Copy paged appendix. Hmm... why does this look so complicated? */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
int err;
u8 *vaddr;
struct page *page = skb_frag_page(frag);
if (copy > len)
copy = len;
vaddr = kmap(page);
err = memcpy_toiovecend(to, vaddr + frag->page_offset +
offset - start, to_offset, copy);
kunmap(page);
if (err)
goto fault;
if (!(len -= copy))
return 0;
offset += copy;
to_offset += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_copy_datagram_const_iovec(frag_iter,
offset - start,
to, to_offset,
copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
to_offset += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_copy_datagram_const_iovec);
/**
* skb_copy_datagram_from_iovec - Copy a datagram from an iovec.
* @skb: buffer to copy
* @offset: offset in the buffer to start copying to
* @from: io vector to copy to
* @from_offset: offset in the io vector to start copying from
* @len: amount of data to copy to buffer from iovec
*
* Returns 0 or -EFAULT.
* Note: the iovec is not modified during the copy.
*/
int skb_copy_datagram_from_iovec(struct sk_buff *skb, int offset,
const struct iovec *from, int from_offset,
int len)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
/* Copy header. */
if (copy > 0) {
if (copy > len)
copy = len;
if (memcpy_fromiovecend(skb->data + offset, from, from_offset,
copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
from_offset += copy;
}
/* Copy paged appendix. Hmm... why does this look so complicated? */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
int err;
u8 *vaddr;
struct page *page = skb_frag_page(frag);
if (copy > len)
copy = len;
vaddr = kmap(page);
err = memcpy_fromiovecend(vaddr + frag->page_offset +
offset - start,
from, from_offset, copy);
kunmap(page);
if (err)
goto fault;
if (!(len -= copy))
return 0;
offset += copy;
from_offset += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_copy_datagram_from_iovec(frag_iter,
offset - start,
from,
from_offset,
copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
from_offset += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_copy_datagram_from_iovec);
static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset,
u8 __user *to, int len,
__wsum *csump)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int pos = 0;
/* Copy header. */
if (copy > 0) {
int err = 0;
if (copy > len)
copy = len;
*csump = csum_and_copy_to_user(skb->data + offset, to, copy,
*csump, &err);
if (err)
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
pos = copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
__wsum csum2;
int err = 0;
u8 *vaddr;
struct page *page = skb_frag_page(frag);
if (copy > len)
copy = len;
vaddr = kmap(page);
csum2 = csum_and_copy_to_user(vaddr +
frag->page_offset +
offset - start,
to, copy, 0, &err);
kunmap(page);
if (err)
goto fault;
*csump = csum_block_add(*csump, csum2, pos);
if (!(len -= copy))
return 0;
offset += copy;
to += copy;
pos += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
__wsum csum2 = 0;
if (copy > len)
copy = len;
if (skb_copy_and_csum_datagram(frag_iter,
offset - start,
to, copy,
&csum2))
goto fault;
*csump = csum_block_add(*csump, csum2, pos);
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
pos += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
__sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
{
__sum16 sum;
sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
if (likely(!sum)) {
if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE))
netdev_rx_csum_fault(skb->dev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
return sum;
}
EXPORT_SYMBOL(__skb_checksum_complete_head);
__sum16 __skb_checksum_complete(struct sk_buff *skb)
{
return __skb_checksum_complete_head(skb, skb->len);
}
EXPORT_SYMBOL(__skb_checksum_complete);
/**
* skb_copy_and_csum_datagram_iovec - Copy and checkum skb to user iovec.
* @skb: skbuff
* @hlen: hardware length
* @iov: io vector
*
* Caller _must_ check that skb will fit to this iovec.
*
* Returns: 0 - success.
* -EINVAL - checksum failure.
* -EFAULT - fault during copy. Beware, in this case iovec
* can be modified!
*/
int skb_copy_and_csum_datagram_iovec(struct sk_buff *skb,
int hlen, struct iovec *iov)
{
__wsum csum;
int chunk = skb->len - hlen;
if (!chunk)
return 0;
/* Skip filled elements.
* Pretty silly, look at memcpy_toiovec, though 8)
*/
while (!iov->iov_len)
iov++;
if (iov->iov_len < chunk) {
if (__skb_checksum_complete(skb))
goto csum_error;
if (skb_copy_datagram_iovec(skb, hlen, iov, chunk))
goto fault;
} else {
csum = csum_partial(skb->data, hlen, skb->csum);
if (skb_copy_and_csum_datagram(skb, hlen, iov->iov_base,
chunk, &csum))
goto fault;
if (csum_fold(csum))
goto csum_error;
if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE))
netdev_rx_csum_fault(skb->dev);
iov->iov_len -= chunk;
iov->iov_base += chunk;
}
return 0;
csum_error:
return -EINVAL;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_copy_and_csum_datagram_iovec);
/**
* datagram_poll - generic datagram poll
* @file: file struct
* @sock: socket
* @wait: poll table
*
* Datagram poll: Again totally generic. This also handles
* sequenced packet sockets providing the socket receive queue
* is only ever holding data ready to receive.
*
* Note: when you _don't_ use this routine for this protocol,
* and you use a different write policy from sock_writeable()
* then please supply your own write_space callback.
*/
unsigned int datagram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
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;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (connection_based(sk)) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* writable? */
if (sock_writeable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
return mask;
}
EXPORT_SYMBOL(datagram_poll);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5562_0 |
crossvul-cpp_data_bad_5603_0 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2003 Intel Corp.
* Copyright (c) 2001-2002 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* These functions interface with the sockets layer to implement the
* SCTP Extensions for the Sockets API.
*
* Note that the descriptions from the specification are USER level
* functions--this file is the functions which populate the struct proto
* for SCTP which is the BOTTOM of the sockets interface.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation 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 GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Narasimha Budihal <narsi@refcode.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Jon Grimm <jgrimm@us.ibm.com>
* Xingang Guo <xingang.guo@intel.com>
* Daisy Chang <daisyc@us.ibm.com>
* Sridhar Samudrala <samudrala@us.ibm.com>
* Inaky Perez-Gonzalez <inaky.gonzalez@intel.com>
* Ardelle Fan <ardelle.fan@intel.com>
* Ryan Layer <rmlayer@us.ibm.com>
* Anup Pemmaiah <pemmaiah@cc.usu.edu>
* Kevin Gao <kevin.gao@intel.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/ip.h>
#include <linux/capability.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/crypto.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/route.h>
#include <net/ipv6.h>
#include <net/inet_common.h>
#include <linux/socket.h> /* for sa_family_t */
#include <linux/export.h>
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* WARNING: Please do not remove the SCTP_STATIC attribute to
* any of the functions below as they are used to export functions
* used by a project regression testsuite.
*/
/* Forward declarations for internal helper functions. */
static int sctp_writeable(struct sock *sk);
static void sctp_wfree(struct sk_buff *skb);
static int sctp_wait_for_sndbuf(struct sctp_association *, long *timeo_p,
size_t msg_len);
static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p);
static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
static int sctp_wait_for_accept(struct sock *sk, long timeo);
static void sctp_wait_for_close(struct sock *sk, long timeo);
static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
union sctp_addr *addr, int len);
static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
static int sctp_send_asconf(struct sctp_association *asoc,
struct sctp_chunk *chunk);
static int sctp_do_bind(struct sock *, union sctp_addr *, int);
static int sctp_autobind(struct sock *sk);
static void sctp_sock_migrate(struct sock *, struct sock *,
struct sctp_association *, sctp_socket_type_t);
extern struct kmem_cache *sctp_bucket_cachep;
extern long sysctl_sctp_mem[3];
extern int sysctl_sctp_rmem[3];
extern int sysctl_sctp_wmem[3];
static int sctp_memory_pressure;
static atomic_long_t sctp_memory_allocated;
struct percpu_counter sctp_sockets_allocated;
static void sctp_enter_memory_pressure(struct sock *sk)
{
sctp_memory_pressure = 1;
}
/* Get the sndbuf space available at the time on the association. */
static inline int sctp_wspace(struct sctp_association *asoc)
{
int amt;
if (asoc->ep->sndbuf_policy)
amt = asoc->sndbuf_used;
else
amt = sk_wmem_alloc_get(asoc->base.sk);
if (amt >= asoc->base.sk->sk_sndbuf) {
if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK)
amt = 0;
else {
amt = sk_stream_wspace(asoc->base.sk);
if (amt < 0)
amt = 0;
}
} else {
amt = asoc->base.sk->sk_sndbuf - amt;
}
return amt;
}
/* Increment the used sndbuf space count of the corresponding association by
* the size of the outgoing data chunk.
* Also, set the skb destructor for sndbuf accounting later.
*
* Since it is always 1-1 between chunk and skb, and also a new skb is always
* allocated for chunk bundling in sctp_packet_transmit(), we can use the
* destructor in the data chunk skb for the purpose of the sndbuf space
* tracking.
*/
static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
{
struct sctp_association *asoc = chunk->asoc;
struct sock *sk = asoc->base.sk;
/* The sndbuf space is tracked per association. */
sctp_association_hold(asoc);
skb_set_owner_w(chunk->skb, sk);
chunk->skb->destructor = sctp_wfree;
/* Save the chunk pointer in skb for sctp_wfree to use later. */
*((struct sctp_chunk **)(chunk->skb->cb)) = chunk;
asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) +
sizeof(struct sk_buff) +
sizeof(struct sctp_chunk);
atomic_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
sk->sk_wmem_queued += chunk->skb->truesize;
sk_mem_charge(sk, chunk->skb->truesize);
}
/* Verify that this is a valid address. */
static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
int len)
{
struct sctp_af *af;
/* Verify basic sockaddr. */
af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
if (!af)
return -EINVAL;
/* Is this a valid SCTP address? */
if (!af->addr_valid(addr, sctp_sk(sk), NULL))
return -EINVAL;
if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
return -EINVAL;
return 0;
}
/* Look up the association by its id. If this is not a UDP-style
* socket, the ID field is always ignored.
*/
struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
{
struct sctp_association *asoc = NULL;
/* If this is not a UDP-style socket, assoc id should be ignored. */
if (!sctp_style(sk, UDP)) {
/* Return NULL if the socket state is not ESTABLISHED. It
* could be a TCP-style listening socket or a socket which
* hasn't yet called connect() to establish an association.
*/
if (!sctp_sstate(sk, ESTABLISHED))
return NULL;
/* Get the first and the only association from the list. */
if (!list_empty(&sctp_sk(sk)->ep->asocs))
asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
struct sctp_association, asocs);
return asoc;
}
/* Otherwise this is a UDP-style socket. */
if (!id || (id == (sctp_assoc_t)-1))
return NULL;
spin_lock_bh(&sctp_assocs_id_lock);
asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
spin_unlock_bh(&sctp_assocs_id_lock);
if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
return NULL;
return asoc;
}
/* Look up the transport from an address and an assoc id. If both address and
* id are specified, the associations matching the address and the id should be
* the same.
*/
static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
struct sockaddr_storage *addr,
sctp_assoc_t id)
{
struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
struct sctp_transport *transport;
union sctp_addr *laddr = (union sctp_addr *)addr;
addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
laddr,
&transport);
if (!addr_asoc)
return NULL;
id_asoc = sctp_id2assoc(sk, id);
if (id_asoc && (id_asoc != addr_asoc))
return NULL;
sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
(union sctp_addr *)addr);
return transport;
}
/* API 3.1.2 bind() - UDP Style Syntax
* The syntax of bind() is,
*
* ret = bind(int sd, struct sockaddr *addr, int addrlen);
*
* sd - the socket descriptor returned by socket().
* addr - the address structure (struct sockaddr_in or struct
* sockaddr_in6 [RFC 2553]),
* addr_len - the size of the address structure.
*/
SCTP_STATIC int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
{
int retval = 0;
sctp_lock_sock(sk);
SCTP_DEBUG_PRINTK("sctp_bind(sk: %p, addr: %p, addr_len: %d)\n",
sk, addr, addr_len);
/* Disallow binding twice. */
if (!sctp_sk(sk)->ep->base.bind_addr.port)
retval = sctp_do_bind(sk, (union sctp_addr *)addr,
addr_len);
else
retval = -EINVAL;
sctp_release_sock(sk);
return retval;
}
static long sctp_get_port_local(struct sock *, union sctp_addr *);
/* Verify this is a valid sockaddr. */
static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
union sctp_addr *addr, int len)
{
struct sctp_af *af;
/* Check minimum size. */
if (len < sizeof (struct sockaddr))
return NULL;
/* V4 mapped address are really of AF_INET family */
if (addr->sa.sa_family == AF_INET6 &&
ipv6_addr_v4mapped(&addr->v6.sin6_addr)) {
if (!opt->pf->af_supported(AF_INET, opt))
return NULL;
} else {
/* Does this PF support this AF? */
if (!opt->pf->af_supported(addr->sa.sa_family, opt))
return NULL;
}
/* If we get this far, af is valid. */
af = sctp_get_af_specific(addr->sa.sa_family);
if (len < af->sockaddr_len)
return NULL;
return af;
}
/* Bind a local address either to an endpoint or to an association. */
SCTP_STATIC int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
struct sctp_bind_addr *bp = &ep->base.bind_addr;
struct sctp_af *af;
unsigned short snum;
int ret = 0;
/* Common sockaddr verification. */
af = sctp_sockaddr_af(sp, addr, len);
if (!af) {
SCTP_DEBUG_PRINTK("sctp_do_bind(sk: %p, newaddr: %p, len: %d) EINVAL\n",
sk, addr, len);
return -EINVAL;
}
snum = ntohs(addr->v4.sin_port);
SCTP_DEBUG_PRINTK_IPADDR("sctp_do_bind(sk: %p, new addr: ",
", port: %d, new port: %d, len: %d)\n",
sk,
addr,
bp->port, snum,
len);
/* PF specific bind() address verification. */
if (!sp->pf->bind_verify(sp, addr))
return -EADDRNOTAVAIL;
/* We must either be unbound, or bind to the same port.
* It's OK to allow 0 ports if we are already bound.
* We'll just inhert an already bound port in this case
*/
if (bp->port) {
if (!snum)
snum = bp->port;
else if (snum != bp->port) {
SCTP_DEBUG_PRINTK("sctp_do_bind:"
" New port %d does not match existing port "
"%d.\n", snum, bp->port);
return -EINVAL;
}
}
if (snum && snum < PROT_SOCK &&
!ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
return -EACCES;
/* See if the address matches any of the addresses we may have
* already bound before checking against other endpoints.
*/
if (sctp_bind_addr_match(bp, addr, sp))
return -EINVAL;
/* Make sure we are allowed to bind here.
* The function sctp_get_port_local() does duplicate address
* detection.
*/
addr->v4.sin_port = htons(snum);
if ((ret = sctp_get_port_local(sk, addr))) {
return -EADDRINUSE;
}
/* Refresh ephemeral port. */
if (!bp->port)
bp->port = inet_sk(sk)->inet_num;
/* Add the address to the bind address list.
* Use GFP_ATOMIC since BHs will be disabled.
*/
ret = sctp_add_bind_addr(bp, addr, SCTP_ADDR_SRC, GFP_ATOMIC);
/* Copy back into socket for getsockname() use. */
if (!ret) {
inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
af->to_sk_saddr(addr, sk);
}
return ret;
}
/* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
*
* R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
* at any one time. If a sender, after sending an ASCONF chunk, decides
* it needs to transfer another ASCONF Chunk, it MUST wait until the
* ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
* subsequent ASCONF. Note this restriction binds each side, so at any
* time two ASCONF may be in-transit on any given association (one sent
* from each endpoint).
*/
static int sctp_send_asconf(struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
struct net *net = sock_net(asoc->base.sk);
int retval = 0;
/* If there is an outstanding ASCONF chunk, queue it for later
* transmission.
*/
if (asoc->addip_last_asconf) {
list_add_tail(&chunk->list, &asoc->addip_chunk_list);
goto out;
}
/* Hold the chunk until an ASCONF_ACK is received. */
sctp_chunk_hold(chunk);
retval = sctp_primitive_ASCONF(net, asoc, chunk);
if (retval)
sctp_chunk_free(chunk);
else
asoc->addip_last_asconf = chunk;
out:
return retval;
}
/* Add a list of addresses as bind addresses to local endpoint or
* association.
*
* Basically run through each address specified in the addrs/addrcnt
* array/length pair, determine if it is IPv6 or IPv4 and call
* sctp_do_bind() on it.
*
* If any of them fails, then the operation will be reversed and the
* ones that were added will be removed.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
{
int cnt;
int retval = 0;
void *addr_buf;
struct sockaddr *sa_addr;
struct sctp_af *af;
SCTP_DEBUG_PRINTK("sctp_bindx_add (sk: %p, addrs: %p, addrcnt: %d)\n",
sk, addrs, addrcnt);
addr_buf = addrs;
for (cnt = 0; cnt < addrcnt; cnt++) {
/* The list may contain either IPv4 or IPv6 address;
* determine the address length for walking thru the list.
*/
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa_family);
if (!af) {
retval = -EINVAL;
goto err_bindx_add;
}
retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
af->sockaddr_len);
addr_buf += af->sockaddr_len;
err_bindx_add:
if (retval < 0) {
/* Failed. Cleanup the ones that have been added */
if (cnt > 0)
sctp_bindx_rem(sk, addrs, cnt);
return retval;
}
}
return retval;
}
/* Send an ASCONF chunk with Add IP address parameters to all the peers of the
* associations that are part of the endpoint indicating that a list of local
* addresses are added to the endpoint.
*
* If any of the addresses is already in the bind address list of the
* association, we do not send the chunk for that association. But it will not
* affect other associations.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_send_asconf_add_ip(struct sock *sk,
struct sockaddr *addrs,
int addrcnt)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct sctp_bind_addr *bp;
struct sctp_chunk *chunk;
struct sctp_sockaddr_entry *laddr;
union sctp_addr *addr;
union sctp_addr saveaddr;
void *addr_buf;
struct sctp_af *af;
struct list_head *p;
int i;
int retval = 0;
if (!net->sctp.addip_enable)
return retval;
sp = sctp_sk(sk);
ep = sp->ep;
SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
__func__, sk, addrs, addrcnt);
list_for_each_entry(asoc, &ep->asocs, asocs) {
if (!asoc->peer.asconf_capable)
continue;
if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
continue;
if (!sctp_state(asoc, ESTABLISHED))
continue;
/* Check if any address in the packed array of addresses is
* in the bind address list of the association. If so,
* do not send the asconf chunk to its peer, but continue with
* other associations.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
if (!af) {
retval = -EINVAL;
goto out;
}
if (sctp_assoc_lookup_laddr(asoc, addr))
break;
addr_buf += af->sockaddr_len;
}
if (i < addrcnt)
continue;
/* Use the first valid address in bind addr list of
* association as Address Parameter of ASCONF CHUNK.
*/
bp = &asoc->base.bind_addr;
p = bp->address_list.next;
laddr = list_entry(p, struct sctp_sockaddr_entry, list);
chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
addrcnt, SCTP_PARAM_ADD_IP);
if (!chunk) {
retval = -ENOMEM;
goto out;
}
/* Add the new addresses to the bind address list with
* use_as_src set to 0.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
memcpy(&saveaddr, addr, af->sockaddr_len);
retval = sctp_add_bind_addr(bp, &saveaddr,
SCTP_ADDR_NEW, GFP_ATOMIC);
addr_buf += af->sockaddr_len;
}
if (asoc->src_out_of_asoc_ok) {
struct sctp_transport *trans;
list_for_each_entry(trans,
&asoc->peer.transport_addr_list, transports) {
/* Clear the source and route cache */
dst_release(trans->dst);
trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
2*asoc->pathmtu, 4380));
trans->ssthresh = asoc->peer.i.a_rwnd;
trans->rto = asoc->rto_initial;
sctp_max_rto(asoc, trans);
trans->rtt = trans->srtt = trans->rttvar = 0;
sctp_transport_route(trans, NULL,
sctp_sk(asoc->base.sk));
}
}
retval = sctp_send_asconf(asoc, chunk);
}
out:
return retval;
}
/* Remove a list of addresses from bind addresses list. Do not remove the
* last address.
*
* Basically run through each address specified in the addrs/addrcnt
* array/length pair, determine if it is IPv6 or IPv4 and call
* sctp_del_bind() on it.
*
* If any of them fails, then the operation will be reversed and the
* ones that were removed will be added back.
*
* At least one address has to be left; if only one address is
* available, the operation will return -EBUSY.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
int cnt;
struct sctp_bind_addr *bp = &ep->base.bind_addr;
int retval = 0;
void *addr_buf;
union sctp_addr *sa_addr;
struct sctp_af *af;
SCTP_DEBUG_PRINTK("sctp_bindx_rem (sk: %p, addrs: %p, addrcnt: %d)\n",
sk, addrs, addrcnt);
addr_buf = addrs;
for (cnt = 0; cnt < addrcnt; cnt++) {
/* If the bind address list is empty or if there is only one
* bind address, there is nothing more to be removed (we need
* at least one address here).
*/
if (list_empty(&bp->address_list) ||
(sctp_list_single_entry(&bp->address_list))) {
retval = -EBUSY;
goto err_bindx_rem;
}
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa.sa_family);
if (!af) {
retval = -EINVAL;
goto err_bindx_rem;
}
if (!af->addr_valid(sa_addr, sp, NULL)) {
retval = -EADDRNOTAVAIL;
goto err_bindx_rem;
}
if (sa_addr->v4.sin_port &&
sa_addr->v4.sin_port != htons(bp->port)) {
retval = -EINVAL;
goto err_bindx_rem;
}
if (!sa_addr->v4.sin_port)
sa_addr->v4.sin_port = htons(bp->port);
/* FIXME - There is probably a need to check if sk->sk_saddr and
* sk->sk_rcv_addr are currently set to one of the addresses to
* be removed. This is something which needs to be looked into
* when we are fixing the outstanding issues with multi-homing
* socket routing and failover schemes. Refer to comments in
* sctp_do_bind(). -daisy
*/
retval = sctp_del_bind_addr(bp, sa_addr);
addr_buf += af->sockaddr_len;
err_bindx_rem:
if (retval < 0) {
/* Failed. Add the ones that has been removed back */
if (cnt > 0)
sctp_bindx_add(sk, addrs, cnt);
return retval;
}
}
return retval;
}
/* Send an ASCONF chunk with Delete IP address parameters to all the peers of
* the associations that are part of the endpoint indicating that a list of
* local addresses are removed from the endpoint.
*
* If any of the addresses is already in the bind address list of the
* association, we do not send the chunk for that association. But it will not
* affect other associations.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_send_asconf_del_ip(struct sock *sk,
struct sockaddr *addrs,
int addrcnt)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct sctp_transport *transport;
struct sctp_bind_addr *bp;
struct sctp_chunk *chunk;
union sctp_addr *laddr;
void *addr_buf;
struct sctp_af *af;
struct sctp_sockaddr_entry *saddr;
int i;
int retval = 0;
int stored = 0;
chunk = NULL;
if (!net->sctp.addip_enable)
return retval;
sp = sctp_sk(sk);
ep = sp->ep;
SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
__func__, sk, addrs, addrcnt);
list_for_each_entry(asoc, &ep->asocs, asocs) {
if (!asoc->peer.asconf_capable)
continue;
if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
continue;
if (!sctp_state(asoc, ESTABLISHED))
continue;
/* Check if any address in the packed array of addresses is
* not present in the bind address list of the association.
* If so, do not send the asconf chunk to its peer, but
* continue with other associations.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
laddr = addr_buf;
af = sctp_get_af_specific(laddr->v4.sin_family);
if (!af) {
retval = -EINVAL;
goto out;
}
if (!sctp_assoc_lookup_laddr(asoc, laddr))
break;
addr_buf += af->sockaddr_len;
}
if (i < addrcnt)
continue;
/* Find one address in the association's bind address list
* that is not in the packed array of addresses. This is to
* make sure that we do not delete all the addresses in the
* association.
*/
bp = &asoc->base.bind_addr;
laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
addrcnt, sp);
if ((laddr == NULL) && (addrcnt == 1)) {
if (asoc->asconf_addr_del_pending)
continue;
asoc->asconf_addr_del_pending =
kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
if (asoc->asconf_addr_del_pending == NULL) {
retval = -ENOMEM;
goto out;
}
asoc->asconf_addr_del_pending->sa.sa_family =
addrs->sa_family;
asoc->asconf_addr_del_pending->v4.sin_port =
htons(bp->port);
if (addrs->sa_family == AF_INET) {
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)addrs;
asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
} else if (addrs->sa_family == AF_INET6) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)addrs;
asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
}
SCTP_DEBUG_PRINTK_IPADDR("send_asconf_del_ip: keep the last address asoc: %p ",
" at %p\n", asoc, asoc->asconf_addr_del_pending,
asoc->asconf_addr_del_pending);
asoc->src_out_of_asoc_ok = 1;
stored = 1;
goto skip_mkasconf;
}
/* We do not need RCU protection throughout this loop
* because this is done under a socket lock from the
* setsockopt call.
*/
chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
SCTP_PARAM_DEL_IP);
if (!chunk) {
retval = -ENOMEM;
goto out;
}
skip_mkasconf:
/* Reset use_as_src flag for the addresses in the bind address
* list that are to be deleted.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
laddr = addr_buf;
af = sctp_get_af_specific(laddr->v4.sin_family);
list_for_each_entry(saddr, &bp->address_list, list) {
if (sctp_cmp_addr_exact(&saddr->a, laddr))
saddr->state = SCTP_ADDR_DEL;
}
addr_buf += af->sockaddr_len;
}
/* Update the route and saddr entries for all the transports
* as some of the addresses in the bind address list are
* about to be deleted and cannot be used as source addresses.
*/
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
dst_release(transport->dst);
sctp_transport_route(transport, NULL,
sctp_sk(asoc->base.sk));
}
if (stored)
/* We don't need to transmit ASCONF */
continue;
retval = sctp_send_asconf(asoc, chunk);
}
out:
return retval;
}
/* set addr events to assocs in the endpoint. ep and addr_wq must be locked */
int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
{
struct sock *sk = sctp_opt2sk(sp);
union sctp_addr *addr;
struct sctp_af *af;
/* It is safe to write port space in caller. */
addr = &addrw->a;
addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
af = sctp_get_af_specific(addr->sa.sa_family);
if (!af)
return -EINVAL;
if (sctp_verify_addr(sk, addr, af->sockaddr_len))
return -EINVAL;
if (addrw->state == SCTP_ADDR_NEW)
return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
else
return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
}
/* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
*
* API 8.1
* int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
* int flags);
*
* If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
* If the sd is an IPv6 socket, the addresses passed can either be IPv4
* or IPv6 addresses.
*
* A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
* Section 3.1.2 for this usage.
*
* addrs is a pointer to an array of one or more socket addresses. Each
* address is contained in its appropriate structure (i.e. struct
* sockaddr_in or struct sockaddr_in6) the family of the address type
* must be used to distinguish the address length (note that this
* representation is termed a "packed array" of addresses). The caller
* specifies the number of addresses in the array with addrcnt.
*
* On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
* -1, and sets errno to the appropriate error code.
*
* For SCTP, the port given in each socket address must be the same, or
* sctp_bindx() will fail, setting errno to EINVAL.
*
* The flags parameter is formed from the bitwise OR of zero or more of
* the following currently defined flags:
*
* SCTP_BINDX_ADD_ADDR
*
* SCTP_BINDX_REM_ADDR
*
* SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
* association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
* addresses from the association. The two flags are mutually exclusive;
* if both are given, sctp_bindx() will fail with EINVAL. A caller may
* not remove all addresses from an association; sctp_bindx() will
* reject such an attempt with EINVAL.
*
* An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
* additional addresses with an endpoint after calling bind(). Or use
* sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
* socket is associated with so that no new association accepted will be
* associated with those addresses. If the endpoint supports dynamic
* address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
* endpoint to send the appropriate message to the peer to change the
* peers address lists.
*
* Adding and removing addresses from a connected association is
* optional functionality. Implementations that do not support this
* functionality should return EOPNOTSUPP.
*
* Basically do nothing but copying the addresses from user to kernel
* land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
* This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
* from userspace.
*
* We don't use copy_from_user() for optimization: we first do the
* sanity checks (buffer size -fast- and access check-healthy
* pointer); if all of those succeed, then we can alloc the memory
* (expensive operation) needed to copy the data to kernel. Then we do
* the copying without checking the user space area
* (__copy_from_user()).
*
* On exit there is no need to do sockfd_put(), sys_setsockopt() does
* it.
*
* sk The sk of the socket
* addrs The pointer to the addresses in user land
* addrssize Size of the addrs buffer
* op Operation to perform (add or remove, see the flags of
* sctp_bindx)
*
* Returns 0 if ok, <0 errno code on error.
*/
SCTP_STATIC int sctp_setsockopt_bindx(struct sock* sk,
struct sockaddr __user *addrs,
int addrs_size, int op)
{
struct sockaddr *kaddrs;
int err;
int addrcnt = 0;
int walk_size = 0;
struct sockaddr *sa_addr;
void *addr_buf;
struct sctp_af *af;
SCTP_DEBUG_PRINTK("sctp_setsockopt_bindx: sk %p addrs %p"
" addrs_size %d opt %d\n", sk, addrs, addrs_size, op);
if (unlikely(addrs_size <= 0))
return -EINVAL;
/* Check the user passed a healthy pointer. */
if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
return -EFAULT;
/* Alloc space for the address array in kernel memory. */
kaddrs = kmalloc(addrs_size, GFP_KERNEL);
if (unlikely(!kaddrs))
return -ENOMEM;
if (__copy_from_user(kaddrs, addrs, addrs_size)) {
kfree(kaddrs);
return -EFAULT;
}
/* Walk through the addrs buffer and count the number of addresses. */
addr_buf = kaddrs;
while (walk_size < addrs_size) {
if (walk_size + sizeof(sa_family_t) > addrs_size) {
kfree(kaddrs);
return -EINVAL;
}
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa_family);
/* If the address family is not supported or if this address
* causes the address buffer to overflow return EINVAL.
*/
if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
kfree(kaddrs);
return -EINVAL;
}
addrcnt++;
addr_buf += af->sockaddr_len;
walk_size += af->sockaddr_len;
}
/* Do the work. */
switch (op) {
case SCTP_BINDX_ADD_ADDR:
err = sctp_bindx_add(sk, kaddrs, addrcnt);
if (err)
goto out;
err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
break;
case SCTP_BINDX_REM_ADDR:
err = sctp_bindx_rem(sk, kaddrs, addrcnt);
if (err)
goto out;
err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
break;
default:
err = -EINVAL;
break;
}
out:
kfree(kaddrs);
return err;
}
/* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
*
* Common routine for handling connect() and sctp_connectx().
* Connect will come in with just a single address.
*/
static int __sctp_connect(struct sock* sk,
struct sockaddr *kaddrs,
int addrs_size,
sctp_assoc_t *assoc_id)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sctp_association *asoc = NULL;
struct sctp_association *asoc2;
struct sctp_transport *transport;
union sctp_addr to;
struct sctp_af *af;
sctp_scope_t scope;
long timeo;
int err = 0;
int addrcnt = 0;
int walk_size = 0;
union sctp_addr *sa_addr = NULL;
void *addr_buf;
unsigned short port;
unsigned int f_flags = 0;
sp = sctp_sk(sk);
ep = sp->ep;
/* connect() cannot be done on a socket that is already in ESTABLISHED
* state - UDP-style peeled off socket or a TCP-style socket that
* is already connected.
* It cannot be done even on a TCP-style listening socket.
*/
if (sctp_sstate(sk, ESTABLISHED) ||
(sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
err = -EISCONN;
goto out_free;
}
/* Walk through the addrs buffer and count the number of addresses. */
addr_buf = kaddrs;
while (walk_size < addrs_size) {
if (walk_size + sizeof(sa_family_t) > addrs_size) {
err = -EINVAL;
goto out_free;
}
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa.sa_family);
/* If the address family is not supported or if this address
* causes the address buffer to overflow return EINVAL.
*/
if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
err = -EINVAL;
goto out_free;
}
port = ntohs(sa_addr->v4.sin_port);
/* Save current address so we can work with it */
memcpy(&to, sa_addr, af->sockaddr_len);
err = sctp_verify_addr(sk, &to, af->sockaddr_len);
if (err)
goto out_free;
/* Make sure the destination port is correctly set
* in all addresses.
*/
if (asoc && asoc->peer.port && asoc->peer.port != port)
goto out_free;
/* Check if there already is a matching association on the
* endpoint (other than the one created here).
*/
asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport);
if (asoc2 && asoc2 != asoc) {
if (asoc2->state >= SCTP_STATE_ESTABLISHED)
err = -EISCONN;
else
err = -EALREADY;
goto out_free;
}
/* If we could not find a matching association on the endpoint,
* make sure that there is no peeled-off association matching
* the peer address even on another socket.
*/
if (sctp_endpoint_is_peeled_off(ep, &to)) {
err = -EADDRNOTAVAIL;
goto out_free;
}
if (!asoc) {
/* If a bind() or sctp_bindx() is not called prior to
* an sctp_connectx() call, the system picks an
* ephemeral port and will choose an address set
* equivalent to binding with a wildcard address.
*/
if (!ep->base.bind_addr.port) {
if (sctp_autobind(sk)) {
err = -EAGAIN;
goto out_free;
}
} else {
/*
* If an unprivileged user inherits a 1-many
* style socket with open associations on a
* privileged port, it MAY be permitted to
* accept new associations, but it SHOULD NOT
* be permitted to open new associations.
*/
if (ep->base.bind_addr.port < PROT_SOCK &&
!ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
err = -EACCES;
goto out_free;
}
}
scope = sctp_scope(&to);
asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
if (!asoc) {
err = -ENOMEM;
goto out_free;
}
err = sctp_assoc_set_bind_addr_from_ep(asoc, scope,
GFP_KERNEL);
if (err < 0) {
goto out_free;
}
}
/* Prime the peer's transport structures. */
transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL,
SCTP_UNKNOWN);
if (!transport) {
err = -ENOMEM;
goto out_free;
}
addrcnt++;
addr_buf += af->sockaddr_len;
walk_size += af->sockaddr_len;
}
/* In case the user of sctp_connectx() wants an association
* id back, assign one now.
*/
if (assoc_id) {
err = sctp_assoc_set_id(asoc, GFP_KERNEL);
if (err < 0)
goto out_free;
}
err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
if (err < 0) {
goto out_free;
}
/* Initialize sk's dport and daddr for getpeername() */
inet_sk(sk)->inet_dport = htons(asoc->peer.port);
af = sctp_get_af_specific(sa_addr->sa.sa_family);
af->to_sk_daddr(sa_addr, sk);
sk->sk_err = 0;
/* in-kernel sockets don't generally have a file allocated to them
* if all they do is call sock_create_kern().
*/
if (sk->sk_socket->file)
f_flags = sk->sk_socket->file->f_flags;
timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK);
err = sctp_wait_for_connect(asoc, &timeo);
if ((err == 0 || err == -EINPROGRESS) && assoc_id)
*assoc_id = asoc->assoc_id;
/* Don't free association on exit. */
asoc = NULL;
out_free:
SCTP_DEBUG_PRINTK("About to exit __sctp_connect() free asoc: %p"
" kaddrs: %p err: %d\n",
asoc, kaddrs, err);
if (asoc) {
/* sctp_primitive_ASSOCIATE may have added this association
* To the hash table, try to unhash it, just in case, its a noop
* if it wasn't hashed so we're safe
*/
sctp_unhash_established(asoc);
sctp_association_free(asoc);
}
return err;
}
/* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
*
* API 8.9
* int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
* sctp_assoc_t *asoc);
*
* If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
* If the sd is an IPv6 socket, the addresses passed can either be IPv4
* or IPv6 addresses.
*
* A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
* Section 3.1.2 for this usage.
*
* addrs is a pointer to an array of one or more socket addresses. Each
* address is contained in its appropriate structure (i.e. struct
* sockaddr_in or struct sockaddr_in6) the family of the address type
* must be used to distengish the address length (note that this
* representation is termed a "packed array" of addresses). The caller
* specifies the number of addresses in the array with addrcnt.
*
* On success, sctp_connectx() returns 0. It also sets the assoc_id to
* the association id of the new association. On failure, sctp_connectx()
* returns -1, and sets errno to the appropriate error code. The assoc_id
* is not touched by the kernel.
*
* For SCTP, the port given in each socket address must be the same, or
* sctp_connectx() will fail, setting errno to EINVAL.
*
* An application can use sctp_connectx to initiate an association with
* an endpoint that is multi-homed. Much like sctp_bindx() this call
* allows a caller to specify multiple addresses at which a peer can be
* reached. The way the SCTP stack uses the list of addresses to set up
* the association is implementation dependent. This function only
* specifies that the stack will try to make use of all the addresses in
* the list when needed.
*
* Note that the list of addresses passed in is only used for setting up
* the association. It does not necessarily equal the set of addresses
* the peer uses for the resulting association. If the caller wants to
* find out the set of peer addresses, it must use sctp_getpaddrs() to
* retrieve them after the association has been set up.
*
* Basically do nothing but copying the addresses from user to kernel
* land and invoking either sctp_connectx(). This is used for tunneling
* the sctp_connectx() request through sctp_setsockopt() from userspace.
*
* We don't use copy_from_user() for optimization: we first do the
* sanity checks (buffer size -fast- and access check-healthy
* pointer); if all of those succeed, then we can alloc the memory
* (expensive operation) needed to copy the data to kernel. Then we do
* the copying without checking the user space area
* (__copy_from_user()).
*
* On exit there is no need to do sockfd_put(), sys_setsockopt() does
* it.
*
* sk The sk of the socket
* addrs The pointer to the addresses in user land
* addrssize Size of the addrs buffer
*
* Returns >=0 if ok, <0 errno code on error.
*/
SCTP_STATIC int __sctp_setsockopt_connectx(struct sock* sk,
struct sockaddr __user *addrs,
int addrs_size,
sctp_assoc_t *assoc_id)
{
int err = 0;
struct sockaddr *kaddrs;
SCTP_DEBUG_PRINTK("%s - sk %p addrs %p addrs_size %d\n",
__func__, sk, addrs, addrs_size);
if (unlikely(addrs_size <= 0))
return -EINVAL;
/* Check the user passed a healthy pointer. */
if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
return -EFAULT;
/* Alloc space for the address array in kernel memory. */
kaddrs = kmalloc(addrs_size, GFP_KERNEL);
if (unlikely(!kaddrs))
return -ENOMEM;
if (__copy_from_user(kaddrs, addrs, addrs_size)) {
err = -EFAULT;
} else {
err = __sctp_connect(sk, kaddrs, addrs_size, assoc_id);
}
kfree(kaddrs);
return err;
}
/*
* This is an older interface. It's kept for backward compatibility
* to the option that doesn't provide association id.
*/
SCTP_STATIC int sctp_setsockopt_connectx_old(struct sock* sk,
struct sockaddr __user *addrs,
int addrs_size)
{
return __sctp_setsockopt_connectx(sk, addrs, addrs_size, NULL);
}
/*
* New interface for the API. The since the API is done with a socket
* option, to make it simple we feed back the association id is as a return
* indication to the call. Error is always negative and association id is
* always positive.
*/
SCTP_STATIC int sctp_setsockopt_connectx(struct sock* sk,
struct sockaddr __user *addrs,
int addrs_size)
{
sctp_assoc_t assoc_id = 0;
int err = 0;
err = __sctp_setsockopt_connectx(sk, addrs, addrs_size, &assoc_id);
if (err)
return err;
else
return assoc_id;
}
/*
* New (hopefully final) interface for the API.
* We use the sctp_getaddrs_old structure so that use-space library
* can avoid any unnecessary allocations. The only defferent part
* is that we store the actual length of the address buffer into the
* addrs_num structure member. That way we can re-use the existing
* code.
*/
SCTP_STATIC int sctp_getsockopt_connectx3(struct sock* sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_getaddrs_old param;
sctp_assoc_t assoc_id = 0;
int err = 0;
if (len < sizeof(param))
return -EINVAL;
if (copy_from_user(¶m, optval, sizeof(param)))
return -EFAULT;
err = __sctp_setsockopt_connectx(sk,
(struct sockaddr __user *)param.addrs,
param.addr_num, &assoc_id);
if (err == 0 || err == -EINPROGRESS) {
if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
return -EFAULT;
if (put_user(sizeof(assoc_id), optlen))
return -EFAULT;
}
return err;
}
/* API 3.1.4 close() - UDP Style Syntax
* Applications use close() to perform graceful shutdown (as described in
* Section 10.1 of [SCTP]) on ALL the associations currently represented
* by a UDP-style socket.
*
* The syntax is
*
* ret = close(int sd);
*
* sd - the socket descriptor of the associations to be closed.
*
* To gracefully shutdown a specific association represented by the
* UDP-style socket, an application should use the sendmsg() call,
* passing no user data, but including the appropriate flag in the
* ancillary data (see Section xxxx).
*
* If sd in the close() call is a branched-off socket representing only
* one association, the shutdown is performed on that association only.
*
* 4.1.6 close() - TCP Style Syntax
*
* Applications use close() to gracefully close down an association.
*
* The syntax is:
*
* int close(int sd);
*
* sd - the socket descriptor of the association to be closed.
*
* After an application calls close() on a socket descriptor, no further
* socket operations will succeed on that descriptor.
*
* API 7.1.4 SO_LINGER
*
* An application using the TCP-style socket can use this option to
* perform the SCTP ABORT primitive. The linger option structure is:
*
* struct linger {
* int l_onoff; // option on/off
* int l_linger; // linger time
* };
*
* To enable the option, set l_onoff to 1. If the l_linger value is set
* to 0, calling close() is the same as the ABORT primitive. If the
* value is set to a negative value, the setsockopt() call will return
* an error. If the value is set to a positive value linger_time, the
* close() can be blocked for at most linger_time ms. If the graceful
* shutdown phase does not finish during this period, close() will
* return but the graceful shutdown phase continues in the system.
*/
SCTP_STATIC void sctp_close(struct sock *sk, long timeout)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct list_head *pos, *temp;
unsigned int data_was_unread;
SCTP_DEBUG_PRINTK("sctp_close(sk: 0x%p, timeout:%ld)\n", sk, timeout);
sctp_lock_sock(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
sk->sk_state = SCTP_SS_CLOSING;
ep = sctp_sk(sk)->ep;
/* Clean up any skbs sitting on the receive queue. */
data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
/* Walk all associations on an endpoint. */
list_for_each_safe(pos, temp, &ep->asocs) {
asoc = list_entry(pos, struct sctp_association, asocs);
if (sctp_style(sk, TCP)) {
/* A closed association can still be in the list if
* it belongs to a TCP-style listening socket that is
* not yet accepted. If so, free it. If not, send an
* ABORT or SHUTDOWN based on the linger options.
*/
if (sctp_state(asoc, CLOSED)) {
sctp_unhash_established(asoc);
sctp_association_free(asoc);
continue;
}
}
if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
!skb_queue_empty(&asoc->ulpq.reasm) ||
(sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
struct sctp_chunk *chunk;
chunk = sctp_make_abort_user(asoc, NULL, 0);
if (chunk)
sctp_primitive_ABORT(net, asoc, chunk);
} else
sctp_primitive_SHUTDOWN(net, asoc, NULL);
}
/* On a TCP-style socket, block for at most linger_time if set. */
if (sctp_style(sk, TCP) && timeout)
sctp_wait_for_close(sk, timeout);
/* This will run the backlog queue. */
sctp_release_sock(sk);
/* Supposedly, no process has access to the socket, but
* the net layers still may.
*/
sctp_local_bh_disable();
sctp_bh_lock_sock(sk);
/* Hold the sock, since sk_common_release() will put sock_put()
* and we have just a little more cleanup.
*/
sock_hold(sk);
sk_common_release(sk);
sctp_bh_unlock_sock(sk);
sctp_local_bh_enable();
sock_put(sk);
SCTP_DBG_OBJCNT_DEC(sock);
}
/* Handle EPIPE error. */
static int sctp_error(struct sock *sk, int flags, int err)
{
if (err == -EPIPE)
err = sock_error(sk) ? : -EPIPE;
if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
return err;
}
/* API 3.1.3 sendmsg() - UDP Style Syntax
*
* An application uses sendmsg() and recvmsg() calls to transmit data to
* and receive data from its peer.
*
* ssize_t sendmsg(int socket, const struct msghdr *message,
* int flags);
*
* socket - the socket descriptor of the endpoint.
* message - pointer to the msghdr structure which contains a single
* user message and possibly some ancillary data.
*
* See Section 5 for complete description of the data
* structures.
*
* flags - flags sent or received with the user message, see Section
* 5 for complete description of the flags.
*
* Note: This function could use a rewrite especially when explicit
* connect support comes in.
*/
/* BUG: We do not implement the equivalent of sk_stream_wait_memory(). */
SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
SCTP_STATIC int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t msg_len)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sctp_association *new_asoc=NULL, *asoc=NULL;
struct sctp_transport *transport, *chunk_tp;
struct sctp_chunk *chunk;
union sctp_addr to;
struct sockaddr *msg_name = NULL;
struct sctp_sndrcvinfo default_sinfo;
struct sctp_sndrcvinfo *sinfo;
struct sctp_initmsg *sinit;
sctp_assoc_t associd = 0;
sctp_cmsgs_t cmsgs = { NULL };
int err;
sctp_scope_t scope;
long timeo;
__u16 sinfo_flags = 0;
struct sctp_datamsg *datamsg;
int msg_flags = msg->msg_flags;
SCTP_DEBUG_PRINTK("sctp_sendmsg(sk: %p, msg: %p, msg_len: %zu)\n",
sk, msg, msg_len);
err = 0;
sp = sctp_sk(sk);
ep = sp->ep;
SCTP_DEBUG_PRINTK("Using endpoint: %p.\n", ep);
/* We cannot send a message over a TCP-style listening socket. */
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
err = -EPIPE;
goto out_nounlock;
}
/* Parse out the SCTP CMSGs. */
err = sctp_msghdr_parse(msg, &cmsgs);
if (err) {
SCTP_DEBUG_PRINTK("msghdr parse err = %x\n", err);
goto out_nounlock;
}
/* Fetch the destination address for this packet. This
* address only selects the association--it is not necessarily
* the address we will send to.
* For a peeled-off socket, msg_name is ignored.
*/
if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
int msg_namelen = msg->msg_namelen;
err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
msg_namelen);
if (err)
return err;
if (msg_namelen > sizeof(to))
msg_namelen = sizeof(to);
memcpy(&to, msg->msg_name, msg_namelen);
msg_name = msg->msg_name;
}
sinfo = cmsgs.info;
sinit = cmsgs.init;
/* Did the user specify SNDRCVINFO? */
if (sinfo) {
sinfo_flags = sinfo->sinfo_flags;
associd = sinfo->sinfo_assoc_id;
}
SCTP_DEBUG_PRINTK("msg_len: %zu, sinfo_flags: 0x%x\n",
msg_len, sinfo_flags);
/* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */
if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) {
err = -EINVAL;
goto out_nounlock;
}
/* If SCTP_EOF is set, no data can be sent. Disallow sending zero
* length messages when SCTP_EOF|SCTP_ABORT is not set.
* If SCTP_ABORT is set, the message length could be non zero with
* the msg_iov set to the user abort reason.
*/
if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) ||
(!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) {
err = -EINVAL;
goto out_nounlock;
}
/* If SCTP_ADDR_OVER is set, there must be an address
* specified in msg_name.
*/
if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) {
err = -EINVAL;
goto out_nounlock;
}
transport = NULL;
SCTP_DEBUG_PRINTK("About to look up association.\n");
sctp_lock_sock(sk);
/* If a msg_name has been specified, assume this is to be used. */
if (msg_name) {
/* Look for a matching association on the endpoint. */
asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
if (!asoc) {
/* If we could not find a matching association on the
* endpoint, make sure that it is not a TCP-style
* socket that already has an association or there is
* no peeled-off association on another socket.
*/
if ((sctp_style(sk, TCP) &&
sctp_sstate(sk, ESTABLISHED)) ||
sctp_endpoint_is_peeled_off(ep, &to)) {
err = -EADDRNOTAVAIL;
goto out_unlock;
}
}
} else {
asoc = sctp_id2assoc(sk, associd);
if (!asoc) {
err = -EPIPE;
goto out_unlock;
}
}
if (asoc) {
SCTP_DEBUG_PRINTK("Just looked up association: %p.\n", asoc);
/* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
* socket that has an association in CLOSED state. This can
* happen when an accepted socket has an association that is
* already CLOSED.
*/
if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
err = -EPIPE;
goto out_unlock;
}
if (sinfo_flags & SCTP_EOF) {
SCTP_DEBUG_PRINTK("Shutting down association: %p\n",
asoc);
sctp_primitive_SHUTDOWN(net, asoc, NULL);
err = 0;
goto out_unlock;
}
if (sinfo_flags & SCTP_ABORT) {
chunk = sctp_make_abort_user(asoc, msg, msg_len);
if (!chunk) {
err = -ENOMEM;
goto out_unlock;
}
SCTP_DEBUG_PRINTK("Aborting association: %p\n", asoc);
sctp_primitive_ABORT(net, asoc, chunk);
err = 0;
goto out_unlock;
}
}
/* Do we need to create the association? */
if (!asoc) {
SCTP_DEBUG_PRINTK("There is no association yet.\n");
if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) {
err = -EINVAL;
goto out_unlock;
}
/* Check for invalid stream against the stream counts,
* either the default or the user specified stream counts.
*/
if (sinfo) {
if (!sinit || (sinit && !sinit->sinit_num_ostreams)) {
/* Check against the defaults. */
if (sinfo->sinfo_stream >=
sp->initmsg.sinit_num_ostreams) {
err = -EINVAL;
goto out_unlock;
}
} else {
/* Check against the requested. */
if (sinfo->sinfo_stream >=
sinit->sinit_num_ostreams) {
err = -EINVAL;
goto out_unlock;
}
}
}
/*
* API 3.1.2 bind() - UDP Style Syntax
* If a bind() or sctp_bindx() is not called prior to a
* sendmsg() call that initiates a new association, the
* system picks an ephemeral port and will choose an address
* set equivalent to binding with a wildcard address.
*/
if (!ep->base.bind_addr.port) {
if (sctp_autobind(sk)) {
err = -EAGAIN;
goto out_unlock;
}
} else {
/*
* If an unprivileged user inherits a one-to-many
* style socket with open associations on a privileged
* port, it MAY be permitted to accept new associations,
* but it SHOULD NOT be permitted to open new
* associations.
*/
if (ep->base.bind_addr.port < PROT_SOCK &&
!ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
err = -EACCES;
goto out_unlock;
}
}
scope = sctp_scope(&to);
new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
if (!new_asoc) {
err = -ENOMEM;
goto out_unlock;
}
asoc = new_asoc;
err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
if (err < 0) {
err = -ENOMEM;
goto out_free;
}
/* If the SCTP_INIT ancillary data is specified, set all
* the association init values accordingly.
*/
if (sinit) {
if (sinit->sinit_num_ostreams) {
asoc->c.sinit_num_ostreams =
sinit->sinit_num_ostreams;
}
if (sinit->sinit_max_instreams) {
asoc->c.sinit_max_instreams =
sinit->sinit_max_instreams;
}
if (sinit->sinit_max_attempts) {
asoc->max_init_attempts
= sinit->sinit_max_attempts;
}
if (sinit->sinit_max_init_timeo) {
asoc->max_init_timeo =
msecs_to_jiffies(sinit->sinit_max_init_timeo);
}
}
/* Prime the peer's transport structures. */
transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN);
if (!transport) {
err = -ENOMEM;
goto out_free;
}
}
/* ASSERT: we have a valid association at this point. */
SCTP_DEBUG_PRINTK("We have a valid association.\n");
if (!sinfo) {
/* If the user didn't specify SNDRCVINFO, make up one with
* some defaults.
*/
memset(&default_sinfo, 0, sizeof(default_sinfo));
default_sinfo.sinfo_stream = asoc->default_stream;
default_sinfo.sinfo_flags = asoc->default_flags;
default_sinfo.sinfo_ppid = asoc->default_ppid;
default_sinfo.sinfo_context = asoc->default_context;
default_sinfo.sinfo_timetolive = asoc->default_timetolive;
default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
sinfo = &default_sinfo;
}
/* API 7.1.7, the sndbuf size per association bounds the
* maximum size of data that can be sent in a single send call.
*/
if (msg_len > sk->sk_sndbuf) {
err = -EMSGSIZE;
goto out_free;
}
if (asoc->pmtu_pending)
sctp_assoc_pending_pmtu(sk, asoc);
/* If fragmentation is disabled and the message length exceeds the
* association fragmentation point, return EMSGSIZE. The I-D
* does not specify what this error is, but this looks like
* a great fit.
*/
if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
err = -EMSGSIZE;
goto out_free;
}
/* Check for invalid stream. */
if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
err = -EINVAL;
goto out_free;
}
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
if (!sctp_wspace(asoc)) {
err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
if (err)
goto out_free;
}
/* If an address is passed with the sendto/sendmsg call, it is used
* to override the primary destination address in the TCP model, or
* when SCTP_ADDR_OVER flag is set in the UDP model.
*/
if ((sctp_style(sk, TCP) && msg_name) ||
(sinfo_flags & SCTP_ADDR_OVER)) {
chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
if (!chunk_tp) {
err = -EINVAL;
goto out_free;
}
} else
chunk_tp = NULL;
/* Auto-connect, if we aren't connected already. */
if (sctp_state(asoc, CLOSED)) {
err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
if (err < 0)
goto out_free;
SCTP_DEBUG_PRINTK("We associated primitively.\n");
}
/* Break the message into multiple chunks of maximum size. */
datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
if (IS_ERR(datamsg)) {
err = PTR_ERR(datamsg);
goto out_free;
}
/* Now send the (possibly) fragmented message. */
list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
sctp_chunk_hold(chunk);
/* Do accounting for the write space. */
sctp_set_owner_w(chunk);
chunk->transport = chunk_tp;
}
/* Send it to the lower layers. Note: all chunks
* must either fail or succeed. The lower layer
* works that way today. Keep it that way or this
* breaks.
*/
err = sctp_primitive_SEND(net, asoc, datamsg);
/* Did the lower layer accept the chunk? */
if (err)
sctp_datamsg_free(datamsg);
else
sctp_datamsg_put(datamsg);
SCTP_DEBUG_PRINTK("We sent primitively.\n");
if (err)
goto out_free;
else
err = msg_len;
/* If we are already past ASSOCIATE, the lower
* layers are responsible for association cleanup.
*/
goto out_unlock;
out_free:
if (new_asoc) {
sctp_unhash_established(asoc);
sctp_association_free(asoc);
}
out_unlock:
sctp_release_sock(sk);
out_nounlock:
return sctp_error(sk, msg_flags, err);
#if 0
do_sock_err:
if (msg_len)
err = msg_len;
else
err = sock_error(sk);
goto out;
do_interrupted:
if (msg_len)
err = msg_len;
goto out;
#endif /* 0 */
}
/* This is an extended version of skb_pull() that removes the data from the
* start of a skb even when data is spread across the list of skb's in the
* frag_list. len specifies the total amount of data that needs to be removed.
* when 'len' bytes could be removed from the skb, it returns 0.
* If 'len' exceeds the total skb length, it returns the no. of bytes that
* could not be removed.
*/
static int sctp_skb_pull(struct sk_buff *skb, int len)
{
struct sk_buff *list;
int skb_len = skb_headlen(skb);
int rlen;
if (len <= skb_len) {
__skb_pull(skb, len);
return 0;
}
len -= skb_len;
__skb_pull(skb, skb_len);
skb_walk_frags(skb, list) {
rlen = sctp_skb_pull(list, len);
skb->len -= (len-rlen);
skb->data_len -= (len-rlen);
if (!rlen)
return 0;
len = rlen;
}
return len;
}
/* API 3.1.3 recvmsg() - UDP Style Syntax
*
* ssize_t recvmsg(int socket, struct msghdr *message,
* int flags);
*
* socket - the socket descriptor of the endpoint.
* message - pointer to the msghdr structure which contains a single
* user message and possibly some ancillary data.
*
* See Section 5 for complete description of the data
* structures.
*
* flags - flags sent or received with the user message, see Section
* 5 for complete description of the flags.
*/
static struct sk_buff *sctp_skb_recv_datagram(struct sock *, int, int, int *);
SCTP_STATIC int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct sctp_ulpevent *event = NULL;
struct sctp_sock *sp = sctp_sk(sk);
struct sk_buff *skb;
int copied;
int err = 0;
int skb_len;
SCTP_DEBUG_PRINTK("sctp_recvmsg(%s: %p, %s: %p, %s: %zd, %s: %d, %s: "
"0x%x, %s: %p)\n", "sk", sk, "msghdr", msg,
"len", len, "knoblauch", noblock,
"flags", flags, "addr_len", addr_len);
sctp_lock_sock(sk);
if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED)) {
err = -ENOTCONN;
goto out;
}
skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
/* Get the total length of the skb including any skb's in the
* frag_list.
*/
skb_len = skb->len;
copied = skb_len;
if (copied > len)
copied = len;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
event = sctp_skb2event(skb);
if (err)
goto out_free;
sock_recv_ts_and_drops(msg, sk, skb);
if (sctp_ulpevent_is_notification(event)) {
msg->msg_flags |= MSG_NOTIFICATION;
sp->pf->event_msgname(event, msg->msg_name, addr_len);
} else {
sp->pf->skb_msgname(skb, msg->msg_name, addr_len);
}
/* Check if we allow SCTP_SNDRCVINFO. */
if (sp->subscribe.sctp_data_io_event)
sctp_ulpevent_read_sndrcvinfo(event, msg);
#if 0
/* FIXME: we should be calling IP/IPv6 layers. */
if (sk->sk_protinfo.af_inet.cmsg_flags)
ip_cmsg_recv(msg, skb);
#endif
err = copied;
/* If skb's length exceeds the user's buffer, update the skb and
* push it back to the receive_queue so that the next call to
* recvmsg() will return the remaining data. Don't set MSG_EOR.
*/
if (skb_len > copied) {
msg->msg_flags &= ~MSG_EOR;
if (flags & MSG_PEEK)
goto out_free;
sctp_skb_pull(skb, copied);
skb_queue_head(&sk->sk_receive_queue, skb);
/* When only partial message is copied to the user, increase
* rwnd by that amount. If all the data in the skb is read,
* rwnd is updated when the event is freed.
*/
if (!sctp_ulpevent_is_notification(event))
sctp_assoc_rwnd_increase(event->asoc, copied);
goto out;
} else if ((event->msg_flags & MSG_NOTIFICATION) ||
(event->msg_flags & MSG_EOR))
msg->msg_flags |= MSG_EOR;
else
msg->msg_flags &= ~MSG_EOR;
out_free:
if (flags & MSG_PEEK) {
/* Release the skb reference acquired after peeking the skb in
* sctp_skb_recv_datagram().
*/
kfree_skb(skb);
} else {
/* Free the event which includes releasing the reference to
* the owner of the skb, freeing the skb and updating the
* rwnd.
*/
sctp_ulpevent_free(event);
}
out:
sctp_release_sock(sk);
return err;
}
/* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
*
* This option is a on/off flag. If enabled no SCTP message
* fragmentation will be performed. Instead if a message being sent
* exceeds the current PMTU size, the message will NOT be sent and
* instead a error will be indicated to the user.
*/
static int sctp_setsockopt_disable_fragments(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
int val;
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
return 0;
}
static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct sctp_association *asoc;
struct sctp_ulpevent *event;
if (optlen > sizeof(struct sctp_event_subscribe))
return -EINVAL;
if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
return -EFAULT;
/*
* At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
* if there is no data to be sent or retransmit, the stack will
* immediately send up this notification.
*/
if (sctp_ulpevent_type_enabled(SCTP_SENDER_DRY_EVENT,
&sctp_sk(sk)->subscribe)) {
asoc = sctp_id2assoc(sk, 0);
if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
event = sctp_ulpevent_make_sender_dry_event(asoc,
GFP_ATOMIC);
if (!event)
return -ENOMEM;
sctp_ulpq_tail_event(&asoc->ulpq, event);
}
}
return 0;
}
/* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
*
* This socket option is applicable to the UDP-style socket only. When
* set it will cause associations that are idle for more than the
* specified number of seconds to automatically close. An association
* being idle is defined an association that has NOT sent or received
* user data. The special value of '0' indicates that no automatic
* close of any associations should be performed. The option expects an
* integer defining the number of seconds of idle time before an
* association is closed.
*/
static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
/* Applicable to UDP-style socket only */
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (optlen != sizeof(int))
return -EINVAL;
if (copy_from_user(&sp->autoclose, optval, optlen))
return -EFAULT;
return 0;
}
/* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
*
* Applications can enable or disable heartbeats for any peer address of
* an association, modify an address's heartbeat interval, force a
* heartbeat to be sent immediately, and adjust the address's maximum
* number of retransmissions sent before an address is considered
* unreachable. The following structure is used to access and modify an
* address's parameters:
*
* struct sctp_paddrparams {
* sctp_assoc_t spp_assoc_id;
* struct sockaddr_storage spp_address;
* uint32_t spp_hbinterval;
* uint16_t spp_pathmaxrxt;
* uint32_t spp_pathmtu;
* uint32_t spp_sackdelay;
* uint32_t spp_flags;
* };
*
* spp_assoc_id - (one-to-many style socket) This is filled in the
* application, and identifies the association for
* this query.
* spp_address - This specifies which address is of interest.
* spp_hbinterval - This contains the value of the heartbeat interval,
* in milliseconds. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmaxrxt - This contains the maximum number of
* retransmissions before this address shall be
* considered unreachable. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmtu - When Path MTU discovery is disabled the value
* specified here will be the "fixed" path mtu.
* Note that if the spp_address field is empty
* then all associations on this address will
* have this fixed path mtu set upon them.
*
* spp_sackdelay - When delayed sack is enabled, this value specifies
* the number of milliseconds that sacks will be delayed
* for. This value will apply to all addresses of an
* association if the spp_address field is empty. Note
* also, that if delayed sack is enabled and this
* value is set to 0, no change is made to the last
* recorded delayed sack timer value.
*
* spp_flags - These flags are used to control various features
* on an association. The flag field may contain
* zero or more of the following options.
*
* SPP_HB_ENABLE - Enable heartbeats on the
* specified address. Note that if the address
* field is empty all addresses for the association
* have heartbeats enabled upon them.
*
* SPP_HB_DISABLE - Disable heartbeats on the
* speicifed address. Note that if the address
* field is empty all addresses for the association
* will have their heartbeats disabled. Note also
* that SPP_HB_ENABLE and SPP_HB_DISABLE are
* mutually exclusive, only one of these two should
* be specified. Enabling both fields will have
* undetermined results.
*
* SPP_HB_DEMAND - Request a user initiated heartbeat
* to be made immediately.
*
* SPP_HB_TIME_IS_ZERO - Specify's that the time for
* heartbeat delayis to be set to the value of 0
* milliseconds.
*
* SPP_PMTUD_ENABLE - This field will enable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected.
*
* SPP_PMTUD_DISABLE - This field will disable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected. Not also that
* SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
* exclusive. Enabling both will have undetermined
* results.
*
* SPP_SACKDELAY_ENABLE - Setting this flag turns
* on delayed sack. The time specified in spp_sackdelay
* is used to specify the sack delay for this address. Note
* that if spp_address is empty then all addresses will
* enable delayed sack and take on the sack delay
* value specified in spp_sackdelay.
* SPP_SACKDELAY_DISABLE - Setting this flag turns
* off delayed sack. If the spp_address field is blank then
* delayed sack is disabled for the entire association. Note
* also that this field is mutually exclusive to
* SPP_SACKDELAY_ENABLE, setting both will have undefined
* results.
*/
static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
struct sctp_transport *trans,
struct sctp_association *asoc,
struct sctp_sock *sp,
int hb_change,
int pmtud_change,
int sackdelay_change)
{
int error;
if (params->spp_flags & SPP_HB_DEMAND && trans) {
struct net *net = sock_net(trans->asoc->base.sk);
error = sctp_primitive_REQUESTHEARTBEAT(net, trans->asoc, trans);
if (error)
return error;
}
/* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
* this field is ignored. Note also that a value of zero indicates
* the current setting should be left unchanged.
*/
if (params->spp_flags & SPP_HB_ENABLE) {
/* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
* set. This lets us use 0 value when this flag
* is set.
*/
if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
params->spp_hbinterval = 0;
if (params->spp_hbinterval ||
(params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
if (trans) {
trans->hbinterval =
msecs_to_jiffies(params->spp_hbinterval);
} else if (asoc) {
asoc->hbinterval =
msecs_to_jiffies(params->spp_hbinterval);
} else {
sp->hbinterval = params->spp_hbinterval;
}
}
}
if (hb_change) {
if (trans) {
trans->param_flags =
(trans->param_flags & ~SPP_HB) | hb_change;
} else if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_HB) | hb_change;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_HB) | hb_change;
}
}
/* When Path MTU discovery is disabled the value specified here will
* be the "fixed" path mtu (i.e. the value of the spp_flags field must
* include the flag SPP_PMTUD_DISABLE for this field to have any
* effect).
*/
if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
if (trans) {
trans->pathmtu = params->spp_pathmtu;
sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc);
} else if (asoc) {
asoc->pathmtu = params->spp_pathmtu;
sctp_frag_point(asoc, params->spp_pathmtu);
} else {
sp->pathmtu = params->spp_pathmtu;
}
}
if (pmtud_change) {
if (trans) {
int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
(params->spp_flags & SPP_PMTUD_ENABLE);
trans->param_flags =
(trans->param_flags & ~SPP_PMTUD) | pmtud_change;
if (update) {
sctp_transport_pmtu(trans, sctp_opt2sk(sp));
sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc);
}
} else if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_PMTUD) | pmtud_change;
}
}
/* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
* value of this field is ignored. Note also that a value of zero
* indicates the current setting should be left unchanged.
*/
if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
if (trans) {
trans->sackdelay =
msecs_to_jiffies(params->spp_sackdelay);
} else if (asoc) {
asoc->sackdelay =
msecs_to_jiffies(params->spp_sackdelay);
} else {
sp->sackdelay = params->spp_sackdelay;
}
}
if (sackdelay_change) {
if (trans) {
trans->param_flags =
(trans->param_flags & ~SPP_SACKDELAY) |
sackdelay_change;
} else if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_SACKDELAY) |
sackdelay_change;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_SACKDELAY) |
sackdelay_change;
}
}
/* Note that a value of zero indicates the current setting should be
left unchanged.
*/
if (params->spp_pathmaxrxt) {
if (trans) {
trans->pathmaxrxt = params->spp_pathmaxrxt;
} else if (asoc) {
asoc->pathmaxrxt = params->spp_pathmaxrxt;
} else {
sp->pathmaxrxt = params->spp_pathmaxrxt;
}
}
return 0;
}
static int sctp_setsockopt_peer_addr_params(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct sctp_paddrparams params;
struct sctp_transport *trans = NULL;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
int error;
int hb_change, pmtud_change, sackdelay_change;
if (optlen != sizeof(struct sctp_paddrparams))
return - EINVAL;
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
/* Validate flags and value parameters. */
hb_change = params.spp_flags & SPP_HB;
pmtud_change = params.spp_flags & SPP_PMTUD;
sackdelay_change = params.spp_flags & SPP_SACKDELAY;
if (hb_change == SPP_HB ||
pmtud_change == SPP_PMTUD ||
sackdelay_change == SPP_SACKDELAY ||
params.spp_sackdelay > 500 ||
(params.spp_pathmtu &&
params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
return -EINVAL;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, ( union sctp_addr *)¶ms.spp_address)) {
trans = sctp_addr_id2transport(sk, ¶ms.spp_address,
params.spp_assoc_id);
if (!trans)
return -EINVAL;
}
/* Get association, if assoc_id != 0 and the socket is a one
* to many style socket, and an association was not found, then
* the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.spp_assoc_id);
if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
/* Heartbeat demand can only be sent on a transport or
* association, but not a socket.
*/
if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc)
return -EINVAL;
/* Process parameters. */
error = sctp_apply_peer_addr_params(¶ms, trans, asoc, sp,
hb_change, pmtud_change,
sackdelay_change);
if (error)
return error;
/* If changes are for association, also apply parameters to each
* transport.
*/
if (!trans && asoc) {
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
sctp_apply_peer_addr_params(¶ms, trans, asoc, sp,
hb_change, pmtud_change,
sackdelay_change);
}
}
return 0;
}
/*
* 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK)
*
* This option will effect the way delayed acks are performed. This
* option allows you to get or set the delayed ack time, in
* milliseconds. It also allows changing the delayed ack frequency.
* Changing the frequency to 1 disables the delayed sack algorithm. If
* the assoc_id is 0, then this sets or gets the endpoints default
* values. If the assoc_id field is non-zero, then the set or get
* effects the specified association for the one to many model (the
* assoc_id field is ignored by the one to one model). Note that if
* sack_delay or sack_freq are 0 when setting this option, then the
* current values will remain unchanged.
*
* struct sctp_sack_info {
* sctp_assoc_t sack_assoc_id;
* uint32_t sack_delay;
* uint32_t sack_freq;
* };
*
* sack_assoc_id - This parameter, indicates which association the user
* is performing an action upon. Note that if this field's value is
* zero then the endpoints default value is changed (effecting future
* associations only).
*
* sack_delay - This parameter contains the number of milliseconds that
* the user is requesting the delayed ACK timer be set to. Note that
* this value is defined in the standard to be between 200 and 500
* milliseconds.
*
* sack_freq - This parameter contains the number of packets that must
* be received before a sack is sent without waiting for the delay
* timer to expire. The default value for this is 2, setting this
* value to 1 will disable the delayed sack algorithm.
*/
static int sctp_setsockopt_delayed_ack(struct sock *sk,
char __user *optval, unsigned int optlen)
{
struct sctp_sack_info params;
struct sctp_transport *trans = NULL;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen == sizeof(struct sctp_sack_info)) {
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
if (params.sack_delay == 0 && params.sack_freq == 0)
return 0;
} else if (optlen == sizeof(struct sctp_assoc_value)) {
pr_warn("Use of struct sctp_assoc_value in delayed_ack socket option deprecated\n");
pr_warn("Use struct sctp_sack_info instead\n");
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
if (params.sack_delay == 0)
params.sack_freq = 1;
else
params.sack_freq = 0;
} else
return - EINVAL;
/* Validate value parameter. */
if (params.sack_delay > 500)
return -EINVAL;
/* Get association, if sack_assoc_id != 0 and the socket is a one
* to many style socket, and an association was not found, then
* the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.sack_assoc_id);
if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (params.sack_delay) {
if (asoc) {
asoc->sackdelay =
msecs_to_jiffies(params.sack_delay);
asoc->param_flags =
(asoc->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_ENABLE;
} else {
sp->sackdelay = params.sack_delay;
sp->param_flags =
(sp->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_ENABLE;
}
}
if (params.sack_freq == 1) {
if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_DISABLE;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_DISABLE;
}
} else if (params.sack_freq > 1) {
if (asoc) {
asoc->sackfreq = params.sack_freq;
asoc->param_flags =
(asoc->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_ENABLE;
} else {
sp->sackfreq = params.sack_freq;
sp->param_flags =
(sp->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_ENABLE;
}
}
/* If change is for association, also apply to each transport. */
if (asoc) {
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
if (params.sack_delay) {
trans->sackdelay =
msecs_to_jiffies(params.sack_delay);
trans->param_flags =
(trans->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_ENABLE;
}
if (params.sack_freq == 1) {
trans->param_flags =
(trans->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_DISABLE;
} else if (params.sack_freq > 1) {
trans->sackfreq = params.sack_freq;
trans->param_flags =
(trans->param_flags & ~SPP_SACKDELAY) |
SPP_SACKDELAY_ENABLE;
}
}
}
return 0;
}
/* 7.1.3 Initialization Parameters (SCTP_INITMSG)
*
* Applications can specify protocol parameters for the default association
* initialization. The option name argument to setsockopt() and getsockopt()
* is SCTP_INITMSG.
*
* Setting initialization parameters is effective only on an unconnected
* socket (for UDP-style sockets only future associations are effected
* by the change). With TCP-style sockets, this option is inherited by
* sockets derived from a listener socket.
*/
static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, unsigned int optlen)
{
struct sctp_initmsg sinit;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen != sizeof(struct sctp_initmsg))
return -EINVAL;
if (copy_from_user(&sinit, optval, optlen))
return -EFAULT;
if (sinit.sinit_num_ostreams)
sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;
if (sinit.sinit_max_instreams)
sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;
if (sinit.sinit_max_attempts)
sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;
if (sinit.sinit_max_init_timeo)
sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;
return 0;
}
/*
* 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
*
* Applications that wish to use the sendto() system call may wish to
* specify a default set of parameters that would normally be supplied
* through the inclusion of ancillary data. This socket option allows
* such an application to set the default sctp_sndrcvinfo structure.
* The application that wishes to use this socket option simply passes
* in to this call the sctp_sndrcvinfo structure defined in Section
* 5.2.2) The input parameters accepted by this call include
* sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
* sinfo_timetolive. The user must provide the sinfo_assoc_id field in
* to this call if the caller is using the UDP model.
*/
static int sctp_setsockopt_default_send_param(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct sctp_sndrcvinfo info;
struct sctp_association *asoc;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen != sizeof(struct sctp_sndrcvinfo))
return -EINVAL;
if (copy_from_user(&info, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
asoc->default_stream = info.sinfo_stream;
asoc->default_flags = info.sinfo_flags;
asoc->default_ppid = info.sinfo_ppid;
asoc->default_context = info.sinfo_context;
asoc->default_timetolive = info.sinfo_timetolive;
} else {
sp->default_stream = info.sinfo_stream;
sp->default_flags = info.sinfo_flags;
sp->default_ppid = info.sinfo_ppid;
sp->default_context = info.sinfo_context;
sp->default_timetolive = info.sinfo_timetolive;
}
return 0;
}
/* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
*
* Requests that the local SCTP stack use the enclosed peer address as
* the association primary. The enclosed address must be one of the
* association peer's addresses.
*/
static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct sctp_prim prim;
struct sctp_transport *trans;
if (optlen != sizeof(struct sctp_prim))
return -EINVAL;
if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
return -EFAULT;
trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
if (!trans)
return -EINVAL;
sctp_assoc_set_primary(trans->asoc, trans);
return 0;
}
/*
* 7.1.5 SCTP_NODELAY
*
* Turn on/off any Nagle-like algorithm. This means that packets are
* generally sent as soon as possible and no unnecessary delays are
* introduced, at the cost of more packets in the network. Expects an
* integer boolean flag.
*/
static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
unsigned int optlen)
{
int val;
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
return 0;
}
/*
*
* 7.1.1 SCTP_RTOINFO
*
* The protocol parameters used to initialize and bound retransmission
* timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
* and modify these parameters.
* All parameters are time values, in milliseconds. A value of 0, when
* modifying the parameters, indicates that the current value should not
* be changed.
*
*/
static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen)
{
struct sctp_rtoinfo rtoinfo;
struct sctp_association *asoc;
if (optlen != sizeof (struct sctp_rtoinfo))
return -EINVAL;
if (copy_from_user(&rtoinfo, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
/* Set the values to the specific association */
if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
if (rtoinfo.srto_initial != 0)
asoc->rto_initial =
msecs_to_jiffies(rtoinfo.srto_initial);
if (rtoinfo.srto_max != 0)
asoc->rto_max = msecs_to_jiffies(rtoinfo.srto_max);
if (rtoinfo.srto_min != 0)
asoc->rto_min = msecs_to_jiffies(rtoinfo.srto_min);
} else {
/* If there is no association or the association-id = 0
* set the values to the endpoint.
*/
struct sctp_sock *sp = sctp_sk(sk);
if (rtoinfo.srto_initial != 0)
sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
if (rtoinfo.srto_max != 0)
sp->rtoinfo.srto_max = rtoinfo.srto_max;
if (rtoinfo.srto_min != 0)
sp->rtoinfo.srto_min = rtoinfo.srto_min;
}
return 0;
}
/*
*
* 7.1.2 SCTP_ASSOCINFO
*
* This option is used to tune the maximum retransmission attempts
* of the association.
* Returns an error if the new association retransmission value is
* greater than the sum of the retransmission value of the peer.
* See [SCTP] for more information.
*
*/
static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen)
{
struct sctp_assocparams assocparams;
struct sctp_association *asoc;
if (optlen != sizeof(struct sctp_assocparams))
return -EINVAL;
if (copy_from_user(&assocparams, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
/* Set the values to the specific association */
if (asoc) {
if (assocparams.sasoc_asocmaxrxt != 0) {
__u32 path_sum = 0;
int paths = 0;
struct sctp_transport *peer_addr;
list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
transports) {
path_sum += peer_addr->pathmaxrxt;
paths++;
}
/* Only validate asocmaxrxt if we have more than
* one path/transport. We do this because path
* retransmissions are only counted when we have more
* then one path.
*/
if (paths > 1 &&
assocparams.sasoc_asocmaxrxt > path_sum)
return -EINVAL;
asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
}
if (assocparams.sasoc_cookie_life != 0) {
asoc->cookie_life.tv_sec =
assocparams.sasoc_cookie_life / 1000;
asoc->cookie_life.tv_usec =
(assocparams.sasoc_cookie_life % 1000)
* 1000;
}
} else {
/* Set the values to the endpoint */
struct sctp_sock *sp = sctp_sk(sk);
if (assocparams.sasoc_asocmaxrxt != 0)
sp->assocparams.sasoc_asocmaxrxt =
assocparams.sasoc_asocmaxrxt;
if (assocparams.sasoc_cookie_life != 0)
sp->assocparams.sasoc_cookie_life =
assocparams.sasoc_cookie_life;
}
return 0;
}
/*
* 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
*
* This socket option is a boolean flag which turns on or off mapped V4
* addresses. If this option is turned on and the socket is type
* PF_INET6, then IPv4 addresses will be mapped to V6 representation.
* If this option is turned off, then no mapping will be done of V4
* addresses and a user will receive both PF_INET6 and PF_INET type
* addresses on the socket.
*/
static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, unsigned int optlen)
{
int val;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
if (val)
sp->v4mapped = 1;
else
sp->v4mapped = 0;
return 0;
}
/*
* 8.1.16. Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
* This option will get or set the maximum size to put in any outgoing
* SCTP DATA chunk. If a message is larger than this size it will be
* fragmented by SCTP into the specified size. Note that the underlying
* SCTP implementation may fragment into smaller sized chunks when the
* PMTU of the underlying association is smaller than the value set by
* the user. The default value for this option is '0' which indicates
* the user is NOT limiting fragmentation and only the PMTU will effect
* SCTP's choice of DATA chunk size. Note also that values set larger
* than the maximum size of an IP datagram will effectively let SCTP
* control fragmentation (i.e. the same as setting this option to 0).
*
* The following structure is used to access and modify this parameter:
*
* struct sctp_assoc_value {
* sctp_assoc_t assoc_id;
* uint32_t assoc_value;
* };
*
* assoc_id: This parameter is ignored for one-to-one style sockets.
* For one-to-many style sockets this parameter indicates which
* association the user is performing an action upon. Note that if
* this field's value is zero then the endpoints default value is
* changed (effecting future associations only).
* assoc_value: This parameter specifies the maximum size in bytes.
*/
static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, unsigned int optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
struct sctp_sock *sp = sctp_sk(sk);
int val;
if (optlen == sizeof(int)) {
pr_warn("Use of int in maxseg socket option deprecated\n");
pr_warn("Use struct sctp_assoc_value instead\n");
if (copy_from_user(&val, optval, optlen))
return -EFAULT;
params.assoc_id = 0;
} else if (optlen == sizeof(struct sctp_assoc_value)) {
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
val = params.assoc_value;
} else
return -EINVAL;
if ((val != 0) && ((val < 8) || (val > SCTP_MAX_CHUNK_LEN)))
return -EINVAL;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
if (val == 0) {
val = asoc->pathmtu;
val -= sp->pf->af->net_header_len;
val -= sizeof(struct sctphdr) +
sizeof(struct sctp_data_chunk);
}
asoc->user_frag = val;
asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
} else {
sp->user_frag = val;
}
return 0;
}
/*
* 7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
*
* Requests that the peer mark the enclosed address as the association
* primary. The enclosed address must be one of the association's
* locally bound addresses. The following structure is used to make a
* set primary request:
*/
static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
struct sctp_association *asoc = NULL;
struct sctp_setpeerprim prim;
struct sctp_chunk *chunk;
struct sctp_af *af;
int err;
sp = sctp_sk(sk);
if (!net->sctp.addip_enable)
return -EPERM;
if (optlen != sizeof(struct sctp_setpeerprim))
return -EINVAL;
if (copy_from_user(&prim, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
if (!asoc)
return -EINVAL;
if (!asoc->peer.asconf_capable)
return -EPERM;
if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
return -EPERM;
if (!sctp_state(asoc, ESTABLISHED))
return -ENOTCONN;
af = sctp_get_af_specific(prim.sspp_addr.ss_family);
if (!af)
return -EINVAL;
if (!af->addr_valid((union sctp_addr *)&prim.sspp_addr, sp, NULL))
return -EADDRNOTAVAIL;
if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
return -EADDRNOTAVAIL;
/* Create an ASCONF chunk with SET_PRIMARY parameter */
chunk = sctp_make_asconf_set_prim(asoc,
(union sctp_addr *)&prim.sspp_addr);
if (!chunk)
return -ENOMEM;
err = sctp_send_asconf(asoc, chunk);
SCTP_DEBUG_PRINTK("We set peer primary addr primitively.\n");
return err;
}
static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct sctp_setadaptation adaptation;
if (optlen != sizeof(struct sctp_setadaptation))
return -EINVAL;
if (copy_from_user(&adaptation, optval, optlen))
return -EFAULT;
sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind;
return 0;
}
/*
* 7.1.29. Set or Get the default context (SCTP_CONTEXT)
*
* The context field in the sctp_sndrcvinfo structure is normally only
* used when a failed message is retrieved holding the value that was
* sent down on the actual send call. This option allows the setting of
* a default context on an association basis that will be received on
* reading messages from the peer. This is especially helpful in the
* one-2-many model for an application to keep some reference to an
* internal state machine that is processing messages on the
* association. Note that the setting of this value only effects
* received messages from the peer and does not effect the value that is
* saved with outbound messages.
*/
static int sctp_setsockopt_context(struct sock *sk, char __user *optval,
unsigned int optlen)
{
struct sctp_assoc_value params;
struct sctp_sock *sp;
struct sctp_association *asoc;
if (optlen != sizeof(struct sctp_assoc_value))
return -EINVAL;
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
sp = sctp_sk(sk);
if (params.assoc_id != 0) {
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc)
return -EINVAL;
asoc->default_rcv_context = params.assoc_value;
} else {
sp->default_rcv_context = params.assoc_value;
}
return 0;
}
/*
* 7.1.24. Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
*
* This options will at a minimum specify if the implementation is doing
* fragmented interleave. Fragmented interleave, for a one to many
* socket, is when subsequent calls to receive a message may return
* parts of messages from different associations. Some implementations
* may allow you to turn this value on or off. If so, when turned off,
* no fragment interleave will occur (which will cause a head of line
* blocking amongst multiple associations sharing the same one to many
* socket). When this option is turned on, then each receive call may
* come from a different association (thus the user must receive data
* with the extended calls (e.g. sctp_recvmsg) to keep track of which
* association each receive belongs to.
*
* This option takes a boolean value. A non-zero value indicates that
* fragmented interleave is on. A value of zero indicates that
* fragmented interleave is off.
*
* Note that it is important that an implementation that allows this
* option to be turned on, have it off by default. Otherwise an unaware
* application using the one to many model may become confused and act
* incorrectly.
*/
static int sctp_setsockopt_fragment_interleave(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
int val;
if (optlen != sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1;
return 0;
}
/*
* 8.1.21. Set or Get the SCTP Partial Delivery Point
* (SCTP_PARTIAL_DELIVERY_POINT)
*
* This option will set or get the SCTP partial delivery point. This
* point is the size of a message where the partial delivery API will be
* invoked to help free up rwnd space for the peer. Setting this to a
* lower value will cause partial deliveries to happen more often. The
* calls argument is an integer that sets or gets the partial delivery
* point. Note also that the call will fail if the user attempts to set
* this value larger than the socket receive buffer size.
*
* Note that any single message having a length smaller than or equal to
* the SCTP partial delivery point will be delivered in one single read
* call as long as the user provided buffer is large enough to hold the
* message.
*/
static int sctp_setsockopt_partial_delivery_point(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
u32 val;
if (optlen != sizeof(u32))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
/* Note: We double the receive buffer from what the user sets
* it to be, also initial rwnd is based on rcvbuf/2.
*/
if (val > (sk->sk_rcvbuf >> 1))
return -EINVAL;
sctp_sk(sk)->pd_point = val;
return 0; /* is this the right error code? */
}
/*
* 7.1.28. Set or Get the maximum burst (SCTP_MAX_BURST)
*
* This option will allow a user to change the maximum burst of packets
* that can be emitted by this association. Note that the default value
* is 4, and some implementations may restrict this setting so that it
* can only be lowered.
*
* NOTE: This text doesn't seem right. Do this on a socket basis with
* future associations inheriting the socket value.
*/
static int sctp_setsockopt_maxburst(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct sctp_assoc_value params;
struct sctp_sock *sp;
struct sctp_association *asoc;
int val;
int assoc_id = 0;
if (optlen == sizeof(int)) {
pr_warn("Use of int in max_burst socket option deprecated\n");
pr_warn("Use struct sctp_assoc_value instead\n");
if (copy_from_user(&val, optval, optlen))
return -EFAULT;
} else if (optlen == sizeof(struct sctp_assoc_value)) {
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
val = params.assoc_value;
assoc_id = params.assoc_id;
} else
return -EINVAL;
sp = sctp_sk(sk);
if (assoc_id != 0) {
asoc = sctp_id2assoc(sk, assoc_id);
if (!asoc)
return -EINVAL;
asoc->max_burst = val;
} else
sp->max_burst = val;
return 0;
}
/*
* 7.1.18. Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
*
* This set option adds a chunk type that the user is requesting to be
* received only in an authenticated way. Changes to the list of chunks
* will only effect future associations on the socket.
*/
static int sctp_setsockopt_auth_chunk(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct net *net = sock_net(sk);
struct sctp_authchunk val;
if (!net->sctp.auth_enable)
return -EACCES;
if (optlen != sizeof(struct sctp_authchunk))
return -EINVAL;
if (copy_from_user(&val, optval, optlen))
return -EFAULT;
switch (val.sauth_chunk) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
case SCTP_CID_SHUTDOWN_COMPLETE:
case SCTP_CID_AUTH:
return -EINVAL;
}
/* add this chunk id to the endpoint */
return sctp_auth_ep_add_chunkid(sctp_sk(sk)->ep, val.sauth_chunk);
}
/*
* 7.1.19. Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
*
* This option gets or sets the list of HMAC algorithms that the local
* endpoint requires the peer to use.
*/
static int sctp_setsockopt_hmac_ident(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct net *net = sock_net(sk);
struct sctp_hmacalgo *hmacs;
u32 idents;
int err;
if (!net->sctp.auth_enable)
return -EACCES;
if (optlen < sizeof(struct sctp_hmacalgo))
return -EINVAL;
hmacs= memdup_user(optval, optlen);
if (IS_ERR(hmacs))
return PTR_ERR(hmacs);
idents = hmacs->shmac_num_idents;
if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
(idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo))) {
err = -EINVAL;
goto out;
}
err = sctp_auth_ep_set_hmacs(sctp_sk(sk)->ep, hmacs);
out:
kfree(hmacs);
return err;
}
/*
* 7.1.20. Set a shared key (SCTP_AUTH_KEY)
*
* This option will set a shared secret key which is used to build an
* association shared key.
*/
static int sctp_setsockopt_auth_key(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct net *net = sock_net(sk);
struct sctp_authkey *authkey;
struct sctp_association *asoc;
int ret;
if (!net->sctp.auth_enable)
return -EACCES;
if (optlen <= sizeof(struct sctp_authkey))
return -EINVAL;
authkey= memdup_user(optval, optlen);
if (IS_ERR(authkey))
return PTR_ERR(authkey);
if (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) {
ret = -EINVAL;
goto out;
}
asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
if (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {
ret = -EINVAL;
goto out;
}
ret = sctp_auth_set_key(sctp_sk(sk)->ep, asoc, authkey);
out:
kzfree(authkey);
return ret;
}
/*
* 7.1.21. Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
*
* This option will get or set the active shared key to be used to build
* the association shared key.
*/
static int sctp_setsockopt_active_key(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct net *net = sock_net(sk);
struct sctp_authkeyid val;
struct sctp_association *asoc;
if (!net->sctp.auth_enable)
return -EACCES;
if (optlen != sizeof(struct sctp_authkeyid))
return -EINVAL;
if (copy_from_user(&val, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, val.scact_assoc_id);
if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
return sctp_auth_set_active_key(sctp_sk(sk)->ep, asoc,
val.scact_keynumber);
}
/*
* 7.1.22. Delete a shared key (SCTP_AUTH_DELETE_KEY)
*
* This set option will delete a shared secret key from use.
*/
static int sctp_setsockopt_del_key(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct net *net = sock_net(sk);
struct sctp_authkeyid val;
struct sctp_association *asoc;
if (!net->sctp.auth_enable)
return -EACCES;
if (optlen != sizeof(struct sctp_authkeyid))
return -EINVAL;
if (copy_from_user(&val, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, val.scact_assoc_id);
if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
return sctp_auth_del_key_id(sctp_sk(sk)->ep, asoc,
val.scact_keynumber);
}
/*
* 8.1.23 SCTP_AUTO_ASCONF
*
* This option will enable or disable the use of the automatic generation of
* ASCONF chunks to add and delete addresses to an existing association. Note
* that this option has two caveats namely: a) it only affects sockets that
* are bound to all addresses available to the SCTP stack, and b) the system
* administrator may have an overriding control that turns the ASCONF feature
* off no matter what setting the socket option may have.
* This option expects an integer boolean flag, where a non-zero value turns on
* the option, and a zero value turns off the option.
* Note. In this implementation, socket operation overrides default parameter
* being set by sysctl as well as FreeBSD implementation
*/
static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
unsigned int optlen)
{
int val;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
if (!sctp_is_ep_boundall(sk) && val)
return -EINVAL;
if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
return 0;
if (val == 0 && sp->do_auto_asconf) {
list_del(&sp->auto_asconf_list);
sp->do_auto_asconf = 0;
} else if (val && !sp->do_auto_asconf) {
list_add_tail(&sp->auto_asconf_list,
&sock_net(sk)->sctp.auto_asconf_splist);
sp->do_auto_asconf = 1;
}
return 0;
}
/*
* SCTP_PEER_ADDR_THLDS
*
* This option allows us to alter the partially failed threshold for one or all
* transports in an association. See Section 6.1 of:
* http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
*/
static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct sctp_paddrthlds val;
struct sctp_transport *trans;
struct sctp_association *asoc;
if (optlen < sizeof(struct sctp_paddrthlds))
return -EINVAL;
if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval,
sizeof(struct sctp_paddrthlds)))
return -EFAULT;
if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
asoc = sctp_id2assoc(sk, val.spt_assoc_id);
if (!asoc)
return -ENOENT;
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
if (val.spt_pathmaxrxt)
trans->pathmaxrxt = val.spt_pathmaxrxt;
trans->pf_retrans = val.spt_pathpfthld;
}
if (val.spt_pathmaxrxt)
asoc->pathmaxrxt = val.spt_pathmaxrxt;
asoc->pf_retrans = val.spt_pathpfthld;
} else {
trans = sctp_addr_id2transport(sk, &val.spt_address,
val.spt_assoc_id);
if (!trans)
return -ENOENT;
if (val.spt_pathmaxrxt)
trans->pathmaxrxt = val.spt_pathmaxrxt;
trans->pf_retrans = val.spt_pathpfthld;
}
return 0;
}
/* API 6.2 setsockopt(), getsockopt()
*
* Applications use setsockopt() and getsockopt() to set or retrieve
* socket options. Socket options are used to change the default
* behavior of sockets calls. They are described in Section 7.
*
* The syntax is:
*
* ret = getsockopt(int sd, int level, int optname, void __user *optval,
* int __user *optlen);
* ret = setsockopt(int sd, int level, int optname, const void __user *optval,
* int optlen);
*
* sd - the socket descript.
* level - set to IPPROTO_SCTP for all SCTP options.
* optname - the option name.
* optval - the buffer to store the value of the option.
* optlen - the size of the buffer.
*/
SCTP_STATIC int sctp_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
int retval = 0;
SCTP_DEBUG_PRINTK("sctp_setsockopt(sk: %p... optname: %d)\n",
sk, optname);
/* I can hardly begin to describe how wrong this is. This is
* so broken as to be worse than useless. The API draft
* REALLY is NOT helpful here... I am not convinced that the
* semantics of setsockopt() with a level OTHER THAN SOL_SCTP
* are at all well-founded.
*/
if (level != SOL_SCTP) {
struct sctp_af *af = sctp_sk(sk)->pf->af;
retval = af->setsockopt(sk, level, optname, optval, optlen);
goto out_nounlock;
}
sctp_lock_sock(sk);
switch (optname) {
case SCTP_SOCKOPT_BINDX_ADD:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
optlen, SCTP_BINDX_ADD_ADDR);
break;
case SCTP_SOCKOPT_BINDX_REM:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
optlen, SCTP_BINDX_REM_ADDR);
break;
case SCTP_SOCKOPT_CONNECTX_OLD:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_connectx_old(sk,
(struct sockaddr __user *)optval,
optlen);
break;
case SCTP_SOCKOPT_CONNECTX:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_connectx(sk,
(struct sockaddr __user *)optval,
optlen);
break;
case SCTP_DISABLE_FRAGMENTS:
retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
break;
case SCTP_EVENTS:
retval = sctp_setsockopt_events(sk, optval, optlen);
break;
case SCTP_AUTOCLOSE:
retval = sctp_setsockopt_autoclose(sk, optval, optlen);
break;
case SCTP_PEER_ADDR_PARAMS:
retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
break;
case SCTP_DELAYED_SACK:
retval = sctp_setsockopt_delayed_ack(sk, optval, optlen);
break;
case SCTP_PARTIAL_DELIVERY_POINT:
retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
break;
case SCTP_INITMSG:
retval = sctp_setsockopt_initmsg(sk, optval, optlen);
break;
case SCTP_DEFAULT_SEND_PARAM:
retval = sctp_setsockopt_default_send_param(sk, optval,
optlen);
break;
case SCTP_PRIMARY_ADDR:
retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
break;
case SCTP_SET_PEER_PRIMARY_ADDR:
retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
break;
case SCTP_NODELAY:
retval = sctp_setsockopt_nodelay(sk, optval, optlen);
break;
case SCTP_RTOINFO:
retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
break;
case SCTP_ASSOCINFO:
retval = sctp_setsockopt_associnfo(sk, optval, optlen);
break;
case SCTP_I_WANT_MAPPED_V4_ADDR:
retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
break;
case SCTP_MAXSEG:
retval = sctp_setsockopt_maxseg(sk, optval, optlen);
break;
case SCTP_ADAPTATION_LAYER:
retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
break;
case SCTP_CONTEXT:
retval = sctp_setsockopt_context(sk, optval, optlen);
break;
case SCTP_FRAGMENT_INTERLEAVE:
retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
break;
case SCTP_MAX_BURST:
retval = sctp_setsockopt_maxburst(sk, optval, optlen);
break;
case SCTP_AUTH_CHUNK:
retval = sctp_setsockopt_auth_chunk(sk, optval, optlen);
break;
case SCTP_HMAC_IDENT:
retval = sctp_setsockopt_hmac_ident(sk, optval, optlen);
break;
case SCTP_AUTH_KEY:
retval = sctp_setsockopt_auth_key(sk, optval, optlen);
break;
case SCTP_AUTH_ACTIVE_KEY:
retval = sctp_setsockopt_active_key(sk, optval, optlen);
break;
case SCTP_AUTH_DELETE_KEY:
retval = sctp_setsockopt_del_key(sk, optval, optlen);
break;
case SCTP_AUTO_ASCONF:
retval = sctp_setsockopt_auto_asconf(sk, optval, optlen);
break;
case SCTP_PEER_ADDR_THLDS:
retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen);
break;
default:
retval = -ENOPROTOOPT;
break;
}
sctp_release_sock(sk);
out_nounlock:
return retval;
}
/* API 3.1.6 connect() - UDP Style Syntax
*
* An application may use the connect() call in the UDP model to initiate an
* association without sending data.
*
* The syntax is:
*
* ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
*
* sd: the socket descriptor to have a new association added to.
*
* nam: the address structure (either struct sockaddr_in or struct
* sockaddr_in6 defined in RFC2553 [7]).
*
* len: the size of the address.
*/
SCTP_STATIC int sctp_connect(struct sock *sk, struct sockaddr *addr,
int addr_len)
{
int err = 0;
struct sctp_af *af;
sctp_lock_sock(sk);
SCTP_DEBUG_PRINTK("%s - sk: %p, sockaddr: %p, addr_len: %d\n",
__func__, sk, addr, addr_len);
/* Validate addr_len before calling common connect/connectx routine. */
af = sctp_get_af_specific(addr->sa_family);
if (!af || addr_len < af->sockaddr_len) {
err = -EINVAL;
} else {
/* Pass correct addr len to common routine (so it knows there
* is only one address being passed.
*/
err = __sctp_connect(sk, addr, af->sockaddr_len, NULL);
}
sctp_release_sock(sk);
return err;
}
/* FIXME: Write comments. */
SCTP_STATIC int sctp_disconnect(struct sock *sk, int flags)
{
return -EOPNOTSUPP; /* STUB */
}
/* 4.1.4 accept() - TCP Style Syntax
*
* Applications use accept() call to remove an established SCTP
* association from the accept queue of the endpoint. A new socket
* descriptor will be returned from accept() to represent the newly
* formed association.
*/
SCTP_STATIC struct sock *sctp_accept(struct sock *sk, int flags, int *err)
{
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sock *newsk = NULL;
struct sctp_association *asoc;
long timeo;
int error = 0;
sctp_lock_sock(sk);
sp = sctp_sk(sk);
ep = sp->ep;
if (!sctp_style(sk, TCP)) {
error = -EOPNOTSUPP;
goto out;
}
if (!sctp_sstate(sk, LISTENING)) {
error = -EINVAL;
goto out;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
error = sctp_wait_for_accept(sk, timeo);
if (error)
goto out;
/* We treat the list of associations on the endpoint as the accept
* queue and pick the first association on the list.
*/
asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
newsk = sp->pf->create_accept_sk(sk, asoc);
if (!newsk) {
error = -ENOMEM;
goto out;
}
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
out:
sctp_release_sock(sk);
*err = error;
return newsk;
}
/* The SCTP ioctl handler. */
SCTP_STATIC int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
int rc = -ENOTCONN;
sctp_lock_sock(sk);
/*
* SEQPACKET-style sockets in LISTENING state are valid, for
* SCTP, so only discard TCP-style sockets in LISTENING state.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
goto out;
switch (cmd) {
case SIOCINQ: {
struct sk_buff *skb;
unsigned int amount = 0;
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL) {
/*
* We will only return the amount of this packet since
* that is all that will be read.
*/
amount = skb->len;
}
rc = put_user(amount, (int __user *)arg);
break;
}
default:
rc = -ENOIOCTLCMD;
break;
}
out:
sctp_release_sock(sk);
return rc;
}
/* This is the function which gets called during socket creation to
* initialized the SCTP-specific portion of the sock.
* The sock structure should already be zero-filled memory.
*/
SCTP_STATIC int sctp_init_sock(struct sock *sk)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
struct sctp_sock *sp;
SCTP_DEBUG_PRINTK("sctp_init_sock(sk: %p)\n", sk);
sp = sctp_sk(sk);
/* Initialize the SCTP per socket area. */
switch (sk->sk_type) {
case SOCK_SEQPACKET:
sp->type = SCTP_SOCKET_UDP;
break;
case SOCK_STREAM:
sp->type = SCTP_SOCKET_TCP;
break;
default:
return -ESOCKTNOSUPPORT;
}
/* Initialize default send parameters. These parameters can be
* modified with the SCTP_DEFAULT_SEND_PARAM socket option.
*/
sp->default_stream = 0;
sp->default_ppid = 0;
sp->default_flags = 0;
sp->default_context = 0;
sp->default_timetolive = 0;
sp->default_rcv_context = 0;
sp->max_burst = net->sctp.max_burst;
sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
/* Initialize default setup parameters. These parameters
* can be modified with the SCTP_INITMSG socket option or
* overridden by the SCTP_INIT CMSG.
*/
sp->initmsg.sinit_num_ostreams = sctp_max_outstreams;
sp->initmsg.sinit_max_instreams = sctp_max_instreams;
sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init;
sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
/* Initialize default RTO related parameters. These parameters can
* be modified for with the SCTP_RTOINFO socket option.
*/
sp->rtoinfo.srto_initial = net->sctp.rto_initial;
sp->rtoinfo.srto_max = net->sctp.rto_max;
sp->rtoinfo.srto_min = net->sctp.rto_min;
/* Initialize default association related parameters. These parameters
* can be modified with the SCTP_ASSOCINFO socket option.
*/
sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
sp->assocparams.sasoc_number_peer_destinations = 0;
sp->assocparams.sasoc_peer_rwnd = 0;
sp->assocparams.sasoc_local_rwnd = 0;
sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
/* Initialize default event subscriptions. By default, all the
* options are off.
*/
memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
/* Default Peer Address Parameters. These defaults can
* be modified via SCTP_PEER_ADDR_PARAMS
*/
sp->hbinterval = net->sctp.hb_interval;
sp->pathmaxrxt = net->sctp.max_retrans_path;
sp->pathmtu = 0; // allow default discovery
sp->sackdelay = net->sctp.sack_timeout;
sp->sackfreq = 2;
sp->param_flags = SPP_HB_ENABLE |
SPP_PMTUD_ENABLE |
SPP_SACKDELAY_ENABLE;
/* If enabled no SCTP message fragmentation will be performed.
* Configure through SCTP_DISABLE_FRAGMENTS socket option.
*/
sp->disable_fragments = 0;
/* Enable Nagle algorithm by default. */
sp->nodelay = 0;
/* Enable by default. */
sp->v4mapped = 1;
/* Auto-close idle associations after the configured
* number of seconds. A value of 0 disables this
* feature. Configure through the SCTP_AUTOCLOSE socket option,
* for UDP-style sockets only.
*/
sp->autoclose = 0;
/* User specified fragmentation limit. */
sp->user_frag = 0;
sp->adaptation_ind = 0;
sp->pf = sctp_get_pf_specific(sk->sk_family);
/* Control variables for partial data delivery. */
atomic_set(&sp->pd_mode, 0);
skb_queue_head_init(&sp->pd_lobby);
sp->frag_interleave = 0;
/* Create a per socket endpoint structure. Even if we
* change the data structure relationships, this may still
* be useful for storing pre-connect address information.
*/
ep = sctp_endpoint_new(sk, GFP_KERNEL);
if (!ep)
return -ENOMEM;
sp->ep = ep;
sp->hmac = NULL;
SCTP_DBG_OBJCNT_INC(sock);
local_bh_disable();
percpu_counter_inc(&sctp_sockets_allocated);
sock_prot_inuse_add(net, sk->sk_prot, 1);
if (net->sctp.default_auto_asconf) {
list_add_tail(&sp->auto_asconf_list,
&net->sctp.auto_asconf_splist);
sp->do_auto_asconf = 1;
} else
sp->do_auto_asconf = 0;
local_bh_enable();
return 0;
}
/* Cleanup any SCTP per socket resources. */
SCTP_STATIC void sctp_destroy_sock(struct sock *sk)
{
struct sctp_sock *sp;
SCTP_DEBUG_PRINTK("sctp_destroy_sock(sk: %p)\n", sk);
/* Release our hold on the endpoint. */
sp = sctp_sk(sk);
if (sp->do_auto_asconf) {
sp->do_auto_asconf = 0;
list_del(&sp->auto_asconf_list);
}
sctp_endpoint_free(sp->ep);
local_bh_disable();
percpu_counter_dec(&sctp_sockets_allocated);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
local_bh_enable();
}
/* API 4.1.7 shutdown() - TCP Style Syntax
* int shutdown(int socket, int how);
*
* sd - the socket descriptor of the association to be closed.
* how - Specifies the type of shutdown. The values are
* as follows:
* SHUT_RD
* Disables further receive operations. No SCTP
* protocol action is taken.
* SHUT_WR
* Disables further send operations, and initiates
* the SCTP shutdown sequence.
* SHUT_RDWR
* Disables further send and receive operations
* and initiates the SCTP shutdown sequence.
*/
SCTP_STATIC void sctp_shutdown(struct sock *sk, int how)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
struct sctp_association *asoc;
if (!sctp_style(sk, TCP))
return;
if (how & SEND_SHUTDOWN) {
ep = sctp_sk(sk)->ep;
if (!list_empty(&ep->asocs)) {
asoc = list_entry(ep->asocs.next,
struct sctp_association, asocs);
sctp_primitive_SHUTDOWN(net, asoc, NULL);
}
}
}
/* 7.2.1 Association Status (SCTP_STATUS)
* Applications can retrieve current status information about an
* association, including association state, peer receiver window size,
* number of unacked data chunks, and number of data chunks pending
* receipt. This information is read-only.
*/
static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_status status;
struct sctp_association *asoc = NULL;
struct sctp_transport *transport;
sctp_assoc_t associd;
int retval = 0;
if (len < sizeof(status)) {
retval = -EINVAL;
goto out;
}
len = sizeof(status);
if (copy_from_user(&status, optval, len)) {
retval = -EFAULT;
goto out;
}
associd = status.sstat_assoc_id;
asoc = sctp_id2assoc(sk, associd);
if (!asoc) {
retval = -EINVAL;
goto out;
}
transport = asoc->peer.primary_path;
status.sstat_assoc_id = sctp_assoc2id(asoc);
status.sstat_state = asoc->state;
status.sstat_rwnd = asoc->peer.rwnd;
status.sstat_unackdata = asoc->unack_data;
status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
status.sstat_instrms = asoc->c.sinit_max_instreams;
status.sstat_outstrms = asoc->c.sinit_num_ostreams;
status.sstat_fragmentation_point = asoc->frag_point;
status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
transport->af_specific->sockaddr_len);
/* Map ipv4 address into v4-mapped-on-v6 address. */
sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
(union sctp_addr *)&status.sstat_primary.spinfo_address);
status.sstat_primary.spinfo_state = transport->state;
status.sstat_primary.spinfo_cwnd = transport->cwnd;
status.sstat_primary.spinfo_srtt = transport->srtt;
status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
status.sstat_primary.spinfo_mtu = transport->pathmtu;
if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
status.sstat_primary.spinfo_state = SCTP_ACTIVE;
if (put_user(len, optlen)) {
retval = -EFAULT;
goto out;
}
SCTP_DEBUG_PRINTK("sctp_getsockopt_sctp_status(%d): %d %d %d\n",
len, status.sstat_state, status.sstat_rwnd,
status.sstat_assoc_id);
if (copy_to_user(optval, &status, len)) {
retval = -EFAULT;
goto out;
}
out:
return retval;
}
/* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
*
* Applications can retrieve information about a specific peer address
* of an association, including its reachability state, congestion
* window, and retransmission timer values. This information is
* read-only.
*/
static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_paddrinfo pinfo;
struct sctp_transport *transport;
int retval = 0;
if (len < sizeof(pinfo)) {
retval = -EINVAL;
goto out;
}
len = sizeof(pinfo);
if (copy_from_user(&pinfo, optval, len)) {
retval = -EFAULT;
goto out;
}
transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
pinfo.spinfo_assoc_id);
if (!transport)
return -EINVAL;
pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
pinfo.spinfo_state = transport->state;
pinfo.spinfo_cwnd = transport->cwnd;
pinfo.spinfo_srtt = transport->srtt;
pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
pinfo.spinfo_mtu = transport->pathmtu;
if (pinfo.spinfo_state == SCTP_UNKNOWN)
pinfo.spinfo_state = SCTP_ACTIVE;
if (put_user(len, optlen)) {
retval = -EFAULT;
goto out;
}
if (copy_to_user(optval, &pinfo, len)) {
retval = -EFAULT;
goto out;
}
out:
return retval;
}
/* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
*
* This option is a on/off flag. If enabled no SCTP message
* fragmentation will be performed. Instead if a message being sent
* exceeds the current PMTU size, the message will NOT be sent and
* instead a error will be indicated to the user.
*/
static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = (sctp_sk(sk)->disable_fragments == 1);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
*
* This socket option is used to specify various notifications and
* ancillary data the user wishes to receive.
*/
static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
int __user *optlen)
{
if (len <= 0)
return -EINVAL;
if (len > sizeof(struct sctp_event_subscribe))
len = sizeof(struct sctp_event_subscribe);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
return -EFAULT;
return 0;
}
/* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
*
* This socket option is applicable to the UDP-style socket only. When
* set it will cause associations that are idle for more than the
* specified number of seconds to automatically close. An association
* being idle is defined an association that has NOT sent or received
* user data. The special value of '0' indicates that no automatic
* close of any associations should be performed. The option expects an
* integer defining the number of seconds of idle time before an
* association is closed.
*/
static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
{
/* Applicable to UDP-style socket only */
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int)))
return -EFAULT;
return 0;
}
/* Helper routine to branch off an association to a new socket. */
int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
{
struct sctp_association *asoc = sctp_id2assoc(sk, id);
struct socket *sock;
struct sctp_af *af;
int err = 0;
if (!asoc)
return -EINVAL;
/* An association cannot be branched off from an already peeled-off
* socket, nor is this supported for tcp style sockets.
*/
if (!sctp_style(sk, UDP))
return -EINVAL;
/* Create a new socket. */
err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
if (err < 0)
return err;
sctp_copy_sock(sock->sk, sk, asoc);
/* Make peeled-off sockets more like 1-1 accepted sockets.
* Set the daddr and initialize id to something more random
*/
af = sctp_get_af_specific(asoc->peer.primary_addr.sa.sa_family);
af->to_sk_daddr(&asoc->peer.primary_addr, sk);
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
*sockp = sock;
return err;
}
EXPORT_SYMBOL(sctp_do_peeloff);
static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
{
sctp_peeloff_arg_t peeloff;
struct socket *newsock;
struct file *newfile;
int retval = 0;
if (len < sizeof(sctp_peeloff_arg_t))
return -EINVAL;
len = sizeof(sctp_peeloff_arg_t);
if (copy_from_user(&peeloff, optval, len))
return -EFAULT;
retval = sctp_do_peeloff(sk, peeloff.associd, &newsock);
if (retval < 0)
goto out;
/* Map the socket to an unused fd that can be returned to the user. */
retval = get_unused_fd();
if (retval < 0) {
sock_release(newsock);
goto out;
}
newfile = sock_alloc_file(newsock, 0, NULL);
if (unlikely(IS_ERR(newfile))) {
put_unused_fd(retval);
sock_release(newsock);
return PTR_ERR(newfile);
}
SCTP_DEBUG_PRINTK("%s: sk: %p newsk: %p sd: %d\n",
__func__, sk, newsock->sk, retval);
/* Return the fd mapped to the new socket. */
if (put_user(len, optlen)) {
fput(newfile);
put_unused_fd(retval);
return -EFAULT;
}
peeloff.sd = retval;
if (copy_to_user(optval, &peeloff, len)) {
fput(newfile);
put_unused_fd(retval);
return -EFAULT;
}
fd_install(retval, newfile);
out:
return retval;
}
/* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
*
* Applications can enable or disable heartbeats for any peer address of
* an association, modify an address's heartbeat interval, force a
* heartbeat to be sent immediately, and adjust the address's maximum
* number of retransmissions sent before an address is considered
* unreachable. The following structure is used to access and modify an
* address's parameters:
*
* struct sctp_paddrparams {
* sctp_assoc_t spp_assoc_id;
* struct sockaddr_storage spp_address;
* uint32_t spp_hbinterval;
* uint16_t spp_pathmaxrxt;
* uint32_t spp_pathmtu;
* uint32_t spp_sackdelay;
* uint32_t spp_flags;
* };
*
* spp_assoc_id - (one-to-many style socket) This is filled in the
* application, and identifies the association for
* this query.
* spp_address - This specifies which address is of interest.
* spp_hbinterval - This contains the value of the heartbeat interval,
* in milliseconds. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmaxrxt - This contains the maximum number of
* retransmissions before this address shall be
* considered unreachable. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmtu - When Path MTU discovery is disabled the value
* specified here will be the "fixed" path mtu.
* Note that if the spp_address field is empty
* then all associations on this address will
* have this fixed path mtu set upon them.
*
* spp_sackdelay - When delayed sack is enabled, this value specifies
* the number of milliseconds that sacks will be delayed
* for. This value will apply to all addresses of an
* association if the spp_address field is empty. Note
* also, that if delayed sack is enabled and this
* value is set to 0, no change is made to the last
* recorded delayed sack timer value.
*
* spp_flags - These flags are used to control various features
* on an association. The flag field may contain
* zero or more of the following options.
*
* SPP_HB_ENABLE - Enable heartbeats on the
* specified address. Note that if the address
* field is empty all addresses for the association
* have heartbeats enabled upon them.
*
* SPP_HB_DISABLE - Disable heartbeats on the
* speicifed address. Note that if the address
* field is empty all addresses for the association
* will have their heartbeats disabled. Note also
* that SPP_HB_ENABLE and SPP_HB_DISABLE are
* mutually exclusive, only one of these two should
* be specified. Enabling both fields will have
* undetermined results.
*
* SPP_HB_DEMAND - Request a user initiated heartbeat
* to be made immediately.
*
* SPP_PMTUD_ENABLE - This field will enable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected.
*
* SPP_PMTUD_DISABLE - This field will disable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected. Not also that
* SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
* exclusive. Enabling both will have undetermined
* results.
*
* SPP_SACKDELAY_ENABLE - Setting this flag turns
* on delayed sack. The time specified in spp_sackdelay
* is used to specify the sack delay for this address. Note
* that if spp_address is empty then all addresses will
* enable delayed sack and take on the sack delay
* value specified in spp_sackdelay.
* SPP_SACKDELAY_DISABLE - Setting this flag turns
* off delayed sack. If the spp_address field is blank then
* delayed sack is disabled for the entire association. Note
* also that this field is mutually exclusive to
* SPP_SACKDELAY_ENABLE, setting both will have undefined
* results.
*/
static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_paddrparams params;
struct sctp_transport *trans = NULL;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
if (len < sizeof(struct sctp_paddrparams))
return -EINVAL;
len = sizeof(struct sctp_paddrparams);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, ( union sctp_addr *)¶ms.spp_address)) {
trans = sctp_addr_id2transport(sk, ¶ms.spp_address,
params.spp_assoc_id);
if (!trans) {
SCTP_DEBUG_PRINTK("Failed no transport\n");
return -EINVAL;
}
}
/* Get association, if assoc_id != 0 and the socket is a one
* to many style socket, and an association was not found, then
* the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.spp_assoc_id);
if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
SCTP_DEBUG_PRINTK("Failed no association\n");
return -EINVAL;
}
if (trans) {
/* Fetch transport values. */
params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
params.spp_pathmtu = trans->pathmtu;
params.spp_pathmaxrxt = trans->pathmaxrxt;
params.spp_sackdelay = jiffies_to_msecs(trans->sackdelay);
/*draft-11 doesn't say what to return in spp_flags*/
params.spp_flags = trans->param_flags;
} else if (asoc) {
/* Fetch association values. */
params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
params.spp_pathmtu = asoc->pathmtu;
params.spp_pathmaxrxt = asoc->pathmaxrxt;
params.spp_sackdelay = jiffies_to_msecs(asoc->sackdelay);
/*draft-11 doesn't say what to return in spp_flags*/
params.spp_flags = asoc->param_flags;
} else {
/* Fetch socket values. */
params.spp_hbinterval = sp->hbinterval;
params.spp_pathmtu = sp->pathmtu;
params.spp_sackdelay = sp->sackdelay;
params.spp_pathmaxrxt = sp->pathmaxrxt;
/*draft-11 doesn't say what to return in spp_flags*/
params.spp_flags = sp->param_flags;
}
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/*
* 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK)
*
* This option will effect the way delayed acks are performed. This
* option allows you to get or set the delayed ack time, in
* milliseconds. It also allows changing the delayed ack frequency.
* Changing the frequency to 1 disables the delayed sack algorithm. If
* the assoc_id is 0, then this sets or gets the endpoints default
* values. If the assoc_id field is non-zero, then the set or get
* effects the specified association for the one to many model (the
* assoc_id field is ignored by the one to one model). Note that if
* sack_delay or sack_freq are 0 when setting this option, then the
* current values will remain unchanged.
*
* struct sctp_sack_info {
* sctp_assoc_t sack_assoc_id;
* uint32_t sack_delay;
* uint32_t sack_freq;
* };
*
* sack_assoc_id - This parameter, indicates which association the user
* is performing an action upon. Note that if this field's value is
* zero then the endpoints default value is changed (effecting future
* associations only).
*
* sack_delay - This parameter contains the number of milliseconds that
* the user is requesting the delayed ACK timer be set to. Note that
* this value is defined in the standard to be between 200 and 500
* milliseconds.
*
* sack_freq - This parameter contains the number of packets that must
* be received before a sack is sent without waiting for the delay
* timer to expire. The default value for this is 2, setting this
* value to 1 will disable the delayed sack algorithm.
*/
static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_sack_info params;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
if (len >= sizeof(struct sctp_sack_info)) {
len = sizeof(struct sctp_sack_info);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else if (len == sizeof(struct sctp_assoc_value)) {
pr_warn("Use of struct sctp_assoc_value in delayed_ack socket option deprecated\n");
pr_warn("Use struct sctp_sack_info instead\n");
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else
return - EINVAL;
/* Get association, if sack_assoc_id != 0 and the socket is a one
* to many style socket, and an association was not found, then
* the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.sack_assoc_id);
if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
/* Fetch association values. */
if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
params.sack_delay = jiffies_to_msecs(
asoc->sackdelay);
params.sack_freq = asoc->sackfreq;
} else {
params.sack_delay = 0;
params.sack_freq = 1;
}
} else {
/* Fetch socket values. */
if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
params.sack_delay = sp->sackdelay;
params.sack_freq = sp->sackfreq;
} else {
params.sack_delay = 0;
params.sack_freq = 1;
}
}
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/* 7.1.3 Initialization Parameters (SCTP_INITMSG)
*
* Applications can specify protocol parameters for the default association
* initialization. The option name argument to setsockopt() and getsockopt()
* is SCTP_INITMSG.
*
* Setting initialization parameters is effective only on an unconnected
* socket (for UDP-style sockets only future associations are effected
* by the change). With TCP-style sockets, this option is inherited by
* sockets derived from a listener socket.
*/
static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
{
if (len < sizeof(struct sctp_initmsg))
return -EINVAL;
len = sizeof(struct sctp_initmsg);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_association *asoc;
int cnt = 0;
struct sctp_getaddrs getaddrs;
struct sctp_transport *from;
void __user *to;
union sctp_addr temp;
struct sctp_sock *sp = sctp_sk(sk);
int addrlen;
size_t space_left;
int bytes_copied;
if (len < sizeof(struct sctp_getaddrs))
return -EINVAL;
if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
return -EFAULT;
/* For UDP-style sockets, id specifies the association to query. */
asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
if (!asoc)
return -EINVAL;
to = optval + offsetof(struct sctp_getaddrs,addrs);
space_left = len - offsetof(struct sctp_getaddrs,addrs);
list_for_each_entry(from, &asoc->peer.transport_addr_list,
transports) {
memcpy(&temp, &from->ipaddr, sizeof(temp));
sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
if (space_left < addrlen)
return -ENOMEM;
if (copy_to_user(to, &temp, addrlen))
return -EFAULT;
to += addrlen;
cnt++;
space_left -= addrlen;
}
if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
return -EFAULT;
bytes_copied = ((char __user *)to) - optval;
if (put_user(bytes_copied, optlen))
return -EFAULT;
return 0;
}
static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
size_t space_left, int *bytes_copied)
{
struct sctp_sockaddr_entry *addr;
union sctp_addr temp;
int cnt = 0;
int addrlen;
struct net *net = sock_net(sk);
rcu_read_lock();
list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
if (!addr->valid)
continue;
if ((PF_INET == sk->sk_family) &&
(AF_INET6 == addr->a.sa.sa_family))
continue;
if ((PF_INET6 == sk->sk_family) &&
inet_v6_ipv6only(sk) &&
(AF_INET == addr->a.sa.sa_family))
continue;
memcpy(&temp, &addr->a, sizeof(temp));
if (!temp.v4.sin_port)
temp.v4.sin_port = htons(port);
sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
&temp);
addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
if (space_left < addrlen) {
cnt = -ENOMEM;
break;
}
memcpy(to, &temp, addrlen);
to += addrlen;
cnt ++;
space_left -= addrlen;
*bytes_copied += addrlen;
}
rcu_read_unlock();
return cnt;
}
static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_bind_addr *bp;
struct sctp_association *asoc;
int cnt = 0;
struct sctp_getaddrs getaddrs;
struct sctp_sockaddr_entry *addr;
void __user *to;
union sctp_addr temp;
struct sctp_sock *sp = sctp_sk(sk);
int addrlen;
int err = 0;
size_t space_left;
int bytes_copied = 0;
void *addrs;
void *buf;
if (len < sizeof(struct sctp_getaddrs))
return -EINVAL;
if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
return -EFAULT;
/*
* For UDP-style sockets, id specifies the association to query.
* If the id field is set to the value '0' then the locally bound
* addresses are returned without regard to any particular
* association.
*/
if (0 == getaddrs.assoc_id) {
bp = &sctp_sk(sk)->ep->base.bind_addr;
} else {
asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
if (!asoc)
return -EINVAL;
bp = &asoc->base.bind_addr;
}
to = optval + offsetof(struct sctp_getaddrs,addrs);
space_left = len - offsetof(struct sctp_getaddrs,addrs);
addrs = kmalloc(space_left, GFP_KERNEL);
if (!addrs)
return -ENOMEM;
/* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
* addresses from the global local address list.
*/
if (sctp_list_single_entry(&bp->address_list)) {
addr = list_entry(bp->address_list.next,
struct sctp_sockaddr_entry, list);
if (sctp_is_any(sk, &addr->a)) {
cnt = sctp_copy_laddrs(sk, bp->port, addrs,
space_left, &bytes_copied);
if (cnt < 0) {
err = cnt;
goto out;
}
goto copy_getaddrs;
}
}
buf = addrs;
/* Protection on the bound address list is not needed since
* in the socket option context we hold a socket lock and
* thus the bound address list can't change.
*/
list_for_each_entry(addr, &bp->address_list, list) {
memcpy(&temp, &addr->a, sizeof(temp));
sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
if (space_left < addrlen) {
err = -ENOMEM; /*fixme: right error?*/
goto out;
}
memcpy(buf, &temp, addrlen);
buf += addrlen;
bytes_copied += addrlen;
cnt ++;
space_left -= addrlen;
}
copy_getaddrs:
if (copy_to_user(to, addrs, bytes_copied)) {
err = -EFAULT;
goto out;
}
if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
err = -EFAULT;
goto out;
}
if (put_user(bytes_copied, optlen))
err = -EFAULT;
out:
kfree(addrs);
return err;
}
/* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
*
* Requests that the local SCTP stack use the enclosed peer address as
* the association primary. The enclosed address must be one of the
* association peer's addresses.
*/
static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_prim prim;
struct sctp_association *asoc;
struct sctp_sock *sp = sctp_sk(sk);
if (len < sizeof(struct sctp_prim))
return -EINVAL;
len = sizeof(struct sctp_prim);
if (copy_from_user(&prim, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
if (!asoc)
return -EINVAL;
if (!asoc->peer.primary_path)
return -ENOTCONN;
memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
asoc->peer.primary_path->af_specific->sockaddr_len);
sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp,
(union sctp_addr *)&prim.ssp_addr);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &prim, len))
return -EFAULT;
return 0;
}
/*
* 7.1.11 Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
*
* Requests that the local endpoint set the specified Adaptation Layer
* Indication parameter for all future INIT and INIT-ACK exchanges.
*/
static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_setadaptation adaptation;
if (len < sizeof(struct sctp_setadaptation))
return -EINVAL;
len = sizeof(struct sctp_setadaptation);
adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &adaptation, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
*
* Applications that wish to use the sendto() system call may wish to
* specify a default set of parameters that would normally be supplied
* through the inclusion of ancillary data. This socket option allows
* such an application to set the default sctp_sndrcvinfo structure.
* The application that wishes to use this socket option simply passes
* in to this call the sctp_sndrcvinfo structure defined in Section
* 5.2.2) The input parameters accepted by this call include
* sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
* sinfo_timetolive. The user must provide the sinfo_assoc_id field in
* to this call if the caller is using the UDP model.
*
* For getsockopt, it get the default sctp_sndrcvinfo structure.
*/
static int sctp_getsockopt_default_send_param(struct sock *sk,
int len, char __user *optval,
int __user *optlen)
{
struct sctp_sndrcvinfo info;
struct sctp_association *asoc;
struct sctp_sock *sp = sctp_sk(sk);
if (len < sizeof(struct sctp_sndrcvinfo))
return -EINVAL;
len = sizeof(struct sctp_sndrcvinfo);
if (copy_from_user(&info, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
info.sinfo_stream = asoc->default_stream;
info.sinfo_flags = asoc->default_flags;
info.sinfo_ppid = asoc->default_ppid;
info.sinfo_context = asoc->default_context;
info.sinfo_timetolive = asoc->default_timetolive;
} else {
info.sinfo_stream = sp->default_stream;
info.sinfo_flags = sp->default_flags;
info.sinfo_ppid = sp->default_ppid;
info.sinfo_context = sp->default_context;
info.sinfo_timetolive = sp->default_timetolive;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.5 SCTP_NODELAY
*
* Turn on/off any Nagle-like algorithm. This means that packets are
* generally sent as soon as possible and no unnecessary delays are
* introduced, at the cost of more packets in the network. Expects an
* integer boolean flag.
*/
static int sctp_getsockopt_nodelay(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = (sctp_sk(sk)->nodelay == 1);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.1 SCTP_RTOINFO
*
* The protocol parameters used to initialize and bound retransmission
* timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
* and modify these parameters.
* All parameters are time values, in milliseconds. A value of 0, when
* modifying the parameters, indicates that the current value should not
* be changed.
*
*/
static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen) {
struct sctp_rtoinfo rtoinfo;
struct sctp_association *asoc;
if (len < sizeof (struct sctp_rtoinfo))
return -EINVAL;
len = sizeof(struct sctp_rtoinfo);
if (copy_from_user(&rtoinfo, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
/* Values corresponding to the specific association. */
if (asoc) {
rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
} else {
/* Values corresponding to the endpoint. */
struct sctp_sock *sp = sctp_sk(sk);
rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
rtoinfo.srto_max = sp->rtoinfo.srto_max;
rtoinfo.srto_min = sp->rtoinfo.srto_min;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &rtoinfo, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.2 SCTP_ASSOCINFO
*
* This option is used to tune the maximum retransmission attempts
* of the association.
* Returns an error if the new association retransmission value is
* greater than the sum of the retransmission value of the peer.
* See [SCTP] for more information.
*
*/
static int sctp_getsockopt_associnfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assocparams assocparams;
struct sctp_association *asoc;
struct list_head *pos;
int cnt = 0;
if (len < sizeof (struct sctp_assocparams))
return -EINVAL;
len = sizeof(struct sctp_assocparams);
if (copy_from_user(&assocparams, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
/* Values correspoinding to the specific association */
if (asoc) {
assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
assocparams.sasoc_local_rwnd = asoc->a_rwnd;
assocparams.sasoc_cookie_life = (asoc->cookie_life.tv_sec
* 1000) +
(asoc->cookie_life.tv_usec
/ 1000);
list_for_each(pos, &asoc->peer.transport_addr_list) {
cnt ++;
}
assocparams.sasoc_number_peer_destinations = cnt;
} else {
/* Values corresponding to the endpoint */
struct sctp_sock *sp = sctp_sk(sk);
assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
assocparams.sasoc_cookie_life =
sp->assocparams.sasoc_cookie_life;
assocparams.sasoc_number_peer_destinations =
sp->assocparams.
sasoc_number_peer_destinations;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &assocparams, len))
return -EFAULT;
return 0;
}
/*
* 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
*
* This socket option is a boolean flag which turns on or off mapped V4
* addresses. If this option is turned on and the socket is type
* PF_INET6, then IPv4 addresses will be mapped to V6 representation.
* If this option is turned off, then no mapping will be done of V4
* addresses and a user will receive both PF_INET6 and PF_INET type
* addresses on the socket.
*/
static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
struct sctp_sock *sp = sctp_sk(sk);
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = sp->v4mapped;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 7.1.29. Set or Get the default context (SCTP_CONTEXT)
* (chapter and verse is quoted at sctp_setsockopt_context())
*/
static int sctp_getsockopt_context(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_sock *sp;
struct sctp_association *asoc;
if (len < sizeof(struct sctp_assoc_value))
return -EINVAL;
len = sizeof(struct sctp_assoc_value);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
sp = sctp_sk(sk);
if (params.assoc_id != 0) {
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc)
return -EINVAL;
params.assoc_value = asoc->default_rcv_context;
} else {
params.assoc_value = sp->default_rcv_context;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
return 0;
}
/*
* 8.1.16. Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
* This option will get or set the maximum size to put in any outgoing
* SCTP DATA chunk. If a message is larger than this size it will be
* fragmented by SCTP into the specified size. Note that the underlying
* SCTP implementation may fragment into smaller sized chunks when the
* PMTU of the underlying association is smaller than the value set by
* the user. The default value for this option is '0' which indicates
* the user is NOT limiting fragmentation and only the PMTU will effect
* SCTP's choice of DATA chunk size. Note also that values set larger
* than the maximum size of an IP datagram will effectively let SCTP
* control fragmentation (i.e. the same as setting this option to 0).
*
* The following structure is used to access and modify this parameter:
*
* struct sctp_assoc_value {
* sctp_assoc_t assoc_id;
* uint32_t assoc_value;
* };
*
* assoc_id: This parameter is ignored for one-to-one style sockets.
* For one-to-many style sockets this parameter indicates which
* association the user is performing an action upon. Note that if
* this field's value is zero then the endpoints default value is
* changed (effecting future associations only).
* assoc_value: This parameter specifies the maximum size in bytes.
*/
static int sctp_getsockopt_maxseg(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
if (len == sizeof(int)) {
pr_warn("Use of int in maxseg socket option deprecated\n");
pr_warn("Use struct sctp_assoc_value instead\n");
params.assoc_id = 0;
} else if (len >= sizeof(struct sctp_assoc_value)) {
len = sizeof(struct sctp_assoc_value);
if (copy_from_user(¶ms, optval, sizeof(params)))
return -EFAULT;
} else
return -EINVAL;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
params.assoc_value = asoc->frag_point;
else
params.assoc_value = sctp_sk(sk)->user_frag;
if (put_user(len, optlen))
return -EFAULT;
if (len == sizeof(int)) {
if (copy_to_user(optval, ¶ms.assoc_value, len))
return -EFAULT;
} else {
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
}
return 0;
}
/*
* 7.1.24. Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
* (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
*/
static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = sctp_sk(sk)->frag_interleave;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 7.1.25. Set or Get the sctp partial delivery point
* (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
*/
static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
u32 val;
if (len < sizeof(u32))
return -EINVAL;
len = sizeof(u32);
val = sctp_sk(sk)->pd_point;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 7.1.28. Set or Get the maximum burst (SCTP_MAX_BURST)
* (chapter and verse is quoted at sctp_setsockopt_maxburst())
*/
static int sctp_getsockopt_maxburst(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_sock *sp;
struct sctp_association *asoc;
if (len == sizeof(int)) {
pr_warn("Use of int in max_burst socket option deprecated\n");
pr_warn("Use struct sctp_assoc_value instead\n");
params.assoc_id = 0;
} else if (len >= sizeof(struct sctp_assoc_value)) {
len = sizeof(struct sctp_assoc_value);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else
return -EINVAL;
sp = sctp_sk(sk);
if (params.assoc_id != 0) {
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc)
return -EINVAL;
params.assoc_value = asoc->max_burst;
} else
params.assoc_value = sp->max_burst;
if (len == sizeof(int)) {
if (copy_to_user(optval, ¶ms.assoc_value, len))
return -EFAULT;
} else {
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
}
return 0;
}
static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct net *net = sock_net(sk);
struct sctp_hmacalgo __user *p = (void __user *)optval;
struct sctp_hmac_algo_param *hmacs;
__u16 data_len = 0;
u32 num_idents;
if (!net->sctp.auth_enable)
return -EACCES;
hmacs = sctp_sk(sk)->ep->auth_hmacs_list;
data_len = ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t);
if (len < sizeof(struct sctp_hmacalgo) + data_len)
return -EINVAL;
len = sizeof(struct sctp_hmacalgo) + data_len;
num_idents = data_len / sizeof(u16);
if (put_user(len, optlen))
return -EFAULT;
if (put_user(num_idents, &p->shmac_num_idents))
return -EFAULT;
if (copy_to_user(p->shmac_idents, hmacs->hmac_ids, data_len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_active_key(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct net *net = sock_net(sk);
struct sctp_authkeyid val;
struct sctp_association *asoc;
if (!net->sctp.auth_enable)
return -EACCES;
if (len < sizeof(struct sctp_authkeyid))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid)))
return -EFAULT;
asoc = sctp_id2assoc(sk, val.scact_assoc_id);
if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
val.scact_keynumber = asoc->active_key_id;
else
val.scact_keynumber = sctp_sk(sk)->ep->active_key_id;
len = sizeof(struct sctp_authkeyid);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct net *net = sock_net(sk);
struct sctp_authchunks __user *p = (void __user *)optval;
struct sctp_authchunks val;
struct sctp_association *asoc;
struct sctp_chunks_param *ch;
u32 num_chunks = 0;
char __user *to;
if (!net->sctp.auth_enable)
return -EACCES;
if (len < sizeof(struct sctp_authchunks))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
return -EFAULT;
to = p->gauth_chunks;
asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
if (!asoc)
return -EINVAL;
ch = asoc->peer.peer_chunks;
if (!ch)
goto num;
/* See if the user provided enough room for all the data */
num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
if (len < num_chunks)
return -EINVAL;
if (copy_to_user(to, ch->chunks, num_chunks))
return -EFAULT;
num:
len = sizeof(struct sctp_authchunks) + num_chunks;
if (put_user(len, optlen)) return -EFAULT;
if (put_user(num_chunks, &p->gauth_number_of_chunks))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct net *net = sock_net(sk);
struct sctp_authchunks __user *p = (void __user *)optval;
struct sctp_authchunks val;
struct sctp_association *asoc;
struct sctp_chunks_param *ch;
u32 num_chunks = 0;
char __user *to;
if (!net->sctp.auth_enable)
return -EACCES;
if (len < sizeof(struct sctp_authchunks))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
return -EFAULT;
to = p->gauth_chunks;
asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
ch = (struct sctp_chunks_param*)asoc->c.auth_chunks;
else
ch = sctp_sk(sk)->ep->auth_chunk_list;
if (!ch)
goto num;
num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
if (len < sizeof(struct sctp_authchunks) + num_chunks)
return -EINVAL;
if (copy_to_user(to, ch->chunks, num_chunks))
return -EFAULT;
num:
len = sizeof(struct sctp_authchunks) + num_chunks;
if (put_user(len, optlen))
return -EFAULT;
if (put_user(num_chunks, &p->gauth_number_of_chunks))
return -EFAULT;
return 0;
}
/*
* 8.2.5. Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
* This option gets the current number of associations that are attached
* to a one-to-many style socket. The option value is an uint32_t.
*/
static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
u32 val = 0;
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(u32))
return -EINVAL;
len = sizeof(u32);
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
val++;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 8.1.23 SCTP_AUTO_ASCONF
* See the corresponding setsockopt entry as description
*/
static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val = 0;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
val = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 8.2.6. Get the Current Identifiers of Associations
* (SCTP_GET_ASSOC_ID_LIST)
*
* This option gets the current list of SCTP association identifiers of
* the SCTP associations handled by a one-to-many style socket.
*/
static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
struct sctp_assoc_ids *ids;
u32 num = 0;
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(struct sctp_assoc_ids))
return -EINVAL;
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
num++;
}
if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
return -EINVAL;
len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
ids = kmalloc(len, GFP_KERNEL);
if (unlikely(!ids))
return -ENOMEM;
ids->gaids_number_of_ids = num;
num = 0;
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
ids->gaids_assoc_id[num++] = asoc->assoc_id;
}
if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
kfree(ids);
return -EFAULT;
}
kfree(ids);
return 0;
}
/*
* SCTP_PEER_ADDR_THLDS
*
* This option allows us to fetch the partially failed threshold for one or all
* transports in an association. See Section 6.1 of:
* http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
*/
static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
char __user *optval,
int len,
int __user *optlen)
{
struct sctp_paddrthlds val;
struct sctp_transport *trans;
struct sctp_association *asoc;
if (len < sizeof(struct sctp_paddrthlds))
return -EINVAL;
len = sizeof(struct sctp_paddrthlds);
if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len))
return -EFAULT;
if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
asoc = sctp_id2assoc(sk, val.spt_assoc_id);
if (!asoc)
return -ENOENT;
val.spt_pathpfthld = asoc->pf_retrans;
val.spt_pathmaxrxt = asoc->pathmaxrxt;
} else {
trans = sctp_addr_id2transport(sk, &val.spt_address,
val.spt_assoc_id);
if (!trans)
return -ENOENT;
val.spt_pathmaxrxt = trans->pathmaxrxt;
val.spt_pathpfthld = trans->pf_retrans;
}
if (put_user(len, optlen) || copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* SCTP_GET_ASSOC_STATS
*
* This option retrieves local per endpoint statistics. It is modeled
* after OpenSolaris' implementation
*/
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_stats sas;
struct sctp_association *asoc = NULL;
/* User must provide at least the assoc id */
if (len < sizeof(sctp_assoc_t))
return -EINVAL;
if (copy_from_user(&sas, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
if (!asoc)
return -EINVAL;
sas.sas_rtxchunks = asoc->stats.rtxchunks;
sas.sas_gapcnt = asoc->stats.gapcnt;
sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
sas.sas_osacks = asoc->stats.osacks;
sas.sas_isacks = asoc->stats.isacks;
sas.sas_octrlchunks = asoc->stats.octrlchunks;
sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
sas.sas_oodchunks = asoc->stats.oodchunks;
sas.sas_iodchunks = asoc->stats.iodchunks;
sas.sas_ouodchunks = asoc->stats.ouodchunks;
sas.sas_iuodchunks = asoc->stats.iuodchunks;
sas.sas_idupchunks = asoc->stats.idupchunks;
sas.sas_opackets = asoc->stats.opackets;
sas.sas_ipackets = asoc->stats.ipackets;
/* New high max rto observed, will return 0 if not a single
* RTO update took place. obs_rto_ipaddr will be bogus
* in such a case
*/
sas.sas_maxrto = asoc->stats.max_obs_rto;
memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
sizeof(struct sockaddr_storage));
/* Mark beginning of a new observation period */
asoc->stats.max_obs_rto = asoc->rto_min;
/* Allow the struct to grow and fill in as much as possible */
len = min_t(size_t, len, sizeof(sas));
if (put_user(len, optlen))
return -EFAULT;
SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n",
len, sas.sas_assoc_id);
if (copy_to_user(optval, &sas, len))
return -EFAULT;
return 0;
}
SCTP_STATIC int sctp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int retval = 0;
int len;
SCTP_DEBUG_PRINTK("sctp_getsockopt(sk: %p... optname: %d)\n",
sk, optname);
/* I can hardly begin to describe how wrong this is. This is
* so broken as to be worse than useless. The API draft
* REALLY is NOT helpful here... I am not convinced that the
* semantics of getsockopt() with a level OTHER THAN SOL_SCTP
* are at all well-founded.
*/
if (level != SOL_SCTP) {
struct sctp_af *af = sctp_sk(sk)->pf->af;
retval = af->getsockopt(sk, level, optname, optval, optlen);
return retval;
}
if (get_user(len, optlen))
return -EFAULT;
sctp_lock_sock(sk);
switch (optname) {
case SCTP_STATUS:
retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
break;
case SCTP_DISABLE_FRAGMENTS:
retval = sctp_getsockopt_disable_fragments(sk, len, optval,
optlen);
break;
case SCTP_EVENTS:
retval = sctp_getsockopt_events(sk, len, optval, optlen);
break;
case SCTP_AUTOCLOSE:
retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
break;
case SCTP_SOCKOPT_PEELOFF:
retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
break;
case SCTP_PEER_ADDR_PARAMS:
retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
optlen);
break;
case SCTP_DELAYED_SACK:
retval = sctp_getsockopt_delayed_ack(sk, len, optval,
optlen);
break;
case SCTP_INITMSG:
retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
break;
case SCTP_GET_PEER_ADDRS:
retval = sctp_getsockopt_peer_addrs(sk, len, optval,
optlen);
break;
case SCTP_GET_LOCAL_ADDRS:
retval = sctp_getsockopt_local_addrs(sk, len, optval,
optlen);
break;
case SCTP_SOCKOPT_CONNECTX3:
retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
break;
case SCTP_DEFAULT_SEND_PARAM:
retval = sctp_getsockopt_default_send_param(sk, len,
optval, optlen);
break;
case SCTP_PRIMARY_ADDR:
retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
break;
case SCTP_NODELAY:
retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
break;
case SCTP_RTOINFO:
retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
break;
case SCTP_ASSOCINFO:
retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
break;
case SCTP_I_WANT_MAPPED_V4_ADDR:
retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
break;
case SCTP_MAXSEG:
retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
break;
case SCTP_GET_PEER_ADDR_INFO:
retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
optlen);
break;
case SCTP_ADAPTATION_LAYER:
retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
optlen);
break;
case SCTP_CONTEXT:
retval = sctp_getsockopt_context(sk, len, optval, optlen);
break;
case SCTP_FRAGMENT_INTERLEAVE:
retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
optlen);
break;
case SCTP_PARTIAL_DELIVERY_POINT:
retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
optlen);
break;
case SCTP_MAX_BURST:
retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
break;
case SCTP_AUTH_KEY:
case SCTP_AUTH_CHUNK:
case SCTP_AUTH_DELETE_KEY:
retval = -EOPNOTSUPP;
break;
case SCTP_HMAC_IDENT:
retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
break;
case SCTP_AUTH_ACTIVE_KEY:
retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
break;
case SCTP_PEER_AUTH_CHUNKS:
retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
optlen);
break;
case SCTP_LOCAL_AUTH_CHUNKS:
retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
optlen);
break;
case SCTP_GET_ASSOC_NUMBER:
retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
break;
case SCTP_GET_ASSOC_ID_LIST:
retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
break;
case SCTP_AUTO_ASCONF:
retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
break;
case SCTP_PEER_ADDR_THLDS:
retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen);
break;
case SCTP_GET_ASSOC_STATS:
retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
break;
default:
retval = -ENOPROTOOPT;
break;
}
sctp_release_sock(sk);
return retval;
}
static void sctp_hash(struct sock *sk)
{
/* STUB */
}
static void sctp_unhash(struct sock *sk)
{
/* STUB */
}
/* Check if port is acceptable. Possibly find first available port.
*
* The port hash table (contained in the 'global' SCTP protocol storage
* returned by struct sctp_protocol *sctp_get_protocol()). The hash
* table is an array of 4096 lists (sctp_bind_hashbucket). Each
* list (the list number is the port number hashed out, so as you
* would expect from a hash function, all the ports in a given list have
* such a number that hashes out to the same list number; you were
* expecting that, right?); so each list has a set of ports, with a
* link to the socket (struct sock) that uses it, the port number and
* a fastreuse flag (FIXME: NPI ipg).
*/
static struct sctp_bind_bucket *sctp_bucket_create(
struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
{
struct sctp_bind_hashbucket *head; /* hash list */
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct hlist_node *node;
unsigned short snum;
int ret;
snum = ntohs(addr->v4.sin_port);
SCTP_DEBUG_PRINTK("sctp_get_port() begins, snum=%d\n", snum);
sctp_local_bh_disable();
if (snum == 0) {
/* Search for an available port. */
int low, high, remaining, index;
unsigned int rover;
inet_get_local_port_range(&low, &high);
remaining = (high - low) + 1;
rover = net_random() % remaining + low;
do {
rover++;
if ((rover < low) || (rover > high))
rover = low;
if (inet_is_reserved_local_port(rover))
continue;
index = sctp_phashfn(sock_net(sk), rover);
head = &sctp_port_hashtable[index];
sctp_spin_lock(&head->lock);
sctp_for_each_hentry(pp, node, &head->chain)
if ((pp->port == rover) &&
net_eq(sock_net(sk), pp->net))
goto next;
break;
next:
sctp_spin_unlock(&head->lock);
} while (--remaining > 0);
/* Exhausted local port range during search? */
ret = 1;
if (remaining <= 0)
goto fail;
/* OK, here is the one we will use. HEAD (the port
* hash table list entry) is non-NULL and we hold it's
* mutex.
*/
snum = rover;
} else {
/* We are given an specific port number; we verify
* that it is not being used. If it is used, we will
* exahust the search in the hash list corresponding
* to the port number (snum) - we detect that with the
* port iterator, pp being NULL.
*/
head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)];
sctp_spin_lock(&head->lock);
sctp_for_each_hentry(pp, node, &head->chain) {
if ((pp->port == snum) && net_eq(pp->net, sock_net(sk)))
goto pp_found;
}
}
pp = NULL;
goto pp_not_found;
pp_found:
if (!hlist_empty(&pp->owner)) {
/* We had a port hash table hit - there is an
* available port (pp != NULL) and it is being
* used by other socket (pp->owner not empty); that other
* socket is going to be sk2.
*/
int reuse = sk->sk_reuse;
struct sock *sk2;
SCTP_DEBUG_PRINTK("sctp_get_port() found a possible match\n");
if (pp->fastreuse && sk->sk_reuse &&
sk->sk_state != SCTP_SS_LISTENING)
goto success;
/* Run through the list of sockets bound to the port
* (pp->port) [via the pointers bind_next and
* bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
* we get the endpoint they describe and run through
* the endpoint's list of IP (v4 or v6) addresses,
* comparing each of the addresses with the address of
* the socket sk. If we find a match, then that means
* that this port/socket (sk) combination are already
* in an endpoint.
*/
sk_for_each_bound(sk2, node, &pp->owner) {
struct sctp_endpoint *ep2;
ep2 = sctp_sk(sk2)->ep;
if (sk == sk2 ||
(reuse && sk2->sk_reuse &&
sk2->sk_state != SCTP_SS_LISTENING))
continue;
if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr,
sctp_sk(sk2), sctp_sk(sk))) {
ret = (long)sk2;
goto fail_unlock;
}
}
SCTP_DEBUG_PRINTK("sctp_get_port(): Found a match\n");
}
pp_not_found:
/* If there was a hash table miss, create a new port. */
ret = 1;
if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum)))
goto fail_unlock;
/* In either case (hit or miss), make sure fastreuse is 1 only
* if sk->sk_reuse is too (that is, if the caller requested
* SO_REUSEADDR on this socket -sk-).
*/
if (hlist_empty(&pp->owner)) {
if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING)
pp->fastreuse = 1;
else
pp->fastreuse = 0;
} else if (pp->fastreuse &&
(!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING))
pp->fastreuse = 0;
/* We are set, so fill up all the data in the hash table
* entry, tie the socket list information with the rest of the
* sockets FIXME: Blurry, NPI (ipg).
*/
success:
if (!sctp_sk(sk)->bind_hash) {
inet_sk(sk)->inet_num = snum;
sk_add_bind_node(sk, &pp->owner);
sctp_sk(sk)->bind_hash = pp;
}
ret = 0;
fail_unlock:
sctp_spin_unlock(&head->lock);
fail:
sctp_local_bh_enable();
return ret;
}
/* Assign a 'snum' port to the socket. If snum == 0, an ephemeral
* port is requested.
*/
static int sctp_get_port(struct sock *sk, unsigned short snum)
{
long ret;
union sctp_addr addr;
struct sctp_af *af = sctp_sk(sk)->pf->af;
/* Set up a dummy address struct from the sk. */
af->from_sk(&addr, sk);
addr.v4.sin_port = htons(snum);
/* Note: sk->sk_num gets filled in if ephemeral port request. */
ret = sctp_get_port_local(sk, &addr);
return ret ? 1 : 0;
}
/*
* Move a socket to LISTENING state.
*/
SCTP_STATIC int sctp_listen_start(struct sock *sk, int backlog)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
struct crypto_hash *tfm = NULL;
char alg[32];
/* Allocate HMAC for generating cookie. */
if (!sp->hmac && sp->sctp_hmac_alg) {
sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
tfm = crypto_alloc_hash(alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm)) {
net_info_ratelimited("failed to load transform for %s: %ld\n",
sp->sctp_hmac_alg, PTR_ERR(tfm));
return -ENOSYS;
}
sctp_sk(sk)->hmac = tfm;
}
/*
* If a bind() or sctp_bindx() is not called prior to a listen()
* call that allows new associations to be accepted, the system
* picks an ephemeral port and will choose an address set equivalent
* to binding with a wildcard address.
*
* This is not currently spelled out in the SCTP sockets
* extensions draft, but follows the practice as seen in TCP
* sockets.
*
*/
sk->sk_state = SCTP_SS_LISTENING;
if (!ep->base.bind_addr.port) {
if (sctp_autobind(sk))
return -EAGAIN;
} else {
if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
sk->sk_state = SCTP_SS_CLOSED;
return -EADDRINUSE;
}
}
sk->sk_max_ack_backlog = backlog;
sctp_hash_endpoint(ep);
return 0;
}
/*
* 4.1.3 / 5.1.3 listen()
*
* By default, new associations are not accepted for UDP style sockets.
* An application uses listen() to mark a socket as being able to
* accept new associations.
*
* On TCP style sockets, applications use listen() to ready the SCTP
* endpoint for accepting inbound associations.
*
* On both types of endpoints a backlog of '0' disables listening.
*
* Move a socket to LISTENING state.
*/
int sctp_inet_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
int err = -EINVAL;
if (unlikely(backlog < 0))
return err;
sctp_lock_sock(sk);
/* Peeled-off sockets are not allowed to listen(). */
if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
goto out;
if (sock->state != SS_UNCONNECTED)
goto out;
/* If backlog is zero, disable listening. */
if (!backlog) {
if (sctp_sstate(sk, CLOSED))
goto out;
err = 0;
sctp_unhash_endpoint(ep);
sk->sk_state = SCTP_SS_CLOSED;
if (sk->sk_reuse)
sctp_sk(sk)->bind_hash->fastreuse = 1;
goto out;
}
/* If we are already listening, just update the backlog */
if (sctp_sstate(sk, LISTENING))
sk->sk_max_ack_backlog = backlog;
else {
err = sctp_listen_start(sk, backlog);
if (err)
goto out;
}
err = 0;
out:
sctp_release_sock(sk);
return err;
}
/*
* This function is done by modeling the current datagram_poll() and the
* tcp_poll(). Note that, based on these implementations, we don't
* lock the socket in this function, even though it seems that,
* ideally, locking or some other mechanisms can be used to ensure
* the integrity of the counters (sndbuf and wmem_alloc) used
* in this place. We assume that we don't need locks either until proven
* otherwise.
*
* Another thing to note is that we include the Async I/O support
* here, again, by modeling the current TCP/UDP code. We don't have
* a good way to test with it yet.
*/
unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
struct sctp_sock *sp = sctp_sk(sk);
unsigned int mask;
poll_wait(file, sk_sleep(sk), wait);
/* A TCP-style listening socket becomes readable when the accept queue
* is not empty.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
return (!list_empty(&sp->ep->asocs)) ?
(POLLIN | POLLRDNORM) : 0;
mask = 0;
/* Is there any exceptional events? */
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;
/* Is it readable? Reconsider this code with TCP-style support. */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* The association is either gone or not ready. */
if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
return mask;
/* Is it writable? */
if (sctp_writeable(sk)) {
mask |= POLLOUT | POLLWRNORM;
} else {
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
/*
* Since the socket is not locked, the buffer
* might be made available after the writeable check and
* before the bit is set. This could cause a lost I/O
* signal. tcp_poll() has a race breaker for this race
* condition. Based on their implementation, we put
* in the following code to cover it as well.
*/
if (sctp_writeable(sk))
mask |= POLLOUT | POLLWRNORM;
}
return mask;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
static struct sctp_bind_bucket *sctp_bucket_create(
struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
{
struct sctp_bind_bucket *pp;
pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
if (pp) {
SCTP_DBG_OBJCNT_INC(bind_bucket);
pp->port = snum;
pp->fastreuse = 0;
INIT_HLIST_HEAD(&pp->owner);
pp->net = net;
hlist_add_head(&pp->node, &head->chain);
}
return pp;
}
/* Caller must hold hashbucket lock for this tb with local BH disabled */
static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
{
if (pp && hlist_empty(&pp->owner)) {
__hlist_del(&pp->node);
kmem_cache_free(sctp_bucket_cachep, pp);
SCTP_DBG_OBJCNT_DEC(bind_bucket);
}
}
/* Release this socket's reference to a local port. */
static inline void __sctp_put_port(struct sock *sk)
{
struct sctp_bind_hashbucket *head =
&sctp_port_hashtable[sctp_phashfn(sock_net(sk),
inet_sk(sk)->inet_num)];
struct sctp_bind_bucket *pp;
sctp_spin_lock(&head->lock);
pp = sctp_sk(sk)->bind_hash;
__sk_del_bind_node(sk);
sctp_sk(sk)->bind_hash = NULL;
inet_sk(sk)->inet_num = 0;
sctp_bucket_destroy(pp);
sctp_spin_unlock(&head->lock);
}
void sctp_put_port(struct sock *sk)
{
sctp_local_bh_disable();
__sctp_put_port(sk);
sctp_local_bh_enable();
}
/*
* The system picks an ephemeral port and choose an address set equivalent
* to binding with a wildcard address.
* One of those addresses will be the primary address for the association.
* This automatically enables the multihoming capability of SCTP.
*/
static int sctp_autobind(struct sock *sk)
{
union sctp_addr autoaddr;
struct sctp_af *af;
__be16 port;
/* Initialize a local sockaddr structure to INADDR_ANY. */
af = sctp_sk(sk)->pf->af;
port = htons(inet_sk(sk)->inet_num);
af->inaddr_any(&autoaddr, port);
return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
}
/* Parse out IPPROTO_SCTP CMSG headers. Perform only minimal validation.
*
* From RFC 2292
* 4.2 The cmsghdr Structure *
*
* When ancillary data is sent or received, any number of ancillary data
* objects can be specified by the msg_control and msg_controllen members of
* the msghdr structure, because each object is preceded by
* a cmsghdr structure defining the object's length (the cmsg_len member).
* Historically Berkeley-derived implementations have passed only one object
* at a time, but this API allows multiple objects to be
* passed in a single call to sendmsg() or recvmsg(). The following example
* shows two ancillary data objects in a control buffer.
*
* |<--------------------------- msg_controllen -------------------------->|
* | |
*
* |<----- ancillary data object ----->|<----- ancillary data object ----->|
*
* |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
* | | |
*
* |<---------- cmsg_len ---------->| |<--------- cmsg_len ----------->| |
*
* |<--------- CMSG_LEN() --------->| |<-------- CMSG_LEN() ---------->| |
* | | | | |
*
* +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
* |cmsg_|cmsg_|cmsg_|XX| |XX|cmsg_|cmsg_|cmsg_|XX| |XX|
*
* |len |level|type |XX|cmsg_data[]|XX|len |level|type |XX|cmsg_data[]|XX|
*
* +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
* ^
* |
*
* msg_control
* points here
*/
SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *msg,
sctp_cmsgs_t *cmsgs)
{
struct cmsghdr *cmsg;
struct msghdr *my_msg = (struct msghdr *)msg;
for (cmsg = CMSG_FIRSTHDR(msg);
cmsg != NULL;
cmsg = CMSG_NXTHDR(my_msg, cmsg)) {
if (!CMSG_OK(my_msg, cmsg))
return -EINVAL;
/* Should we parse this header or ignore? */
if (cmsg->cmsg_level != IPPROTO_SCTP)
continue;
/* Strictly check lengths following example in SCM code. */
switch (cmsg->cmsg_type) {
case SCTP_INIT:
/* SCTP Socket API Extension
* 5.2.1 SCTP Initiation Structure (SCTP_INIT)
*
* This cmsghdr structure provides information for
* initializing new SCTP associations with sendmsg().
* The SCTP_INITMSG socket option uses this same data
* structure. This structure is not used for
* recvmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ----------------------
* IPPROTO_SCTP SCTP_INIT struct sctp_initmsg
*/
if (cmsg->cmsg_len !=
CMSG_LEN(sizeof(struct sctp_initmsg)))
return -EINVAL;
cmsgs->init = (struct sctp_initmsg *)CMSG_DATA(cmsg);
break;
case SCTP_SNDRCV:
/* SCTP Socket API Extension
* 5.2.2 SCTP Header Information Structure(SCTP_SNDRCV)
*
* This cmsghdr structure specifies SCTP options for
* sendmsg() and describes SCTP header information
* about a received message through recvmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ----------------------
* IPPROTO_SCTP SCTP_SNDRCV struct sctp_sndrcvinfo
*/
if (cmsg->cmsg_len !=
CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
return -EINVAL;
cmsgs->info =
(struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
/* Minimally, validate the sinfo_flags. */
if (cmsgs->info->sinfo_flags &
~(SCTP_UNORDERED | SCTP_ADDR_OVER |
SCTP_ABORT | SCTP_EOF))
return -EINVAL;
break;
default:
return -EINVAL;
}
}
return 0;
}
/*
* Wait for a packet..
* Note: This function is the same function as in core/datagram.c
* with a few modifications to make lksctp work.
*/
static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p)
{
int error;
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/* Socket errors? */
error = sock_error(sk);
if (error)
goto out;
if (!skb_queue_empty(&sk->sk_receive_queue))
goto ready;
/* Socket shut down? */
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto out;
/* Sequenced packets can come disconnected. If so we report the
* problem.
*/
error = -ENOTCONN;
/* Is there a good reason to think that we may receive some data? */
if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
goto out;
/* Handle signals. */
if (signal_pending(current))
goto interrupted;
/* Let another process have a go. Since we are going to sleep
* anyway. Note: This may cause odd behaviors if the message
* does not fit in the user's buffer, but this seems to be the
* only way to honor MSG_DONTWAIT realistically.
*/
sctp_release_sock(sk);
*timeo_p = schedule_timeout(*timeo_p);
sctp_lock_sock(sk);
ready:
finish_wait(sk_sleep(sk), &wait);
return 0;
interrupted:
error = sock_intr_errno(*timeo_p);
out:
finish_wait(sk_sleep(sk), &wait);
*err = error;
return error;
}
/* Receive a datagram.
* Note: This is pretty much the same routine as in core/datagram.c
* with a few changes to make lksctp work.
*/
static struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
int noblock, int *err)
{
int error;
struct sk_buff *skb;
long timeo;
timeo = sock_rcvtimeo(sk, noblock);
SCTP_DEBUG_PRINTK("Timeout: timeo: %ld, MAX: %ld.\n",
timeo, MAX_SCHEDULE_TIMEOUT);
do {
/* Again only user level code calls this function,
* so nothing interrupt level
* will suddenly eat the receive_queue.
*
* Look at current nfs client by the way...
* However, this function was correct in any case. 8)
*/
if (flags & MSG_PEEK) {
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
atomic_inc(&skb->users);
spin_unlock_bh(&sk->sk_receive_queue.lock);
} else {
skb = skb_dequeue(&sk->sk_receive_queue);
}
if (skb)
return skb;
/* Caller is allowed not to check sk->sk_err before calling. */
error = sock_error(sk);
if (error)
goto no_packet;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
/* User doesn't want to wait. */
error = -EAGAIN;
if (!timeo)
goto no_packet;
} while (sctp_wait_for_packet(sk, err, &timeo) == 0);
return NULL;
no_packet:
*err = error;
return NULL;
}
/* If sndbuf has changed, wake up per association sndbuf waiters. */
static void __sctp_write_space(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct socket *sock = sk->sk_socket;
if ((sctp_wspace(asoc) > 0) && sock) {
if (waitqueue_active(&asoc->wait))
wake_up_interruptible(&asoc->wait);
if (sctp_writeable(sk)) {
wait_queue_head_t *wq = sk_sleep(sk);
if (wq && waitqueue_active(wq))
wake_up_interruptible(wq);
/* Note that we try to include the Async I/O support
* here by modeling from the current TCP/UDP code.
* We have not tested with it yet.
*/
if (!(sk->sk_shutdown & SEND_SHUTDOWN))
sock_wake_async(sock,
SOCK_WAKE_SPACE, POLL_OUT);
}
}
}
/* Do accounting for the sndbuf space.
* Decrement the used sndbuf space of the corresponding association by the
* data size which was just transmitted(freed).
*/
static void sctp_wfree(struct sk_buff *skb)
{
struct sctp_association *asoc;
struct sctp_chunk *chunk;
struct sock *sk;
/* Get the saved chunk pointer. */
chunk = *((struct sctp_chunk **)(skb->cb));
asoc = chunk->asoc;
sk = asoc->base.sk;
asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) +
sizeof(struct sk_buff) +
sizeof(struct sctp_chunk);
atomic_sub(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
/*
* This undoes what is done via sctp_set_owner_w and sk_mem_charge
*/
sk->sk_wmem_queued -= skb->truesize;
sk_mem_uncharge(sk, skb->truesize);
sock_wfree(skb);
__sctp_write_space(asoc);
sctp_association_put(asoc);
}
/* Do accounting for the receive space on the socket.
* Accounting for the association is done in ulpevent.c
* We set this as a destructor for the cloned data skbs so that
* accounting is done at the correct time.
*/
void sctp_sock_rfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct sctp_ulpevent *event = sctp_skb2event(skb);
atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
/*
* Mimic the behavior of sock_rfree
*/
sk_mem_uncharge(sk, event->rmem_len);
}
/* Helper function to wait for space in the sndbuf. */
static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
size_t msg_len)
{
struct sock *sk = asoc->base.sk;
int err = 0;
long current_timeo = *timeo_p;
DEFINE_WAIT(wait);
SCTP_DEBUG_PRINTK("wait_for_sndbuf: asoc=%p, timeo=%ld, msg_len=%zu\n",
asoc, (long)(*timeo_p), msg_len);
/* Increment the association's refcnt. */
sctp_association_hold(asoc);
/* Wait on the association specific sndbuf space. */
for (;;) {
prepare_to_wait_exclusive(&asoc->wait, &wait,
TASK_INTERRUPTIBLE);
if (!*timeo_p)
goto do_nonblock;
if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
asoc->base.dead)
goto do_error;
if (signal_pending(current))
goto do_interrupted;
if (msg_len <= sctp_wspace(asoc))
break;
/* Let another process have a go. Since we are going
* to sleep anyway.
*/
sctp_release_sock(sk);
current_timeo = schedule_timeout(current_timeo);
BUG_ON(sk != asoc->base.sk);
sctp_lock_sock(sk);
*timeo_p = current_timeo;
}
out:
finish_wait(&asoc->wait, &wait);
/* Release the association's refcnt. */
sctp_association_put(asoc);
return err;
do_error:
err = -EPIPE;
goto out;
do_interrupted:
err = sock_intr_errno(*timeo_p);
goto out;
do_nonblock:
err = -EAGAIN;
goto out;
}
void sctp_data_ready(struct sock *sk, int len)
{
struct socket_wq *wq;
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();
}
/* If socket sndbuf has changed, wake up all per association waiters. */
void sctp_write_space(struct sock *sk)
{
struct sctp_association *asoc;
/* Wake up the tasks in each wait queue. */
list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
__sctp_write_space(asoc);
}
}
/* Is there any sndbuf space available on the socket?
*
* Note that sk_wmem_alloc is the sum of the send buffers on all of the
* associations on the same socket. For a UDP-style socket with
* multiple associations, it is possible for it to be "unwriteable"
* prematurely. I assume that this is acceptable because
* a premature "unwriteable" is better than an accidental "writeable" which
* would cause an unwanted block under certain circumstances. For the 1-1
* UDP-style sockets or TCP-style sockets, this code should work.
* - Daisy
*/
static int sctp_writeable(struct sock *sk)
{
int amt = 0;
amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amt < 0)
amt = 0;
return amt;
}
/* Wait for an association to go into ESTABLISHED state. If timeout is 0,
* returns immediately with EINPROGRESS.
*/
static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
{
struct sock *sk = asoc->base.sk;
int err = 0;
long current_timeo = *timeo_p;
DEFINE_WAIT(wait);
SCTP_DEBUG_PRINTK("%s: asoc=%p, timeo=%ld\n", __func__, asoc,
(long)(*timeo_p));
/* Increment the association's refcnt. */
sctp_association_hold(asoc);
for (;;) {
prepare_to_wait_exclusive(&asoc->wait, &wait,
TASK_INTERRUPTIBLE);
if (!*timeo_p)
goto do_nonblock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
asoc->base.dead)
goto do_error;
if (signal_pending(current))
goto do_interrupted;
if (sctp_state(asoc, ESTABLISHED))
break;
/* Let another process have a go. Since we are going
* to sleep anyway.
*/
sctp_release_sock(sk);
current_timeo = schedule_timeout(current_timeo);
sctp_lock_sock(sk);
*timeo_p = current_timeo;
}
out:
finish_wait(&asoc->wait, &wait);
/* Release the association's refcnt. */
sctp_association_put(asoc);
return err;
do_error:
if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
err = -ETIMEDOUT;
else
err = -ECONNREFUSED;
goto out;
do_interrupted:
err = sock_intr_errno(*timeo_p);
goto out;
do_nonblock:
err = -EINPROGRESS;
goto out;
}
static int sctp_wait_for_accept(struct sock *sk, long timeo)
{
struct sctp_endpoint *ep;
int err = 0;
DEFINE_WAIT(wait);
ep = sctp_sk(sk)->ep;
for (;;) {
prepare_to_wait_exclusive(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
if (list_empty(&ep->asocs)) {
sctp_release_sock(sk);
timeo = schedule_timeout(timeo);
sctp_lock_sock(sk);
}
err = -EINVAL;
if (!sctp_sstate(sk, LISTENING))
break;
err = 0;
if (!list_empty(&ep->asocs))
break;
err = sock_intr_errno(timeo);
if (signal_pending(current))
break;
err = -EAGAIN;
if (!timeo)
break;
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void sctp_wait_for_close(struct sock *sk, long timeout)
{
DEFINE_WAIT(wait);
do {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (list_empty(&sctp_sk(sk)->ep->asocs))
break;
sctp_release_sock(sk);
timeout = schedule_timeout(timeout);
sctp_lock_sock(sk);
} while (!signal_pending(current) && timeout);
finish_wait(sk_sleep(sk), &wait);
}
static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
{
struct sk_buff *frag;
if (!skb->data_len)
goto done;
/* Don't forget the fragments. */
skb_walk_frags(skb, frag)
sctp_skb_set_owner_r_frag(frag, sk);
done:
sctp_skb_set_owner_r(skb, sk);
}
void sctp_copy_sock(struct sock *newsk, struct sock *sk,
struct sctp_association *asoc)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_sock *newinet;
newsk->sk_type = sk->sk_type;
newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
newsk->sk_flags = sk->sk_flags;
newsk->sk_no_check = sk->sk_no_check;
newsk->sk_reuse = sk->sk_reuse;
newsk->sk_shutdown = sk->sk_shutdown;
newsk->sk_destruct = inet_sock_destruct;
newsk->sk_family = sk->sk_family;
newsk->sk_protocol = IPPROTO_SCTP;
newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
newsk->sk_sndbuf = sk->sk_sndbuf;
newsk->sk_rcvbuf = sk->sk_rcvbuf;
newsk->sk_lingertime = sk->sk_lingertime;
newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
newsk->sk_sndtimeo = sk->sk_sndtimeo;
newinet = inet_sk(newsk);
/* Initialize sk's sport, dport, rcv_saddr and daddr for
* getsockname() and getpeername()
*/
newinet->inet_sport = inet->inet_sport;
newinet->inet_saddr = inet->inet_saddr;
newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
newinet->inet_dport = htons(asoc->peer.port);
newinet->pmtudisc = inet->pmtudisc;
newinet->inet_id = asoc->next_tsn ^ jiffies;
newinet->uc_ttl = inet->uc_ttl;
newinet->mc_loop = 1;
newinet->mc_ttl = 1;
newinet->mc_index = 0;
newinet->mc_list = NULL;
}
/* Populate the fields of the newsk from the oldsk and migrate the assoc
* and its messages to the newsk.
*/
static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
sctp_socket_type_t type)
{
struct sctp_sock *oldsp = sctp_sk(oldsk);
struct sctp_sock *newsp = sctp_sk(newsk);
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct sctp_endpoint *newep = newsp->ep;
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
struct sctp_bind_hashbucket *head;
struct list_head tmplist;
/* Migrate socket buffer sizes and all the socket level options to the
* new socket.
*/
newsk->sk_sndbuf = oldsk->sk_sndbuf;
newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
/* Brute force copy old sctp opt. */
if (oldsp->do_auto_asconf) {
memcpy(&tmplist, &newsp->auto_asconf_list, sizeof(tmplist));
inet_sk_copy_descendant(newsk, oldsk);
memcpy(&newsp->auto_asconf_list, &tmplist, sizeof(tmplist));
} else
inet_sk_copy_descendant(newsk, oldsk);
/* Restore the ep value that was overwritten with the above structure
* copy.
*/
newsp->ep = newep;
newsp->hmac = NULL;
/* Hook this new socket in to the bind_hash list. */
head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
inet_sk(oldsk)->inet_num)];
sctp_local_bh_disable();
sctp_spin_lock(&head->lock);
pp = sctp_sk(oldsk)->bind_hash;
sk_add_bind_node(newsk, &pp->owner);
sctp_sk(newsk)->bind_hash = pp;
inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
sctp_spin_unlock(&head->lock);
sctp_local_bh_enable();
/* Copy the bind_addr list from the original endpoint to the new
* endpoint so that we can handle restarts properly
*/
sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
&oldsp->ep->base.bind_addr, GFP_KERNEL);
/* Move any messages in the old socket's receive queue that are for the
* peeled off association to the new socket's receive queue.
*/
sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsk->sk_receive_queue);
__skb_queue_tail(&newsk->sk_receive_queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clean up any messages pending delivery due to partial
* delivery. Three cases:
* 1) No partial deliver; no work.
* 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
* 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
*/
skb_queue_head_init(&newsp->pd_lobby);
atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
struct sk_buff_head *queue;
/* Decide which queue to move pd_lobby skbs to. */
if (assoc->ulpq.pd_mode) {
queue = &newsp->pd_lobby;
} else
queue = &newsk->sk_receive_queue;
/* Walk through the pd_lobby, looking for skbs that
* need moved to the new socket.
*/
sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsp->pd_lobby);
__skb_queue_tail(queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clear up any skbs waiting for the partial
* delivery to finish.
*/
if (assoc->ulpq.pd_mode)
sctp_clear_pd(oldsk, NULL);
}
sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
/* Set the type of socket to indicate that it is peeled off from the
* original UDP-style socket or created with the accept() call on a
* TCP-style socket..
*/
newsp->type = type;
/* Mark the new socket "in-use" by the user so that any packets
* that may arrive on the association after we've moved it are
* queued to the backlog. This prevents a potential race between
* backlog processing on the old socket and new-packet processing
* on the new socket.
*
* The caller has just allocated newsk so we can guarantee that other
* paths won't try to lock it and then oldsk.
*/
lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
sctp_assoc_migrate(assoc, newsk);
/* If the association on the newsk is already closed before accept()
* is called, set RCV_SHUTDOWN flag.
*/
if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
newsk->sk_shutdown |= RCV_SHUTDOWN;
newsk->sk_state = SCTP_SS_ESTABLISHED;
sctp_release_sock(newsk);
}
/* This proto struct describes the ULP interface for SCTP. */
struct proto sctp_prot = {
.name = "SCTP",
.owner = THIS_MODULE,
.close = sctp_close,
.connect = sctp_connect,
.disconnect = sctp_disconnect,
.accept = sctp_accept,
.ioctl = sctp_ioctl,
.init = sctp_init_sock,
.destroy = sctp_destroy_sock,
.shutdown = sctp_shutdown,
.setsockopt = sctp_setsockopt,
.getsockopt = sctp_getsockopt,
.sendmsg = sctp_sendmsg,
.recvmsg = sctp_recvmsg,
.bind = sctp_bind,
.backlog_rcv = sctp_backlog_rcv,
.hash = sctp_hash,
.unhash = sctp_unhash,
.get_port = sctp_get_port,
.obj_size = sizeof(struct sctp_sock),
.sysctl_mem = sysctl_sctp_mem,
.sysctl_rmem = sysctl_sctp_rmem,
.sysctl_wmem = sysctl_sctp_wmem,
.memory_pressure = &sctp_memory_pressure,
.enter_memory_pressure = sctp_enter_memory_pressure,
.memory_allocated = &sctp_memory_allocated,
.sockets_allocated = &sctp_sockets_allocated,
};
#if IS_ENABLED(CONFIG_IPV6)
struct proto sctpv6_prot = {
.name = "SCTPv6",
.owner = THIS_MODULE,
.close = sctp_close,
.connect = sctp_connect,
.disconnect = sctp_disconnect,
.accept = sctp_accept,
.ioctl = sctp_ioctl,
.init = sctp_init_sock,
.destroy = sctp_destroy_sock,
.shutdown = sctp_shutdown,
.setsockopt = sctp_setsockopt,
.getsockopt = sctp_getsockopt,
.sendmsg = sctp_sendmsg,
.recvmsg = sctp_recvmsg,
.bind = sctp_bind,
.backlog_rcv = sctp_backlog_rcv,
.hash = sctp_hash,
.unhash = sctp_unhash,
.get_port = sctp_get_port,
.obj_size = sizeof(struct sctp6_sock),
.sysctl_mem = sysctl_sctp_mem,
.sysctl_rmem = sysctl_sctp_rmem,
.sysctl_wmem = sysctl_sctp_wmem,
.memory_pressure = &sctp_memory_pressure,
.enter_memory_pressure = sctp_enter_memory_pressure,
.memory_allocated = &sctp_memory_allocated,
.sockets_allocated = &sctp_sockets_allocated,
};
#endif /* IS_ENABLED(CONFIG_IPV6) */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5603_0 |
crossvul-cpp_data_bad_1363_0 | /* A Bison parser, made by GNU Bison 3.2.4. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, 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 3 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/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Undocumented macros, especially those whose name start with YY_,
are private implementation details. Do not rely on them. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.2.4"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 2
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* First part of user prologue. */
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "libyang.h"
#include "common.h"
#include "context.h"
#include "resolve.h"
#include "parser_yang.h"
#include "parser_yang_lex.h"
#include "parser.h"
#define YANG_ADDELEM(current_ptr, size, array_name) \
if ((size) == LY_ARRAY_MAX(size)) { \
LOGERR(trg->ctx, LY_EINT, "Reached limit (%"PRIu64") for storing %s.", LY_ARRAY_MAX(size), array_name); \
free(s); \
YYABORT; \
} else if (!((size) % LY_YANG_ARRAY_SIZE)) { \
void *tmp; \
\
tmp = realloc((current_ptr), (sizeof *(current_ptr)) * ((size) + LY_YANG_ARRAY_SIZE)); \
if (!tmp) { \
LOGMEM(trg->ctx); \
free(s); \
YYABORT; \
} \
memset(tmp + (sizeof *(current_ptr)) * (size), 0, (sizeof *(current_ptr)) * LY_YANG_ARRAY_SIZE); \
(current_ptr) = tmp; \
} \
actual = &(current_ptr)[(size)++]; \
void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...);
/* pointer on the current parsed element 'actual' */
# ifndef YY_NULLPTR
# if defined __cplusplus
# if 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# else
# define YY_NULLPTR ((void*)0)
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* In a future release of Bison, this section will be replaced
by #include "parser_yang_bis.h". */
#ifndef YY_YY_PARSER_YANG_BIS_H_INCLUDED
# define YY_YY_PARSER_YANG_BIS_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
UNION_KEYWORD = 258,
ANYXML_KEYWORD = 259,
WHITESPACE = 260,
ERROR = 261,
EOL = 262,
STRING = 263,
STRINGS = 264,
IDENTIFIER = 265,
IDENTIFIERPREFIX = 266,
REVISION_DATE = 267,
TAB = 268,
DOUBLEDOT = 269,
URI = 270,
INTEGER = 271,
NON_NEGATIVE_INTEGER = 272,
ZERO = 273,
DECIMAL = 274,
ARGUMENT_KEYWORD = 275,
AUGMENT_KEYWORD = 276,
BASE_KEYWORD = 277,
BELONGS_TO_KEYWORD = 278,
BIT_KEYWORD = 279,
CASE_KEYWORD = 280,
CHOICE_KEYWORD = 281,
CONFIG_KEYWORD = 282,
CONTACT_KEYWORD = 283,
CONTAINER_KEYWORD = 284,
DEFAULT_KEYWORD = 285,
DESCRIPTION_KEYWORD = 286,
ENUM_KEYWORD = 287,
ERROR_APP_TAG_KEYWORD = 288,
ERROR_MESSAGE_KEYWORD = 289,
EXTENSION_KEYWORD = 290,
DEVIATION_KEYWORD = 291,
DEVIATE_KEYWORD = 292,
FEATURE_KEYWORD = 293,
FRACTION_DIGITS_KEYWORD = 294,
GROUPING_KEYWORD = 295,
IDENTITY_KEYWORD = 296,
IF_FEATURE_KEYWORD = 297,
IMPORT_KEYWORD = 298,
INCLUDE_KEYWORD = 299,
INPUT_KEYWORD = 300,
KEY_KEYWORD = 301,
LEAF_KEYWORD = 302,
LEAF_LIST_KEYWORD = 303,
LENGTH_KEYWORD = 304,
LIST_KEYWORD = 305,
MANDATORY_KEYWORD = 306,
MAX_ELEMENTS_KEYWORD = 307,
MIN_ELEMENTS_KEYWORD = 308,
MODULE_KEYWORD = 309,
MUST_KEYWORD = 310,
NAMESPACE_KEYWORD = 311,
NOTIFICATION_KEYWORD = 312,
ORDERED_BY_KEYWORD = 313,
ORGANIZATION_KEYWORD = 314,
OUTPUT_KEYWORD = 315,
PATH_KEYWORD = 316,
PATTERN_KEYWORD = 317,
POSITION_KEYWORD = 318,
PREFIX_KEYWORD = 319,
PRESENCE_KEYWORD = 320,
RANGE_KEYWORD = 321,
REFERENCE_KEYWORD = 322,
REFINE_KEYWORD = 323,
REQUIRE_INSTANCE_KEYWORD = 324,
REVISION_KEYWORD = 325,
REVISION_DATE_KEYWORD = 326,
RPC_KEYWORD = 327,
STATUS_KEYWORD = 328,
SUBMODULE_KEYWORD = 329,
TYPE_KEYWORD = 330,
TYPEDEF_KEYWORD = 331,
UNIQUE_KEYWORD = 332,
UNITS_KEYWORD = 333,
USES_KEYWORD = 334,
VALUE_KEYWORD = 335,
WHEN_KEYWORD = 336,
YANG_VERSION_KEYWORD = 337,
YIN_ELEMENT_KEYWORD = 338,
ADD_KEYWORD = 339,
CURRENT_KEYWORD = 340,
DELETE_KEYWORD = 341,
DEPRECATED_KEYWORD = 342,
FALSE_KEYWORD = 343,
NOT_SUPPORTED_KEYWORD = 344,
OBSOLETE_KEYWORD = 345,
REPLACE_KEYWORD = 346,
SYSTEM_KEYWORD = 347,
TRUE_KEYWORD = 348,
UNBOUNDED_KEYWORD = 349,
USER_KEYWORD = 350,
ACTION_KEYWORD = 351,
MODIFIER_KEYWORD = 352,
ANYDATA_KEYWORD = 353,
NODE = 354,
NODE_PRINT = 355,
EXTENSION_INSTANCE = 356,
SUBMODULE_EXT_KEYWORD = 357
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
int32_t i;
uint32_t uint;
char *str;
char **p_str;
void *v;
char ch;
struct yang_type *type;
struct lys_deviation *dev;
struct lys_deviate *deviate;
union {
uint32_t index;
struct lys_node_container *container;
struct lys_node_anydata *anydata;
struct type_node node;
struct lys_node_case *cs;
struct lys_node_grp *grouping;
struct lys_refine *refine;
struct lys_node_notif *notif;
struct lys_node_uses *uses;
struct lys_node_inout *inout;
struct lys_node_augment *augment;
} nodes;
enum yytokentype token;
struct {
void *actual;
enum yytokentype token;
} backup_token;
struct {
struct lys_revision **revision;
int index;
} revisions;
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
/* Location type. */
#if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
typedef struct YYLTYPE YYLTYPE;
struct YYLTYPE
{
int first_line;
int first_column;
int last_line;
int last_column;
};
# define YYLTYPE_IS_DECLARED 1
# define YYLTYPE_IS_TRIVIAL 1
#endif
int yyparse (void *scanner, struct yang_parameter *param);
#endif /* !YY_YY_PARSER_YANG_BIS_H_INCLUDED */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \
&& defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
YYLTYPE yyls_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \
+ 2 * YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 6
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 3466
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 113
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 329
/* YYNRULES -- Number of rules. */
#define YYNRULES 827
/* YYNSTATES -- Number of states. */
#define YYNSTATES 1318
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 357
#define YYTRANSLATE(YYX) \
((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
111, 112, 2, 103, 2, 2, 2, 107, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 106,
2, 110, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 108, 2, 109, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 104, 2, 105, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 338, 338, 339, 340, 342, 365, 368, 370, 369,
393, 404, 414, 424, 425, 431, 436, 442, 453, 463,
476, 477, 483, 485, 489, 491, 495, 497, 498, 499,
501, 509, 517, 518, 523, 534, 545, 556, 564, 569,
570, 574, 575, 586, 597, 608, 612, 614, 637, 654,
658, 660, 661, 666, 671, 676, 682, 686, 688, 692,
694, 698, 700, 704, 706, 719, 730, 731, 743, 747,
748, 752, 753, 758, 765, 765, 776, 782, 830, 849,
852, 853, 854, 855, 856, 857, 858, 859, 860, 861,
864, 879, 886, 887, 891, 892, 893, 899, 904, 910,
928, 930, 931, 935, 940, 941, 963, 964, 965, 978,
983, 985, 986, 987, 988, 1003, 1017, 1022, 1023, 1038,
1039, 1040, 1046, 1051, 1057, 1114, 1119, 1120, 1122, 1138,
1143, 1144, 1169, 1170, 1184, 1185, 1191, 1196, 1202, 1206,
1208, 1261, 1272, 1275, 1278, 1283, 1288, 1294, 1299, 1305,
1310, 1319, 1320, 1324, 1371, 1372, 1374, 1375, 1379, 1385,
1398, 1399, 1400, 1404, 1405, 1407, 1411, 1429, 1434, 1436,
1437, 1453, 1458, 1467, 1468, 1472, 1488, 1493, 1498, 1503,
1509, 1513, 1529, 1544, 1545, 1549, 1550, 1560, 1565, 1570,
1575, 1581, 1585, 1596, 1608, 1609, 1612, 1620, 1631, 1632,
1647, 1648, 1649, 1661, 1667, 1672, 1678, 1683, 1685, 1686,
1701, 1706, 1707, 1712, 1716, 1718, 1723, 1725, 1726, 1727,
1740, 1752, 1753, 1755, 1763, 1775, 1776, 1791, 1792, 1793,
1805, 1811, 1816, 1822, 1827, 1829, 1830, 1846, 1850, 1852,
1856, 1858, 1862, 1864, 1868, 1870, 1880, 1887, 1888, 1892,
1893, 1899, 1904, 1909, 1910, 1911, 1912, 1913, 1919, 1920,
1921, 1922, 1923, 1924, 1925, 1926, 1929, 1939, 1946, 1947,
1970, 1971, 1972, 1973, 1974, 1979, 1985, 1991, 1996, 2001,
2002, 2003, 2008, 2009, 2011, 2051, 2061, 2064, 2065, 2066,
2069, 2074, 2075, 2080, 2086, 2092, 2098, 2103, 2109, 2119,
2174, 2177, 2178, 2179, 2182, 2193, 2198, 2199, 2205, 2218,
2231, 2241, 2247, 2252, 2258, 2268, 2315, 2318, 2319, 2320,
2321, 2330, 2336, 2342, 2355, 2368, 2378, 2384, 2389, 2394,
2395, 2396, 2397, 2402, 2404, 2414, 2421, 2422, 2442, 2445,
2446, 2447, 2457, 2464, 2471, 2478, 2484, 2490, 2492, 2493,
2495, 2496, 2497, 2498, 2499, 2500, 2501, 2507, 2517, 2524,
2525, 2539, 2540, 2541, 2542, 2548, 2553, 2558, 2561, 2571,
2578, 2588, 2595, 2596, 2619, 2622, 2623, 2624, 2625, 2632,
2639, 2646, 2651, 2657, 2667, 2674, 2675, 2707, 2708, 2709,
2710, 2716, 2721, 2726, 2727, 2729, 2730, 2732, 2745, 2750,
2751, 2783, 2786, 2800, 2816, 2838, 2889, 2908, 2927, 2948,
2969, 2974, 2980, 2981, 2984, 2999, 3008, 3009, 3011, 3022,
3031, 3032, 3033, 3034, 3040, 3045, 3050, 3051, 3052, 3057,
3059, 3074, 3081, 3091, 3098, 3099, 3123, 3126, 3127, 3133,
3138, 3143, 3144, 3145, 3152, 3160, 3175, 3205, 3206, 3207,
3208, 3209, 3211, 3226, 3256, 3265, 3272, 3273, 3305, 3306,
3307, 3308, 3314, 3319, 3324, 3325, 3326, 3328, 3340, 3360,
3361, 3367, 3373, 3375, 3376, 3378, 3379, 3382, 3390, 3395,
3396, 3398, 3399, 3400, 3402, 3410, 3415, 3416, 3448, 3449,
3455, 3456, 3462, 3468, 3475, 3482, 3490, 3499, 3507, 3512,
3513, 3545, 3546, 3552, 3553, 3559, 3566, 3574, 3579, 3580,
3594, 3595, 3596, 3602, 3608, 3615, 3622, 3630, 3639, 3648,
3653, 3654, 3658, 3659, 3664, 3670, 3675, 3677, 3678, 3679,
3692, 3697, 3699, 3700, 3701, 3714, 3718, 3720, 3725, 3727,
3728, 3748, 3753, 3755, 3756, 3757, 3777, 3782, 3784, 3785,
3786, 3798, 3867, 3872, 3873, 3877, 3881, 3883, 3884, 3886,
3890, 3892, 3892, 3899, 3902, 3911, 3930, 3932, 3933, 3936,
3936, 3953, 3953, 3960, 3960, 3967, 3970, 3972, 3974, 3975,
3977, 3979, 3981, 3982, 3984, 3986, 3987, 3989, 3990, 3992,
3994, 3997, 4000, 4002, 4003, 4005, 4006, 4008, 4010, 4021,
4022, 4025, 4026, 4038, 4039, 4041, 4042, 4044, 4045, 4051,
4052, 4055, 4056, 4057, 4081, 4082, 4085, 4091, 4095, 4100,
4101, 4102, 4105, 4110, 4120, 4122, 4123, 4125, 4126, 4128,
4129, 4130, 4132, 4133, 4135, 4136, 4138, 4139, 4143, 4144,
4171, 4209, 4210, 4212, 4214, 4216, 4217, 4219, 4220, 4222,
4223, 4226, 4227, 4230, 4232, 4233, 4236, 4236, 4243, 4245,
4246, 4247, 4248, 4249, 4250, 4251, 4253, 4254, 4255, 4257,
4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4269,
4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279,
4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289,
4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299,
4300, 4301, 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309,
4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319,
4320, 4321, 4322, 4323, 4324, 4325, 4326, 4327, 4328, 4329,
4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340,
4347, 4354, 4374, 4392, 4408, 4435, 4442, 4460, 4500, 4502,
4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4512,
4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4523,
4524, 4525, 4526, 4527, 4528, 4529, 4531, 4532, 4533, 4534,
4536, 4544, 4545, 4550, 4555, 4560, 4565, 4570, 4575, 4580,
4585, 4590, 4595, 4600, 4605, 4610, 4615, 4620, 4634, 4654,
4659, 4664, 4669, 4682, 4687, 4691, 4701, 4716, 4731, 4746,
4761, 4781, 4796, 4797, 4803, 4810, 4825, 4828
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 0
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "UNION_KEYWORD", "ANYXML_KEYWORD",
"WHITESPACE", "ERROR", "EOL", "STRING", "STRINGS", "IDENTIFIER",
"IDENTIFIERPREFIX", "REVISION_DATE", "TAB", "DOUBLEDOT", "URI",
"INTEGER", "NON_NEGATIVE_INTEGER", "ZERO", "DECIMAL", "ARGUMENT_KEYWORD",
"AUGMENT_KEYWORD", "BASE_KEYWORD", "BELONGS_TO_KEYWORD", "BIT_KEYWORD",
"CASE_KEYWORD", "CHOICE_KEYWORD", "CONFIG_KEYWORD", "CONTACT_KEYWORD",
"CONTAINER_KEYWORD", "DEFAULT_KEYWORD", "DESCRIPTION_KEYWORD",
"ENUM_KEYWORD", "ERROR_APP_TAG_KEYWORD", "ERROR_MESSAGE_KEYWORD",
"EXTENSION_KEYWORD", "DEVIATION_KEYWORD", "DEVIATE_KEYWORD",
"FEATURE_KEYWORD", "FRACTION_DIGITS_KEYWORD", "GROUPING_KEYWORD",
"IDENTITY_KEYWORD", "IF_FEATURE_KEYWORD", "IMPORT_KEYWORD",
"INCLUDE_KEYWORD", "INPUT_KEYWORD", "KEY_KEYWORD", "LEAF_KEYWORD",
"LEAF_LIST_KEYWORD", "LENGTH_KEYWORD", "LIST_KEYWORD",
"MANDATORY_KEYWORD", "MAX_ELEMENTS_KEYWORD", "MIN_ELEMENTS_KEYWORD",
"MODULE_KEYWORD", "MUST_KEYWORD", "NAMESPACE_KEYWORD",
"NOTIFICATION_KEYWORD", "ORDERED_BY_KEYWORD", "ORGANIZATION_KEYWORD",
"OUTPUT_KEYWORD", "PATH_KEYWORD", "PATTERN_KEYWORD", "POSITION_KEYWORD",
"PREFIX_KEYWORD", "PRESENCE_KEYWORD", "RANGE_KEYWORD",
"REFERENCE_KEYWORD", "REFINE_KEYWORD", "REQUIRE_INSTANCE_KEYWORD",
"REVISION_KEYWORD", "REVISION_DATE_KEYWORD", "RPC_KEYWORD",
"STATUS_KEYWORD", "SUBMODULE_KEYWORD", "TYPE_KEYWORD", "TYPEDEF_KEYWORD",
"UNIQUE_KEYWORD", "UNITS_KEYWORD", "USES_KEYWORD", "VALUE_KEYWORD",
"WHEN_KEYWORD", "YANG_VERSION_KEYWORD", "YIN_ELEMENT_KEYWORD",
"ADD_KEYWORD", "CURRENT_KEYWORD", "DELETE_KEYWORD", "DEPRECATED_KEYWORD",
"FALSE_KEYWORD", "NOT_SUPPORTED_KEYWORD", "OBSOLETE_KEYWORD",
"REPLACE_KEYWORD", "SYSTEM_KEYWORD", "TRUE_KEYWORD", "UNBOUNDED_KEYWORD",
"USER_KEYWORD", "ACTION_KEYWORD", "MODIFIER_KEYWORD", "ANYDATA_KEYWORD",
"NODE", "NODE_PRINT", "EXTENSION_INSTANCE", "SUBMODULE_EXT_KEYWORD",
"'+'", "'{'", "'}'", "';'", "'/'", "'['", "']'", "'='", "'('", "')'",
"$accept", "start", "tmp_string", "string_1", "string_2", "$@1",
"module_arg_str", "module_stmt", "module_header_stmts",
"module_header_stmt", "submodule_arg_str", "submodule_stmt",
"submodule_header_stmts", "submodule_header_stmt", "yang_version_arg",
"yang_version_stmt", "namespace_arg_str", "namespace_stmt",
"linkage_stmts", "import_stmt", "import_arg_str", "import_opt_stmt",
"include_arg_str", "include_stmt", "include_end", "include_opt_stmt",
"revision_date_arg", "revision_date_stmt", "belongs_to_arg_str",
"belongs_to_stmt", "prefix_arg", "prefix_stmt", "meta_stmts",
"organization_arg", "organization_stmt", "contact_arg", "contact_stmt",
"description_arg", "description_stmt", "reference_arg", "reference_stmt",
"revision_stmts", "revision_arg_stmt", "revision_stmts_opt",
"revision_stmt", "revision_end", "revision_opt_stmt", "date_arg_str",
"$@2", "body_stmts_end", "body_stmts", "body_stmt", "extension_arg_str",
"extension_stmt", "extension_end", "extension_opt_stmt", "argument_str",
"argument_stmt", "argument_end", "yin_element_arg", "yin_element_stmt",
"yin_element_arg_str", "status_arg", "status_stmt", "status_arg_str",
"feature_arg_str", "feature_stmt", "feature_end", "feature_opt_stmt",
"if_feature_arg", "if_feature_stmt", "if_feature_end",
"identity_arg_str", "identity_stmt", "identity_end", "identity_opt_stmt",
"base_arg", "base_stmt", "typedef_arg_str", "typedef_stmt",
"type_opt_stmt", "type_stmt", "type_arg_str", "type_end",
"type_body_stmts", "some_restrictions", "union_stmt", "union_spec",
"fraction_digits_arg", "fraction_digits_stmt", "fraction_digits_arg_str",
"length_stmt", "length_arg_str", "length_end", "message_opt_stmt",
"pattern_sep", "pattern_stmt", "pattern_arg_str", "pattern_end",
"pattern_opt_stmt", "modifier_arg", "modifier_stmt",
"enum_specification", "enum_stmts", "enum_stmt", "enum_arg_str",
"enum_end", "enum_opt_stmt", "value_arg", "value_stmt",
"integer_value_arg_str", "range_stmt", "range_end", "path_arg",
"path_stmt", "require_instance_arg", "require_instance_stmt",
"require_instance_arg_str", "bits_specification", "bit_stmts",
"bit_stmt", "bit_arg_str", "bit_end", "bit_opt_stmt",
"position_value_arg", "position_stmt", "position_value_arg_str",
"error_message_arg", "error_message_stmt", "error_app_tag_arg",
"error_app_tag_stmt", "units_arg", "units_stmt", "default_arg",
"default_stmt", "grouping_arg_str", "grouping_stmt", "grouping_end",
"grouping_opt_stmt", "data_def_stmt", "container_arg_str",
"container_stmt", "container_end", "container_opt_stmt", "leaf_stmt",
"leaf_arg_str", "leaf_opt_stmt", "leaf_list_arg_str", "leaf_list_stmt",
"leaf_list_opt_stmt", "list_arg_str", "list_stmt", "list_opt_stmt",
"choice_arg_str", "choice_stmt", "choice_end", "choice_opt_stmt",
"short_case_case_stmt", "short_case_stmt", "case_arg_str", "case_stmt",
"case_end", "case_opt_stmt", "anyxml_arg_str", "anyxml_stmt",
"anydata_arg_str", "anydata_stmt", "anyxml_end", "anyxml_opt_stmt",
"uses_arg_str", "uses_stmt", "uses_end", "uses_opt_stmt",
"refine_args_str", "refine_arg_str", "refine_stmt", "refine_end",
"refine_body_opt_stmts", "uses_augment_arg_str", "uses_augment_arg",
"uses_augment_stmt", "augment_arg_str", "augment_arg", "augment_stmt",
"augment_opt_stmt", "action_arg_str", "action_stmt", "rpc_arg_str",
"rpc_stmt", "rpc_end", "rpc_opt_stmt", "input_arg", "input_stmt",
"input_output_opt_stmt", "output_arg", "output_stmt",
"notification_arg_str", "notification_stmt", "notification_end",
"notification_opt_stmt", "deviation_arg", "deviation_stmt",
"deviation_opt_stmt", "deviation_arg_str", "deviate_body_stmt",
"deviate_not_supported", "deviate_not_supported_stmt",
"deviate_not_supported_end", "deviate_stmts", "deviate_add",
"deviate_add_stmt", "deviate_add_end", "deviate_add_opt_stmt",
"deviate_delete", "deviate_delete_stmt", "deviate_delete_end",
"deviate_delete_opt_stmt", "deviate_replace", "deviate_replace_stmt",
"deviate_replace_end", "deviate_replace_opt_stmt", "when_arg_str",
"when_stmt", "when_end", "when_opt_stmt", "config_arg", "config_stmt",
"config_arg_str", "mandatory_arg", "mandatory_stmt", "mandatory_arg_str",
"presence_arg", "presence_stmt", "min_value_arg", "min_elements_stmt",
"min_value_arg_str", "max_value_arg", "max_elements_stmt",
"max_value_arg_str", "ordered_by_arg", "ordered_by_stmt",
"ordered_by_arg_str", "must_agr_str", "must_stmt", "must_end",
"unique_arg", "unique_stmt", "unique_arg_str", "key_arg", "key_stmt",
"key_arg_str", "$@3", "range_arg_str", "absolute_schema_nodeid",
"absolute_schema_nodeids", "absolute_schema_nodeid_opt",
"descendant_schema_nodeid", "$@4", "path_arg_str", "$@5", "$@6",
"absolute_path", "absolute_paths", "absolute_path_opt", "relative_path",
"relative_path_part1", "relative_path_part1_opt", "descendant_path",
"descendant_path_opt", "path_predicate", "path_equality_expr",
"path_key_expr", "rel_path_keyexpr", "rel_path_keyexpr_part1",
"rel_path_keyexpr_part1_opt", "rel_path_keyexpr_part2",
"current_function_invocation", "positive_integer_value",
"non_negative_integer_value", "integer_value", "integer_value_convert",
"prefix_arg_str", "identifier_arg_str", "node_identifier",
"identifier_ref_arg_str", "stmtend", "semicolom", "curly_bracket_close",
"curly_bracket_open", "stmtsep", "unknown_statement", "string_opt",
"string_opt_part1", "string_opt_part2", "unknown_string",
"unknown_string_part1", "unknown_string_part2", "unknown_statement_end",
"unknown_statement2_opt", "unknown_statement2", "unknown_statement2_end",
"unknown_statement2_yang_stmt", "unknown_statement2_module_stmt",
"unknown_statement3_opt", "unknown_statement3_opt_end", "sep_stmt",
"optsep", "sep", "whitespace_opt", "string", "$@7", "strings",
"identifier", "identifier1", "yang_stmt", "identifiers",
"identifiers_ref", "type_ext_alloc", "typedef_ext_alloc",
"iffeature_ext_alloc", "restriction_ext_alloc", "when_ext_alloc",
"revision_ext_alloc", "datadef_ext_check", "not_supported_ext_check",
"not_supported_ext", "datadef_ext_stmt", "restriction_ext_stmt",
"ext_substatements", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 302, 303, 304,
305, 306, 307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 328, 329, 330, 331, 332, 333, 334,
335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354,
355, 356, 357, 43, 123, 125, 59, 47, 91, 93,
61, 40, 41
};
# endif
#define YYPACT_NINF -1012
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-1012)))
#define YYTABLE_NINF -757
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int16 yypact[] =
{
440, 100, -1012, -1012, 566, 1894, -1012, -1012, -1012, 266,
266, -1012, 266, -1012, 266, 266, -1012, 266, 266, 266,
266, -1012, 266, 266, -1012, -1012, -1012, -1012, 266, -1012,
-1012, -1012, 266, 266, 266, 266, 266, 266, 266, 266,
266, 266, 266, 266, 266, 266, 266, 266, 266, 266,
-1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -8, 31, 79, 868, 70, 125, 481,
266, -1012, -1012, 3273, 3273, 3273, 2893, 3273, 71, 2703,
2703, 2703, 2703, 2703, 98, 2988, 94, 52, 287, 2703,
77, 2703, 104, 287, 3273, 2703, 2703, 182, 58, 246,
2988, 2703, 321, 2703, 279, 279, 266, -1012, 266, -1012,
266, -1012, 266, 266, 266, 266, -1012, -1012, -1012, -1012,
-1012, 266, -1012, 266, -1012, 266, 266, 266, 266, 266,
-1012, 266, 266, 266, 266, -1012, 266, 266, 266, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
29, -1012, 134, -1012, -1012, -1012, -22, 2798, 266, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, 151, -1012, -1012, -1012, -1012, -1012, 156,
-1012, 67, -1012, -1012, -1012, 224, -1012, -1012, -1012, 161,
-1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, 224,
-1012, 224, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012,
-1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, 224,
-1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012,
-1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, 224,
-1012, -1012, 224, -1012, 262, 202, -1012, 224, -1012, -1012,
-1012, 224, -1012, -1012, 224, -1012, 224, -1012, -1012, -1012,
-1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012,
-1012, 224, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012,
-1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012,
-1012, -1012, -1012, 2893, 279, 3273, 279, 2703, 279, 2703,
2703, 2703, -1012, 2703, 279, 2703, 279, 58, 279, 3273,
3273, 3273, 3273, 3273, 266, 3273, 3273, 3273, 3273, 266,
2893, 3273, 3273, -1012, -1012, 279, -1012, -1012, -1012, -1012,
-1012, -1012, 266, -1012, 266, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, 266, 266, -1012, 266, 266, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012,
266, 266, -1012, 266, -1012, 266, -1012, 266, -1012, 266,
266, -1012, -1012, -1012, 3368, -1012, -1012, 291, -1012, -1012,
-1012, 266, -1012, 266, -1012, -1012, 266, 266, -1012, -1012,
-1012, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012,
266, -1012, 228, 2703, 266, 274, -1012, 189, -1012, 288,
-1012, 298, -1012, 303, -1012, 370, -1012, 380, -1012, 389,
-1012, 393, -1012, 407, -1012, 411, -1012, 419, -1012, 426,
-1012, 463, -1012, 238, -1012, 314, -1012, 317, -1012, 505,
-1012, 506, -1012, 521, -1012, 407, -1012, 279, 279, 266,
266, 266, 266, 326, 279, 279, 109, 279, 112, 608,
266, 266, -1012, 262, -1012, 3083, 266, 332, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, 1964, 1994, 2191, 347,
-1012, -1012, 19, -1012, 54, 266, 355, -1012, -1012, 368,
373, -1012, -1012, -1012, 48, 3368, -1012, 266, 831, 279,
186, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 279, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, 266, -1012, 127, 515, 266, -1012, -1012,
-1012, 515, -1012, -1012, 188, -1012, 279, -1012, 473, -1012,
306, -1012, 2552, 266, 266, 397, 1000, -1012, -1012, -1012,
-1012, 783, -1012, 230, 503, 404, 887, 359, 438, 929,
1958, 1645, 817, 947, 344, 2074, 1547, 1768, 235, 852,
279, 279, 279, 279, 266, -22, 280, -1012, 266, 266,
-1012, -1012, 375, 2703, 375, 279, -1012, -1012, -1012, 224,
-1012, -1012, 3368, -1012, -1012, -1012, -1012, -1012, 266, 266,
-1012, 3273, 2703, -1012, -1012, -1012, -8, -1012, -1012, -1012,
-1012, -1012, -1012, 279, 474, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, 3273, 3273, 279, 279, -1012, -1012,
-1012, -1012, -1012, 125, 224, -1012, -1012, 266, 266, -1012,
399, 473, 266, 528, 528, 545, -1012, 567, -1012, 279,
-1012, 279, 279, 279, 480, -1012, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 279, 279, 279,
2988, 2988, 279, 279, 279, 279, 279, 279, 279, 279,
279, 266, 266, 423, -1012, 570, -1012, 428, 2046, -1012,
-1012, 434, -1012, 465, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, 479, -1012, -1012,
-1012, 571, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266,
266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, 279, -1012, 473, 266, 279,
279, 279, 279, -1012, 266, -1012, -1012, -1012, 266, 279,
279, 266, 51, 3273, 51, 3273, 3273, 3273, 279, 266,
459, 2367, 385, 509, 279, 279, 341, 365, -1012, -1012,
483, -1012, -1012, 574, -1012, -1012, 486, -1012, -1012, 591,
-1012, 592, -1012, 521, -1012, 473, -1012, 473, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, 885, 1126, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, 332, 266, -1012, -1012, -1012, -1012, 266,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, 467, 492, 279,
279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, 279, 279, 279, 279, 279, 473, 473, 279,
279, 279, 279, 279, 279, 279, 279, 1460, 205, 524,
216, 201, 493, 579, -1012, -1012, -1012, -1012, -1012, -1012,
266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279,
293, 279, 279, 497, 3178, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473,
-1012, -1012, 279, 73, 120, 133, 163, -1012, 50, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, 510, 222, 279, 279, 279, 473, -1012, 824, 346,
985, 3368, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, 279, 279, 279
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint16 yydefact[] =
{
790, 0, 2, 3, 0, 757, 1, 649, 650, 0,
0, 652, 0, 763, 0, 0, 761, 0, 0, 0,
0, 762, 0, 0, 766, 764, 765, 767, 0, 768,
769, 770, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
759, 760, 0, 771, 802, 806, 619, 792, 803, 797,
793, 794, 619, 809, 796, 815, 814, 819, 804, 813,
818, 799, 800, 795, 798, 810, 811, 805, 816, 817,
812, 820, 801, 0, 0, 0, 0, 0, 0, 0,
627, 758, 651, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 571, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 791, 822, 0, 619, 0, 619,
0, 619, 0, 0, 0, 0, 789, 787, 788, 786,
619, 0, 619, 0, 619, 0, 0, 0, 0, 0,
651, 0, 0, 0, 0, 651, 0, 0, 0, 778,
777, 780, 781, 782, 776, 775, 774, 773, 785, 772,
0, 779, 0, 784, 783, 619, 0, 629, 653, 679,
5, 669, 680, 681, 682, 683, 684, 685, 686, 687,
688, 689, 690, 691, 692, 693, 694, 695, 696, 697,
698, 699, 700, 701, 702, 703, 704, 705, 706, 707,
708, 709, 710, 711, 712, 713, 666, 714, 715, 716,
717, 718, 719, 720, 721, 722, 723, 724, 725, 726,
727, 728, 729, 730, 731, 732, 733, 734, 735, 736,
737, 738, 739, 740, 741, 742, 743, 670, 744, 671,
672, 673, 674, 745, 675, 676, 677, 678, 746, 747,
748, 651, 608, 0, 10, 749, 667, 668, 651, 0,
17, 0, 99, 750, 613, 0, 138, 651, 651, 0,
47, 651, 651, 529, 0, 525, 659, 662, 660, 664,
665, 663, 658, 0, 58, 656, 661, 0, 243, 0,
60, 0, 239, 0, 237, 598, 170, 0, 167, 651,
610, 563, 0, 559, 561, 609, 651, 651, 534, 0,
530, 651, 545, 0, 541, 651, 599, 540, 0, 537,
600, 651, 0, 25, 651, 651, 550, 0, 546, 0,
56, 575, 0, 213, 0, 0, 236, 0, 233, 651,
605, 0, 49, 651, 0, 535, 0, 62, 651, 651,
219, 0, 215, 74, 76, 0, 45, 651, 651, 651,
114, 0, 109, 558, 0, 555, 651, 569, 0, 241,
603, 604, 601, 209, 0, 206, 651, 602, 0, 191,
621, 620, 651, 0, 807, 0, 808, 0, 821, 0,
0, 0, 180, 0, 823, 0, 824, 0, 825, 0,
0, 0, 0, 0, 445, 0, 0, 0, 0, 452,
0, 0, 0, 619, 619, 826, 651, 651, 827, 651,
628, 651, 7, 619, 607, 619, 619, 101, 100, 618,
616, 139, 619, 619, 611, 612, 619, 528, 527, 526,
59, 651, 244, 61, 240, 238, 168, 169, 560, 651,
533, 532, 531, 543, 542, 544, 538, 539, 26, 549,
548, 547, 57, 214, 0, 578, 572, 0, 574, 582,
234, 235, 50, 606, 536, 63, 218, 217, 216, 651,
46, 111, 113, 112, 110, 556, 557, 567, 242, 207,
208, 192, 0, 625, 624, 0, 150, 0, 140, 0,
124, 0, 172, 0, 551, 0, 182, 0, 564, 0,
518, 0, 65, 0, 368, 0, 357, 0, 334, 0,
266, 0, 245, 0, 285, 0, 298, 0, 314, 0,
454, 0, 383, 0, 430, 0, 370, 447, 447, 645,
647, 632, 630, 6, 13, 20, 104, 614, 0, 0,
657, 562, 587, 577, 581, 0, 75, 570, 651, 634,
622, 623, 626, 619, 151, 149, 619, 619, 126, 125,
619, 173, 171, 619, 553, 552, 619, 183, 181, 619,
211, 210, 619, 520, 519, 619, 69, 68, 619, 372,
369, 619, 359, 358, 619, 336, 335, 619, 268, 267,
619, 247, 246, 619, 619, 619, 619, 456, 455, 619,
385, 384, 619, 434, 431, 371, 0, 0, 0, 631,
651, 27, 12, 27, 19, 0, 0, 617, 619, 0,
576, 579, 583, 580, 585, 0, 568, 636, 156, 142,
0, 175, 175, 185, 175, 522, 71, 374, 361, 338,
270, 249, 286, 300, 316, 458, 387, 436, 446, 619,
619, 619, 258, 259, 260, 261, 262, 263, 264, 265,
619, 453, 651, 627, 651, 0, 51, 0, 14, 15,
16, 51, 21, 619, 0, 102, 615, 48, 654, 584,
0, 565, 0, 0, 0, 0, 153, 154, 619, 155,
221, 0, 127, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
449, 450, 451, 448, 648, 0, 0, 8, 0, 0,
619, 619, 66, 0, 66, 22, 651, 651, 108, 0,
103, 655, 0, 586, 644, 635, 638, 651, 627, 627,
643, 0, 0, 152, 159, 619, 0, 162, 619, 619,
619, 158, 157, 194, 220, 141, 147, 148, 146, 619,
144, 145, 174, 178, 179, 176, 177, 554, 184, 189,
190, 186, 187, 188, 212, 521, 523, 524, 70, 72,
73, 373, 381, 382, 380, 619, 619, 378, 379, 619,
360, 365, 366, 364, 619, 619, 619, 337, 345, 346,
344, 619, 341, 350, 351, 352, 353, 356, 619, 348,
349, 354, 355, 619, 342, 343, 269, 277, 278, 276,
619, 619, 619, 619, 619, 619, 619, 275, 274, 619,
248, 251, 252, 250, 619, 619, 619, 619, 619, 284,
296, 297, 295, 619, 619, 290, 292, 619, 293, 294,
619, 299, 312, 313, 311, 619, 619, 305, 304, 619,
307, 308, 309, 310, 619, 315, 327, 328, 326, 619,
619, 619, 619, 619, 619, 619, 322, 323, 324, 325,
619, 321, 320, 457, 462, 463, 461, 619, 619, 619,
619, 619, 0, 0, 386, 391, 392, 390, 619, 619,
619, 619, 435, 439, 440, 438, 619, 619, 619, 619,
619, 646, 651, 651, 0, 0, 28, 29, 52, 53,
54, 55, 78, 64, 0, 23, 78, 107, 106, 105,
0, 654, 637, 0, 0, 0, 224, 0, 197, 164,
165, 160, 161, 163, 193, 222, 143, 376, 375, 377,
363, 367, 362, 340, 347, 339, 272, 282, 279, 283,
280, 281, 271, 273, 254, 253, 255, 256, 257, 288,
289, 287, 291, 302, 303, 301, 306, 318, 329, 330,
333, 331, 332, 317, 319, 460, 464, 465, 466, 459,
0, 0, 389, 393, 394, 388, 437, 441, 442, 443,
444, 633, 9, 0, 31, 0, 37, 0, 77, 619,
24, 0, 588, 0, 651, 641, 639, 640, 619, 225,
619, 619, 198, 196, 619, 413, 414, 0, 651, 396,
397, 0, 651, 619, 619, 39, 38, 651, 0, 0,
0, 0, 0, 0, 619, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 67, 651, 654, 645, 227,
223, 200, 195, 619, 412, 619, 399, 398, 395, 32,
41, 11, 0, 0, 0, 0, 0, 0, 79, 18,
0, 0, 0, 0, 420, 401, 0, 0, 417, 418,
0, 567, 651, 0, 90, 474, 0, 467, 651, 0,
115, 0, 128, 0, 432, 654, 589, 654, 642, 226,
231, 232, 230, 619, 229, 199, 204, 205, 203, 619,
202, 0, 0, 30, 36, 33, 34, 35, 40, 44,
42, 43, 619, 566, 416, 619, 92, 91, 619, 473,
619, 117, 116, 619, 130, 129, 433, 0, 0, 228,
201, 415, 424, 425, 423, 619, 619, 619, 619, 619,
619, 400, 410, 411, 619, 405, 406, 407, 404, 408,
409, 619, 420, 94, 469, 119, 132, 654, 654, 422,
426, 429, 427, 428, 421, 403, 402, 0, 0, 0,
0, 0, 0, 0, 419, 93, 97, 98, 619, 96,
0, 468, 470, 471, 118, 122, 123, 121, 619, 131,
136, 137, 135, 619, 133, 597, 654, 590, 593, 95,
0, 120, 134, 0, 0, 484, 497, 477, 506, 619,
651, 475, 476, 651, 481, 651, 483, 651, 482, 654,
594, 595, 472, 0, 0, 0, 0, 592, 591, 619,
479, 478, 619, 486, 485, 619, 499, 498, 619, 508,
507, 0, 0, 488, 501, 510, 654, 480, 0, 0,
0, 0, 487, 489, 492, 493, 494, 495, 496, 619,
491, 500, 502, 505, 619, 504, 509, 619, 512, 513,
514, 515, 516, 517, 596, 490, 503, 511
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int16 yypgoto[] =
{
-1012, -1012, -1012, 245, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -16, -1012, -2, -9, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1011, -1012, 22,
-1012, -534, -24, -1012, 658, -1012, 681, -1012, 63, -1012,
105, -41, -1012, -1012, -237, -1012, -1012, 305, -1012, -225,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -486, -1012, -1012,
-1012, -1012, -1012, 41, -1012, -1012, -1012, -1012, -1012, -1012,
-11, -1012, -1012, -1012, -1012, -1012, -1012, -657, -1012, -3,
-1012, -653, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 23,
-1012, 30, -1012, -1012, 53, -1012, 35, -1012, -1012, -1012,
-1012, 10, -1012, -1012, -236, -1012, -1012, -1012, -1012, -366,
-1012, 38, -1012, -1012, 40, -1012, 43, -1012, -1012, -1012,
-21, -1012, -1012, -1012, -1012, -355, -1012, -1012, 12, -1012,
18, -1012, -704, -1012, -480, -1012, 16, -1012, -1012, -560,
-1012, -80, -1012, -1012, -67, -1012, -1012, -1012, -63, -1012,
-1012, -39, -1012, -1012, -36, -1012, -1012, -1012, -1012, -1012,
-33, -1012, -1012, -1012, -28, -1012, -27, 206, -1012, -1012,
667, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -435, -1012, -62, -1012, -1012, -365,
-1012, -1012, 42, 211, -1012, 44, -1012, -87, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012,
-1012, -1012, 74, -1012, -1012, -1012, -473, -1012, -1012, -667,
-1012, -1012, -675, -1012, -722, -1012, -1012, -662, -1012, -1012,
-271, -1012, -1012, -35, -1012, -1012, -725, -1012, -1012, 46,
-1012, -1012, -1012, -390, -319, -335, -461, -1012, -1012, -1012,
-1012, 214, 97, -1012, -1012, 239, -1012, -1012, -1012, 135,
-1012, -1012, -1012, -441, -1012, -1012, -1012, 155, 693, -1012,
-1012, -1012, 185, -93, -328, 1164, -1012, -1012, -1012, 526,
110, -1012, -1012, -1012, -433, -1012, -1012, -1012, -1012, -1012,
-143, -1012, -1012, -260, 84, -4, 1453, 166, -694, 119,
-1012, 660, -12, -1012, 137, -20, -23, -1012, -1012, -1012,
-1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int16 yydefgoto[] =
{
-1, 1, 261, 262, 553, 933, 263, 2, 631, 632,
269, 3, 633, 634, 944, 688, 332, 54, 686, 740,
1023, 1106, 1025, 741, 1056, 1107, 365, 55, 279, 56,
351, 57, 742, 339, 938, 293, 939, 299, 783, 356,
784, 942, 521, 943, 144, 597, 718, 366, 489, 1027,
1028, 1064, 1113, 1065, 1157, 1208, 271, 62, 438, 749,
636, 750, 371, 1174, 372, 1119, 1066, 1162, 1210, 509,
1175, 579, 1121, 1067, 1165, 1211, 275, 64, 507, 669,
711, 127, 505, 575, 705, 706, 765, 766, 307, 65,
308, 136, 511, 582, 713, 401, 137, 515, 588, 715,
388, 66, 707, 964, 708, 957, 1043, 1103, 384, 67,
385, 138, 591, 342, 68, 361, 69, 362, 709, 774,
710, 955, 1040, 1102, 347, 70, 348, 303, 785, 301,
786, 378, 73, 297, 74, 531, 670, 612, 723, 671,
529, 672, 609, 722, 673, 533, 724, 535, 674, 725,
537, 675, 726, 527, 676, 606, 721, 828, 829, 525,
1177, 603, 720, 523, 677, 545, 678, 600, 719, 541,
679, 621, 728, 1050, 1051, 919, 1087, 1142, 1046, 1047,
920, 1109, 1110, 1071, 1141, 543, 1178, 1123, 1072, 624,
729, 170, 171, 626, 172, 173, 539, 1179, 618, 727,
1116, 1074, 1209, 1117, 1249, 1250, 1251, 1271, 1252, 1253,
1254, 1274, 1288, 1255, 1256, 1277, 1289, 1257, 1258, 1280,
1290, 519, 1180, 594, 717, 284, 75, 285, 319, 76,
320, 354, 77, 328, 78, 329, 323, 79, 324, 337,
80, 338, 513, 680, 585, 374, 81, 375, 312, 82,
313, 459, 517, 646, 1112, 567, 376, 497, 343, 344,
345, 475, 476, 563, 478, 479, 565, 643, 699, 640,
950, 1126, 1237, 1238, 1244, 1268, 1127, 330, 331, 386,
387, 352, 264, 377, 276, 441, 442, 638, 443, 124,
390, 502, 503, 571, 176, 430, 629, 570, 702, 757,
1036, 758, 759, 628, 428, 391, 4, 177, 752, 294,
451, 295, 265, 266, 267, 268, 392, 83, 84, 85,
86, 87, 88, 89, 90, 91, 175, 140, 5
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int16 yytable[] =
{
11, 901, 174, 881, 897, 92, 92, 780, 92, 160,
92, 92, 314, 92, 92, 92, 92, 71, 92, 92,
865, 877, 161, 72, 92, 639, 162, 169, 92, 92,
92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
92, 92, 92, 92, 92, 92, 63, 848, 92, 764,
163, 139, 808, 164, 835, 751, 165, 869, 779, 180,
180, 166, 167, 882, 898, 506, 180, 126, 60, 305,
363, 864, 876, 278, 131, 36, 277, 15, 7, 180,
8, 129, 426, 41, 427, 180, 92, 296, 296, 296,
296, 296, 542, 315, 353, 1144, 1149, 296, 690, 296,
6, 687, 180, 296, 296, 159, 180, 128, 315, 296,
61, 296, 180, 960, 7, 305, 8, 7, -573, 8,
273, 130, 92, 273, 92, 7, 92, 8, 92, 92,
92, 92, 7, 423, 8, 737, 687, 92, 7, 92,
8, 92, 92, 92, 92, 92, 321, 92, 92, 92,
92, 141, 92, 92, 92, -587, -587, -654, 645, 281,
815, 142, 843, 856, 282, 296, 892, 910, 7, 334,
8, 436, 335, 437, 11, 93, 94, 1269, 95, 1270,
96, 97, 316, 98, 99, 100, 101, 317, 102, 103,
180, 7, 635, 8, 104, 143, 180, 273, 105, 106,
107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, 118, 119, 120, 121, 122, 477, 637, 123, 298,
300, 302, 304, 14, 1272, 12, 1273, 7, 333, 8,
340, 781, 20, 273, 355, 357, 20, 1275, 424, 1276,
379, 822, 389, 130, 866, 878, 807, 20, 834, 847,
735, 868, 880, 896, 180, 433, 912, 1033, 130, 309,
435, 20, 325, 22, 23, 446, 20, 1278, 43, 1279,
358, 7, 43, 8, 46, 359, 746, 130, 46, 270,
272, 747, 280, 43, 7, 7, 8, 8, 932, 46,
273, 712, 393, 576, 395, 180, 397, 43, 399, 400,
402, 403, 43, 913, 305, 326, 1229, 405, 46, 407,
1215, 409, 410, 411, 412, 413, 141, 415, 416, 417,
418, 1224, 420, 421, 422, 953, 954, 1287, 439, 180,
440, 367, 568, 368, 569, 782, 369, 380, 381, 382,
914, 274, 613, 283, 292, 292, 292, 292, 292, 306,
311, 318, 322, 327, 292, 336, 292, 341, 346, 350,
292, 292, 360, 364, 370, 373, 292, 383, 292, 474,
278, 17, 20, 277, 19, 20, 19, 1245, 573, 1246,
574, 562, 1247, 1100, 1248, 296, 130, 296, 296, 296,
20, 296, 577, 296, 578, 33, 20, 278, 564, 133,
277, 133, 580, 18, 581, 41, 20, 583, 43, 584,
11, 43, 45, 474, 698, 11, 20, 46, 614, 126,
1189, 615, 48, 47, 48, 141, 43, 130, 11, 630,
11, 1167, 43, 1168, 38, 20, 45, 22, 23, 645,
11, 11, 43, 11, 11, -651, 1143, -651, 40, 859,
684, 1301, 43, 11, 883, 899, 11, 11, 46, 11,
695, 11, 315, 11, 795, 11, 11, 1188, 1070, 20,
1148, 43, 644, 697, 586, 1187, 587, 11, 751, 11,
1190, 698, 11, 11, 589, 145, 590, 11, 11, 11,
1129, 296, 11, 592, -651, 593, 11, 595, 703, 596,
11, 52, 763, 1212, 1213, 43, 146, 147, 1032, 788,
148, 598, 704, 599, -651, 601, 510, 602, 512, 514,
516, 149, 518, 604, 520, 605, 150, 1053, 151, 152,
607, 153, 608, 1057, 20, 683, 22, 23, 154, 1076,
20, 155, 1243, 798, 1125, 11, 11, 11, 11, 1048,
1052, 130, 701, 315, 1234, 20, 11, 11, 738, 739,
156, 1220, 11, 1300, 1305, 1267, 1297, 610, 1312, 611,
43, 7, 1145, 8, 1281, 1077, 43, 157, 1197, 158,
508, 1176, 46, 1083, 1293, 1302, 1308, 1152, 125, 49,
1158, 43, 1291, 1236, 524, 526, 528, 530, 532, 1198,
534, 536, 538, 540, 1259, 1235, 544, 546, 787, 616,
619, 617, 620, 7, 1135, 8, 315, 1286, 692, 273,
9, 1296, 572, 1311, 691, 622, 1298, 623, 1313, 1221,
689, 92, 1034, 315, 1035, 845, 858, 1307, 274, 894,
10, 823, 292, 11, 292, 292, 292, 1176, 292, 1038,
292, 1039, 364, 394, 824, 396, 693, 398, 825, 951,
844, 857, 1185, 58, 893, 274, 404, 744, 406, 1186,
408, 1041, 41, 1042, 1054, 1085, 1055, 1086, 1155, 92,
1156, 11, 826, 92, 809, 827, 59, 849, 830, 870,
884, 900, 911, 831, 832, 1160, 1163, 1161, 1164, 92,
92, 425, 1111, 946, 1111, 714, 1029, 716, 805, 814,
821, 840, 522, 863, 875, 889, 907, 918, 926, 841,
854, 1031, 1218, 890, 908, 791, 927, 792, 1044, 767,
11, 296, 11, 793, 92, 92, 768, 1140, 842, 855,
315, 769, 891, 909, 770, 928, 771, 1134, 292, 772,
296, 625, 778, 965, 92, 92, 168, 1207, 1166, 627,
804, 813, 820, 839, 853, 862, 874, 888, 906, 917,
925, 929, 902, 930, 776, 1118, 1153, 641, 789, 700,
796, 799, 802, 811, 818, 837, 851, 860, 872, 886,
904, 915, 923, 806, 816, 833, 846, 753, 867, 879,
895, 694, 921, 1260, 642, 940, 349, 940, 1294, 1303,
1309, 1037, 756, 19, 20, 1295, 777, 1310, 1101, 931,
790, 145, 797, 800, 803, 812, 819, 838, 852, 861,
873, 887, 905, 916, 924, 0, 7, 431, 8, 760,
0, 0, 273, 147, 17, 0, 148, 941, 20, 941,
43, 17, 0, 743, 19, 703, 46, 149, 126, 130,
0, 48, 945, 704, 151, 152, 0, 153, 0, 761,
762, 0, 133, 0, 154, 33, 34, 35, 0, 133,
0, 958, 42, 20, 43, 0, 0, 0, 775, 145,
46, 0, 149, 128, 130, 0, 156, 150, 141, 0,
0, 47, 48, 0, 934, 935, 0, 0, 92, 92,
146, 147, 155, 157, 148, 158, 20, 132, 20, 43,
22, 23, 836, 133, 0, 46, 0, 130, 128, 1292,
134, 0, 151, 152, 135, 153, 0, 0, 0, 748,
0, 1073, 154, 11, 11, 0, 956, 0, 11, 547,
548, 145, 43, 0, 43, 0, 17, 922, 46, 554,
20, 555, 556, 0, 156, 0, 141, 0, 557, 558,
0, 130, 559, 147, 0, 0, 148, 0, 20, 0,
33, 157, 0, 158, 133, 0, 0, 149, 292, 0,
1171, 0, 794, 0, 151, 152, 43, 153, 315, 315,
0, 0, 46, 0, 154, 0, 0, 292, 683, 0,
141, 0, 17, 0, 43, 19, 0, 11, 11, 0,
46, 0, 14, 128, 0, 1068, 156, 0, 0, 0,
0, 0, 0, 0, 801, 0, 33, 34, 35, 28,
0, 0, 0, 157, 1069, 158, 0, 0, 0, 132,
0, 0, 850, 0, 92, 92, 92, 92, 92, 92,
126, 39, 134, 48, 0, 0, 135, 0, 0, 44,
0, 0, 0, 0, 11, -166, 0, 0, 1010, 1011,
11, 0, 0, 0, 11, 0, 0, 11, 0, 315,
1306, 1133, 1139, 0, 0, 11, 0, 0, 0, 648,
0, 0, 649, 650, 0, 0, 651, 1191, 0, 652,
0, 0, 653, 0, 0, 654, 0, 0, 655, 1024,
1026, 656, 0, 0, 657, 0, 0, 658, 0, 0,
659, 1184, 0, 660, 0, 0, 661, 0, 0, 662,
663, 664, 665, 1132, 1138, 666, 0, 0, 667, 0,
11, 1261, 0, 17, 0, 11, 19, 20, 0, 0,
0, 0, 0, 0, 696, 1130, 1136, 0, 130, 1146,
1150, 0, 0, 0, 0, 0, 0, 33, 34, 35,
0, 133, 0, 0, 0, 0, 0, 0, 0, 0,
0, 42, 0, 43, 0, 730, 731, 732, 1314, 1228,
1233, 0, 0, 0, 1172, 1182, 733, 1131, 1137, 0,
0, 1147, 1151, 0, 0, 0, 92, 0, 0, 745,
0, 0, 0, 0, 1092, 1093, 1094, 1095, 1096, 1097,
0, 1181, 315, 0, 773, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1173, 1183, 0, 1219,
0, 1227, 1232, 1299, 1304, 1045, 1049, 0, 0, 11,
11, 11, 11, 0, 0, 0, 936, 937, 0, 0,
1172, 1216, 1222, 1225, 1230, 0, 0, 0, 1114, 315,
1120, 1122, 1124, 0, 0, 0, 0, 0, 0, 0,
0, 959, 0, 0, 961, 962, 963, 0, 0, 0,
0, 0, 0, 0, 0, 966, 0, 0, 0, 0,
0, 0, 1173, 1217, 1223, 1226, 1231, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 967, 968, 0, 0, 969, 0, 1108, 0, 1115,
970, 971, 972, 0, 0, 0, 0, 973, 0, 0,
0, 0, 0, 0, 974, 0, 0, 0, 0, 975,
0, 0, 0, 0, 0, 0, 976, 977, 978, 979,
980, 981, 982, 0, 0, 983, 0, 0, 0, 0,
984, 985, 986, 987, 988, 0, 1240, 0, 0, 989,
990, 0, 0, 991, 0, 0, 992, 0, 0, 0,
0, 993, 994, 0, 0, 995, 0, 0, 0, 0,
996, 0, 0, 0, 0, 997, 998, 999, 1000, 1001,
1002, 1003, 0, 0, 0, 0, 1004, 0, 0, 0,
0, 0, 0, 1005, 1006, 1007, 1008, 1009, 0, 0,
0, 0, 0, 0, 1012, 1013, 1014, 1015, 449, 0,
0, 0, 1016, 1017, 1018, 1019, 1020, 450, 0, 0,
0, 452, 0, 453, 145, 454, 0, 455, 0, 0,
0, 456, 0, 0, 0, 0, 458, 0, 0, 0,
0, 0, 0, 462, 0, 146, 147, 464, 0, 148,
0, 20, 466, 0, 0, 0, 468, 0, 0, 0,
0, 471, 130, 472, 0, 0, 473, 151, 152, 0,
153, 480, 0, 0, 0, 482, 0, 154, 484, 0,
485, 0, 0, 0, 0, 488, 0, 43, 0, 490,
0, 0, 0, 46, 0, 494, 0, 0, 495, 156,
0, 141, 498, 0, 0, 178, 0, 0, 499, 0,
0, 145, 501, 0, 0, 1075, 157, 0, 158, 0,
0, 0, 0, 0, 1079, 1214, 1080, 1081, 0, 0,
1082, 0, 0, 147, 17, 0, 148, 0, 20, 1089,
1090, 0, 0, 0, 0, 0, 0, 149, 0, 130,
1098, 0, 0, 32, 151, 152, 0, 153, 0, 34,
35, 0, 133, 414, 154, 37, 0, 0, 419, 1104,
0, 1105, 0, 0, 43, 0, 0, 0, 0, 0,
46, 0, 0, 128, 47, 0, 156, 0, 141, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 157, 0, 158, 0, 0, 0, 145,
0, 0, 885, 0, 0, 0, 0, 0, 0, 1169,
0, 0, 0, 0, 0, 1170, 0, 0, 0, 0,
146, 147, 17, 0, 148, 19, 20, 0, 1192, 0,
0, 1193, 0, 0, 1194, 0, 1195, 130, 0, 1196,
0, 0, 151, 152, 0, 153, 33, 0, 0, 0,
0, 1199, 1200, 1201, 1202, 1203, 1204, 0, 0, 0,
1205, 0, 43, 0, 432, 0, 0, 1206, 46, 0,
0, 434, 0, 0, 0, 0, 141, 0, 0, 0,
444, 445, 0, 0, 447, 448, 0, 0, 0, 0,
0, 0, 0, 158, 1239, 0, 0, 0, 0, 0,
817, 0, 0, 0, 1241, 0, 0, 0, 0, 1242,
0, 0, 457, 0, 0, 0, 0, 0, 0, 460,
461, 0, 145, 0, 463, 1262, 0, 0, 465, 0,
0, 0, 0, 0, 467, 0, 0, 469, 470, 0,
0, 0, 0, 0, 147, 1282, 0, 148, 1283, 20,
0, 1284, 481, 0, 1285, 0, 483, 0, 149, 0,
130, 486, 487, 0, 0, 151, 152, 0, 153, 0,
491, 492, 493, 133, 0, 1315, 0, 0, 0, 496,
1316, 0, 0, 1317, 0, 43, 0, 0, 0, 500,
0, 46, 0, 0, 128, 504, 0, 156, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 158, 0, 0, 0,
0, 0, 0, 903, 0, 0, 0, 0, 0, 549,
550, 0, 551, 0, 552, 0, 0, 0, 0, 0,
0, 0, 0, 0, -4, 0, 0, 0, 0, 0,
0, 0, 0, 0, 560, 0, 0, 0, 0, 0,
0, 0, 561, 949, 12, 13, 14, 15, 16, 0,
0, 17, 18, 0, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 0, 29, -753, 30, 31, 0,
32, 0, 566, -754, 0, 33, 34, 35, 0, -754,
36, 0, 37, 38, 0, 39, -754, 40, 41, 42,
-754, 43, 145, 44, -756, 45, 0, 46, 145, -751,
-752, 47, 48, 0, 49, -755, 50, 51, 0, 0,
0, 0, 0, 0, 147, 0, 0, 148, 0, 20,
147, 52, 0, 148, 0, 0, 53, 0, 145, 0,
130, 0, 0, 0, 149, 151, 152, 0, 153, 0,
0, 151, 152, 0, 153, 0, 0, 0, 0, 133,
147, 647, 0, 148, 0, 43, 0, 0, 0, 0,
0, 46, 0, 0, 149, 0, 0, 156, 0, 141,
128, 151, 152, 156, 153, 0, 0, 0, 0, 133,
145, 0, 0, 0, 0, 0, 158, 0, 0, 0,
0, 0, 158, 810, 0, 0, 0, 1058, 0, 668,
128, 0, 147, 156, 0, 148, 0, 0, 0, 0,
0, 1059, 1060, 685, 1061, 0, 149, 1062, 0, 0,
0, 0, 158, 151, 152, 0, 153, 0, 0, 681,
0, 17, 0, 154, 19, 20, 0, 0, 1030, 0,
0, 0, 0, 0, 0, 0, 130, 0, 1063, 0,
0, 0, 128, 0, 0, 156, 34, 35, 0, 133,
0, 0, 37, 0, 0, 734, 0, 736, 0, 0,
0, 43, 0, 0, 158, 0, 0, 46, 0, 126,
0, 0, 48, 0, 0, 141, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 871,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 179, 0, 0, 0, 947,
948, 181, 310, 0, 0, 0, 0, 0, 0, 0,
952, 182, 183, 184, 185, 186, 187, 188, 189, 190,
191, 192, 193, 194, 195, 196, 197, 198, 199, 200,
201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 213, 214, 215, 216, 217, 218, 219, 220,
221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240,
241, 242, 243, 244, 245, 246, 247, 248, 249, 250,
251, 252, 253, 254, 255, 256, 257, 258, 259, 260,
0, 0, 0, 0, 0, 0, 682, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 179, 0, 0, 0, 0, 0, 181, 310, 0,
0, 0, 0, 0, 0, 1021, 1022, 182, 183, 184,
185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212, 213, 214,
215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
255, 256, 257, 258, 259, 260, 0, 0, 0, 0,
0, 0, 1128, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1078, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1084, 0, 0, 0, 1088, 0, 0, 0, 0,
1091, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1099,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 179, 0, 0, 0,
0, 0, 0, 273, 0, 1154, 0, 0, 0, 0,
0, 1159, 182, 183, 184, 185, 186, 187, 188, 189,
190, 191, 192, 193, 194, 195, 196, 197, 198, 199,
200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 754, 217, 218, 219,
220, 221, 222, 223, 224, 225, 226, 227, 228, 229,
230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 0, 248, 0,
0, 0, 0, 253, 0, 0, 0, 0, 258, 259,
260, 0, 0, 0, 0, 0, 0, 755, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1263, 0, 0, 1264, 179, 1265, 0,
1266, 180, 286, 181, 287, 288, 0, 0, 0, 289,
290, 291, 0, 182, 183, 184, 185, 186, 187, 188,
189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
229, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258,
259, 260, 179, 0, 0, 0, 429, 286, 181, 287,
288, 0, 0, 0, 289, 290, 291, 0, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
234, 235, 236, 237, 238, 239, 240, 241, 242, 243,
244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260, 179, 0, 0,
0, 180, 0, 181, 273, 0, 0, 0, 0, 0,
0, 0, 0, 182, 183, 184, 185, 186, 187, 188,
189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
229, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258,
259, 260, 179, 0, 0, 0, 180, 0, 181, 310,
0, 0, 0, 0, 0, 0, 0, 0, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
234, 235, 236, 237, 238, 239, 240, 241, 242, 243,
244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260, 179, 0, 0,
0, 0, 0, 181, 310, 0, 0, 477, 0, 0,
0, 0, 0, 182, 183, 184, 185, 186, 187, 188,
189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
229, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258,
259, 260, 179, 0, 0, 0, 0, 0, 181, 310,
0, 0, 1236, 0, 0, 0, 0, 0, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
234, 235, 236, 237, 238, 239, 240, 241, 242, 243,
244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260, 179, 0, 0,
0, 180, 0, 181, 0, 0, 0, 0, 0, 0,
0, 0, 0, 182, 183, 184, 185, 186, 187, 188,
189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
229, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258,
259, 260, 179, 0, 0, 0, 0, 0, 181, 310,
0, 0, 0, 0, 0, 0, 0, 0, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
234, 235, 236, 237, 238, 239, 240, 241, 242, 243,
244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260
};
static const yytype_int16 yycheck[] =
{
4, 726, 89, 725, 726, 9, 10, 711, 12, 89,
14, 15, 105, 17, 18, 19, 20, 5, 22, 23,
724, 725, 89, 5, 28, 559, 89, 89, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 5, 722, 52, 706,
89, 86, 719, 89, 721, 5, 89, 724, 711, 8,
8, 89, 89, 725, 726, 393, 8, 75, 5, 17,
12, 724, 725, 96, 85, 56, 96, 23, 5, 8,
7, 84, 104, 64, 106, 8, 90, 99, 100, 101,
102, 103, 420, 105, 114, 1106, 1107, 109, 632, 111,
0, 82, 8, 115, 116, 89, 8, 76, 120, 121,
5, 123, 8, 766, 5, 17, 7, 5, 14, 7,
11, 42, 126, 11, 128, 5, 130, 7, 132, 133,
134, 135, 5, 104, 7, 8, 82, 141, 5, 143,
7, 145, 146, 147, 148, 149, 94, 151, 152, 153,
154, 81, 156, 157, 158, 107, 108, 107, 107, 88,
720, 87, 722, 723, 93, 177, 726, 727, 5, 92,
7, 104, 95, 106, 178, 9, 10, 104, 12, 106,
14, 15, 88, 17, 18, 19, 20, 93, 22, 23,
8, 5, 83, 7, 28, 70, 8, 11, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 14, 105, 52, 100,
101, 102, 103, 22, 104, 20, 106, 5, 109, 7,
111, 711, 31, 11, 115, 116, 31, 104, 104, 106,
121, 721, 123, 42, 724, 725, 719, 31, 721, 722,
683, 724, 725, 726, 8, 104, 21, 951, 42, 104,
104, 31, 107, 33, 34, 104, 31, 104, 67, 106,
88, 5, 67, 7, 73, 93, 88, 42, 73, 94,
95, 93, 97, 67, 5, 5, 7, 7, 8, 73,
11, 105, 126, 104, 128, 8, 130, 67, 132, 133,
134, 135, 67, 68, 17, 18, 105, 141, 73, 143,
105, 145, 146, 147, 148, 149, 81, 151, 152, 153,
154, 105, 156, 157, 158, 758, 759, 105, 104, 8,
106, 85, 104, 87, 106, 105, 90, 16, 17, 18,
105, 96, 104, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 107,
393, 27, 31, 393, 30, 31, 30, 84, 104, 86,
106, 474, 89, 1077, 91, 397, 42, 399, 400, 401,
31, 403, 104, 405, 106, 51, 31, 420, 107, 55,
420, 55, 104, 28, 106, 64, 31, 104, 67, 106,
414, 67, 71, 107, 108, 419, 31, 73, 104, 75,
1142, 104, 78, 77, 78, 81, 67, 42, 432, 103,
434, 1125, 67, 1127, 59, 31, 71, 33, 34, 107,
444, 445, 67, 447, 448, 5, 105, 7, 63, 105,
103, 105, 67, 457, 725, 726, 460, 461, 73, 463,
105, 465, 474, 467, 105, 469, 470, 1142, 1028, 31,
105, 67, 565, 105, 104, 1142, 106, 481, 5, 483,
1142, 108, 486, 487, 104, 4, 106, 491, 492, 493,
105, 503, 496, 104, 54, 106, 500, 104, 24, 106,
504, 97, 105, 1197, 1198, 67, 25, 26, 109, 105,
29, 104, 32, 106, 74, 104, 397, 106, 399, 400,
401, 40, 403, 104, 405, 106, 45, 104, 47, 48,
104, 50, 106, 105, 31, 628, 33, 34, 57, 105,
31, 60, 1236, 105, 85, 549, 550, 551, 552, 1010,
1011, 42, 645, 565, 1211, 31, 560, 561, 43, 44,
79, 37, 566, 1288, 1289, 1259, 1288, 104, 1290, 106,
67, 5, 1106, 7, 1268, 110, 67, 96, 111, 98,
395, 1141, 73, 104, 1288, 1289, 1290, 104, 62, 80,
104, 67, 1286, 14, 409, 410, 411, 412, 413, 107,
415, 416, 417, 418, 107, 112, 421, 422, 105, 104,
104, 106, 106, 5, 105, 7, 628, 107, 634, 11,
54, 1288, 503, 1290, 633, 104, 1288, 106, 1290, 105,
632, 635, 104, 645, 106, 722, 723, 1290, 393, 726,
74, 721, 397, 647, 399, 400, 401, 1207, 403, 104,
405, 106, 407, 127, 721, 129, 634, 131, 721, 752,
722, 723, 1142, 5, 726, 420, 140, 691, 142, 1142,
144, 104, 64, 106, 104, 104, 106, 106, 104, 683,
106, 685, 721, 687, 719, 721, 5, 722, 721, 724,
725, 726, 727, 721, 721, 104, 104, 106, 106, 703,
704, 175, 1092, 744, 1094, 652, 943, 654, 719, 720,
721, 722, 407, 724, 725, 726, 727, 728, 729, 722,
723, 946, 1208, 726, 727, 715, 729, 715, 964, 706,
734, 743, 736, 715, 738, 739, 706, 1103, 722, 723,
752, 706, 726, 727, 706, 729, 706, 1102, 503, 706,
762, 545, 711, 774, 758, 759, 89, 1192, 1123, 548,
719, 720, 721, 722, 723, 724, 725, 726, 727, 728,
729, 729, 726, 729, 711, 1094, 1111, 563, 715, 644,
717, 718, 719, 720, 721, 722, 723, 724, 725, 726,
727, 728, 729, 719, 720, 721, 722, 700, 724, 725,
726, 635, 728, 1244, 565, 742, 113, 744, 1288, 1289,
1290, 954, 702, 30, 31, 1288, 711, 1290, 1078, 735,
715, 4, 717, 718, 719, 720, 721, 722, 723, 724,
725, 726, 727, 728, 729, -1, 5, 177, 7, 702,
-1, -1, 11, 26, 27, -1, 29, 742, 31, 744,
67, 27, -1, 687, 30, 24, 73, 40, 75, 42,
-1, 78, 743, 32, 47, 48, -1, 50, -1, 703,
704, -1, 55, -1, 57, 51, 52, 53, -1, 55,
-1, 762, 65, 31, 67, -1, -1, -1, 105, 4,
73, -1, 40, 76, 42, -1, 79, 45, 81, -1,
-1, 77, 78, -1, 738, 739, -1, -1, 912, 913,
25, 26, 60, 96, 29, 98, 31, 49, 31, 67,
33, 34, 105, 55, -1, 73, -1, 42, 76, 105,
62, -1, 47, 48, 66, 50, -1, -1, -1, 694,
-1, 1028, 57, 947, 948, -1, 761, -1, 952, 423,
424, 4, 67, -1, 67, -1, 27, 105, 73, 433,
31, 435, 436, -1, 79, -1, 81, -1, 442, 443,
-1, 42, 446, 26, -1, -1, 29, -1, 31, -1,
51, 96, -1, 98, 55, -1, -1, 40, 743, -1,
105, -1, 105, -1, 47, 48, 67, 50, 1010, 1011,
-1, -1, 73, -1, 57, -1, -1, 762, 1101, -1,
81, -1, 27, -1, 67, 30, -1, 1021, 1022, -1,
73, -1, 22, 76, -1, 1028, 79, -1, -1, -1,
-1, -1, -1, -1, 105, -1, 51, 52, 53, 39,
-1, -1, -1, 96, 1028, 98, -1, -1, -1, 49,
-1, -1, 105, -1, 1058, 1059, 1060, 1061, 1062, 1063,
75, 61, 62, 78, -1, -1, 66, -1, -1, 69,
-1, -1, -1, -1, 1078, 75, -1, -1, 912, 913,
1084, -1, -1, -1, 1088, -1, -1, 1091, -1, 1101,
105, 1102, 1103, -1, -1, 1099, -1, -1, -1, 573,
-1, -1, 576, 577, -1, -1, 580, 1142, -1, 583,
-1, -1, 586, -1, -1, 589, -1, -1, 592, 934,
935, 595, -1, -1, 598, -1, -1, 601, -1, -1,
604, 1142, -1, 607, -1, -1, 610, -1, -1, 613,
614, 615, 616, 1102, 1103, 619, -1, -1, 622, -1,
1154, 1244, -1, 27, -1, 1159, 30, 31, -1, -1,
-1, -1, -1, -1, 638, 1102, 1103, -1, 42, 1106,
1107, -1, -1, -1, -1, -1, -1, 51, 52, 53,
-1, 55, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 65, -1, 67, -1, 669, 670, 671, 1291, 1210,
1211, -1, -1, -1, 1141, 1142, 680, 1102, 1103, -1,
-1, 1106, 1107, -1, -1, -1, 1220, -1, -1, 693,
-1, -1, -1, -1, 1058, 1059, 1060, 1061, 1062, 1063,
-1, 105, 1244, -1, 708, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 1141, 1142, -1, 1208,
-1, 1210, 1211, 1288, 1289, 1010, 1011, -1, -1, 1263,
1264, 1265, 1266, -1, -1, -1, 740, 741, -1, -1,
1207, 1208, 1209, 1210, 1211, -1, -1, -1, 1093, 1291,
1095, 1096, 1097, -1, -1, -1, -1, -1, -1, -1,
-1, 765, -1, -1, 768, 769, 770, -1, -1, -1,
-1, -1, -1, -1, -1, 779, -1, -1, -1, -1,
-1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 805, 806, -1, -1, 809, -1, 1092, -1, 1094,
814, 815, 816, -1, -1, -1, -1, 821, -1, -1,
-1, -1, -1, -1, 828, -1, -1, -1, -1, 833,
-1, -1, -1, -1, -1, -1, 840, 841, 842, 843,
844, 845, 846, -1, -1, 849, -1, -1, -1, -1,
854, 855, 856, 857, 858, -1, 1220, -1, -1, 863,
864, -1, -1, 867, -1, -1, 870, -1, -1, -1,
-1, 875, 876, -1, -1, 879, -1, -1, -1, -1,
884, -1, -1, -1, -1, 889, 890, 891, 892, 893,
894, 895, -1, -1, -1, -1, 900, -1, -1, -1,
-1, -1, -1, 907, 908, 909, 910, 911, -1, -1,
-1, -1, -1, -1, 918, 919, 920, 921, 284, -1,
-1, -1, 926, 927, 928, 929, 930, 293, -1, -1,
-1, 297, -1, 299, 4, 301, -1, 303, -1, -1,
-1, 307, -1, -1, -1, -1, 312, -1, -1, -1,
-1, -1, -1, 319, -1, 25, 26, 323, -1, 29,
-1, 31, 328, -1, -1, -1, 332, -1, -1, -1,
-1, 337, 42, 339, -1, -1, 342, 47, 48, -1,
50, 347, -1, -1, -1, 351, -1, 57, 354, -1,
356, -1, -1, -1, -1, 361, -1, 67, -1, 365,
-1, -1, -1, 73, -1, 371, -1, -1, 374, 79,
-1, 81, 378, -1, -1, 92, -1, -1, 384, -1,
-1, 4, 388, -1, -1, 1029, 96, -1, 98, -1,
-1, -1, -1, -1, 1038, 105, 1040, 1041, -1, -1,
1044, -1, -1, 26, 27, -1, 29, -1, 31, 1053,
1054, -1, -1, -1, -1, -1, -1, 40, -1, 42,
1064, -1, -1, 46, 47, 48, -1, 50, -1, 52,
53, -1, 55, 150, 57, 58, -1, -1, 155, 1083,
-1, 1085, -1, -1, 67, -1, -1, -1, -1, -1,
73, -1, -1, 76, 77, -1, 79, -1, 81, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 96, -1, 98, -1, -1, -1, 4,
-1, -1, 105, -1, -1, -1, -1, -1, -1, 1133,
-1, -1, -1, -1, -1, 1139, -1, -1, -1, -1,
25, 26, 27, -1, 29, 30, 31, -1, 1152, -1,
-1, 1155, -1, -1, 1158, -1, 1160, 42, -1, 1163,
-1, -1, 47, 48, -1, 50, 51, -1, -1, -1,
-1, 1175, 1176, 1177, 1178, 1179, 1180, -1, -1, -1,
1184, -1, 67, -1, 261, -1, -1, 1191, 73, -1,
-1, 268, -1, -1, -1, -1, 81, -1, -1, -1,
277, 278, -1, -1, 281, 282, -1, -1, -1, -1,
-1, -1, -1, 98, 1218, -1, -1, -1, -1, -1,
105, -1, -1, -1, 1228, -1, -1, -1, -1, 1233,
-1, -1, 309, -1, -1, -1, -1, -1, -1, 316,
317, -1, 4, -1, 321, 1249, -1, -1, 325, -1,
-1, -1, -1, -1, 331, -1, -1, 334, 335, -1,
-1, -1, -1, -1, 26, 1269, -1, 29, 1272, 31,
-1, 1275, 349, -1, 1278, -1, 353, -1, 40, -1,
42, 358, 359, -1, -1, 47, 48, -1, 50, -1,
367, 368, 369, 55, -1, 1299, -1, -1, -1, 376,
1304, -1, -1, 1307, -1, 67, -1, -1, -1, 386,
-1, 73, -1, -1, 76, 392, -1, 79, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 98, -1, -1, -1,
-1, -1, -1, 105, -1, -1, -1, -1, -1, 426,
427, -1, 429, -1, 431, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 0, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 451, -1, -1, -1, -1, -1,
-1, -1, 459, 749, 20, 21, 22, 23, 24, -1,
-1, 27, 28, -1, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, -1, 41, 42, 43, 44, -1,
46, -1, 489, 49, -1, 51, 52, 53, -1, 55,
56, -1, 58, 59, -1, 61, 62, 63, 64, 65,
66, 67, 4, 69, 70, 71, -1, 73, 4, 75,
76, 77, 78, -1, 80, 81, 82, 83, -1, -1,
-1, -1, -1, -1, 26, -1, -1, 29, -1, 31,
26, 97, -1, 29, -1, -1, 102, -1, 4, -1,
42, -1, -1, -1, 40, 47, 48, -1, 50, -1,
-1, 47, 48, -1, 50, -1, -1, -1, -1, 55,
26, 568, -1, 29, -1, 67, -1, -1, -1, -1,
-1, 73, -1, -1, 40, -1, -1, 79, -1, 81,
76, 47, 48, 79, 50, -1, -1, -1, -1, 55,
4, -1, -1, -1, -1, -1, 98, -1, -1, -1,
-1, -1, 98, 105, -1, -1, -1, 21, -1, 105,
76, -1, 26, 79, -1, 29, -1, -1, -1, -1,
-1, 35, 36, 630, 38, -1, 40, 41, -1, -1,
-1, -1, 98, 47, 48, -1, 50, -1, -1, 105,
-1, 27, -1, 57, 30, 31, -1, -1, 944, -1,
-1, -1, -1, -1, -1, -1, 42, -1, 72, -1,
-1, -1, 76, -1, -1, 79, 52, 53, -1, 55,
-1, -1, 58, -1, -1, 682, -1, 684, -1, -1,
-1, 67, -1, -1, 98, -1, -1, 73, -1, 75,
-1, -1, 78, -1, -1, 81, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 105,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 4, -1, -1, -1, 746,
747, 10, 11, -1, -1, -1, -1, -1, -1, -1,
757, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
-1, -1, -1, -1, -1, -1, 105, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 4, -1, -1, -1, -1, -1, 10, 11, -1,
-1, -1, -1, -1, -1, 932, 933, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, -1, -1, -1, -1,
-1, -1, 105, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 1034, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 1048, -1, -1, -1, 1052, -1, -1, -1, -1,
1057, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 1076,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 4, -1, -1, -1,
-1, -1, -1, 11, -1, 1112, -1, -1, -1, -1,
-1, 1118, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, -1, 86, -1,
-1, -1, -1, 91, -1, -1, -1, -1, 96, 97,
98, -1, -1, -1, -1, -1, -1, 105, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 1250, -1, -1, 1253, 4, 1255, -1,
1257, 8, 9, 10, 11, 12, -1, -1, -1, 16,
17, 18, -1, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 4, -1, -1, -1, 8, 9, 10, 11,
12, -1, -1, -1, 16, 17, 18, -1, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 4, -1, -1,
-1, 8, -1, 10, 11, -1, -1, -1, -1, -1,
-1, -1, -1, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 4, -1, -1, -1, 8, -1, 10, 11,
-1, -1, -1, -1, -1, -1, -1, -1, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 4, -1, -1,
-1, -1, -1, 10, 11, -1, -1, 14, -1, -1,
-1, -1, -1, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 4, -1, -1, -1, -1, -1, 10, 11,
-1, -1, 14, -1, -1, -1, -1, -1, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 4, -1, -1,
-1, 8, -1, 10, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 4, -1, -1, -1, -1, -1, 10, 11,
-1, -1, -1, -1, -1, -1, -1, -1, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint16 yystos[] =
{
0, 114, 120, 124, 419, 441, 0, 5, 7, 54,
74, 418, 20, 21, 22, 23, 24, 27, 28, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 41,
43, 44, 46, 51, 52, 53, 56, 58, 59, 61,
63, 64, 65, 67, 69, 71, 73, 77, 78, 80,
82, 83, 97, 102, 130, 140, 142, 144, 147, 149,
151, 153, 170, 176, 190, 202, 214, 222, 227, 229,
238, 241, 243, 245, 247, 339, 342, 345, 347, 350,
353, 359, 362, 430, 431, 432, 433, 434, 435, 436,
437, 438, 418, 420, 420, 420, 420, 420, 420, 420,
420, 420, 420, 420, 420, 420, 420, 420, 420, 420,
420, 420, 420, 420, 420, 420, 420, 420, 420, 420,
420, 420, 420, 420, 402, 402, 75, 194, 76, 192,
42, 183, 49, 55, 62, 66, 204, 209, 224, 356,
440, 81, 335, 70, 157, 4, 25, 26, 29, 40,
45, 47, 48, 50, 57, 60, 79, 96, 98, 249,
254, 257, 261, 264, 267, 273, 277, 279, 283, 299,
304, 305, 307, 308, 310, 439, 407, 420, 419, 4,
8, 10, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 115, 116, 119, 395, 425, 426, 427, 428, 123,
395, 169, 395, 11, 116, 189, 397, 428, 429, 141,
395, 88, 93, 116, 338, 340, 9, 11, 12, 16,
17, 18, 116, 148, 422, 424, 425, 246, 422, 150,
422, 242, 422, 240, 422, 17, 116, 201, 203, 390,
11, 116, 361, 363, 396, 425, 88, 93, 116, 341,
343, 94, 116, 349, 351, 390, 18, 116, 346, 348,
390, 391, 129, 422, 92, 95, 116, 352, 354, 146,
422, 116, 226, 371, 372, 373, 116, 237, 239, 391,
116, 143, 394, 428, 344, 422, 152, 422, 88, 93,
116, 228, 230, 12, 116, 139, 160, 85, 87, 90,
116, 175, 177, 116, 358, 360, 369, 396, 244, 422,
16, 17, 18, 116, 221, 223, 392, 393, 213, 422,
403, 418, 429, 420, 402, 420, 402, 420, 402, 420,
420, 208, 420, 420, 402, 420, 402, 420, 402, 420,
420, 420, 420, 420, 419, 420, 420, 420, 420, 419,
420, 420, 420, 104, 104, 402, 104, 106, 417, 8,
408, 424, 419, 104, 419, 104, 104, 106, 171, 104,
106, 398, 399, 401, 419, 419, 104, 419, 419, 398,
398, 423, 398, 398, 398, 398, 398, 419, 398, 364,
419, 419, 398, 419, 398, 419, 398, 419, 398, 419,
419, 398, 398, 398, 107, 374, 375, 14, 377, 378,
398, 419, 398, 419, 398, 398, 419, 419, 398, 161,
398, 419, 419, 419, 398, 398, 419, 370, 398, 398,
419, 398, 404, 405, 419, 195, 397, 191, 395, 182,
422, 205, 422, 355, 422, 210, 422, 365, 422, 334,
422, 155, 160, 276, 395, 272, 395, 266, 395, 253,
395, 248, 395, 258, 395, 260, 395, 263, 395, 309,
395, 282, 397, 298, 395, 278, 395, 402, 402, 419,
419, 419, 419, 117, 402, 402, 402, 402, 402, 402,
419, 419, 396, 376, 107, 379, 419, 368, 104, 106,
410, 406, 422, 104, 106, 196, 104, 104, 106, 184,
104, 106, 206, 104, 106, 357, 104, 106, 211, 104,
106, 225, 104, 106, 336, 104, 106, 158, 104, 106,
280, 104, 106, 274, 104, 106, 268, 104, 106, 255,
104, 106, 250, 104, 104, 104, 104, 106, 311, 104,
106, 284, 104, 106, 302, 280, 306, 306, 416, 409,
103, 121, 122, 125, 126, 83, 173, 105, 400, 144,
382, 374, 378, 380, 396, 107, 366, 419, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 105, 192,
249, 252, 254, 257, 261, 264, 267, 277, 279, 283,
356, 105, 105, 396, 103, 419, 131, 82, 128, 130,
144, 131, 128, 142, 420, 105, 402, 105, 108, 381,
382, 396, 411, 24, 32, 197, 198, 215, 217, 231,
233, 193, 105, 207, 207, 212, 207, 337, 159, 281,
275, 269, 256, 251, 259, 262, 265, 312, 285, 303,
402, 402, 402, 402, 419, 407, 419, 8, 43, 44,
132, 136, 145, 420, 145, 402, 88, 93, 116, 172,
174, 5, 421, 375, 54, 105, 403, 412, 414, 415,
427, 420, 420, 105, 190, 199, 200, 202, 204, 209,
224, 227, 229, 402, 232, 105, 151, 153, 176, 194,
245, 247, 105, 151, 153, 241, 243, 105, 105, 151,
153, 214, 241, 243, 105, 105, 151, 153, 105, 151,
153, 105, 151, 153, 176, 183, 335, 339, 342, 356,
105, 151, 153, 176, 183, 252, 335, 105, 151, 153,
176, 183, 247, 254, 257, 261, 264, 267, 270, 271,
273, 277, 279, 335, 339, 342, 105, 151, 153, 176,
183, 192, 249, 252, 299, 310, 335, 339, 345, 356,
105, 151, 153, 176, 192, 249, 252, 299, 310, 105,
151, 153, 176, 183, 194, 245, 247, 335, 339, 342,
356, 105, 151, 153, 176, 183, 194, 245, 247, 335,
339, 347, 350, 353, 356, 105, 151, 153, 176, 183,
192, 249, 252, 299, 310, 335, 339, 347, 350, 353,
356, 359, 362, 105, 151, 153, 176, 183, 192, 249,
252, 356, 21, 68, 105, 151, 153, 176, 183, 288,
293, 335, 105, 151, 153, 176, 183, 192, 249, 305,
308, 417, 8, 118, 420, 420, 402, 402, 147, 149,
151, 153, 154, 156, 127, 422, 154, 419, 419, 398,
383, 396, 419, 407, 407, 234, 395, 218, 422, 402,
194, 402, 402, 402, 216, 233, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
420, 420, 402, 402, 402, 402, 402, 402, 402, 402,
402, 419, 419, 133, 395, 135, 395, 162, 163, 157,
398, 162, 109, 421, 104, 106, 413, 413, 104, 106,
235, 104, 106, 219, 217, 116, 291, 292, 369, 116,
286, 287, 369, 104, 104, 106, 137, 105, 21, 35,
36, 38, 41, 72, 164, 166, 179, 186, 192, 249,
252, 296, 301, 310, 314, 402, 105, 110, 419, 402,
402, 402, 402, 104, 419, 104, 106, 289, 419, 402,
402, 419, 420, 420, 420, 420, 420, 420, 402, 419,
421, 416, 236, 220, 402, 402, 134, 138, 116, 294,
295, 366, 367, 165, 395, 116, 313, 316, 367, 178,
395, 185, 395, 300, 395, 85, 384, 389, 105, 105,
151, 153, 176, 183, 238, 105, 151, 153, 176, 183,
222, 297, 290, 105, 140, 144, 151, 153, 105, 140,
151, 153, 104, 368, 419, 104, 106, 167, 104, 419,
104, 106, 180, 104, 106, 187, 302, 421, 421, 402,
402, 105, 151, 153, 176, 183, 252, 273, 299, 310,
335, 105, 151, 153, 183, 247, 339, 342, 345, 347,
350, 356, 402, 402, 402, 402, 402, 111, 107, 402,
402, 402, 402, 402, 402, 402, 402, 297, 168, 315,
181, 188, 421, 421, 105, 105, 151, 153, 170, 176,
37, 105, 151, 153, 105, 151, 153, 176, 183, 105,
151, 153, 176, 183, 190, 112, 14, 385, 386, 402,
420, 402, 402, 421, 387, 84, 86, 89, 91, 317,
318, 319, 321, 322, 323, 326, 327, 330, 331, 107,
386, 396, 402, 419, 419, 419, 419, 421, 388, 104,
106, 320, 104, 106, 324, 104, 106, 328, 104, 106,
332, 421, 402, 402, 402, 402, 107, 105, 325, 329,
333, 421, 105, 245, 247, 339, 342, 347, 350, 356,
359, 105, 245, 247, 356, 359, 105, 194, 245, 247,
339, 342, 347, 350, 396, 402, 402, 402
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint16 yyr1[] =
{
0, 113, 114, 114, 114, 115, 116, 117, 118, 117,
119, 120, 121, 122, 122, 122, 122, 123, 124, 125,
126, 126, 126, 127, 128, 129, 130, 131, 131, 131,
132, 133, 134, 134, 134, 134, 134, 135, 136, 137,
137, 138, 138, 138, 138, 139, 140, 141, 142, 143,
144, 145, 145, 145, 145, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 156, 157, 158,
158, 159, 159, 159, 161, 160, 160, 162, 163, 163,
164, 164, 164, 164, 164, 164, 164, 164, 164, 164,
165, 166, 167, 167, 168, 168, 168, 168, 168, 169,
170, 171, 171, 172, 173, 173, 174, 174, 174, 175,
176, 177, 177, 177, 177, 178, 179, 180, 180, 181,
181, 181, 181, 181, 182, 183, 184, 184, 185, 186,
187, 187, 188, 188, 188, 188, 188, 188, 189, 190,
191, 192, 193, 193, 193, 193, 193, 193, 193, 194,
195, 196, 196, 197, 197, 197, 198, 198, 198, 198,
198, 198, 198, 198, 198, 199, 200, 201, 202, 203,
203, 204, 205, 206, 206, 207, 207, 207, 207, 207,
208, 209, 210, 211, 211, 212, 212, 212, 212, 212,
212, 213, 214, 215, 216, 216, 217, 218, 219, 219,
220, 220, 220, 220, 220, 220, 221, 222, 223, 223,
224, 225, 225, 226, 227, 228, 229, 230, 230, 230,
231, 232, 232, 233, 234, 235, 235, 236, 236, 236,
236, 236, 236, 237, 238, 239, 239, 240, 241, 242,
243, 244, 245, 246, 247, 248, 249, 250, 250, 251,
251, 251, 251, 251, 251, 251, 251, 251, 252, 252,
252, 252, 252, 252, 252, 252, 253, 254, 255, 255,
256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
256, 256, 256, 256, 257, 258, 259, 259, 259, 259,
259, 259, 259, 259, 259, 259, 259, 259, 260, 261,
262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
262, 262, 262, 262, 263, 264, 265, 265, 265, 265,
265, 265, 265, 265, 265, 265, 265, 265, 265, 265,
265, 265, 265, 265, 266, 267, 268, 268, 269, 269,
269, 269, 269, 269, 269, 269, 269, 269, 270, 270,
271, 271, 271, 271, 271, 271, 271, 272, 273, 274,
274, 275, 275, 275, 275, 275, 275, 275, 276, 277,
278, 279, 280, 280, 281, 281, 281, 281, 281, 281,
281, 281, 281, 282, 283, 284, 284, 285, 285, 285,
285, 285, 285, 285, 285, 286, 286, 287, 288, 289,
289, 290, 290, 290, 290, 290, 290, 290, 290, 290,
290, 290, 291, 291, 292, 293, 294, 294, 295, 296,
297, 297, 297, 297, 297, 297, 297, 297, 297, 297,
298, 299, 300, 301, 302, 302, 303, 303, 303, 303,
303, 303, 303, 303, 303, 304, 305, 306, 306, 306,
306, 306, 307, 308, 309, 310, 311, 311, 312, 312,
312, 312, 312, 312, 312, 312, 312, 313, 314, 315,
315, 315, 315, 316, 316, 317, 317, 318, 319, 320,
320, 321, 321, 321, 322, 323, 324, 324, 325, 325,
325, 325, 325, 325, 325, 325, 325, 326, 327, 328,
328, 329, 329, 329, 329, 329, 330, 331, 332, 332,
333, 333, 333, 333, 333, 333, 333, 333, 334, 335,
336, 336, 337, 337, 337, 338, 339, 340, 340, 340,
341, 342, 343, 343, 343, 344, 345, 346, 347, 348,
348, 349, 350, 351, 351, 351, 352, 353, 354, 354,
354, 355, 356, 357, 357, 358, 359, 360, 360, 361,
362, 364, 363, 363, 365, 366, 367, 368, 368, 370,
369, 372, 371, 373, 371, 371, 374, 375, 376, 376,
377, 378, 379, 379, 380, 381, 381, 382, 382, 383,
384, 385, 386, 387, 387, 388, 388, 389, 390, 391,
391, 392, 392, 393, 393, 394, 394, 395, 395, 396,
396, 397, 397, 397, 398, 398, 399, 400, 401, 402,
402, 402, 403, 404, 405, 406, 406, 407, 407, 408,
408, 408, 409, 409, 410, 410, 411, 411, 412, 412,
412, 413, 413, 414, 415, 416, 416, 417, 417, 418,
418, 419, 419, 420, 421, 421, 423, 422, 422, 424,
424, 424, 424, 424, 424, 424, 425, 425, 425, 426,
426, 426, 426, 426, 426, 426, 426, 426, 426, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 427,
427, 427, 427, 427, 427, 427, 427, 427, 427, 428,
429, 430, 431, 432, 433, 434, 435, 436, 437, 438,
438, 438, 438, 438, 438, 438, 438, 438, 438, 438,
438, 438, 439, 439, 439, 439, 439, 439, 439, 439,
439, 439, 439, 439, 439, 439, 440, 440, 440, 440,
441, 441, 441, 441, 441, 441, 441, 441, 441, 441,
441, 441, 441, 441, 441, 441, 441, 441, 441, 441,
441, 441, 441, 441, 441, 441, 441, 441, 441, 441,
441, 441, 441, 441, 441, 441, 441, 441
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 1, 1, 1, 1, 3, 0, 0, 6,
1, 13, 1, 0, 2, 2, 2, 1, 13, 1,
0, 2, 3, 1, 4, 1, 4, 0, 3, 3,
7, 1, 0, 2, 2, 2, 2, 1, 4, 1,
4, 0, 2, 2, 2, 1, 4, 1, 7, 1,
4, 0, 2, 2, 2, 2, 1, 4, 1, 4,
1, 4, 1, 4, 1, 1, 0, 3, 4, 1,
4, 0, 2, 2, 0, 3, 1, 1, 0, 3,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 4, 1, 4, 0, 3, 2, 2, 2, 1,
4, 1, 4, 1, 0, 4, 2, 2, 1, 1,
4, 2, 2, 2, 1, 1, 4, 1, 4, 0,
3, 2, 2, 2, 1, 4, 1, 3, 1, 4,
1, 4, 0, 2, 3, 2, 2, 2, 1, 4,
1, 7, 0, 3, 2, 2, 2, 2, 2, 4,
1, 1, 4, 1, 1, 1, 0, 2, 2, 2,
3, 3, 2, 3, 3, 2, 0, 1, 4, 2,
1, 4, 1, 1, 4, 0, 2, 2, 2, 2,
1, 4, 1, 1, 4, 0, 2, 2, 2, 2,
2, 1, 4, 3, 0, 3, 4, 1, 1, 4,
0, 3, 2, 2, 2, 2, 1, 4, 2, 1,
4, 1, 4, 1, 4, 1, 4, 2, 2, 1,
2, 0, 2, 5, 1, 1, 4, 0, 3, 2,
2, 2, 2, 1, 4, 2, 1, 1, 4, 1,
4, 1, 4, 1, 4, 1, 4, 1, 4, 0,
2, 2, 2, 3, 3, 3, 3, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 4, 1, 4,
0, 3, 3, 3, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 7, 1, 0, 3, 3, 3,
2, 3, 2, 2, 2, 2, 2, 2, 1, 7,
0, 3, 3, 3, 2, 2, 3, 2, 2, 2,
2, 2, 2, 2, 1, 7, 0, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 1, 4, 1, 4, 0, 3,
3, 2, 2, 2, 2, 2, 2, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 4, 1,
4, 0, 3, 3, 2, 2, 2, 3, 1, 4,
1, 4, 1, 4, 0, 3, 3, 3, 2, 2,
2, 2, 2, 1, 4, 1, 4, 0, 3, 3,
2, 2, 2, 3, 3, 2, 1, 1, 4, 1,
4, 0, 3, 3, 2, 2, 2, 2, 2, 2,
2, 2, 2, 1, 1, 7, 2, 1, 1, 7,
0, 3, 3, 2, 2, 2, 3, 3, 3, 3,
1, 4, 1, 4, 1, 4, 0, 3, 2, 2,
2, 3, 3, 3, 3, 2, 5, 0, 3, 3,
3, 3, 2, 5, 1, 4, 1, 4, 0, 3,
3, 2, 2, 2, 3, 3, 3, 1, 7, 0,
2, 2, 5, 2, 1, 1, 1, 1, 3, 1,
3, 1, 1, 1, 1, 3, 1, 4, 0, 2,
3, 2, 2, 2, 2, 2, 2, 1, 3, 1,
4, 0, 2, 3, 2, 2, 1, 3, 1, 4,
0, 3, 2, 2, 2, 2, 2, 2, 1, 4,
1, 4, 0, 2, 2, 1, 4, 2, 2, 1,
1, 4, 2, 2, 1, 1, 4, 1, 4, 2,
1, 1, 4, 2, 2, 1, 1, 4, 2, 2,
1, 1, 4, 1, 4, 1, 4, 2, 1, 1,
4, 0, 3, 1, 1, 2, 2, 0, 2, 0,
3, 0, 2, 0, 2, 1, 3, 2, 0, 2,
3, 2, 0, 2, 2, 0, 2, 0, 5, 5,
5, 4, 4, 0, 2, 0, 5, 5, 1, 1,
1, 1, 1, 1, 1, 1, 2, 2, 1, 1,
1, 2, 2, 1, 2, 4, 1, 1, 1, 0,
2, 2, 3, 2, 1, 0, 1, 0, 2, 0,
2, 3, 0, 5, 1, 4, 0, 3, 1, 3,
3, 1, 4, 1, 1, 0, 4, 2, 5, 1,
1, 0, 2, 2, 0, 1, 0, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 3, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 4, 4, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 4, 3, 4, 4, 4, 4, 4
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (&yylloc, scanner, param, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (N) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
} \
else \
{ \
(Current).first_line = (Current).last_line = \
YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = \
YYRHSLOC (Rhs, 0).last_column; \
} \
while (0)
#endif
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* YY_LOCATION_PRINT -- Print the location on the stream.
This macro was not mandated originally: define only if we know
we won't break user code: when these are the locations we know. */
#ifndef YY_LOCATION_PRINT
# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
/* Print *YYLOCP on YYO. Private, do not rely on its existence. */
YY_ATTRIBUTE_UNUSED
static int
yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp)
{
int res = 0;
int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0;
if (0 <= yylocp->first_line)
{
res += YYFPRINTF (yyo, "%d", yylocp->first_line);
if (0 <= yylocp->first_column)
res += YYFPRINTF (yyo, ".%d", yylocp->first_column);
}
if (0 <= yylocp->last_line)
{
if (yylocp->first_line < yylocp->last_line)
{
res += YYFPRINTF (yyo, "-%d", yylocp->last_line);
if (0 <= end_col)
res += YYFPRINTF (yyo, ".%d", end_col);
}
else if (0 <= end_col && yylocp->first_column < end_col)
res += YYFPRINTF (yyo, "-%d", end_col);
}
return res;
}
# define YY_LOCATION_PRINT(File, Loc) \
yy_location_print_ (File, &(Loc))
# else
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value, Location, scanner, param); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*-----------------------------------.
| Print this symbol's value on YYO. |
`-----------------------------------*/
static void
yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param)
{
FILE *yyoutput = yyo;
YYUSE (yyoutput);
YYUSE (yylocationp);
YYUSE (scanner);
YYUSE (param);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyo, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*---------------------------.
| Print this symbol on YYO. |
`---------------------------*/
static void
yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param)
{
YYFPRINTF (yyo, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
YY_LOCATION_PRINT (yyo, *yylocationp);
YYFPRINTF (yyo, ": ");
yy_symbol_value_print (yyo, yytype, yyvaluep, yylocationp, scanner, param);
YYFPRINTF (yyo, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, void *scanner, struct yang_parameter *param)
{
unsigned long yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
, &(yylsp[(yyi + 1) - (yynrhs)]) , scanner, param);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, yylsp, Rule, scanner, param); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return (YYSIZE_T) (yystpcpy (yyres, yystr) - yyres);
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
default: /* Avoid compiler warnings. */
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, void *scanner, struct yang_parameter *param)
{
YYUSE (yyvaluep);
YYUSE (yylocationp);
YYUSE (scanner);
YYUSE (param);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
switch (yytype)
{
case 115: /* tmp_string */
{ free((((*yyvaluep).p_str)) ? *((*yyvaluep).p_str) : NULL); }
break;
case 210: /* pattern_arg_str */
{ free(((*yyvaluep).str)); }
break;
case 399: /* semicolom */
{ free(((*yyvaluep).str)); }
break;
case 401: /* curly_bracket_open */
{ free(((*yyvaluep).str)); }
break;
case 405: /* string_opt_part1 */
{ free(((*yyvaluep).str)); }
break;
case 430: /* type_ext_alloc */
{ yang_type_free(param->module->ctx, ((*yyvaluep).v)); }
break;
case 431: /* typedef_ext_alloc */
{ yang_type_free(param->module->ctx, &((struct lys_tpdf *)((*yyvaluep).v))->type); }
break;
default:
break;
}
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*----------.
| yyparse. |
`----------*/
int
yyparse (void *scanner, struct yang_parameter *param)
{
/* The lookahead symbol. */
int yychar;
char *s = NULL, *tmp_s = NULL, *ext_name = NULL;
struct lys_module *trg = NULL;
struct lys_node *tpdf_parent = NULL, *data_node = NULL;
struct lys_ext_instance_complex *ext_instance = NULL;
int is_ext_instance;
void *actual = NULL;
enum yytokentype backup_type, actual_type = MODULE_KEYWORD;
int64_t cnt_val = 0;
int is_value = 0;
void *yang_type = NULL;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Location data for the lookahead symbol. */
static YYLTYPE yyloc_default
# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
= { 1, 1, 1, 1 }
# endif
;
YYLTYPE yylloc = yyloc_default;
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
'yyls': related to locations.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
/* The location stack. */
YYLTYPE yylsa[YYINITDEPTH];
YYLTYPE *yyls;
YYLTYPE *yylsp;
/* The locations where the error started and ended. */
YYLTYPE yyerror_range[3];
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
YYLTYPE yyloc;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yylsp = yyls = yylsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* User initialization code. */
{ yylloc.last_column = 0;
if (param->flags & EXT_INSTANCE_SUBSTMT) {
is_ext_instance = 1;
ext_instance = (struct lys_ext_instance_complex *)param->actual_node;
ext_name = (char *)param->data_node;
} else {
is_ext_instance = 0;
}
yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */
param->value = &s;
param->data_node = (void **)&data_node;
param->actual_node = &actual;
backup_type = NODE;
trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module;
}
yylsp[0] = yylloc;
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = (yytype_int16) yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1);
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
YYLTYPE *yyls1 = yyls;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yyls1, yysize * sizeof (*yylsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
yyls = yyls1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
YYSTACK_RELOCATE (yyls_alloc, yyls);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
yylsp = yyls + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, &yylloc, scanner);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
*++yylsp = yylloc;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
/* Default location. */
YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen);
yyerror_range[1] = yyloc;
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 5:
{ if (yyget_text(scanner)[0] == '"') {
char *tmp;
s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) {
YYABORT;
}
s = tmp;
} else {
s = calloc(1, yyget_leng(scanner) - 1);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2);
}
(yyval.p_str) = &s;
}
break;
case 8:
{ if (yyget_leng(scanner) > 2) {
int length_s = strlen(s), length_tmp = yyget_leng(scanner);
char *tmp;
tmp = realloc(s, length_s + length_tmp - 1);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
s = tmp;
if (yyget_text(scanner)[0] == '"') {
if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) {
YYABORT;
}
s = tmp;
} else {
memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2);
s[length_s + length_tmp - 2] = '\0';
}
}
}
break;
case 10:
{ if (param->submodule) {
free(s);
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module");
YYABORT;
}
trg = param->module;
yang_read_common(trg,s,MODULE_KEYWORD);
s = NULL;
actual_type = MODULE_KEYWORD;
}
break;
case 12:
{ if (!param->module->ns) {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module");
YYABORT;
}
if (!param->module->prefix) {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module");
YYABORT;
}
}
break;
case 13:
{ (yyval.i) = 0; }
break;
case 14:
{ if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) {
YYABORT;
}
(yyval.i) = 1;
s = NULL;
}
break;
case 15:
{ if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 16:
{ if (yang_read_prefix(trg, NULL, s)) {
YYABORT;
}
s = NULL;
}
break;
case 17:
{ if (!param->submodule) {
free(s);
LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL);
YYABORT;
}
trg = (struct lys_module *)param->submodule;
yang_read_common(trg,s,MODULE_KEYWORD);
s = NULL;
actual_type = SUBMODULE_KEYWORD;
}
break;
case 19:
{ if (!param->submodule->prefix) {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule");
YYABORT;
}
if (!(yyvsp[0].i)) {
/* check version compatibility with the main module */
if (param->module->version > 1) {
LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL);
YYABORT;
}
}
}
break;
case 20:
{ (yyval.i) = 0; }
break;
case 21:
{ if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) {
YYABORT;
}
(yyval.i) = 1;
s = NULL;
}
break;
case 23:
{ backup_type = actual_type;
actual_type = YANG_VERSION_KEYWORD;
}
break;
case 25:
{ backup_type = actual_type;
actual_type = NAMESPACE_KEYWORD;
}
break;
case 30:
{ actual_type = (yyvsp[-4].token);
backup_type = NODE;
actual = NULL;
}
break;
case 31:
{ YANG_ADDELEM(trg->imp, trg->imp_size, "imports");
/* HACK for unres */
((struct lys_import *)actual)->module = (struct lys_module *)s;
s = NULL;
(yyval.token) = actual_type;
actual_type = IMPORT_KEYWORD;
}
break;
case 32:
{ (yyval.i) = 0; }
break;
case 33:
{ if (yang_read_prefix(trg, actual, s)) {
YYABORT;
}
s = NULL;
}
break;
case 34:
{ if (trg->version != 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description");
free(s);
YYABORT;
}
if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.i) = (yyvsp[-1].i);
}
break;
case 35:
{ if (trg->version != 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference");
free(s);
YYABORT;
}
if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.i) = (yyvsp[-1].i);
}
break;
case 36:
{ if ((yyvsp[-1].i)) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import");
free(s);
YYABORT;
}
memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1);
free(s);
s = NULL;
(yyval.i) = 1;
}
break;
case 37:
{ YANG_ADDELEM(trg->inc, trg->inc_size, "includes");
/* HACK for unres */
((struct lys_include *)actual)->submodule = (struct lys_submodule *)s;
s = NULL;
(yyval.token) = actual_type;
actual_type = INCLUDE_KEYWORD;
}
break;
case 38:
{ actual_type = (yyvsp[-1].token);
backup_type = NODE;
actual = NULL;
}
break;
case 41:
{ (yyval.i) = 0; }
break;
case 42:
{ if (trg->version != 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description");
free(s);
YYABORT;
}
if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.i) = (yyvsp[-1].i);
}
break;
case 43:
{ if (trg->version != 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference");
free(s);
YYABORT;
}
if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.i) = (yyvsp[-1].i);
}
break;
case 44:
{ if ((yyvsp[-1].i)) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include");
free(s);
YYABORT;
}
memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1);
free(s);
s = NULL;
(yyval.i) = 1;
}
break;
case 45:
{ backup_type = actual_type;
actual_type = REVISION_DATE_KEYWORD;
}
break;
case 47:
{ (yyval.token) = actual_type;
if (is_ext_instance) {
if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, s,
0, LY_STMT_BELONGSTO)) {
YYABORT;
}
} else {
if (param->submodule->prefix) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule");
free(s);
YYABORT;
}
if (!ly_strequal(s, param->submodule->belongsto->name, 0)) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to");
free(s);
YYABORT;
}
free(s);
}
s = NULL;
actual_type = BELONGS_TO_KEYWORD;
}
break;
case 48:
{ if (is_ext_instance) {
if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", s,
LY_STMT_BELONGSTO, LY_STMT_PREFIX)) {
YYABORT;
}
} else {
if (yang_read_prefix(trg, NULL, s)) {
YYABORT;
}
}
s = NULL;
actual_type = (yyvsp[-4].token);
}
break;
case 49:
{ backup_type = actual_type;
actual_type = PREFIX_KEYWORD;
}
break;
case 52:
{ if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 53:
{ if (yang_read_common(trg, s, CONTACT_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 54:
{ if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 55:
{ if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) {
YYABORT;
}
s=NULL;
}
break;
case 56:
{ backup_type = actual_type;
actual_type = ORGANIZATION_KEYWORD;
}
break;
case 58:
{ backup_type = actual_type;
actual_type = CONTACT_KEYWORD;
}
break;
case 60:
{ backup_type = actual_type;
actual_type = DESCRIPTION_KEYWORD;
}
break;
case 62:
{ backup_type = actual_type;
actual_type = REFERENCE_KEYWORD;
}
break;
case 64:
{ if (trg->rev_size) {
struct lys_revision *tmp;
tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
trg->rev = tmp;
}
}
break;
case 65:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!is_ext_instance) {
YANG_ADDELEM(trg->rev, trg->rev_size, "revisions");
}
memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE);
free(s);
s = NULL;
actual_type = REVISION_KEYWORD;
}
break;
case 67:
{ int i;
/* check uniqueness of the revision date - not required by RFC */
for (i = 0; i < (trg->rev_size - 1); i++) {
if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) {
LOGWRN(trg->ctx, "Module's revisions are not unique (%s).",
trg->rev[trg->rev_size - 1].date);
break;
}
}
}
break;
case 68:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 72:
{ if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 73:
{ if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 74:
{ s = strdup(yyget_text(scanner));
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
if (lyp_check_date(trg->ctx, s)) {
free(s);
YYABORT;
}
}
break;
case 76:
{ if (lyp_check_date(trg->ctx, s)) {
free(s);
YYABORT;
}
}
break;
case 77:
{ void *tmp;
if (trg->tpdf_size) {
tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
trg->tpdf = tmp;
}
if (trg->features_size) {
tmp = realloc(trg->features, trg->features_size * sizeof *trg->features);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
trg->features = tmp;
}
if (trg->ident_size) {
tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
trg->ident = tmp;
}
if (trg->augment_size) {
tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
trg->augment = tmp;
}
if (trg->extensions_size) {
tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
trg->extensions = tmp;
}
}
break;
case 78:
{ /* check the module with respect to the context now */
if (!param->submodule) {
switch (lyp_ctx_check_module(trg)) {
case -1:
YYABORT;
case 0:
break;
case 1:
/* it's already there */
param->flags |= YANG_EXIST_MODULE;
YYABORT;
}
}
param->flags &= (~YANG_REMOVE_IMPORT);
if (yang_check_imports(trg, param->unres)) {
YYABORT;
}
actual = NULL;
}
break;
case 79:
{ actual = NULL; }
break;
case 90:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions");
trg->extensions_size--;
((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s);
((struct lys_ext *)actual)->module = trg;
if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) {
trg->extensions_size++;
YYABORT;
}
trg->extensions_size++;
s = NULL;
actual_type = EXTENSION_KEYWORD;
}
break;
case 91:
{ struct lys_ext *ext = actual;
ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 96:
{ if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension");
YYABORT;
}
((struct lys_ext *)actual)->flags |= (yyvsp[0].i);
}
break;
case 97:
{ if (yang_read_description(trg, actual, s, "extension", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 98:
{ if (yang_read_reference(trg, actual, s, "extension", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 99:
{ (yyval.token) = actual_type;
if (is_ext_instance) {
if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, s,
0, LY_STMT_ARGUMENT)) {
YYABORT;
}
} else {
if (((struct lys_ext *)actual)->argument) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension");
free(s);
YYABORT;
}
((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s);
}
s = NULL;
actual_type = ARGUMENT_KEYWORD;
}
break;
case 100:
{ actual_type = (yyvsp[-1].token); }
break;
case 103:
{ (yyval.uint) = (yyvsp[0].uint);
backup_type = actual_type;
actual_type = YIN_ELEMENT_KEYWORD;
}
break;
case 105:
{ if (is_ext_instance) {
int c;
const char ***p;
uint8_t *val;
struct lyext_substmt *info;
c = 0;
p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info);
if (info->cardinality >= LY_STMT_CARD_SOME) {
/* get the index in the array to add new item */
for (c = 0; p[0][c + 1]; c++);
val = (uint8_t *)p[1];
} else {
val = (uint8_t *)(p + 1);
}
val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2;
} else {
((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint);
}
}
break;
case 106:
{ (yyval.uint) = LYS_YINELEM; }
break;
case 107:
{ (yyval.uint) = 0; }
break;
case 108:
{ if (!strcmp(s, "true")) {
(yyval.uint) = LYS_YINELEM;
} else if (!strcmp(s, "false")) {
(yyval.uint) = 0;
} else {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s);
free(s);
YYABORT;
}
free(s);
s = NULL;
}
break;
case 109:
{ (yyval.i) = (yyvsp[0].i);
backup_type = actual_type;
actual_type = STATUS_KEYWORD;
}
break;
case 110:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 111:
{ (yyval.i) = LYS_STATUS_CURR; }
break;
case 112:
{ (yyval.i) = LYS_STATUS_OBSLT; }
break;
case 113:
{ (yyval.i) = LYS_STATUS_DEPRC; }
break;
case 114:
{ if (!strcmp(s, "current")) {
(yyval.i) = LYS_STATUS_CURR;
} else if (!strcmp(s, "obsolete")) {
(yyval.i) = LYS_STATUS_OBSLT;
} else if (!strcmp(s, "deprecated")) {
(yyval.i) = LYS_STATUS_DEPRC;
} else {
LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s);
free(s);
YYABORT;
}
free(s);
s = NULL;
}
break;
case 115:
{ /* check uniqueness of feature's names */
if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) {
free(s);
YYABORT;
}
(yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
YANG_ADDELEM(trg->features, trg->features_size, "features");
((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s);
((struct lys_feature *)actual)->module = trg;
s = NULL;
actual_type = FEATURE_KEYWORD;
}
break;
case 116:
{ actual = (yyvsp[-1].backup_token).actual;
actual_type = (yyvsp[-1].backup_token).token;
}
break;
case 118:
{ struct lys_iffeature *tmp;
if (((struct lys_feature *)actual)->iffeature_size) {
tmp = realloc(((struct lys_feature *)actual)->iffeature,
((struct lys_feature *)actual)->iffeature_size * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_feature *)actual)->iffeature = tmp;
}
}
break;
case 121:
{ if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature");
YYABORT;
}
((struct lys_feature *)actual)->flags |= (yyvsp[0].i);
}
break;
case 122:
{ if (yang_read_description(trg, actual, s, "feature", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 123:
{ if (yang_read_reference(trg, actual, s, "feature", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 124:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
switch (actual_type) {
case FEATURE_KEYWORD:
YANG_ADDELEM(((struct lys_feature *)actual)->iffeature,
((struct lys_feature *)actual)->iffeature_size, "if-features");
break;
case IDENTITY_KEYWORD:
if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity");
free(s);
YYABORT;
}
YANG_ADDELEM(((struct lys_ident *)actual)->iffeature,
((struct lys_ident *)actual)->iffeature_size, "if-features");
break;
case ENUM_KEYWORD:
if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature");
free(s);
YYABORT;
}
YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature,
((struct lys_type_enum *)actual)->iffeature_size, "if-features");
break;
case BIT_KEYWORD:
if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit");
free(s);
YYABORT;
}
YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature,
((struct lys_type_bit *)actual)->iffeature_size, "if-features");
break;
case REFINE_KEYWORD:
if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature");
free(s);
YYABORT;
}
YANG_ADDELEM(((struct lys_refine *)actual)->iffeature,
((struct lys_refine *)actual)->iffeature_size, "if-features");
break;
case EXTENSION_INSTANCE:
/* nothing change */
break;
default:
/* lys_node_* */
YANG_ADDELEM(((struct lys_node *)actual)->iffeature,
((struct lys_node *)actual)->iffeature_size, "if-features");
break;
}
((struct lys_iffeature *)actual)->features = (struct lys_feature **)s;
s = NULL;
actual_type = IF_FEATURE_KEYWORD;
}
break;
case 125:
{ actual = (yyvsp[-1].backup_token).actual;
actual_type = (yyvsp[-1].backup_token).token;
}
break;
case 128:
{ const char *tmp;
tmp = lydict_insert_zc(trg->ctx, s);
s = NULL;
if (dup_identities_check(tmp, trg)) {
lydict_remove(trg->ctx, tmp);
YYABORT;
}
(yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
YANG_ADDELEM(trg->ident, trg->ident_size, "identities");
((struct lys_ident *)actual)->name = tmp;
((struct lys_ident *)actual)->module = trg;
actual_type = IDENTITY_KEYWORD;
}
break;
case 129:
{ actual = (yyvsp[-1].backup_token).actual;
actual_type = (yyvsp[-1].backup_token).token;
}
break;
case 131:
{ void *tmp;
if (((struct lys_ident *)actual)->base_size) {
tmp = realloc(((struct lys_ident *)actual)->base,
((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_ident *)actual)->base = tmp;
}
if (((struct lys_ident *)actual)->iffeature_size) {
tmp = realloc(((struct lys_ident *)actual)->iffeature,
((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_ident *)actual)->iffeature = tmp;
}
}
break;
case 133:
{ void *identity;
if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) {
free(s);
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity");
YYABORT;
}
identity = actual;
YANG_ADDELEM(((struct lys_ident *)actual)->base,
((struct lys_ident *)actual)->base_size, "bases");
*((struct lys_ident **)actual) = (struct lys_ident *)s;
s = NULL;
actual = identity;
}
break;
case 135:
{ if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity");
YYABORT;
}
((struct lys_ident *)actual)->flags |= (yyvsp[0].i);
}
break;
case 136:
{ if (yang_read_description(trg, actual, s, "identity", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 137:
{ if (yang_read_reference(trg, actual, s, "identity", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 138:
{ backup_type = actual_type;
actual_type = BASE_KEYWORD;
}
break;
case 140:
{ tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual;
(yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) {
free(s);
YYABORT;
}
switch (actual_type) {
case MODULE_KEYWORD:
case SUBMODULE_KEYWORD:
YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs");
break;
case GROUPING_KEYWORD:
YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf,
((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs");
break;
case CONTAINER_KEYWORD:
YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf,
((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs");
break;
case LIST_KEYWORD:
YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf,
((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs");
break;
case RPC_KEYWORD:
case ACTION_KEYWORD:
YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf,
((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs");
break;
case INPUT_KEYWORD:
case OUTPUT_KEYWORD:
YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf,
((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs");
break;
case NOTIFICATION_KEYWORD:
YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf,
((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs");
break;
case EXTENSION_INSTANCE:
/* typedef is already allocated */
break;
default:
/* another type of nodetype is error*/
LOGINT(trg->ctx);
free(s);
YYABORT;
}
((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s);
((struct lys_tpdf *)actual)->module = trg;
s = NULL;
actual_type = TYPEDEF_KEYWORD;
}
break;
case 141:
{ if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef");
YYABORT;
}
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
}
break;
case 142:
{ (yyval.nodes).node.ptr_tpdf = actual;
(yyval.nodes).node.flag = 0;
}
break;
case 143:
{ (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;
(yyval.nodes) = (yyvsp[-2].nodes);
}
break;
case 144:
{ if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 145:
{ if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 146:
{ if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i);
}
break;
case 147:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 148:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 149:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 150:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) {
YYABORT;
}
s = NULL;
actual_type = TYPE_KEYWORD;
}
break;
case 153:
{ if (((struct yang_type *)actual)->base == LY_TYPE_STRING &&
((struct yang_type *)actual)->type->info.str.pat_count) {
void *tmp;
tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns,
((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct yang_type *)actual)->type->info.str.patterns = tmp;
#ifdef LY_ENABLED_CACHE
if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) {
tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre,
2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp;
}
#endif
}
if (((struct yang_type *)actual)->base == LY_TYPE_UNION) {
struct lys_type *tmp;
tmp = realloc(((struct yang_type *)actual)->type->info.uni.types,
((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct yang_type *)actual)->type->info.uni.types = tmp;
}
if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) {
struct lys_ident **tmp;
tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref,
((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct yang_type *)actual)->type->info.ident.ref = tmp;
}
}
break;
case 157:
{ if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) {
YYABORT;
}
}
break;
case 158:
{ /* leafref_specification */
if (yang_read_leafref_path(trg, actual, s)) {
YYABORT;
}
s = NULL;
}
break;
case 159:
{ /* identityref_specification */
if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base");
return EXIT_FAILURE;
}
((struct yang_type *)actual)->base = LY_TYPE_IDENT;
yang_type = actual;
YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref,
((struct yang_type *)actual)->type->info.ident.count, "identity refs");
*((struct lys_ident **)actual) = (struct lys_ident *)s;
actual = yang_type;
s = NULL;
}
break;
case 162:
{ if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) {
YYABORT;
}
}
break;
case 165:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 166:
{ struct yang_type *stype = (struct yang_type *)actual;
(yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (stype->base != 0 && stype->base != LY_TYPE_UNION) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement.");
YYABORT;
}
stype->base = LY_TYPE_UNION;
if (strcmp(stype->name, "union")) {
/* type can be a substatement only in "union" type, not in derived types */
LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type");
YYABORT;
}
YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types")
actual_type = UNION_KEYWORD;
}
break;
case 167:
{ (yyval.uint) = (yyvsp[0].uint);
backup_type = actual_type;
actual_type = FRACTION_DIGITS_KEYWORD;
}
break;
case 168:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 169:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 170:
{ char *endptr = NULL;
unsigned long val;
errno = 0;
val = strtoul(s, &endptr, 10);
if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits");
free(s);
s = NULL;
YYABORT;
}
(yyval.uint) = (uint32_t) val;
free(s);
s =NULL;
}
break;
case 171:
{ actual = (yyvsp[-1].backup_token).actual;
actual_type = (yyvsp[-1].backup_token).token;
}
break;
case 172:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) {
YYABORT;
}
actual_type = LENGTH_KEYWORD;
s = NULL;
}
break;
case 175:
{ switch (actual_type) {
case MUST_KEYWORD:
(yyval.str) = "must";
break;
case LENGTH_KEYWORD:
(yyval.str) = "length";
break;
case RANGE_KEYWORD:
(yyval.str) = "range";
break;
default:
LOGINT(trg->ctx);
YYABORT;
break;
}
}
break;
case 176:
{ if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 177:
{ if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 178:
{ if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 179:
{ if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 180:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
}
break;
case 181:
{struct lys_restr *pattern = actual;
actual = NULL;
#ifdef LY_ENABLED_CACHE
if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE &&
!(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) {
unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1);
YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns");
}
#endif
if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) {
YYABORT;
}
actual_type = (yyvsp[-2].backup_token).token;
actual = (yyvsp[-2].backup_token).actual;
}
break;
case 182:
{ if (actual_type != EXTENSION_INSTANCE) {
if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) {
free(s);
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement.");
YYABORT;
}
((struct yang_type *)actual)->base = LY_TYPE_STRING;
YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns,
((struct yang_type *)actual)->type->info.str.pat_count, "patterns");
}
(yyval.str) = s;
s = NULL;
actual_type = PATTERN_KEYWORD;
}
break;
case 183:
{ (yyval.ch) = 0x06; }
break;
case 184:
{ (yyval.ch) = (yyvsp[-1].ch); }
break;
case 185:
{ (yyval.ch) = 0x06; /* ACK */ }
break;
case 186:
{ if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier");
YYABORT;
}
if ((yyvsp[-1].ch) != 0x06) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern");
YYABORT;
}
(yyval.ch) = (yyvsp[0].ch);
}
break;
case 187:
{ if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 188:
{ if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 189:
{ if (yang_read_description(trg, actual, s, "pattern", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 190:
{ if (yang_read_reference(trg, actual, s, "pattern", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 191:
{ backup_type = actual_type;
actual_type = MODIFIER_KEYWORD;
}
break;
case 192:
{ if (!strcmp(s, "invert-match")) {
(yyval.ch) = 0x15;
free(s);
s = NULL;
} else {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s);
free(s);
YYABORT;
}
}
break;
case 193:
{ struct lys_type_enum * tmp;
cnt_val = 0;
tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm,
((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct yang_type *)actual)->type->info.enums.enm = tmp;
}
break;
case 196:
{ if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) {
YYABORT;
}
actual = (yyvsp[-1].backup_token).actual;
actual_type = (yyvsp[-1].backup_token).token;
}
break;
case 197:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = yang_type = actual;
YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums");
if (yang_read_enum(trg->ctx, yang_type, actual, s)) {
YYABORT;
}
s = NULL;
is_value = 0;
actual_type = ENUM_KEYWORD;
}
break;
case 199:
{ if (((struct lys_type_enum *)actual)->iffeature_size) {
struct lys_iffeature *tmp;
tmp = realloc(((struct lys_type_enum *)actual)->iffeature,
((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_type_enum *)actual)->iffeature = tmp;
}
}
break;
case 202:
{ if (is_value) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum");
YYABORT;
}
((struct lys_type_enum *)actual)->value = (yyvsp[0].i);
/* keep the highest enum value for automatic increment */
if ((yyvsp[0].i) >= cnt_val) {
cnt_val = (yyvsp[0].i) + 1;
}
is_value = 1;
}
break;
case 203:
{ if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum");
YYABORT;
}
((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i);
}
break;
case 204:
{ if (yang_read_description(trg, actual, s, "enum", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 205:
{ if (yang_read_reference(trg, actual, s, "enum", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 206:
{ (yyval.i) = (yyvsp[0].i);
backup_type = actual_type;
actual_type = VALUE_KEYWORD;
}
break;
case 207:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 208:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 209:
{ /* convert it to int32_t */
int64_t val;
char *endptr;
val = strtoll(s, &endptr, 10);
if (val < INT32_MIN || val > INT32_MAX || *endptr) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value");
free(s);
YYABORT;
}
free(s);
s = NULL;
(yyval.i) = (int32_t) val;
}
break;
case 210:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 213:
{ backup_type = actual_type;
actual_type = PATH_KEYWORD;
}
break;
case 215:
{ (yyval.i) = (yyvsp[0].i);
backup_type = actual_type;
actual_type = REQUIRE_INSTANCE_KEYWORD;
}
break;
case 216:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 217:
{ (yyval.i) = 1; }
break;
case 218:
{ (yyval.i) = -1; }
break;
case 219:
{ if (!strcmp(s,"true")) {
(yyval.i) = 1;
} else if (!strcmp(s,"false")) {
(yyval.i) = -1;
} else {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance");
free(s);
YYABORT;
}
free(s);
s = NULL;
}
break;
case 220:
{ struct lys_type_bit * tmp;
cnt_val = 0;
tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit,
((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct yang_type *)actual)->type->info.bits.bit = tmp;
}
break;
case 223:
{ if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) {
YYABORT;
}
actual = (yyvsp[-2].backup_token).actual;
actual_type = (yyvsp[-2].backup_token).token;
}
break;
case 224:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = yang_type = actual;
YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit,
((struct yang_type *)actual)->type->info.bits.count, "bits");
if (yang_read_bit(trg->ctx, yang_type, actual, s)) {
YYABORT;
}
s = NULL;
is_value = 0;
actual_type = BIT_KEYWORD;
}
break;
case 226:
{ if (((struct lys_type_bit *)actual)->iffeature_size) {
struct lys_iffeature *tmp;
tmp = realloc(((struct lys_type_bit *)actual)->iffeature,
((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_type_bit *)actual)->iffeature = tmp;
}
}
break;
case 229:
{ if (is_value) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit");
YYABORT;
}
((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint);
/* keep the highest position value for automatic increment */
if ((yyvsp[0].uint) >= cnt_val) {
cnt_val = (yyvsp[0].uint) + 1;
}
is_value = 1;
}
break;
case 230:
{ if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit");
YYABORT;
}
((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i);
}
break;
case 231:
{ if (yang_read_description(trg, actual, s, "bit", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 232:
{ if (yang_read_reference(trg, actual, s, "bit", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 233:
{ (yyval.uint) = (yyvsp[0].uint);
backup_type = actual_type;
actual_type = POSITION_KEYWORD;
}
break;
case 234:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 235:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 236:
{ /* convert it to uint32_t */
unsigned long val;
char *endptr = NULL;
errno = 0;
val = strtoul(s, &endptr, 10);
if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position");
free(s);
YYABORT;
}
free(s);
s = NULL;
(yyval.uint) = (uint32_t) val;
}
break;
case 237:
{ backup_type = actual_type;
actual_type = ERROR_MESSAGE_KEYWORD;
}
break;
case 239:
{ backup_type = actual_type;
actual_type = ERROR_APP_TAG_KEYWORD;
}
break;
case 241:
{ backup_type = actual_type;
actual_type = UNITS_KEYWORD;
}
break;
case 243:
{ backup_type = actual_type;
actual_type = DEFAULT_KEYWORD;
}
break;
case 245:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) {
YYABORT;
}
s = NULL;
data_node = actual;
actual_type = GROUPING_KEYWORD;
}
break;
case 246:
{ LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 249:
{ (yyval.nodes).grouping = actual; }
break;
case 250:
{ if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping");
YYABORT;
}
(yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i);
}
break;
case 251:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 252:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 257:
{ if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification");
YYABORT;
}
}
break;
case 266:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = CONTAINER_KEYWORD;
}
break;
case 267:
{ LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 269:
{ void *tmp;
if ((yyvsp[-1].nodes).container->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).container->iffeature = tmp;
}
if ((yyvsp[-1].nodes).container->must_size) {
tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).container->must = tmp;
}
}
break;
case 270:
{ (yyval.nodes).container = actual; }
break;
case 274:
{ if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) {
YYABORT;
}
s = NULL;
}
break;
case 275:
{ if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container");
YYABORT;
}
(yyvsp[-1].nodes).container->flags |= (yyvsp[0].i);
}
break;
case 276:
{ if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container");
YYABORT;
}
(yyvsp[-1].nodes).container->flags |= (yyvsp[0].i);
}
break;
case 277:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 278:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 281:
{ if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification");
YYABORT;
}
}
break;
case 284:
{ void *tmp;
if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf");
YYABORT;
}
if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) {
/* RFC 6020, 7.6.4 - default statement must not with mandatory true */
LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\".");
YYABORT;
}
if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaf->must = tmp;
}
LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 285:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = LEAF_KEYWORD;
}
break;
case 286:
{ (yyval.nodes).node.ptr_leaf = actual;
(yyval.nodes).node.flag = 0;
}
break;
case 289:
{ (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;
(yyval.nodes) = (yyvsp[-2].nodes);
}
break;
case 290:
{ if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 292:
{ if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 293:
{ if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);
}
break;
case 294:
{ if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);
}
break;
case 295:
{ if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i);
}
break;
case 296:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 297:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 298:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = LEAF_LIST_KEYWORD;
}
break;
case 299:
{ void *tmp;
if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) {
/* RFC 6020, 7.7.5 - ignore ordering when the list represents state data
* ignore oredering MASK - 0x7F
*/
(yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F;
}
if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list");
YYABORT;
}
if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) {
LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist,
"The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement.");
YYABORT;
}
if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->must = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp;
}
LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 300:
{ (yyval.nodes).node.ptr_leaflist = actual;
(yyval.nodes).node.flag = 0;
}
break;
case 303:
{ (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF;
(yyval.nodes) = (yyvsp[-2].nodes);
}
break;
case 304:
{ if (trg->version < 2) {
free(s);
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default");
YYABORT;
}
YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt,
(yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults");
(*(const char **)actual) = lydict_insert_zc(param->module->ctx, s);
s = NULL;
actual = (yyvsp[-1].nodes).node.ptr_leaflist;
}
break;
case 305:
{ if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) {
YYABORT;
}
s = NULL;
}
break;
case 307:
{ if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i);
}
break;
case 308:
{ if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint);
(yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS;
(yyval.nodes) = (yyvsp[-1].nodes);
if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\".");
YYABORT;
}
}
break;
case 309:
{ if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint);
(yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS;
(yyval.nodes) = (yyvsp[-1].nodes);
if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\".");
YYABORT;
}
}
break;
case 310:
{ if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list");
YYABORT;
}
if ((yyvsp[0].i) & LYS_USERORDERED) {
(yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED;
}
(yyvsp[-1].nodes).node.flag |= (yyvsp[0].i);
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 311:
{ if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i);
}
break;
case 312:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 313:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 314:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = LIST_KEYWORD;
}
break;
case 315:
{ void *tmp;
if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->iffeature = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_list->must_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->must = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->tpdf = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_list->unique_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->unique = tmp;
}
LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 316:
{ (yyval.nodes).node.ptr_list = actual;
(yyval.nodes).node.flag = 0;
}
break;
case 320:
{ if ((yyvsp[-1].nodes).node.ptr_list->keys) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list");
free(s);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s;
(yyval.nodes) = (yyvsp[-1].nodes);
s = NULL;
}
break;
case 321:
{ YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques");
((struct lys_unique *)actual)->expr = (const char **)s;
(yyval.nodes) = (yyvsp[-1].nodes);
s = NULL;
actual = (yyvsp[-1].nodes).node.ptr_list;
}
break;
case 322:
{ if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i);
}
break;
case 323:
{ if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint);
(yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS;
(yyval.nodes) = (yyvsp[-1].nodes);
if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\".");
YYABORT;
}
}
break;
case 324:
{ if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint);
(yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS;
(yyval.nodes) = (yyvsp[-1].nodes);
if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\".");
YYABORT;
}
}
break;
case 325:
{ if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list");
YYABORT;
}
if ((yyvsp[0].i) & LYS_USERORDERED) {
(yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED;
}
(yyvsp[-1].nodes).node.flag |= (yyvsp[0].i);
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 326:
{ if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i);
}
break;
case 327:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 328:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 332:
{ if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification");
YYABORT;
}
}
break;
case 334:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = CHOICE_KEYWORD;
}
break;
case 335:
{ LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 337:
{ struct lys_iffeature *tmp;
if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) {
LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\".");
YYABORT;
}
if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp;
}
}
break;
case 338:
{ (yyval.nodes).node.ptr_choice = actual;
(yyval.nodes).node.flag = 0;
}
break;
case 341:
{ if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice");
free(s);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s;
s = NULL;
(yyval.nodes) = (yyvsp[-1].nodes);
(yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT;
}
break;
case 342:
{ if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 343:
{ if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 344:
{ if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i);
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 345:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) {
YYABORT;
}
s = NULL;
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 346:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) {
YYABORT;
}
s = NULL;
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 356:
{ if (trg->version < 2 ) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice");
YYABORT;
}
}
break;
case 357:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = CASE_KEYWORD;
}
break;
case 358:
{ LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 360:
{ struct lys_iffeature *tmp;
if ((yyvsp[-1].nodes).cs->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).cs->iffeature = tmp;
}
}
break;
case 361:
{ (yyval.nodes).cs = actual; }
break;
case 364:
{ if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case");
YYABORT;
}
(yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i);
}
break;
case 365:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 366:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 368:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = ANYXML_KEYWORD;
}
break;
case 369:
{ LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 370:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = ANYDATA_KEYWORD;
}
break;
case 371:
{ LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 373:
{ void *tmp;
if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_anydata->must = tmp;
}
}
break;
case 374:
{ (yyval.nodes).node.ptr_anydata = actual;
(yyval.nodes).node.flag = actual_type;
}
break;
case 378:
{ if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config",
((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);
}
break;
case 379:
{ if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory",
((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);
}
break;
case 380:
{ if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status",
((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i);
}
break;
case 381:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 382:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 383:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = USES_KEYWORD;
}
break;
case 384:
{ LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 386:
{ void *tmp;
if ((yyvsp[-1].nodes).uses->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).uses->iffeature = tmp;
}
if ((yyvsp[-1].nodes).uses->refine_size) {
tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).uses->refine = tmp;
}
if ((yyvsp[-1].nodes).uses->augment_size) {
tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).uses->augment = tmp;
}
}
break;
case 387:
{ (yyval.nodes).uses = actual; }
break;
case 390:
{ if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses");
YYABORT;
}
(yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i);
}
break;
case 391:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 392:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 397:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
YANG_ADDELEM(((struct lys_node_uses *)actual)->refine,
((struct lys_node_uses *)actual)->refine_size, "refines");
((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s);
free(s);
s = NULL;
if (!((struct lys_refine *)actual)->target_name) {
YYABORT;
}
actual_type = REFINE_KEYWORD;
}
break;
case 398:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 400:
{ void *tmp;
if ((yyvsp[-1].nodes).refine->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).refine->iffeature = tmp;
}
if ((yyvsp[-1].nodes).refine->must_size) {
tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).refine->must = tmp;
}
if ((yyvsp[-1].nodes).refine->dflt_size) {
tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).refine->dflt = tmp;
}
}
break;
case 401:
{ (yyval.nodes).refine = actual;
actual_type = REFINE_KEYWORD;
}
break;
case 402:
{ actual = (yyvsp[-2].nodes).refine;
actual_type = REFINE_KEYWORD;
if ((yyvsp[-2].nodes).refine->target_type) {
if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) {
(yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML);
} else {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML;
}
}
break;
case 403:
{ /* leaf, leaf-list, list, container or anyxml */
/* check possibility of statements combination */
if ((yyvsp[-2].nodes).refine->target_type) {
if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) {
(yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA);
} else {
free(s);
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA;
}
}
break;
case 404:
{ if ((yyvsp[-1].nodes).refine->target_type) {
if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) {
if ((yyvsp[-1].nodes).refine->mod.presence) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine");
free(s);
YYABORT;
}
(yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER;
(yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s);
} else {
free(s);
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER;
(yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s);
}
s = NULL;
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 405:
{ int i;
if ((yyvsp[-1].nodes).refine->dflt_size) {
if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine");
YYABORT;
}
if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) {
(yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST;
} else {
free(s);
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
if ((yyvsp[-1].nodes).refine->target_type) {
if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) {
(yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE);
} if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) {
/* YANG 1.1 */
(yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE);
} else {
free(s);
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
if (trg->version < 2) {
(yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE;
} else {
/* YANG 1.1 */
(yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE;
}
}
}
/* check for duplicity */
for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) {
if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s);
YYABORT;
}
}
YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults");
*((const char **)actual) = lydict_insert_zc(trg->ctx, s);
actual = (yyvsp[-1].nodes).refine;
s = NULL;
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 406:
{ if ((yyvsp[-1].nodes).refine->target_type) {
if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) {
(yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST);
if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine");
YYABORT;
}
(yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);
} else {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST;
(yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);
}
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 407:
{ if ((yyvsp[-1].nodes).refine->target_type) {
if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) {
(yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML);
if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine");
YYABORT;
}
(yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);
} else {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML;
(yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i);
}
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 408:
{ if ((yyvsp[-1].nodes).refine->target_type) {
if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) {
(yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST);
if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine");
YYABORT;
}
(yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET;
(yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint);
} else {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST;
(yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET;
(yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint);
}
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 409:
{ if ((yyvsp[-1].nodes).refine->target_type) {
if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) {
(yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST);
if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine");
YYABORT;
}
(yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET;
(yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint);
} else {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine");
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements.");
YYABORT;
}
} else {
(yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST;
(yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET;
(yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint);
}
(yyval.nodes) = (yyvsp[-1].nodes);
}
break;
case 410:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 411:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 414:
{ void *parent;
(yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
parent = actual;
YANG_ADDELEM(((struct lys_node_uses *)actual)->augment,
((struct lys_node_uses *)actual)->augment_size, "augments");
if (yang_read_augment(trg, parent, actual, s)) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = AUGMENT_KEYWORD;
}
break;
case 415:
{ LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 418:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
YANG_ADDELEM(trg->augment, trg->augment_size, "augments");
if (yang_read_augment(trg, NULL, actual, s)) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = AUGMENT_KEYWORD;
}
break;
case 419:
{ LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 420:
{ (yyval.nodes).augment = actual; }
break;
case 423:
{ if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment");
YYABORT;
}
(yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i);
}
break;
case 424:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 425:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 428:
{ if (trg->version < 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification");
YYABORT;
}
}
break;
case 430:
{ if (param->module->version != 2) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action");
free(s);
YYABORT;
}
(yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = ACTION_KEYWORD;
}
break;
case 431:
{ LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 432:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = RPC_KEYWORD;
}
break;
case 433:
{ LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 435:
{ void *tmp;
if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp;
}
if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) {
tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp;
}
}
break;
case 436:
{ (yyval.nodes).node.ptr_rpc = actual;
(yyval.nodes).node.flag = 0;
}
break;
case 438:
{ if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc");
YYABORT;
}
(yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i);
}
break;
case 439:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 440:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 443:
{ if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc");
YYABORT;
}
(yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT;
(yyval.nodes) = (yyvsp[-2].nodes);
}
break;
case 444:
{ if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc");
YYABORT;
}
(yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT;
(yyval.nodes) = (yyvsp[-2].nodes);
}
break;
case 445:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
s = strdup("input");
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = INPUT_KEYWORD;
}
break;
case 446:
{ void *tmp;
struct lys_node_inout *input = actual;
if (input->must_size) {
tmp = realloc(input->must, input->must_size * sizeof *input->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
input->must = tmp;
}
if (input->tpdf_size) {
tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
input->tpdf = tmp;
}
LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 452:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
s = strdup("output");
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) {
YYABORT;
}
data_node = actual;
s = NULL;
actual_type = OUTPUT_KEYWORD;
}
break;
case 453:
{ void *tmp;
struct lys_node_inout *output = actual;
if (output->must_size) {
tmp = realloc(output->must, output->must_size * sizeof *output->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
output->must = tmp;
}
if (output->tpdf_size) {
tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
output->tpdf = tmp;
}
LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name);
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
data_node = (yyvsp[-4].backup_token).actual;
}
break;
case 454:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) {
YYABORT;
}
data_node = actual;
actual_type = NOTIFICATION_KEYWORD;
}
break;
case 455:
{ LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name);
actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
data_node = (yyvsp[-1].backup_token).actual;
}
break;
case 457:
{ void *tmp;
if ((yyvsp[-1].nodes).notif->must_size) {
tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).notif->must = tmp;
}
if ((yyvsp[-1].nodes).notif->iffeature_size) {
tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).notif->iffeature = tmp;
}
if ((yyvsp[-1].nodes).notif->tpdf_size) {
tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].nodes).notif->tpdf = tmp;
}
}
break;
case 458:
{ (yyval.nodes).notif = actual; }
break;
case 461:
{ if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification");
YYABORT;
}
(yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i);
}
break;
case 462:
{ if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 463:
{ if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) {
YYABORT;
}
s = NULL;
}
break;
case 467:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations");
((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s);
free(s);
if (!((struct lys_deviation *)actual)->target_name) {
YYABORT;
}
s = NULL;
actual_type = DEVIATION_KEYWORD;
}
break;
case 468:
{ void *tmp;
if ((yyvsp[-1].dev)->deviate_size) {
tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate);
if (!tmp) {
LOGINT(trg->ctx);
YYABORT;
}
(yyvsp[-1].dev)->deviate = tmp;
} else {
LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation");
YYABORT;
}
actual_type = (yyvsp[-4].backup_token).token;
actual = (yyvsp[-4].backup_token).actual;
}
break;
case 469:
{ (yyval.dev) = actual; }
break;
case 470:
{ if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) {
YYABORT;
}
s = NULL;
(yyval.dev) = (yyvsp[-1].dev);
}
break;
case 471:
{ if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) {
YYABORT;
}
s = NULL;
(yyval.dev) = (yyvsp[-1].dev);
}
break;
case 477:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) {
YYABORT;
}
actual_type = NOT_SUPPORTED_KEYWORD;
}
break;
case 478:
{ actual_type = (yyvsp[-2].backup_token).token;
actual = (yyvsp[-2].backup_token).actual;
}
break;
case 484:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) {
YYABORT;
}
actual_type = ADD_KEYWORD;
}
break;
case 485:
{ actual_type = (yyvsp[-2].backup_token).token;
actual = (yyvsp[-2].backup_token).actual;
}
break;
case 487:
{ void *tmp;
if ((yyvsp[-1].deviate)->must_size) {
tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->must = tmp;
}
if ((yyvsp[-1].deviate)->unique_size) {
tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->unique = tmp;
}
if ((yyvsp[-1].deviate)->dflt_size) {
tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->dflt = tmp;
}
}
break;
case 488:
{ (yyval.deviate) = actual; }
break;
case 489:
{ if (yang_read_units(trg, actual, s, ADD_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 491:
{ YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques");
((struct lys_unique *)actual)->expr = (const char **)s;
s = NULL;
actual = (yyvsp[-1].deviate);
(yyval.deviate)= (yyvsp[-1].deviate);
}
break;
case 492:
{ YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults");
*((const char **)actual) = lydict_insert_zc(trg->ctx, s);
s = NULL;
actual = (yyvsp[-1].deviate);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 493:
{ if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate");
YYABORT;
}
(yyvsp[-1].deviate)->flags = (yyvsp[0].i);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 494:
{ if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate");
YYABORT;
}
(yyvsp[-1].deviate)->flags = (yyvsp[0].i);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 495:
{ if ((yyvsp[-1].deviate)->min_set) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation");
YYABORT;
}
(yyvsp[-1].deviate)->min = (yyvsp[0].uint);
(yyvsp[-1].deviate)->min_set = 1;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 496:
{ if ((yyvsp[-1].deviate)->max_set) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation");
YYABORT;
}
(yyvsp[-1].deviate)->max = (yyvsp[0].uint);
(yyvsp[-1].deviate)->max_set = 1;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 497:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) {
YYABORT;
}
actual_type = DELETE_KEYWORD;
}
break;
case 498:
{ actual_type = (yyvsp[-2].backup_token).token;
actual = (yyvsp[-2].backup_token).actual;
}
break;
case 500:
{ void *tmp;
if ((yyvsp[-1].deviate)->must_size) {
tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->must = tmp;
}
if ((yyvsp[-1].deviate)->unique_size) {
tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->unique = tmp;
}
if ((yyvsp[-1].deviate)->dflt_size) {
tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->dflt = tmp;
}
}
break;
case 501:
{ (yyval.deviate) = actual; }
break;
case 502:
{ if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 504:
{ YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques");
((struct lys_unique *)actual)->expr = (const char **)s;
s = NULL;
actual = (yyvsp[-1].deviate);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 505:
{ YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults");
*((const char **)actual) = lydict_insert_zc(trg->ctx, s);
s = NULL;
actual = (yyvsp[-1].deviate);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 506:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) {
YYABORT;
}
actual_type = REPLACE_KEYWORD;
}
break;
case 507:
{ actual_type = (yyvsp[-2].backup_token).token;
actual = (yyvsp[-2].backup_token).actual;
}
break;
case 509:
{ void *tmp;
if ((yyvsp[-1].deviate)->dflt_size) {
tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt);
if (!tmp) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyvsp[-1].deviate)->dflt = tmp;
}
}
break;
case 510:
{ (yyval.deviate) = actual; }
break;
case 512:
{ if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) {
YYABORT;
}
s = NULL;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 513:
{ YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults");
*((const char **)actual) = lydict_insert_zc(trg->ctx, s);
s = NULL;
actual = (yyvsp[-1].deviate);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 514:
{ if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate");
YYABORT;
}
(yyvsp[-1].deviate)->flags = (yyvsp[0].i);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 515:
{ if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate");
YYABORT;
}
(yyvsp[-1].deviate)->flags = (yyvsp[0].i);
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 516:
{ if ((yyvsp[-1].deviate)->min_set) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation");
YYABORT;
}
(yyvsp[-1].deviate)->min = (yyvsp[0].uint);
(yyvsp[-1].deviate)->min_set = 1;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 517:
{ if ((yyvsp[-1].deviate)->max_set) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation");
YYABORT;
}
(yyvsp[-1].deviate)->max = (yyvsp[0].uint);
(yyvsp[-1].deviate)->max_set = 1;
(yyval.deviate) = (yyvsp[-1].deviate);
}
break;
case 518:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_when(trg, actual, actual_type, s))) {
YYABORT;
}
s = NULL;
actual_type = WHEN_KEYWORD;
}
break;
case 519:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 523:
{ if (yang_read_description(trg, actual, s, "when", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 524:
{ if (yang_read_reference(trg, actual, s, "when", NODE)) {
YYABORT;
}
s = NULL;
}
break;
case 525:
{ (yyval.i) = (yyvsp[0].i);
backup_type = actual_type;
actual_type = CONFIG_KEYWORD;
}
break;
case 526:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 527:
{ (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; }
break;
case 528:
{ (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; }
break;
case 529:
{ if (!strcmp(s, "true")) {
(yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET;
} else if (!strcmp(s, "false")) {
(yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET;
} else {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config");
free(s);
YYABORT;
}
free(s);
s = NULL;
}
break;
case 530:
{ (yyval.i) = (yyvsp[0].i);
backup_type = actual_type;
actual_type = MANDATORY_KEYWORD;
}
break;
case 531:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 532:
{ (yyval.i) = LYS_MAND_TRUE; }
break;
case 533:
{ (yyval.i) = LYS_MAND_FALSE; }
break;
case 534:
{ if (!strcmp(s, "true")) {
(yyval.i) = LYS_MAND_TRUE;
} else if (!strcmp(s, "false")) {
(yyval.i) = LYS_MAND_FALSE;
} else {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory");
free(s);
YYABORT;
}
free(s);
s = NULL;
}
break;
case 535:
{ backup_type = actual_type;
actual_type = PRESENCE_KEYWORD;
}
break;
case 537:
{ (yyval.uint) = (yyvsp[0].uint);
backup_type = actual_type;
actual_type = MIN_ELEMENTS_KEYWORD;
}
break;
case 538:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 539:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 540:
{ if (strlen(s) == 1 && s[0] == '0') {
(yyval.uint) = 0;
} else {
/* convert it to uint32_t */
uint64_t val;
char *endptr = NULL;
errno = 0;
val = strtoul(s, &endptr, 10);
if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements");
free(s);
YYABORT;
}
(yyval.uint) = (uint32_t) val;
}
free(s);
s = NULL;
}
break;
case 541:
{ (yyval.uint) = (yyvsp[0].uint);
backup_type = actual_type;
actual_type = MAX_ELEMENTS_KEYWORD;
}
break;
case 542:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 543:
{ (yyval.uint) = 0; }
break;
case 544:
{ (yyval.uint) = (yyvsp[-1].uint); }
break;
case 545:
{ if (!strcmp(s, "unbounded")) {
(yyval.uint) = 0;
} else {
/* convert it to uint32_t */
uint64_t val;
char *endptr = NULL;
errno = 0;
val = strtoul(s, &endptr, 10);
if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) {
LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements");
free(s);
YYABORT;
}
(yyval.uint) = (uint32_t) val;
}
free(s);
s = NULL;
}
break;
case 546:
{ (yyval.i) = (yyvsp[0].i);
backup_type = actual_type;
actual_type = ORDERED_BY_KEYWORD;
}
break;
case 547:
{ (yyval.i) = (yyvsp[-1].i); }
break;
case 548:
{ (yyval.i) = LYS_USERORDERED; }
break;
case 549:
{ (yyval.i) = LYS_SYSTEMORDERED; }
break;
case 550:
{ if (!strcmp(s, "user")) {
(yyval.i) = LYS_USERORDERED;
} else if (!strcmp(s, "system")) {
(yyval.i) = LYS_SYSTEMORDERED;
} else {
free(s);
YYABORT;
}
free(s);
s=NULL;
}
break;
case 551:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
switch (actual_type) {
case CONTAINER_KEYWORD:
YANG_ADDELEM(((struct lys_node_container *)actual)->must,
((struct lys_node_container *)actual)->must_size, "musts");
break;
case ANYDATA_KEYWORD:
case ANYXML_KEYWORD:
YANG_ADDELEM(((struct lys_node_anydata *)actual)->must,
((struct lys_node_anydata *)actual)->must_size, "musts");
break;
case LEAF_KEYWORD:
YANG_ADDELEM(((struct lys_node_leaf *)actual)->must,
((struct lys_node_leaf *)actual)->must_size, "musts");
break;
case LEAF_LIST_KEYWORD:
YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must,
((struct lys_node_leaflist *)actual)->must_size, "musts");
break;
case LIST_KEYWORD:
YANG_ADDELEM(((struct lys_node_list *)actual)->must,
((struct lys_node_list *)actual)->must_size, "musts");
break;
case REFINE_KEYWORD:
YANG_ADDELEM(((struct lys_refine *)actual)->must,
((struct lys_refine *)actual)->must_size, "musts");
break;
case ADD_KEYWORD:
case DELETE_KEYWORD:
YANG_ADDELEM(((struct lys_deviate *)actual)->must,
((struct lys_deviate *)actual)->must_size, "musts");
break;
case NOTIFICATION_KEYWORD:
if (trg->version < 2) {
free(s);
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must");
YYABORT;
}
YANG_ADDELEM(((struct lys_node_notif *)actual)->must,
((struct lys_node_notif *)actual)->must_size, "musts");
break;
case INPUT_KEYWORD:
case OUTPUT_KEYWORD:
if (trg->version < 2) {
free(s);
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must");
YYABORT;
}
YANG_ADDELEM(((struct lys_node_inout *)actual)->must,
((struct lys_node_inout *)actual)->must_size, "musts");
break;
case EXTENSION_INSTANCE:
/* must is already allocated */
break;
default:
free(s);
LOGINT(trg->ctx);
YYABORT;
}
((struct lys_restr *)actual)->expr = transform_schema2json(trg, s);
free(s);
if (!((struct lys_restr *)actual)->expr) {
YYABORT;
}
s = NULL;
actual_type = MUST_KEYWORD;
}
break;
case 552:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 555:
{ backup_type = actual_type;
actual_type = UNIQUE_KEYWORD;
}
break;
case 559:
{ backup_type = actual_type;
actual_type = KEY_KEYWORD;
}
break;
case 561:
{ s = strdup(yyget_text(scanner));
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
}
break;
case 564:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) {
YYABORT;
}
actual_type = RANGE_KEYWORD;
s = NULL;
}
break;
case 565:
{ if (s) {
s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
strcat(s,"/");
strcat(s, yyget_text(scanner));
} else {
s = malloc(yyget_leng(scanner) + 2);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
s[0]='/';
memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1);
}
}
break;
case 569:
{ if (s) {
s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
strcat(s, yyget_text(scanner));
} else {
s = strdup(yyget_text(scanner));
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
}
}
break;
case 571:
{ tmp_s = yyget_text(scanner); }
break;
case 572:
{ s = strdup(tmp_s);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
s[strlen(s) - 1] = '\0';
}
break;
case 573:
{ tmp_s = yyget_text(scanner); }
break;
case 574:
{ s = strdup(tmp_s);
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
s[strlen(s) - 1] = '\0';
}
break;
case 598:
{ /* convert it to uint32_t */
unsigned long val;
val = strtoul(yyget_text(scanner), NULL, 10);
if (val > UINT32_MAX) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long.");
YYABORT;
}
(yyval.uint) = (uint32_t) val;
}
break;
case 599:
{ (yyval.uint) = 0; }
break;
case 600:
{ (yyval.uint) = (yyvsp[0].uint); }
break;
case 601:
{ (yyval.i) = 0; }
break;
case 602:
{ /* convert it to int32_t */
int64_t val;
val = strtoll(yyget_text(scanner), NULL, 10);
if (val < INT32_MIN || val > INT32_MAX) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val);
YYABORT;
}
(yyval.i) = (int32_t) val;
}
break;
case 608:
{ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {
free(s);
YYABORT;
}
}
break;
case 613:
{ char *tmp;
if ((tmp = strchr(s, ':'))) {
*tmp = '\0';
/* check prefix */
if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {
free(s);
YYABORT;
}
/* check identifier */
if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) {
free(s);
YYABORT;
}
*tmp = ':';
} else {
/* check identifier */
if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) {
free(s);
YYABORT;
}
}
}
break;
case 614:
{ s = (yyvsp[-1].str); }
break;
case 615:
{ s = (yyvsp[-3].str); }
break;
case 616:
{ actual_type = backup_type;
backup_type = NODE;
(yyval.str) = s;
s = NULL;
}
break;
case 617:
{ actual_type = backup_type;
backup_type = NODE;
}
break;
case 618:
{ (yyval.str) = s;
s = NULL;
}
break;
case 622:
{ actual_type = (yyvsp[-1].backup_token).token;
actual = (yyvsp[-1].backup_token).actual;
}
break;
case 623:
{ (yyval.backup_token).token = actual_type;
(yyval.backup_token).actual = actual;
if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s,
actual_type, backup_type, is_ext_instance))) {
YYABORT;
}
s = NULL;
actual_type = EXTENSION_INSTANCE;
}
break;
case 624:
{ (yyval.str) = s; s = NULL; }
break;
case 639:
{ struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent;
int32_t length = 0, old_length = 0;
char *tmp_value;
if (!substmt) {
substmt = calloc(1, sizeof *substmt);
if (!substmt) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_ext_instance *)actual)->parent = substmt;
}
length = strlen((yyvsp[-2].str));
old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2;
tmp_value = realloc(substmt->ext_substmt, old_length + length + 1);
if (!tmp_value) {
LOGMEM(trg->ctx);
YYABORT;
}
substmt->ext_substmt = tmp_value;
tmp_value += old_length - 2;
memcpy(tmp_value, (yyvsp[-2].str), length);
tmp_value[length] = ' ';
tmp_value[length + 1] = '\0';
tmp_value[length + 2] = '\0';
}
break;
case 640:
{ struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent;
int32_t length;
char *tmp_value, **array;
int i = 0;
if (!substmt) {
substmt = calloc(1, sizeof *substmt);
if (!substmt) {
LOGMEM(trg->ctx);
YYABORT;
}
((struct lys_ext_instance *)actual)->parent = substmt;
}
length = strlen((yyvsp[-2].str));
if (!substmt->ext_modules) {
array = malloc(2 * sizeof *substmt->ext_modules);
} else {
for (i = 0; substmt->ext_modules[i]; ++i);
array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules);
}
if (!array) {
LOGMEM(trg->ctx);
YYABORT;
}
substmt->ext_modules = array;
array[i + 1] = NULL;
tmp_value = malloc(length + 2);
if (!tmp_value) {
LOGMEM(trg->ctx);
YYABORT;
}
array[i] = tmp_value;
memcpy(tmp_value, (yyvsp[-2].str), length);
tmp_value[length] = '\0';
tmp_value[length + 1] = '\0';
}
break;
case 643:
{ (yyval.str) = yyget_text(scanner); }
break;
case 644:
{ (yyval.str) = yyget_text(scanner); }
break;
case 656:
{ s = strdup(yyget_text(scanner));
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
}
break;
case 749:
{ s = strdup(yyget_text(scanner));
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
}
break;
case 750:
{ s = strdup(yyget_text(scanner));
if (!s) {
LOGMEM(trg->ctx);
YYABORT;
}
}
break;
case 751:
{ struct lys_type **type;
type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"type", LY_STMT_TYPE);
if (!type) {
YYABORT;
}
/* allocate type structure */
(*type) = calloc(1, sizeof **type);
if (!*type) {
LOGMEM(trg->ctx);
YYABORT;
}
/* HACK for unres */
(*type)->parent = (struct lys_tpdf *)ext_instance;
(yyval.v) = actual = *type;
is_ext_instance = 0;
}
break;
case 752:
{ struct lys_tpdf **tpdf;
tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"typedef", LY_STMT_TYPEDEF);
if (!tpdf) {
YYABORT;
}
/* allocate typedef structure */
(*tpdf) = calloc(1, sizeof **tpdf);
if (!*tpdf) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyval.v) = actual = *tpdf;
is_ext_instance = 0;
}
break;
case 753:
{ struct lys_iffeature **iffeature;
iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"if-feature", LY_STMT_IFFEATURE);
if (!iffeature) {
YYABORT;
}
/* allocate typedef structure */
(*iffeature) = calloc(1, sizeof **iffeature);
if (!*iffeature) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyval.v) = actual = *iffeature;
}
break;
case 754:
{ struct lys_restr **restr;
LY_STMT stmt;
s = yyget_text(scanner);
if (!strcmp(s, "must")) {
stmt = LY_STMT_MUST;
} else if (!strcmp(s, "pattern")) {
stmt = LY_STMT_PATTERN;
} else if (!strcmp(s, "range")) {
stmt = LY_STMT_RANGE;
} else {
stmt = LY_STMT_LENGTH;
}
restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt);
if (!restr) {
YYABORT;
}
/* allocate structure for must */
(*restr) = calloc(1, sizeof(struct lys_restr));
if (!*restr) {
LOGMEM(trg->ctx);
YYABORT;
}
(yyval.v) = actual = *restr;
s = NULL;
}
break;
case 755:
{ actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN);
if (!actual) {
YYABORT;
}
(yyval.v) = actual;
}
break;
case 756:
{ struct lys_revision **rev;
int i;
rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name,
"revision", LY_STMT_REVISION);
if (!rev) {
YYABORT;
}
rev[i] = calloc(1, sizeof **rev);
if (!rev[i]) {
LOGMEM(trg->ctx);
YYABORT;
}
actual = rev[i];
(yyval.revisions).revision = rev;
(yyval.revisions).index = i;
}
break;
case 757:
{ LY_STMT stmt;
s = yyget_text(scanner);
if (!strcmp(s, "action")) {
stmt = LY_STMT_ACTION;
} else if (!strcmp(s, "anydata")) {
stmt = LY_STMT_ANYDATA;
} else if (!strcmp(s, "anyxml")) {
stmt = LY_STMT_ANYXML;
} else if (!strcmp(s, "case")) {
stmt = LY_STMT_CASE;
} else if (!strcmp(s, "choice")) {
stmt = LY_STMT_CHOICE;
} else if (!strcmp(s, "container")) {
stmt = LY_STMT_CONTAINER;
} else if (!strcmp(s, "grouping")) {
stmt = LY_STMT_GROUPING;
} else if (!strcmp(s, "input")) {
stmt = LY_STMT_INPUT;
} else if (!strcmp(s, "leaf")) {
stmt = LY_STMT_LEAF;
} else if (!strcmp(s, "leaf-list")) {
stmt = LY_STMT_LEAFLIST;
} else if (!strcmp(s, "list")) {
stmt = LY_STMT_LIST;
} else if (!strcmp(s, "notification")) {
stmt = LY_STMT_NOTIFICATION;
} else if (!strcmp(s, "output")) {
stmt = LY_STMT_OUTPUT;
} else {
stmt = LY_STMT_USES;
}
if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) {
YYABORT;
}
actual = NULL;
s = NULL;
is_ext_instance = 0;
}
break;
case 758:
{ LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); }
break;
case 790:
{ actual_type = EXTENSION_INSTANCE;
actual = ext_instance;
if (!is_ext_instance) {
LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner));
YYABORT;
}
(yyval.i) = 0;
}
break;
case 792:
{ if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, s,
0, LY_STMT_PREFIX)) {
YYABORT;
}
}
break;
case 793:
{ if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, s,
0, LY_STMT_DESCRIPTION)) {
YYABORT;
}
}
break;
case 794:
{ if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, s,
0, LY_STMT_REFERENCE)) {
YYABORT;
}
}
break;
case 795:
{ if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, s,
0, LY_STMT_UNITS)) {
YYABORT;
}
}
break;
case 796:
{ if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, s,
0, LY_STMT_BASE)) {
YYABORT;
}
}
break;
case 797:
{ if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, s,
0, LY_STMT_CONTACT)) {
YYABORT;
}
}
break;
case 798:
{ if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, s,
0, LY_STMT_DEFAULT)) {
YYABORT;
}
}
break;
case 799:
{ if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, s,
0, LY_STMT_ERRMSG)) {
YYABORT;
}
}
break;
case 800:
{ if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, s,
0, LY_STMT_ERRTAG)) {
YYABORT;
}
}
break;
case 801:
{ if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, s,
0, LY_STMT_KEY)) {
YYABORT;
}
}
break;
case 802:
{ if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, s,
0, LY_STMT_NAMESPACE)) {
YYABORT;
}
}
break;
case 803:
{ if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, s,
0, LY_STMT_ORGANIZATION)) {
YYABORT;
}
}
break;
case 804:
{ if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, s,
0, LY_STMT_PATH)) {
YYABORT;
}
}
break;
case 805:
{ if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, s,
0, LY_STMT_PRESENCE)) {
YYABORT;
}
}
break;
case 806:
{ if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, s,
0, LY_STMT_REVISIONDATE)) {
YYABORT;
}
}
break;
case 807:
{ struct lys_type *type = (yyvsp[-2].v);
if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) {
yang_type_free(trg->ctx, type);
YYABORT;
}
if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) {
yang_type_free(trg->ctx, type);
YYABORT;
}
actual = ext_instance;
is_ext_instance = 1;
}
break;
case 808:
{ struct lys_tpdf *tpdf = (yyvsp[-2].v);
if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) {
yang_type_free(trg->ctx, &tpdf->type);
}
if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) {
YYABORT;
}
if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) {
yang_type_free(trg->ctx, &tpdf->type);
YYABORT;
}
/* check default value*/
if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) {
YYABORT;
}
actual = ext_instance;
is_ext_instance = 1;
}
break;
case 809:
{ if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS,
(yyvsp[0].i), LYS_STATUS_MASK)) {
YYABORT;
}
}
break;
case 810:
{ if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG,
(yyvsp[0].i), LYS_CONFIG_MASK)) {
YYABORT;
}
}
break;
case 811:
{ if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY,
(yyvsp[0].i), LYS_MAND_MASK)) {
YYABORT;
}
}
break;
case 812:
{ if ((yyvsp[-1].i) & LYS_ORDERED_MASK) {
LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name);
YYABORT;
}
if ((yyvsp[0].i) & LYS_USERORDERED) {
if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY,
(yyvsp[0].i), LYS_USERORDERED)) {
YYABORT;
}
}
(yyvsp[-1].i) |= (yyvsp[0].i);
(yyval.i) = (yyvsp[-1].i);
}
break;
case 813:
{ if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance",
LY_STMT_REQINSTANCE, (yyvsp[0].i))) {
YYABORT;
}
}
break;
case 814:
{ if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) {
YYABORT;
}
}
break;
case 815:
{ /* range check */
if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) {
LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits");
YYABORT;
}
if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) {
YYABORT;
}
}
break;
case 816:
{ uint32_t **val;
val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"min-elements", LY_STMT_MIN);
if (!val) {
YYABORT;
}
/* store the value */
*val = malloc(sizeof(uint32_t));
if (!*val) {
LOGMEM(trg->ctx);
YYABORT;
}
**val = (yyvsp[0].uint);
}
break;
case 817:
{ uint32_t **val;
val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"max-elements", LY_STMT_MAX);
if (!val) {
YYABORT;
}
/* store the value */
*val = malloc(sizeof(uint32_t));
if (!*val) {
LOGMEM(trg->ctx);
YYABORT;
}
**val = (yyvsp[0].uint);
}
break;
case 818:
{ uint32_t **val;
val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"position", LY_STMT_POSITION);
if (!val) {
YYABORT;
}
/* store the value */
*val = malloc(sizeof(uint32_t));
if (!*val) {
LOGMEM(trg->ctx);
YYABORT;
}
**val = (yyvsp[0].uint);
}
break;
case 819:
{ int32_t **val;
val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"value", LY_STMT_VALUE);
if (!val) {
YYABORT;
}
/* store the value */
*val = malloc(sizeof(int32_t));
if (!*val) {
LOGMEM(trg->ctx);
YYABORT;
}
**val = (yyvsp[0].i);
}
break;
case 820:
{ struct lys_unique **unique;
int rc;
unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name,
"unique", LY_STMT_UNIQUE);
if (!unique) {
YYABORT;
}
*unique = calloc(1, sizeof(struct lys_unique));
if (!*unique) {
LOGMEM(trg->ctx);
YYABORT;
}
rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres);
free(s);
s = NULL;
if (rc) {
YYABORT;
}
}
break;
case 821:
{ struct lys_iffeature *iffeature;
iffeature = (yyvsp[-2].v);
s = (char *)iffeature->features;
iffeature->features = NULL;
if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) {
YYABORT;
}
if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) {
YYABORT;
}
s = NULL;
actual = ext_instance;
}
break;
case 823:
{ if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) {
YYABORT;
}
actual = ext_instance;
}
break;
case 824:
{ if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size,
*(struct lys_when **)(yyvsp[-2].v), param->unres)) {
YYABORT;
}
actual = ext_instance;
}
break;
case 825:
{ int i;
for (i = 0; i < (yyvsp[-2].revisions).index; ++i) {
if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) {
LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date);
break;
}
}
if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size,
&(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) {
YYABORT;
}
actual = ext_instance;
}
break;
case 826:
{ actual = ext_instance;
is_ext_instance = 1;
}
break;
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
*++yylsp = yyloc;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
{
const int yylhs = yyr1[yyn] - YYNTOKENS;
const int yyi = yypgoto[yylhs] + *yyssp;
yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp
? yytable[yyi]
: yydefgoto[yylhs]);
}
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (&yylloc, scanner, param, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (&yylloc, scanner, param, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
yyerror_range[1] = yylloc;
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, &yylloc, scanner, param);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yyerror_range[1] = *yylsp;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, yylsp, scanner, param);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
yyerror_range[2] = yylloc;
/* Using YYLLOC is tempting, but would change the location of
the lookahead. YYLOC is available though. */
YYLLOC_DEFAULT (yyloc, yyerror_range, 2);
*++yylsp = yyloc;
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (&yylloc, scanner, param, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, &yylloc, scanner, param);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, yylsp, scanner, param);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
void
yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...)
{
free(*param->value);
*param->value = NULL;
if (yylloc->first_line != -1) {
if (*param->data_node && (*param->data_node) == (*param->actual_node)) {
LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner));
} else {
LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner));
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1363_0 |
crossvul-cpp_data_good_3581_0 | /*
* Functions related to io context handling
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/bootmem.h> /* for max_pfn/max_low_pfn */
#include "blk.h"
/*
* For io context allocations
*/
static struct kmem_cache *iocontext_cachep;
static void cfq_dtor(struct io_context *ioc)
{
if (!hlist_empty(&ioc->cic_list)) {
struct cfq_io_context *cic;
cic = list_entry(ioc->cic_list.first, struct cfq_io_context,
cic_list);
cic->dtor(ioc);
}
}
/*
* IO Context helper functions. put_io_context() returns 1 if there are no
* more users of this io context, 0 otherwise.
*/
int put_io_context(struct io_context *ioc)
{
if (ioc == NULL)
return 1;
BUG_ON(atomic_long_read(&ioc->refcount) == 0);
if (atomic_long_dec_and_test(&ioc->refcount)) {
rcu_read_lock();
if (ioc->aic && ioc->aic->dtor)
ioc->aic->dtor(ioc->aic);
cfq_dtor(ioc);
rcu_read_unlock();
kmem_cache_free(iocontext_cachep, ioc);
return 1;
}
return 0;
}
EXPORT_SYMBOL(put_io_context);
static void cfq_exit(struct io_context *ioc)
{
rcu_read_lock();
if (!hlist_empty(&ioc->cic_list)) {
struct cfq_io_context *cic;
cic = list_entry(ioc->cic_list.first, struct cfq_io_context,
cic_list);
cic->exit(ioc);
}
rcu_read_unlock();
}
/* Called by the exitting task */
void exit_io_context(struct task_struct *task)
{
struct io_context *ioc;
task_lock(task);
ioc = task->io_context;
task->io_context = NULL;
task_unlock(task);
if (atomic_dec_and_test(&ioc->nr_tasks)) {
if (ioc->aic && ioc->aic->exit)
ioc->aic->exit(ioc->aic);
cfq_exit(ioc);
}
put_io_context(ioc);
}
struct io_context *alloc_io_context(gfp_t gfp_flags, int node)
{
struct io_context *ret;
ret = kmem_cache_alloc_node(iocontext_cachep, gfp_flags, node);
if (ret) {
atomic_long_set(&ret->refcount, 1);
atomic_set(&ret->nr_tasks, 1);
spin_lock_init(&ret->lock);
ret->ioprio_changed = 0;
ret->ioprio = 0;
ret->last_waited = jiffies; /* doesn't matter... */
ret->nr_batch_requests = 0; /* because this is 0 */
ret->aic = NULL;
INIT_RADIX_TREE(&ret->radix_root, GFP_ATOMIC | __GFP_HIGH);
INIT_HLIST_HEAD(&ret->cic_list);
ret->ioc_data = NULL;
}
return ret;
}
/*
* If the current task has no IO context then create one and initialise it.
* Otherwise, return its existing IO context.
*
* This returned IO context doesn't have a specifically elevated refcount,
* but since the current task itself holds a reference, the context can be
* used in general code, so long as it stays within `current` context.
*/
struct io_context *current_io_context(gfp_t gfp_flags, int node)
{
struct task_struct *tsk = current;
struct io_context *ret;
ret = tsk->io_context;
if (likely(ret))
return ret;
ret = alloc_io_context(gfp_flags, node);
if (ret) {
/* make sure set_task_ioprio() sees the settings above */
smp_wmb();
tsk->io_context = ret;
}
return ret;
}
/*
* If the current task has no IO context then create one and initialise it.
* If it does have a context, take a ref on it.
*
* This is always called in the context of the task which submitted the I/O.
*/
struct io_context *get_io_context(gfp_t gfp_flags, int node)
{
struct io_context *ret = NULL;
/*
* Check for unlikely race with exiting task. ioc ref count is
* zero when ioc is being detached.
*/
do {
ret = current_io_context(gfp_flags, node);
if (unlikely(!ret))
break;
} while (!atomic_long_inc_not_zero(&ret->refcount));
return ret;
}
EXPORT_SYMBOL(get_io_context);
void copy_io_context(struct io_context **pdst, struct io_context **psrc)
{
struct io_context *src = *psrc;
struct io_context *dst = *pdst;
if (src) {
BUG_ON(atomic_long_read(&src->refcount) == 0);
atomic_long_inc(&src->refcount);
put_io_context(dst);
*pdst = src;
}
}
EXPORT_SYMBOL(copy_io_context);
static int __init blk_ioc_init(void)
{
iocontext_cachep = kmem_cache_create("blkdev_ioc",
sizeof(struct io_context), 0, SLAB_PANIC, NULL);
return 0;
}
subsys_initcall(blk_ioc_init);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3581_0 |
crossvul-cpp_data_bad_1776_0 | /*
* IPv6 Address [auto]configuration
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
* 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.
*/
/*
* Changes:
*
* Janos Farkas : delete timer on ifdown
* <chexum@bankinf.banki.hu>
* Andi Kleen : kill double kfree on module
* unload.
* Maciej W. Rozycki : FDDI support
* sekiya@USAGI : Don't send too many RS
* packets.
* yoshfuji@USAGI : Fixed interval between DAD
* packets.
* YOSHIFUJI Hideaki @USAGI : improved accuracy of
* address validation timer.
* YOSHIFUJI Hideaki @USAGI : Privacy Extensions (RFC3041)
* support.
* Yuji SEKIYA @USAGI : Don't assign a same IPv6
* address on a same interface.
* YOSHIFUJI Hideaki @USAGI : ARCnet support
* YOSHIFUJI Hideaki @USAGI : convert /proc/net/if_inet6 to
* seq_file.
* YOSHIFUJI Hideaki @USAGI : improved source address
* selection; consider scope,
* status etc.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/if_addr.h>
#include <linux/if_arp.h>
#include <linux/if_arcnet.h>
#include <linux/if_infiniband.h>
#include <linux/route.h>
#include <linux/inetdevice.h>
#include <linux/init.h>
#include <linux/slab.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
#include <linux/capability.h>
#include <linux/delay.h>
#include <linux/notifier.h>
#include <linux/string.h>
#include <linux/hash.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/af_ieee802154.h>
#include <net/firewire.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/ndisc.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/tcp.h>
#include <net/ip.h>
#include <net/netlink.h>
#include <net/pkt_sched.h>
#include <linux/if_tunnel.h>
#include <linux/rtnetlink.h>
#include <linux/netconf.h>
#include <linux/random.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/export.h>
/* Set to 3 to get tracing... */
#define ACONF_DEBUG 2
#if ACONF_DEBUG >= 3
#define ADBG(fmt, ...) printk(fmt, ##__VA_ARGS__)
#else
#define ADBG(fmt, ...) do { if (0) printk(fmt, ##__VA_ARGS__); } while (0)
#endif
#define INFINITY_LIFE_TIME 0xFFFFFFFF
static inline u32 cstamp_delta(unsigned long cstamp)
{
return (cstamp - INITIAL_JIFFIES) * 100UL / HZ;
}
#ifdef CONFIG_SYSCTL
static int addrconf_sysctl_register(struct inet6_dev *idev);
static void addrconf_sysctl_unregister(struct inet6_dev *idev);
#else
static inline int addrconf_sysctl_register(struct inet6_dev *idev)
{
return 0;
}
static inline void addrconf_sysctl_unregister(struct inet6_dev *idev)
{
}
#endif
static void __ipv6_regen_rndid(struct inet6_dev *idev);
static void __ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr);
static void ipv6_regen_rndid(unsigned long data);
static int ipv6_generate_eui64(u8 *eui, struct net_device *dev);
static int ipv6_count_addresses(struct inet6_dev *idev);
/*
* Configured unicast address hash table
*/
static struct hlist_head inet6_addr_lst[IN6_ADDR_HSIZE];
static DEFINE_SPINLOCK(addrconf_hash_lock);
static void addrconf_verify(void);
static void addrconf_verify_rtnl(void);
static void addrconf_verify_work(struct work_struct *);
static struct workqueue_struct *addrconf_wq;
static DECLARE_DELAYED_WORK(addr_chk_work, addrconf_verify_work);
static void addrconf_join_anycast(struct inet6_ifaddr *ifp);
static void addrconf_leave_anycast(struct inet6_ifaddr *ifp);
static void addrconf_type_change(struct net_device *dev,
unsigned long event);
static int addrconf_ifdown(struct net_device *dev, int how);
static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
int plen,
const struct net_device *dev,
u32 flags, u32 noflags);
static void addrconf_dad_start(struct inet6_ifaddr *ifp);
static void addrconf_dad_work(struct work_struct *w);
static void addrconf_dad_completed(struct inet6_ifaddr *ifp);
static void addrconf_dad_run(struct inet6_dev *idev);
static void addrconf_rs_timer(unsigned long data);
static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
static void inet6_prefix_notify(int event, struct inet6_dev *idev,
struct prefix_info *pinfo);
static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
struct net_device *dev);
static struct ipv6_devconf ipv6_devconf __read_mostly = {
.forwarding = 0,
.hop_limit = IPV6_DEFAULT_HOPLIMIT,
.mtu6 = IPV6_MIN_MTU,
.accept_ra = 1,
.accept_redirects = 1,
.autoconf = 1,
.force_mld_version = 0,
.mldv1_unsolicited_report_interval = 10 * HZ,
.mldv2_unsolicited_report_interval = HZ,
.dad_transmits = 1,
.rtr_solicits = MAX_RTR_SOLICITATIONS,
.rtr_solicit_interval = RTR_SOLICITATION_INTERVAL,
.rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY,
.use_tempaddr = 0,
.temp_valid_lft = TEMP_VALID_LIFETIME,
.temp_prefered_lft = TEMP_PREFERRED_LIFETIME,
.regen_max_retry = REGEN_MAX_RETRY,
.max_desync_factor = MAX_DESYNC_FACTOR,
.max_addresses = IPV6_MAX_ADDRESSES,
.accept_ra_defrtr = 1,
.accept_ra_from_local = 0,
.accept_ra_pinfo = 1,
#ifdef CONFIG_IPV6_ROUTER_PREF
.accept_ra_rtr_pref = 1,
.rtr_probe_interval = 60 * HZ,
#ifdef CONFIG_IPV6_ROUTE_INFO
.accept_ra_rt_info_max_plen = 0,
#endif
#endif
.proxy_ndp = 0,
.accept_source_route = 0, /* we do not accept RH0 by default. */
.disable_ipv6 = 0,
.accept_dad = 1,
.suppress_frag_ndisc = 1,
.accept_ra_mtu = 1,
};
static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = {
.forwarding = 0,
.hop_limit = IPV6_DEFAULT_HOPLIMIT,
.mtu6 = IPV6_MIN_MTU,
.accept_ra = 1,
.accept_redirects = 1,
.autoconf = 1,
.force_mld_version = 0,
.mldv1_unsolicited_report_interval = 10 * HZ,
.mldv2_unsolicited_report_interval = HZ,
.dad_transmits = 1,
.rtr_solicits = MAX_RTR_SOLICITATIONS,
.rtr_solicit_interval = RTR_SOLICITATION_INTERVAL,
.rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY,
.use_tempaddr = 0,
.temp_valid_lft = TEMP_VALID_LIFETIME,
.temp_prefered_lft = TEMP_PREFERRED_LIFETIME,
.regen_max_retry = REGEN_MAX_RETRY,
.max_desync_factor = MAX_DESYNC_FACTOR,
.max_addresses = IPV6_MAX_ADDRESSES,
.accept_ra_defrtr = 1,
.accept_ra_from_local = 0,
.accept_ra_pinfo = 1,
#ifdef CONFIG_IPV6_ROUTER_PREF
.accept_ra_rtr_pref = 1,
.rtr_probe_interval = 60 * HZ,
#ifdef CONFIG_IPV6_ROUTE_INFO
.accept_ra_rt_info_max_plen = 0,
#endif
#endif
.proxy_ndp = 0,
.accept_source_route = 0, /* we do not accept RH0 by default. */
.disable_ipv6 = 0,
.accept_dad = 1,
.suppress_frag_ndisc = 1,
.accept_ra_mtu = 1,
};
/* Check if a valid qdisc is available */
static inline bool addrconf_qdisc_ok(const struct net_device *dev)
{
return !qdisc_tx_is_noop(dev);
}
static void addrconf_del_rs_timer(struct inet6_dev *idev)
{
if (del_timer(&idev->rs_timer))
__in6_dev_put(idev);
}
static void addrconf_del_dad_work(struct inet6_ifaddr *ifp)
{
if (cancel_delayed_work(&ifp->dad_work))
__in6_ifa_put(ifp);
}
static void addrconf_mod_rs_timer(struct inet6_dev *idev,
unsigned long when)
{
if (!timer_pending(&idev->rs_timer))
in6_dev_hold(idev);
mod_timer(&idev->rs_timer, jiffies + when);
}
static void addrconf_mod_dad_work(struct inet6_ifaddr *ifp,
unsigned long delay)
{
if (!delayed_work_pending(&ifp->dad_work))
in6_ifa_hold(ifp);
mod_delayed_work(addrconf_wq, &ifp->dad_work, delay);
}
static int snmp6_alloc_dev(struct inet6_dev *idev)
{
int i;
idev->stats.ipv6 = alloc_percpu(struct ipstats_mib);
if (!idev->stats.ipv6)
goto err_ip;
for_each_possible_cpu(i) {
struct ipstats_mib *addrconf_stats;
addrconf_stats = per_cpu_ptr(idev->stats.ipv6, i);
u64_stats_init(&addrconf_stats->syncp);
}
idev->stats.icmpv6dev = kzalloc(sizeof(struct icmpv6_mib_device),
GFP_KERNEL);
if (!idev->stats.icmpv6dev)
goto err_icmp;
idev->stats.icmpv6msgdev = kzalloc(sizeof(struct icmpv6msg_mib_device),
GFP_KERNEL);
if (!idev->stats.icmpv6msgdev)
goto err_icmpmsg;
return 0;
err_icmpmsg:
kfree(idev->stats.icmpv6dev);
err_icmp:
free_percpu(idev->stats.ipv6);
err_ip:
return -ENOMEM;
}
static struct inet6_dev *ipv6_add_dev(struct net_device *dev)
{
struct inet6_dev *ndev;
int err = -ENOMEM;
ASSERT_RTNL();
if (dev->mtu < IPV6_MIN_MTU)
return ERR_PTR(-EINVAL);
ndev = kzalloc(sizeof(struct inet6_dev), GFP_KERNEL);
if (ndev == NULL)
return ERR_PTR(err);
rwlock_init(&ndev->lock);
ndev->dev = dev;
INIT_LIST_HEAD(&ndev->addr_list);
setup_timer(&ndev->rs_timer, addrconf_rs_timer,
(unsigned long)ndev);
memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf));
ndev->cnf.mtu6 = dev->mtu;
ndev->cnf.sysctl = NULL;
ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl);
if (ndev->nd_parms == NULL) {
kfree(ndev);
return ERR_PTR(err);
}
if (ndev->cnf.forwarding)
dev_disable_lro(dev);
/* We refer to the device */
dev_hold(dev);
if (snmp6_alloc_dev(ndev) < 0) {
ADBG(KERN_WARNING
"%s: cannot allocate memory for statistics; dev=%s.\n",
__func__, dev->name);
neigh_parms_release(&nd_tbl, ndev->nd_parms);
dev_put(dev);
kfree(ndev);
return ERR_PTR(err);
}
if (snmp6_register_dev(ndev) < 0) {
ADBG(KERN_WARNING
"%s: cannot create /proc/net/dev_snmp6/%s\n",
__func__, dev->name);
goto err_release;
}
/* One reference from device. We must do this before
* we invoke __ipv6_regen_rndid().
*/
in6_dev_hold(ndev);
if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
ndev->cnf.accept_dad = -1;
#if IS_ENABLED(CONFIG_IPV6_SIT)
if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) {
pr_info("%s: Disabled Multicast RS\n", dev->name);
ndev->cnf.rtr_solicits = 0;
}
#endif
INIT_LIST_HEAD(&ndev->tempaddr_list);
setup_timer(&ndev->regen_timer, ipv6_regen_rndid, (unsigned long)ndev);
if ((dev->flags&IFF_LOOPBACK) ||
dev->type == ARPHRD_TUNNEL ||
dev->type == ARPHRD_TUNNEL6 ||
dev->type == ARPHRD_SIT ||
dev->type == ARPHRD_NONE) {
ndev->cnf.use_tempaddr = -1;
} else {
in6_dev_hold(ndev);
ipv6_regen_rndid((unsigned long) ndev);
}
ndev->token = in6addr_any;
if (netif_running(dev) && addrconf_qdisc_ok(dev))
ndev->if_flags |= IF_READY;
ipv6_mc_init_dev(ndev);
ndev->tstamp = jiffies;
err = addrconf_sysctl_register(ndev);
if (err) {
ipv6_mc_destroy_dev(ndev);
del_timer(&ndev->regen_timer);
goto err_release;
}
/* protected by rtnl_lock */
rcu_assign_pointer(dev->ip6_ptr, ndev);
/* Join interface-local all-node multicast group */
ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allnodes);
/* Join all-node multicast group */
ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes);
/* Join all-router multicast group if forwarding is set */
if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST))
ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
return ndev;
err_release:
neigh_parms_release(&nd_tbl, ndev->nd_parms);
ndev->dead = 1;
in6_dev_finish_destroy(ndev);
return ERR_PTR(err);
}
static struct inet6_dev *ipv6_find_idev(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = __in6_dev_get(dev);
if (!idev) {
idev = ipv6_add_dev(dev);
if (IS_ERR(idev))
return NULL;
}
if (dev->flags&IFF_UP)
ipv6_mc_up(idev);
return idev;
}
static int inet6_netconf_msgsize_devconf(int type)
{
int size = NLMSG_ALIGN(sizeof(struct netconfmsg))
+ nla_total_size(4); /* NETCONFA_IFINDEX */
/* type -1 is used for ALL */
if (type == -1 || type == NETCONFA_FORWARDING)
size += nla_total_size(4);
#ifdef CONFIG_IPV6_MROUTE
if (type == -1 || type == NETCONFA_MC_FORWARDING)
size += nla_total_size(4);
#endif
if (type == -1 || type == NETCONFA_PROXY_NEIGH)
size += nla_total_size(4);
return size;
}
static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex,
struct ipv6_devconf *devconf, u32 portid,
u32 seq, int event, unsigned int flags,
int type)
{
struct nlmsghdr *nlh;
struct netconfmsg *ncm;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
flags);
if (nlh == NULL)
return -EMSGSIZE;
ncm = nlmsg_data(nlh);
ncm->ncm_family = AF_INET6;
if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0)
goto nla_put_failure;
/* type -1 is used for ALL */
if ((type == -1 || type == NETCONFA_FORWARDING) &&
nla_put_s32(skb, NETCONFA_FORWARDING, devconf->forwarding) < 0)
goto nla_put_failure;
#ifdef CONFIG_IPV6_MROUTE
if ((type == -1 || type == NETCONFA_MC_FORWARDING) &&
nla_put_s32(skb, NETCONFA_MC_FORWARDING,
devconf->mc_forwarding) < 0)
goto nla_put_failure;
#endif
if ((type == -1 || type == NETCONFA_PROXY_NEIGH) &&
nla_put_s32(skb, NETCONFA_PROXY_NEIGH, devconf->proxy_ndp) < 0)
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
void inet6_netconf_notify_devconf(struct net *net, int type, int ifindex,
struct ipv6_devconf *devconf)
{
struct sk_buff *skb;
int err = -ENOBUFS;
skb = nlmsg_new(inet6_netconf_msgsize_devconf(type), GFP_ATOMIC);
if (skb == NULL)
goto errout;
err = inet6_netconf_fill_devconf(skb, ifindex, devconf, 0, 0,
RTM_NEWNETCONF, 0, type);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_NETCONF, NULL, GFP_ATOMIC);
return;
errout:
rtnl_set_sk_err(net, RTNLGRP_IPV6_NETCONF, err);
}
static const struct nla_policy devconf_ipv6_policy[NETCONFA_MAX+1] = {
[NETCONFA_IFINDEX] = { .len = sizeof(int) },
[NETCONFA_FORWARDING] = { .len = sizeof(int) },
[NETCONFA_PROXY_NEIGH] = { .len = sizeof(int) },
};
static int inet6_netconf_get_devconf(struct sk_buff *in_skb,
struct nlmsghdr *nlh)
{
struct net *net = sock_net(in_skb->sk);
struct nlattr *tb[NETCONFA_MAX+1];
struct netconfmsg *ncm;
struct sk_buff *skb;
struct ipv6_devconf *devconf;
struct inet6_dev *in6_dev;
struct net_device *dev;
int ifindex;
int err;
err = nlmsg_parse(nlh, sizeof(*ncm), tb, NETCONFA_MAX,
devconf_ipv6_policy);
if (err < 0)
goto errout;
err = EINVAL;
if (!tb[NETCONFA_IFINDEX])
goto errout;
ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
switch (ifindex) {
case NETCONFA_IFINDEX_ALL:
devconf = net->ipv6.devconf_all;
break;
case NETCONFA_IFINDEX_DEFAULT:
devconf = net->ipv6.devconf_dflt;
break;
default:
dev = __dev_get_by_index(net, ifindex);
if (dev == NULL)
goto errout;
in6_dev = __in6_dev_get(dev);
if (in6_dev == NULL)
goto errout;
devconf = &in6_dev->cnf;
break;
}
err = -ENOBUFS;
skb = nlmsg_new(inet6_netconf_msgsize_devconf(-1), GFP_ATOMIC);
if (skb == NULL)
goto errout;
err = inet6_netconf_fill_devconf(skb, ifindex, devconf,
NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
-1);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
}
static int inet6_netconf_dump_devconf(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
int h, s_h;
int idx, s_idx;
struct net_device *dev;
struct inet6_dev *idev;
struct hlist_head *head;
s_h = cb->args[0];
s_idx = idx = cb->args[1];
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &net->dev_index_head[h];
rcu_read_lock();
cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^
net->dev_base_seq;
hlist_for_each_entry_rcu(dev, head, index_hlist) {
if (idx < s_idx)
goto cont;
idev = __in6_dev_get(dev);
if (!idev)
goto cont;
if (inet6_netconf_fill_devconf(skb, dev->ifindex,
&idev->cnf,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_NEWNETCONF,
NLM_F_MULTI,
-1) < 0) {
rcu_read_unlock();
goto done;
}
nl_dump_check_consistent(cb, nlmsg_hdr(skb));
cont:
idx++;
}
rcu_read_unlock();
}
if (h == NETDEV_HASHENTRIES) {
if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_NEWNETCONF, NLM_F_MULTI,
-1) < 0)
goto done;
else
h++;
}
if (h == NETDEV_HASHENTRIES + 1) {
if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_NEWNETCONF, NLM_F_MULTI,
-1) < 0)
goto done;
else
h++;
}
done:
cb->args[0] = h;
cb->args[1] = idx;
return skb->len;
}
#ifdef CONFIG_SYSCTL
static void dev_forward_change(struct inet6_dev *idev)
{
struct net_device *dev;
struct inet6_ifaddr *ifa;
if (!idev)
return;
dev = idev->dev;
if (idev->cnf.forwarding)
dev_disable_lro(dev);
if (dev->flags & IFF_MULTICAST) {
if (idev->cnf.forwarding) {
ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allrouters);
ipv6_dev_mc_inc(dev, &in6addr_sitelocal_allrouters);
} else {
ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters);
ipv6_dev_mc_dec(dev, &in6addr_interfacelocal_allrouters);
ipv6_dev_mc_dec(dev, &in6addr_sitelocal_allrouters);
}
}
list_for_each_entry(ifa, &idev->addr_list, if_list) {
if (ifa->flags&IFA_F_TENTATIVE)
continue;
if (idev->cnf.forwarding)
addrconf_join_anycast(ifa);
else
addrconf_leave_anycast(ifa);
}
inet6_netconf_notify_devconf(dev_net(dev), NETCONFA_FORWARDING,
dev->ifindex, &idev->cnf);
}
static void addrconf_forward_change(struct net *net, __s32 newf)
{
struct net_device *dev;
struct inet6_dev *idev;
for_each_netdev(net, dev) {
idev = __in6_dev_get(dev);
if (idev) {
int changed = (!idev->cnf.forwarding) ^ (!newf);
idev->cnf.forwarding = newf;
if (changed)
dev_forward_change(idev);
}
}
}
static int addrconf_fixup_forwarding(struct ctl_table *table, int *p, int newf)
{
struct net *net;
int old;
if (!rtnl_trylock())
return restart_syscall();
net = (struct net *)table->extra2;
old = *p;
*p = newf;
if (p == &net->ipv6.devconf_dflt->forwarding) {
if ((!newf) ^ (!old))
inet6_netconf_notify_devconf(net, NETCONFA_FORWARDING,
NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt);
rtnl_unlock();
return 0;
}
if (p == &net->ipv6.devconf_all->forwarding) {
net->ipv6.devconf_dflt->forwarding = newf;
addrconf_forward_change(net, newf);
if ((!newf) ^ (!old))
inet6_netconf_notify_devconf(net, NETCONFA_FORWARDING,
NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all);
} else if ((!newf) ^ (!old))
dev_forward_change((struct inet6_dev *)table->extra1);
rtnl_unlock();
if (newf)
rt6_purge_dflt_routers(net);
return 1;
}
#endif
/* Nobody refers to this ifaddr, destroy it */
void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp)
{
WARN_ON(!hlist_unhashed(&ifp->addr_lst));
#ifdef NET_REFCNT_DEBUG
pr_debug("%s\n", __func__);
#endif
in6_dev_put(ifp->idev);
if (cancel_delayed_work(&ifp->dad_work))
pr_notice("delayed DAD work was pending while freeing ifa=%p\n",
ifp);
if (ifp->state != INET6_IFADDR_STATE_DEAD) {
pr_warn("Freeing alive inet6 address %p\n", ifp);
return;
}
ip6_rt_put(ifp->rt);
kfree_rcu(ifp, rcu);
}
static void
ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp)
{
struct list_head *p;
int ifp_scope = ipv6_addr_src_scope(&ifp->addr);
/*
* Each device address list is sorted in order of scope -
* global before linklocal.
*/
list_for_each(p, &idev->addr_list) {
struct inet6_ifaddr *ifa
= list_entry(p, struct inet6_ifaddr, if_list);
if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr))
break;
}
list_add_tail(&ifp->if_list, p);
}
static u32 inet6_addr_hash(const struct in6_addr *addr)
{
return hash_32(ipv6_addr_hash(addr), IN6_ADDR_HSIZE_SHIFT);
}
/* On success it returns ifp with increased reference count */
static struct inet6_ifaddr *
ipv6_add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
const struct in6_addr *peer_addr, int pfxlen,
int scope, u32 flags, u32 valid_lft, u32 prefered_lft)
{
struct inet6_ifaddr *ifa = NULL;
struct rt6_info *rt;
unsigned int hash;
int err = 0;
int addr_type = ipv6_addr_type(addr);
if (addr_type == IPV6_ADDR_ANY ||
addr_type & IPV6_ADDR_MULTICAST ||
(!(idev->dev->flags & IFF_LOOPBACK) &&
addr_type & IPV6_ADDR_LOOPBACK))
return ERR_PTR(-EADDRNOTAVAIL);
rcu_read_lock_bh();
if (idev->dead) {
err = -ENODEV; /*XXX*/
goto out2;
}
if (idev->cnf.disable_ipv6) {
err = -EACCES;
goto out2;
}
spin_lock(&addrconf_hash_lock);
/* Ignore adding duplicate addresses on an interface */
if (ipv6_chk_same_addr(dev_net(idev->dev), addr, idev->dev)) {
ADBG("ipv6_add_addr: already assigned\n");
err = -EEXIST;
goto out;
}
ifa = kzalloc(sizeof(struct inet6_ifaddr), GFP_ATOMIC);
if (ifa == NULL) {
ADBG("ipv6_add_addr: malloc failed\n");
err = -ENOBUFS;
goto out;
}
rt = addrconf_dst_alloc(idev, addr, false);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
goto out;
}
neigh_parms_data_state_setall(idev->nd_parms);
ifa->addr = *addr;
if (peer_addr)
ifa->peer_addr = *peer_addr;
spin_lock_init(&ifa->lock);
spin_lock_init(&ifa->state_lock);
INIT_DELAYED_WORK(&ifa->dad_work, addrconf_dad_work);
INIT_HLIST_NODE(&ifa->addr_lst);
ifa->scope = scope;
ifa->prefix_len = pfxlen;
ifa->flags = flags | IFA_F_TENTATIVE;
ifa->valid_lft = valid_lft;
ifa->prefered_lft = prefered_lft;
ifa->cstamp = ifa->tstamp = jiffies;
ifa->tokenized = false;
ifa->rt = rt;
ifa->idev = idev;
in6_dev_hold(idev);
/* For caller */
in6_ifa_hold(ifa);
/* Add to big hash table */
hash = inet6_addr_hash(addr);
hlist_add_head_rcu(&ifa->addr_lst, &inet6_addr_lst[hash]);
spin_unlock(&addrconf_hash_lock);
write_lock(&idev->lock);
/* Add to inet6_dev unicast addr list. */
ipv6_link_dev_addr(idev, ifa);
if (ifa->flags&IFA_F_TEMPORARY) {
list_add(&ifa->tmp_list, &idev->tempaddr_list);
in6_ifa_hold(ifa);
}
in6_ifa_hold(ifa);
write_unlock(&idev->lock);
out2:
rcu_read_unlock_bh();
if (likely(err == 0))
inet6addr_notifier_call_chain(NETDEV_UP, ifa);
else {
kfree(ifa);
ifa = ERR_PTR(err);
}
return ifa;
out:
spin_unlock(&addrconf_hash_lock);
goto out2;
}
enum cleanup_prefix_rt_t {
CLEANUP_PREFIX_RT_NOP, /* no cleanup action for prefix route */
CLEANUP_PREFIX_RT_DEL, /* delete the prefix route */
CLEANUP_PREFIX_RT_EXPIRE, /* update the lifetime of the prefix route */
};
/*
* Check, whether the prefix for ifp would still need a prefix route
* after deleting ifp. The function returns one of the CLEANUP_PREFIX_RT_*
* constants.
*
* 1) we don't purge prefix if address was not permanent.
* prefix is managed by its own lifetime.
* 2) we also don't purge, if the address was IFA_F_NOPREFIXROUTE.
* 3) if there are no addresses, delete prefix.
* 4) if there are still other permanent address(es),
* corresponding prefix is still permanent.
* 5) if there are still other addresses with IFA_F_NOPREFIXROUTE,
* don't purge the prefix, assume user space is managing it.
* 6) otherwise, update prefix lifetime to the
* longest valid lifetime among the corresponding
* addresses on the device.
* Note: subsequent RA will update lifetime.
**/
static enum cleanup_prefix_rt_t
check_cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long *expires)
{
struct inet6_ifaddr *ifa;
struct inet6_dev *idev = ifp->idev;
unsigned long lifetime;
enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_DEL;
*expires = jiffies;
list_for_each_entry(ifa, &idev->addr_list, if_list) {
if (ifa == ifp)
continue;
if (!ipv6_prefix_equal(&ifa->addr, &ifp->addr,
ifp->prefix_len))
continue;
if (ifa->flags & (IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE))
return CLEANUP_PREFIX_RT_NOP;
action = CLEANUP_PREFIX_RT_EXPIRE;
spin_lock(&ifa->lock);
lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ);
/*
* Note: Because this address is
* not permanent, lifetime <
* LONG_MAX / HZ here.
*/
if (time_before(*expires, ifa->tstamp + lifetime * HZ))
*expires = ifa->tstamp + lifetime * HZ;
spin_unlock(&ifa->lock);
}
return action;
}
static void
cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long expires, bool del_rt)
{
struct rt6_info *rt;
rt = addrconf_get_prefix_route(&ifp->addr,
ifp->prefix_len,
ifp->idev->dev,
0, RTF_GATEWAY | RTF_DEFAULT);
if (rt) {
if (del_rt)
ip6_del_rt(rt);
else {
if (!(rt->rt6i_flags & RTF_EXPIRES))
rt6_set_expires(rt, expires);
ip6_rt_put(rt);
}
}
}
/* This function wants to get referenced ifp and releases it before return */
static void ipv6_del_addr(struct inet6_ifaddr *ifp)
{
int state;
enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_NOP;
unsigned long expires;
ASSERT_RTNL();
spin_lock_bh(&ifp->state_lock);
state = ifp->state;
ifp->state = INET6_IFADDR_STATE_DEAD;
spin_unlock_bh(&ifp->state_lock);
if (state == INET6_IFADDR_STATE_DEAD)
goto out;
spin_lock_bh(&addrconf_hash_lock);
hlist_del_init_rcu(&ifp->addr_lst);
spin_unlock_bh(&addrconf_hash_lock);
write_lock_bh(&ifp->idev->lock);
if (ifp->flags&IFA_F_TEMPORARY) {
list_del(&ifp->tmp_list);
if (ifp->ifpub) {
in6_ifa_put(ifp->ifpub);
ifp->ifpub = NULL;
}
__in6_ifa_put(ifp);
}
if (ifp->flags & IFA_F_PERMANENT && !(ifp->flags & IFA_F_NOPREFIXROUTE))
action = check_cleanup_prefix_route(ifp, &expires);
list_del_init(&ifp->if_list);
__in6_ifa_put(ifp);
write_unlock_bh(&ifp->idev->lock);
addrconf_del_dad_work(ifp);
ipv6_ifa_notify(RTM_DELADDR, ifp);
inet6addr_notifier_call_chain(NETDEV_DOWN, ifp);
if (action != CLEANUP_PREFIX_RT_NOP) {
cleanup_prefix_route(ifp, expires,
action == CLEANUP_PREFIX_RT_DEL);
}
/* clean up prefsrc entries */
rt6_remove_prefsrc(ifp);
out:
in6_ifa_put(ifp);
}
static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, struct inet6_ifaddr *ift)
{
struct inet6_dev *idev = ifp->idev;
struct in6_addr addr, *tmpaddr;
unsigned long tmp_prefered_lft, tmp_valid_lft, tmp_tstamp, age;
unsigned long regen_advance;
int tmp_plen;
int ret = 0;
u32 addr_flags;
unsigned long now = jiffies;
write_lock_bh(&idev->lock);
if (ift) {
spin_lock_bh(&ift->lock);
memcpy(&addr.s6_addr[8], &ift->addr.s6_addr[8], 8);
spin_unlock_bh(&ift->lock);
tmpaddr = &addr;
} else {
tmpaddr = NULL;
}
retry:
in6_dev_hold(idev);
if (idev->cnf.use_tempaddr <= 0) {
write_unlock_bh(&idev->lock);
pr_info("%s: use_tempaddr is disabled\n", __func__);
in6_dev_put(idev);
ret = -1;
goto out;
}
spin_lock_bh(&ifp->lock);
if (ifp->regen_count++ >= idev->cnf.regen_max_retry) {
idev->cnf.use_tempaddr = -1; /*XXX*/
spin_unlock_bh(&ifp->lock);
write_unlock_bh(&idev->lock);
pr_warn("%s: regeneration time exceeded - disabled temporary address support\n",
__func__);
in6_dev_put(idev);
ret = -1;
goto out;
}
in6_ifa_hold(ifp);
memcpy(addr.s6_addr, ifp->addr.s6_addr, 8);
__ipv6_try_regen_rndid(idev, tmpaddr);
memcpy(&addr.s6_addr[8], idev->rndid, 8);
age = (now - ifp->tstamp) / HZ;
tmp_valid_lft = min_t(__u32,
ifp->valid_lft,
idev->cnf.temp_valid_lft + age);
tmp_prefered_lft = min_t(__u32,
ifp->prefered_lft,
idev->cnf.temp_prefered_lft + age -
idev->cnf.max_desync_factor);
tmp_plen = ifp->prefix_len;
tmp_tstamp = ifp->tstamp;
spin_unlock_bh(&ifp->lock);
regen_advance = idev->cnf.regen_max_retry *
idev->cnf.dad_transmits *
NEIGH_VAR(idev->nd_parms, RETRANS_TIME) / HZ;
write_unlock_bh(&idev->lock);
/* A temporary address is created only if this calculated Preferred
* Lifetime is greater than REGEN_ADVANCE time units. In particular,
* an implementation must not create a temporary address with a zero
* Preferred Lifetime.
* Use age calculation as in addrconf_verify to avoid unnecessary
* temporary addresses being generated.
*/
age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
if (tmp_prefered_lft <= regen_advance + age) {
in6_ifa_put(ifp);
in6_dev_put(idev);
ret = -1;
goto out;
}
addr_flags = IFA_F_TEMPORARY;
/* set in addrconf_prefix_rcv() */
if (ifp->flags & IFA_F_OPTIMISTIC)
addr_flags |= IFA_F_OPTIMISTIC;
ift = ipv6_add_addr(idev, &addr, NULL, tmp_plen,
ipv6_addr_scope(&addr), addr_flags,
tmp_valid_lft, tmp_prefered_lft);
if (IS_ERR(ift)) {
in6_ifa_put(ifp);
in6_dev_put(idev);
pr_info("%s: retry temporary address regeneration\n", __func__);
tmpaddr = &addr;
write_lock_bh(&idev->lock);
goto retry;
}
spin_lock_bh(&ift->lock);
ift->ifpub = ifp;
ift->cstamp = now;
ift->tstamp = tmp_tstamp;
spin_unlock_bh(&ift->lock);
addrconf_dad_start(ift);
in6_ifa_put(ift);
in6_dev_put(idev);
out:
return ret;
}
/*
* Choose an appropriate source address (RFC3484)
*/
enum {
IPV6_SADDR_RULE_INIT = 0,
IPV6_SADDR_RULE_LOCAL,
IPV6_SADDR_RULE_SCOPE,
IPV6_SADDR_RULE_PREFERRED,
#ifdef CONFIG_IPV6_MIP6
IPV6_SADDR_RULE_HOA,
#endif
IPV6_SADDR_RULE_OIF,
IPV6_SADDR_RULE_LABEL,
IPV6_SADDR_RULE_PRIVACY,
IPV6_SADDR_RULE_ORCHID,
IPV6_SADDR_RULE_PREFIX,
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
IPV6_SADDR_RULE_NOT_OPTIMISTIC,
#endif
IPV6_SADDR_RULE_MAX
};
struct ipv6_saddr_score {
int rule;
int addr_type;
struct inet6_ifaddr *ifa;
DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX);
int scopedist;
int matchlen;
};
struct ipv6_saddr_dst {
const struct in6_addr *addr;
int ifindex;
int scope;
int label;
unsigned int prefs;
};
static inline int ipv6_saddr_preferred(int type)
{
if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK))
return 1;
return 0;
}
static inline bool ipv6_use_optimistic_addr(struct inet6_dev *idev)
{
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
return idev && idev->cnf.optimistic_dad && idev->cnf.use_optimistic;
#else
return false;
#endif
}
static int ipv6_get_saddr_eval(struct net *net,
struct ipv6_saddr_score *score,
struct ipv6_saddr_dst *dst,
int i)
{
int ret;
if (i <= score->rule) {
switch (i) {
case IPV6_SADDR_RULE_SCOPE:
ret = score->scopedist;
break;
case IPV6_SADDR_RULE_PREFIX:
ret = score->matchlen;
break;
default:
ret = !!test_bit(i, score->scorebits);
}
goto out;
}
switch (i) {
case IPV6_SADDR_RULE_INIT:
/* Rule 0: remember if hiscore is not ready yet */
ret = !!score->ifa;
break;
case IPV6_SADDR_RULE_LOCAL:
/* Rule 1: Prefer same address */
ret = ipv6_addr_equal(&score->ifa->addr, dst->addr);
break;
case IPV6_SADDR_RULE_SCOPE:
/* Rule 2: Prefer appropriate scope
*
* ret
* ^
* -1 | d 15
* ---+--+-+---> scope
* |
* | d is scope of the destination.
* B-d | \
* | \ <- smaller scope is better if
* B-15 | \ if scope is enough for destination.
* | ret = B - scope (-1 <= scope >= d <= 15).
* d-C-1 | /
* |/ <- greater is better
* -C / if scope is not enough for destination.
* /| ret = scope - C (-1 <= d < scope <= 15).
*
* d - C - 1 < B -15 (for all -1 <= d <= 15).
* C > d + 14 - B >= 15 + 14 - B = 29 - B.
* Assume B = 0 and we get C > 29.
*/
ret = __ipv6_addr_src_scope(score->addr_type);
if (ret >= dst->scope)
ret = -ret;
else
ret -= 128; /* 30 is enough */
score->scopedist = ret;
break;
case IPV6_SADDR_RULE_PREFERRED:
{
/* Rule 3: Avoid deprecated and optimistic addresses */
u8 avoid = IFA_F_DEPRECATED;
if (!ipv6_use_optimistic_addr(score->ifa->idev))
avoid |= IFA_F_OPTIMISTIC;
ret = ipv6_saddr_preferred(score->addr_type) ||
!(score->ifa->flags & avoid);
break;
}
#ifdef CONFIG_IPV6_MIP6
case IPV6_SADDR_RULE_HOA:
{
/* Rule 4: Prefer home address */
int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA);
ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome;
break;
}
#endif
case IPV6_SADDR_RULE_OIF:
/* Rule 5: Prefer outgoing interface */
ret = (!dst->ifindex ||
dst->ifindex == score->ifa->idev->dev->ifindex);
break;
case IPV6_SADDR_RULE_LABEL:
/* Rule 6: Prefer matching label */
ret = ipv6_addr_label(net,
&score->ifa->addr, score->addr_type,
score->ifa->idev->dev->ifindex) == dst->label;
break;
case IPV6_SADDR_RULE_PRIVACY:
{
/* Rule 7: Prefer public address
* Note: prefer temporary address if use_tempaddr >= 2
*/
int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ?
!!(dst->prefs & IPV6_PREFER_SRC_TMP) :
score->ifa->idev->cnf.use_tempaddr >= 2;
ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp;
break;
}
case IPV6_SADDR_RULE_ORCHID:
/* Rule 8-: Prefer ORCHID vs ORCHID or
* non-ORCHID vs non-ORCHID
*/
ret = !(ipv6_addr_orchid(&score->ifa->addr) ^
ipv6_addr_orchid(dst->addr));
break;
case IPV6_SADDR_RULE_PREFIX:
/* Rule 8: Use longest matching prefix */
ret = ipv6_addr_diff(&score->ifa->addr, dst->addr);
if (ret > score->ifa->prefix_len)
ret = score->ifa->prefix_len;
score->matchlen = ret;
break;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
case IPV6_SADDR_RULE_NOT_OPTIMISTIC:
/* Optimistic addresses still have lower precedence than other
* preferred addresses.
*/
ret = !(score->ifa->flags & IFA_F_OPTIMISTIC);
break;
#endif
default:
ret = 0;
}
if (ret)
__set_bit(i, score->scorebits);
score->rule = i;
out:
return ret;
}
int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev,
const struct in6_addr *daddr, unsigned int prefs,
struct in6_addr *saddr)
{
struct ipv6_saddr_score scores[2],
*score = &scores[0], *hiscore = &scores[1];
struct ipv6_saddr_dst dst;
struct net_device *dev;
int dst_type;
dst_type = __ipv6_addr_type(daddr);
dst.addr = daddr;
dst.ifindex = dst_dev ? dst_dev->ifindex : 0;
dst.scope = __ipv6_addr_src_scope(dst_type);
dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex);
dst.prefs = prefs;
hiscore->rule = -1;
hiscore->ifa = NULL;
rcu_read_lock();
for_each_netdev_rcu(net, dev) {
struct inet6_dev *idev;
/* Candidate Source Address (section 4)
* - multicast and link-local destination address,
* the set of candidate source address MUST only
* include addresses assigned to interfaces
* belonging to the same link as the outgoing
* interface.
* (- For site-local destination addresses, the
* set of candidate source addresses MUST only
* include addresses assigned to interfaces
* belonging to the same site as the outgoing
* interface.)
*/
if (((dst_type & IPV6_ADDR_MULTICAST) ||
dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL) &&
dst.ifindex && dev->ifindex != dst.ifindex)
continue;
idev = __in6_dev_get(dev);
if (!idev)
continue;
read_lock_bh(&idev->lock);
list_for_each_entry(score->ifa, &idev->addr_list, if_list) {
int i;
/*
* - Tentative Address (RFC2462 section 5.4)
* - A tentative address is not considered
* "assigned to an interface" in the traditional
* sense, unless it is also flagged as optimistic.
* - Candidate Source Address (section 4)
* - In any case, anycast addresses, multicast
* addresses, and the unspecified address MUST
* NOT be included in a candidate set.
*/
if ((score->ifa->flags & IFA_F_TENTATIVE) &&
(!(score->ifa->flags & IFA_F_OPTIMISTIC)))
continue;
score->addr_type = __ipv6_addr_type(&score->ifa->addr);
if (unlikely(score->addr_type == IPV6_ADDR_ANY ||
score->addr_type & IPV6_ADDR_MULTICAST)) {
net_dbg_ratelimited("ADDRCONF: unspecified / multicast address assigned as unicast address on %s",
dev->name);
continue;
}
score->rule = -1;
bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX);
for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) {
int minihiscore, miniscore;
minihiscore = ipv6_get_saddr_eval(net, hiscore, &dst, i);
miniscore = ipv6_get_saddr_eval(net, score, &dst, i);
if (minihiscore > miniscore) {
if (i == IPV6_SADDR_RULE_SCOPE &&
score->scopedist > 0) {
/*
* special case:
* each remaining entry
* has too small (not enough)
* scope, because ifa entries
* are sorted by their scope
* values.
*/
goto try_nextdev;
}
break;
} else if (minihiscore < miniscore) {
if (hiscore->ifa)
in6_ifa_put(hiscore->ifa);
in6_ifa_hold(score->ifa);
swap(hiscore, score);
/* restore our iterator */
score->ifa = hiscore->ifa;
break;
}
}
}
try_nextdev:
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
if (!hiscore->ifa)
return -EADDRNOTAVAIL;
*saddr = hiscore->ifa->addr;
in6_ifa_put(hiscore->ifa);
return 0;
}
EXPORT_SYMBOL(ipv6_dev_get_saddr);
int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr,
u32 banned_flags)
{
struct inet6_ifaddr *ifp;
int err = -EADDRNOTAVAIL;
list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
if (ifp->scope > IFA_LINK)
break;
if (ifp->scope == IFA_LINK &&
!(ifp->flags & banned_flags)) {
*addr = ifp->addr;
err = 0;
break;
}
}
return err;
}
int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr,
u32 banned_flags)
{
struct inet6_dev *idev;
int err = -EADDRNOTAVAIL;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev) {
read_lock_bh(&idev->lock);
err = __ipv6_get_lladdr(idev, addr, banned_flags);
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
return err;
}
static int ipv6_count_addresses(struct inet6_dev *idev)
{
int cnt = 0;
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
list_for_each_entry(ifp, &idev->addr_list, if_list)
cnt++;
read_unlock_bh(&idev->lock);
return cnt;
}
int ipv6_chk_addr(struct net *net, const struct in6_addr *addr,
const struct net_device *dev, int strict)
{
return ipv6_chk_addr_and_flags(net, addr, dev, strict, IFA_F_TENTATIVE);
}
EXPORT_SYMBOL(ipv6_chk_addr);
int ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
const struct net_device *dev, int strict,
u32 banned_flags)
{
struct inet6_ifaddr *ifp;
unsigned int hash = inet6_addr_hash(addr);
u32 ifp_flags;
rcu_read_lock_bh();
hlist_for_each_entry_rcu(ifp, &inet6_addr_lst[hash], addr_lst) {
if (!net_eq(dev_net(ifp->idev->dev), net))
continue;
/* Decouple optimistic from tentative for evaluation here.
* Ban optimistic addresses explicitly, when required.
*/
ifp_flags = (ifp->flags&IFA_F_OPTIMISTIC)
? (ifp->flags&~IFA_F_TENTATIVE)
: ifp->flags;
if (ipv6_addr_equal(&ifp->addr, addr) &&
!(ifp_flags&banned_flags) &&
(dev == NULL || ifp->idev->dev == dev ||
!(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) {
rcu_read_unlock_bh();
return 1;
}
}
rcu_read_unlock_bh();
return 0;
}
EXPORT_SYMBOL(ipv6_chk_addr_and_flags);
static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
struct net_device *dev)
{
unsigned int hash = inet6_addr_hash(addr);
struct inet6_ifaddr *ifp;
hlist_for_each_entry(ifp, &inet6_addr_lst[hash], addr_lst) {
if (!net_eq(dev_net(ifp->idev->dev), net))
continue;
if (ipv6_addr_equal(&ifp->addr, addr)) {
if (dev == NULL || ifp->idev->dev == dev)
return true;
}
}
return false;
}
/* Compares an address/prefix_len with addresses on device @dev.
* If one is found it returns true.
*/
bool ipv6_chk_custom_prefix(const struct in6_addr *addr,
const unsigned int prefix_len, struct net_device *dev)
{
struct inet6_dev *idev;
struct inet6_ifaddr *ifa;
bool ret = false;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev) {
read_lock_bh(&idev->lock);
list_for_each_entry(ifa, &idev->addr_list, if_list) {
ret = ipv6_prefix_equal(addr, &ifa->addr, prefix_len);
if (ret)
break;
}
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(ipv6_chk_custom_prefix);
int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev)
{
struct inet6_dev *idev;
struct inet6_ifaddr *ifa;
int onlink;
onlink = 0;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev) {
read_lock_bh(&idev->lock);
list_for_each_entry(ifa, &idev->addr_list, if_list) {
onlink = ipv6_prefix_equal(addr, &ifa->addr,
ifa->prefix_len);
if (onlink)
break;
}
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
return onlink;
}
EXPORT_SYMBOL(ipv6_chk_prefix);
struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr,
struct net_device *dev, int strict)
{
struct inet6_ifaddr *ifp, *result = NULL;
unsigned int hash = inet6_addr_hash(addr);
rcu_read_lock_bh();
hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[hash], addr_lst) {
if (!net_eq(dev_net(ifp->idev->dev), net))
continue;
if (ipv6_addr_equal(&ifp->addr, addr)) {
if (dev == NULL || ifp->idev->dev == dev ||
!(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) {
result = ifp;
in6_ifa_hold(ifp);
break;
}
}
}
rcu_read_unlock_bh();
return result;
}
/* Gets referenced address, destroys ifaddr */
static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed)
{
if (ifp->flags&IFA_F_PERMANENT) {
spin_lock_bh(&ifp->lock);
addrconf_del_dad_work(ifp);
ifp->flags |= IFA_F_TENTATIVE;
if (dad_failed)
ifp->flags |= IFA_F_DADFAILED;
spin_unlock_bh(&ifp->lock);
if (dad_failed)
ipv6_ifa_notify(0, ifp);
in6_ifa_put(ifp);
} else if (ifp->flags&IFA_F_TEMPORARY) {
struct inet6_ifaddr *ifpub;
spin_lock_bh(&ifp->lock);
ifpub = ifp->ifpub;
if (ifpub) {
in6_ifa_hold(ifpub);
spin_unlock_bh(&ifp->lock);
ipv6_create_tempaddr(ifpub, ifp);
in6_ifa_put(ifpub);
} else {
spin_unlock_bh(&ifp->lock);
}
ipv6_del_addr(ifp);
} else {
ipv6_del_addr(ifp);
}
}
static int addrconf_dad_end(struct inet6_ifaddr *ifp)
{
int err = -ENOENT;
spin_lock_bh(&ifp->state_lock);
if (ifp->state == INET6_IFADDR_STATE_DAD) {
ifp->state = INET6_IFADDR_STATE_POSTDAD;
err = 0;
}
spin_unlock_bh(&ifp->state_lock);
return err;
}
void addrconf_dad_failure(struct inet6_ifaddr *ifp)
{
struct inet6_dev *idev = ifp->idev;
if (addrconf_dad_end(ifp)) {
in6_ifa_put(ifp);
return;
}
net_info_ratelimited("%s: IPv6 duplicate address %pI6c detected!\n",
ifp->idev->dev->name, &ifp->addr);
if (idev->cnf.accept_dad > 1 && !idev->cnf.disable_ipv6) {
struct in6_addr addr;
addr.s6_addr32[0] = htonl(0xfe800000);
addr.s6_addr32[1] = 0;
if (!ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) &&
ipv6_addr_equal(&ifp->addr, &addr)) {
/* DAD failed for link-local based on MAC address */
idev->cnf.disable_ipv6 = 1;
pr_info("%s: IPv6 being disabled!\n",
ifp->idev->dev->name);
}
}
spin_lock_bh(&ifp->state_lock);
/* transition from _POSTDAD to _ERRDAD */
ifp->state = INET6_IFADDR_STATE_ERRDAD;
spin_unlock_bh(&ifp->state_lock);
addrconf_mod_dad_work(ifp, 0);
}
/* Join to solicited addr multicast group.
* caller must hold RTNL */
void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr)
{
struct in6_addr maddr;
if (dev->flags&(IFF_LOOPBACK|IFF_NOARP))
return;
addrconf_addr_solict_mult(addr, &maddr);
ipv6_dev_mc_inc(dev, &maddr);
}
/* caller must hold RTNL */
void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr)
{
struct in6_addr maddr;
if (idev->dev->flags&(IFF_LOOPBACK|IFF_NOARP))
return;
addrconf_addr_solict_mult(addr, &maddr);
__ipv6_dev_mc_dec(idev, &maddr);
}
/* caller must hold RTNL */
static void addrconf_join_anycast(struct inet6_ifaddr *ifp)
{
struct in6_addr addr;
if (ifp->prefix_len >= 127) /* RFC 6164 */
return;
ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
if (ipv6_addr_any(&addr))
return;
__ipv6_dev_ac_inc(ifp->idev, &addr);
}
/* caller must hold RTNL */
static void addrconf_leave_anycast(struct inet6_ifaddr *ifp)
{
struct in6_addr addr;
if (ifp->prefix_len >= 127) /* RFC 6164 */
return;
ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
if (ipv6_addr_any(&addr))
return;
__ipv6_dev_ac_dec(ifp->idev, &addr);
}
static int addrconf_ifid_eui48(u8 *eui, struct net_device *dev)
{
if (dev->addr_len != ETH_ALEN)
return -1;
memcpy(eui, dev->dev_addr, 3);
memcpy(eui + 5, dev->dev_addr + 3, 3);
/*
* The zSeries OSA network cards can be shared among various
* OS instances, but the OSA cards have only one MAC address.
* This leads to duplicate address conflicts in conjunction
* with IPv6 if more than one instance uses the same card.
*
* The driver for these cards can deliver a unique 16-bit
* identifier for each instance sharing the same card. It is
* placed instead of 0xFFFE in the interface identifier. The
* "u" bit of the interface identifier is not inverted in this
* case. Hence the resulting interface identifier has local
* scope according to RFC2373.
*/
if (dev->dev_id) {
eui[3] = (dev->dev_id >> 8) & 0xFF;
eui[4] = dev->dev_id & 0xFF;
} else {
eui[3] = 0xFF;
eui[4] = 0xFE;
eui[0] ^= 2;
}
return 0;
}
static int addrconf_ifid_eui64(u8 *eui, struct net_device *dev)
{
if (dev->addr_len != IEEE802154_ADDR_LEN)
return -1;
memcpy(eui, dev->dev_addr, 8);
eui[0] ^= 2;
return 0;
}
static int addrconf_ifid_ieee1394(u8 *eui, struct net_device *dev)
{
union fwnet_hwaddr *ha;
if (dev->addr_len != FWNET_ALEN)
return -1;
ha = (union fwnet_hwaddr *)dev->dev_addr;
memcpy(eui, &ha->uc.uniq_id, sizeof(ha->uc.uniq_id));
eui[0] ^= 2;
return 0;
}
static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev)
{
/* XXX: inherit EUI-64 from other interface -- yoshfuji */
if (dev->addr_len != ARCNET_ALEN)
return -1;
memset(eui, 0, 7);
eui[7] = *(u8 *)dev->dev_addr;
return 0;
}
static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev)
{
if (dev->addr_len != INFINIBAND_ALEN)
return -1;
memcpy(eui, dev->dev_addr + 12, 8);
eui[0] |= 2;
return 0;
}
static int __ipv6_isatap_ifid(u8 *eui, __be32 addr)
{
if (addr == 0)
return -1;
eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) ||
ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) ||
ipv4_is_private_172(addr) || ipv4_is_test_192(addr) ||
ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) ||
ipv4_is_test_198(addr) || ipv4_is_multicast(addr) ||
ipv4_is_lbcast(addr)) ? 0x00 : 0x02;
eui[1] = 0;
eui[2] = 0x5E;
eui[3] = 0xFE;
memcpy(eui + 4, &addr, 4);
return 0;
}
static int addrconf_ifid_sit(u8 *eui, struct net_device *dev)
{
if (dev->priv_flags & IFF_ISATAP)
return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
return -1;
}
static int addrconf_ifid_gre(u8 *eui, struct net_device *dev)
{
return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
}
static int addrconf_ifid_ip6tnl(u8 *eui, struct net_device *dev)
{
memcpy(eui, dev->perm_addr, 3);
memcpy(eui + 5, dev->perm_addr + 3, 3);
eui[3] = 0xFF;
eui[4] = 0xFE;
eui[0] ^= 2;
return 0;
}
static int ipv6_generate_eui64(u8 *eui, struct net_device *dev)
{
switch (dev->type) {
case ARPHRD_ETHER:
case ARPHRD_FDDI:
return addrconf_ifid_eui48(eui, dev);
case ARPHRD_ARCNET:
return addrconf_ifid_arcnet(eui, dev);
case ARPHRD_INFINIBAND:
return addrconf_ifid_infiniband(eui, dev);
case ARPHRD_SIT:
return addrconf_ifid_sit(eui, dev);
case ARPHRD_IPGRE:
return addrconf_ifid_gre(eui, dev);
case ARPHRD_6LOWPAN:
case ARPHRD_IEEE802154:
return addrconf_ifid_eui64(eui, dev);
case ARPHRD_IEEE1394:
return addrconf_ifid_ieee1394(eui, dev);
case ARPHRD_TUNNEL6:
return addrconf_ifid_ip6tnl(eui, dev);
}
return -1;
}
static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev)
{
int err = -1;
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
if (ifp->scope > IFA_LINK)
break;
if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) {
memcpy(eui, ifp->addr.s6_addr+8, 8);
err = 0;
break;
}
}
read_unlock_bh(&idev->lock);
return err;
}
/* (re)generation of randomized interface identifier (RFC 3041 3.2, 3.5) */
static void __ipv6_regen_rndid(struct inet6_dev *idev)
{
regen:
get_random_bytes(idev->rndid, sizeof(idev->rndid));
idev->rndid[0] &= ~0x02;
/*
* <draft-ietf-ipngwg-temp-addresses-v2-00.txt>:
* check if generated address is not inappropriate
*
* - Reserved subnet anycast (RFC 2526)
* 11111101 11....11 1xxxxxxx
* - ISATAP (RFC4214) 6.1
* 00-00-5E-FE-xx-xx-xx-xx
* - value 0
* - XXX: already assigned to an address on the device
*/
if (idev->rndid[0] == 0xfd &&
(idev->rndid[1]&idev->rndid[2]&idev->rndid[3]&idev->rndid[4]&idev->rndid[5]&idev->rndid[6]) == 0xff &&
(idev->rndid[7]&0x80))
goto regen;
if ((idev->rndid[0]|idev->rndid[1]) == 0) {
if (idev->rndid[2] == 0x5e && idev->rndid[3] == 0xfe)
goto regen;
if ((idev->rndid[2]|idev->rndid[3]|idev->rndid[4]|idev->rndid[5]|idev->rndid[6]|idev->rndid[7]) == 0x00)
goto regen;
}
}
static void ipv6_regen_rndid(unsigned long data)
{
struct inet6_dev *idev = (struct inet6_dev *) data;
unsigned long expires;
rcu_read_lock_bh();
write_lock_bh(&idev->lock);
if (idev->dead)
goto out;
__ipv6_regen_rndid(idev);
expires = jiffies +
idev->cnf.temp_prefered_lft * HZ -
idev->cnf.regen_max_retry * idev->cnf.dad_transmits *
NEIGH_VAR(idev->nd_parms, RETRANS_TIME) -
idev->cnf.max_desync_factor * HZ;
if (time_before(expires, jiffies)) {
pr_warn("%s: too short regeneration interval; timer disabled for %s\n",
__func__, idev->dev->name);
goto out;
}
if (!mod_timer(&idev->regen_timer, expires))
in6_dev_hold(idev);
out:
write_unlock_bh(&idev->lock);
rcu_read_unlock_bh();
in6_dev_put(idev);
}
static void __ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr)
{
if (tmpaddr && memcmp(idev->rndid, &tmpaddr->s6_addr[8], 8) == 0)
__ipv6_regen_rndid(idev);
}
/*
* Add prefix route.
*/
static void
addrconf_prefix_route(struct in6_addr *pfx, int plen, struct net_device *dev,
unsigned long expires, u32 flags)
{
struct fib6_config cfg = {
.fc_table = RT6_TABLE_PREFIX,
.fc_metric = IP6_RT_PRIO_ADDRCONF,
.fc_ifindex = dev->ifindex,
.fc_expires = expires,
.fc_dst_len = plen,
.fc_flags = RTF_UP | flags,
.fc_nlinfo.nl_net = dev_net(dev),
.fc_protocol = RTPROT_KERNEL,
};
cfg.fc_dst = *pfx;
/* Prevent useless cloning on PtP SIT.
This thing is done here expecting that the whole
class of non-broadcast devices need not cloning.
*/
#if IS_ENABLED(CONFIG_IPV6_SIT)
if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT))
cfg.fc_flags |= RTF_NONEXTHOP;
#endif
ip6_route_add(&cfg);
}
static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
int plen,
const struct net_device *dev,
u32 flags, u32 noflags)
{
struct fib6_node *fn;
struct rt6_info *rt = NULL;
struct fib6_table *table;
table = fib6_get_table(dev_net(dev), RT6_TABLE_PREFIX);
if (table == NULL)
return NULL;
read_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0);
if (!fn)
goto out;
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (rt->dst.dev->ifindex != dev->ifindex)
continue;
if ((rt->rt6i_flags & flags) != flags)
continue;
if ((rt->rt6i_flags & noflags) != 0)
continue;
dst_hold(&rt->dst);
break;
}
out:
read_unlock_bh(&table->tb6_lock);
return rt;
}
/* Create "default" multicast route to the interface */
static void addrconf_add_mroute(struct net_device *dev)
{
struct fib6_config cfg = {
.fc_table = RT6_TABLE_LOCAL,
.fc_metric = IP6_RT_PRIO_ADDRCONF,
.fc_ifindex = dev->ifindex,
.fc_dst_len = 8,
.fc_flags = RTF_UP,
.fc_nlinfo.nl_net = dev_net(dev),
};
ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0);
ip6_route_add(&cfg);
}
static struct inet6_dev *addrconf_add_dev(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = ipv6_find_idev(dev);
if (!idev)
return ERR_PTR(-ENOBUFS);
if (idev->cnf.disable_ipv6)
return ERR_PTR(-EACCES);
/* Add default multicast route */
if (!(dev->flags & IFF_LOOPBACK))
addrconf_add_mroute(dev);
return idev;
}
static void manage_tempaddrs(struct inet6_dev *idev,
struct inet6_ifaddr *ifp,
__u32 valid_lft, __u32 prefered_lft,
bool create, unsigned long now)
{
u32 flags;
struct inet6_ifaddr *ift;
read_lock_bh(&idev->lock);
/* update all temporary addresses in the list */
list_for_each_entry(ift, &idev->tempaddr_list, tmp_list) {
int age, max_valid, max_prefered;
if (ifp != ift->ifpub)
continue;
/* RFC 4941 section 3.3:
* If a received option will extend the lifetime of a public
* address, the lifetimes of temporary addresses should
* be extended, subject to the overall constraint that no
* temporary addresses should ever remain "valid" or "preferred"
* for a time longer than (TEMP_VALID_LIFETIME) or
* (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), respectively.
*/
age = (now - ift->cstamp) / HZ;
max_valid = idev->cnf.temp_valid_lft - age;
if (max_valid < 0)
max_valid = 0;
max_prefered = idev->cnf.temp_prefered_lft -
idev->cnf.max_desync_factor - age;
if (max_prefered < 0)
max_prefered = 0;
if (valid_lft > max_valid)
valid_lft = max_valid;
if (prefered_lft > max_prefered)
prefered_lft = max_prefered;
spin_lock(&ift->lock);
flags = ift->flags;
ift->valid_lft = valid_lft;
ift->prefered_lft = prefered_lft;
ift->tstamp = now;
if (prefered_lft > 0)
ift->flags &= ~IFA_F_DEPRECATED;
spin_unlock(&ift->lock);
if (!(flags&IFA_F_TENTATIVE))
ipv6_ifa_notify(0, ift);
}
if ((create || list_empty(&idev->tempaddr_list)) &&
idev->cnf.use_tempaddr > 0) {
/* When a new public address is created as described
* in [ADDRCONF], also create a new temporary address.
* Also create a temporary address if it's enabled but
* no temporary address currently exists.
*/
read_unlock_bh(&idev->lock);
ipv6_create_tempaddr(ifp, NULL);
} else {
read_unlock_bh(&idev->lock);
}
}
void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao)
{
struct prefix_info *pinfo;
__u32 valid_lft;
__u32 prefered_lft;
int addr_type;
struct inet6_dev *in6_dev;
struct net *net = dev_net(dev);
pinfo = (struct prefix_info *) opt;
if (len < sizeof(struct prefix_info)) {
ADBG("addrconf: prefix option too short\n");
return;
}
/*
* Validation checks ([ADDRCONF], page 19)
*/
addr_type = ipv6_addr_type(&pinfo->prefix);
if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL))
return;
valid_lft = ntohl(pinfo->valid);
prefered_lft = ntohl(pinfo->prefered);
if (prefered_lft > valid_lft) {
net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n");
return;
}
in6_dev = in6_dev_get(dev);
if (in6_dev == NULL) {
net_dbg_ratelimited("addrconf: device %s not configured\n",
dev->name);
return;
}
/*
* Two things going on here:
* 1) Add routes for on-link prefixes
* 2) Configure prefixes with the auto flag set
*/
if (pinfo->onlink) {
struct rt6_info *rt;
unsigned long rt_expires;
/* Avoid arithmetic overflow. Really, we could
* save rt_expires in seconds, likely valid_lft,
* but it would require division in fib gc, that it
* not good.
*/
if (HZ > USER_HZ)
rt_expires = addrconf_timeout_fixup(valid_lft, HZ);
else
rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ);
if (addrconf_finite_timeout(rt_expires))
rt_expires *= HZ;
rt = addrconf_get_prefix_route(&pinfo->prefix,
pinfo->prefix_len,
dev,
RTF_ADDRCONF | RTF_PREFIX_RT,
RTF_GATEWAY | RTF_DEFAULT);
if (rt) {
/* Autoconf prefix route */
if (valid_lft == 0) {
ip6_del_rt(rt);
rt = NULL;
} else if (addrconf_finite_timeout(rt_expires)) {
/* not infinity */
rt6_set_expires(rt, jiffies + rt_expires);
} else {
rt6_clean_expires(rt);
}
} else if (valid_lft) {
clock_t expires = 0;
int flags = RTF_ADDRCONF | RTF_PREFIX_RT;
if (addrconf_finite_timeout(rt_expires)) {
/* not infinity */
flags |= RTF_EXPIRES;
expires = jiffies_to_clock_t(rt_expires);
}
addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len,
dev, expires, flags);
}
ip6_rt_put(rt);
}
/* Try to figure out our local address for this prefix */
if (pinfo->autoconf && in6_dev->cnf.autoconf) {
struct inet6_ifaddr *ifp;
struct in6_addr addr;
int create = 0, update_lft = 0;
bool tokenized = false;
if (pinfo->prefix_len == 64) {
memcpy(&addr, &pinfo->prefix, 8);
if (!ipv6_addr_any(&in6_dev->token)) {
read_lock_bh(&in6_dev->lock);
memcpy(addr.s6_addr + 8,
in6_dev->token.s6_addr + 8, 8);
read_unlock_bh(&in6_dev->lock);
tokenized = true;
} else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) &&
ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) {
in6_dev_put(in6_dev);
return;
}
goto ok;
}
net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n",
pinfo->prefix_len);
in6_dev_put(in6_dev);
return;
ok:
ifp = ipv6_get_ifaddr(net, &addr, dev, 1);
if (ifp == NULL && valid_lft) {
int max_addresses = in6_dev->cnf.max_addresses;
u32 addr_flags = 0;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
if (in6_dev->cnf.optimistic_dad &&
!net->ipv6.devconf_all->forwarding && sllao)
addr_flags = IFA_F_OPTIMISTIC;
#endif
/* Do not allow to create too much of autoconfigured
* addresses; this would be too easy way to crash kernel.
*/
if (!max_addresses ||
ipv6_count_addresses(in6_dev) < max_addresses)
ifp = ipv6_add_addr(in6_dev, &addr, NULL,
pinfo->prefix_len,
addr_type&IPV6_ADDR_SCOPE_MASK,
addr_flags, valid_lft,
prefered_lft);
if (IS_ERR_OR_NULL(ifp)) {
in6_dev_put(in6_dev);
return;
}
update_lft = 0;
create = 1;
spin_lock_bh(&ifp->lock);
ifp->flags |= IFA_F_MANAGETEMPADDR;
ifp->cstamp = jiffies;
ifp->tokenized = tokenized;
spin_unlock_bh(&ifp->lock);
addrconf_dad_start(ifp);
}
if (ifp) {
u32 flags;
unsigned long now;
u32 stored_lft;
/* update lifetime (RFC2462 5.5.3 e) */
spin_lock(&ifp->lock);
now = jiffies;
if (ifp->valid_lft > (now - ifp->tstamp) / HZ)
stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ;
else
stored_lft = 0;
if (!update_lft && !create && stored_lft) {
const u32 minimum_lft = min_t(u32,
stored_lft, MIN_VALID_LIFETIME);
valid_lft = max(valid_lft, minimum_lft);
/* RFC4862 Section 5.5.3e:
* "Note that the preferred lifetime of the
* corresponding address is always reset to
* the Preferred Lifetime in the received
* Prefix Information option, regardless of
* whether the valid lifetime is also reset or
* ignored."
*
* So we should always update prefered_lft here.
*/
update_lft = 1;
}
if (update_lft) {
ifp->valid_lft = valid_lft;
ifp->prefered_lft = prefered_lft;
ifp->tstamp = now;
flags = ifp->flags;
ifp->flags &= ~IFA_F_DEPRECATED;
spin_unlock(&ifp->lock);
if (!(flags&IFA_F_TENTATIVE))
ipv6_ifa_notify(0, ifp);
} else
spin_unlock(&ifp->lock);
manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft,
create, now);
in6_ifa_put(ifp);
addrconf_verify();
}
}
inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo);
in6_dev_put(in6_dev);
}
/*
* Set destination address.
* Special case for SIT interfaces where we create a new "virtual"
* device.
*/
int addrconf_set_dstaddr(struct net *net, void __user *arg)
{
struct in6_ifreq ireq;
struct net_device *dev;
int err = -EINVAL;
rtnl_lock();
err = -EFAULT;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
goto err_exit;
dev = __dev_get_by_index(net, ireq.ifr6_ifindex);
err = -ENODEV;
if (dev == NULL)
goto err_exit;
#if IS_ENABLED(CONFIG_IPV6_SIT)
if (dev->type == ARPHRD_SIT) {
const struct net_device_ops *ops = dev->netdev_ops;
struct ifreq ifr;
struct ip_tunnel_parm p;
err = -EADDRNOTAVAIL;
if (!(ipv6_addr_type(&ireq.ifr6_addr) & IPV6_ADDR_COMPATv4))
goto err_exit;
memset(&p, 0, sizeof(p));
p.iph.daddr = ireq.ifr6_addr.s6_addr32[3];
p.iph.saddr = 0;
p.iph.version = 4;
p.iph.ihl = 5;
p.iph.protocol = IPPROTO_IPV6;
p.iph.ttl = 64;
ifr.ifr_ifru.ifru_data = (__force void __user *)&p;
if (ops->ndo_do_ioctl) {
mm_segment_t oldfs = get_fs();
set_fs(KERNEL_DS);
err = ops->ndo_do_ioctl(dev, &ifr, SIOCADDTUNNEL);
set_fs(oldfs);
} else
err = -EOPNOTSUPP;
if (err == 0) {
err = -ENOBUFS;
dev = __dev_get_by_name(net, p.name);
if (!dev)
goto err_exit;
err = dev_open(dev);
}
}
#endif
err_exit:
rtnl_unlock();
return err;
}
/*
* Manual configuration of address on an interface
*/
static int inet6_addr_add(struct net *net, int ifindex,
const struct in6_addr *pfx,
const struct in6_addr *peer_pfx,
unsigned int plen, __u32 ifa_flags,
__u32 prefered_lft, __u32 valid_lft)
{
struct inet6_ifaddr *ifp;
struct inet6_dev *idev;
struct net_device *dev;
int scope;
u32 flags;
clock_t expires;
unsigned long timeout;
ASSERT_RTNL();
if (plen > 128)
return -EINVAL;
/* check the lifetime */
if (!valid_lft || prefered_lft > valid_lft)
return -EINVAL;
if (ifa_flags & IFA_F_MANAGETEMPADDR && plen != 64)
return -EINVAL;
dev = __dev_get_by_index(net, ifindex);
if (!dev)
return -ENODEV;
idev = addrconf_add_dev(dev);
if (IS_ERR(idev))
return PTR_ERR(idev);
scope = ipv6_addr_scope(pfx);
timeout = addrconf_timeout_fixup(valid_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
expires = jiffies_to_clock_t(timeout * HZ);
valid_lft = timeout;
flags = RTF_EXPIRES;
} else {
expires = 0;
flags = 0;
ifa_flags |= IFA_F_PERMANENT;
}
timeout = addrconf_timeout_fixup(prefered_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
if (timeout == 0)
ifa_flags |= IFA_F_DEPRECATED;
prefered_lft = timeout;
}
ifp = ipv6_add_addr(idev, pfx, peer_pfx, plen, scope, ifa_flags,
valid_lft, prefered_lft);
if (!IS_ERR(ifp)) {
if (!(ifa_flags & IFA_F_NOPREFIXROUTE)) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len, dev,
expires, flags);
}
/*
* Note that section 3.1 of RFC 4429 indicates
* that the Optimistic flag should not be set for
* manually configured addresses
*/
addrconf_dad_start(ifp);
if (ifa_flags & IFA_F_MANAGETEMPADDR)
manage_tempaddrs(idev, ifp, valid_lft, prefered_lft,
true, jiffies);
in6_ifa_put(ifp);
addrconf_verify_rtnl();
return 0;
}
return PTR_ERR(ifp);
}
static int inet6_addr_del(struct net *net, int ifindex, u32 ifa_flags,
const struct in6_addr *pfx, unsigned int plen)
{
struct inet6_ifaddr *ifp;
struct inet6_dev *idev;
struct net_device *dev;
if (plen > 128)
return -EINVAL;
dev = __dev_get_by_index(net, ifindex);
if (!dev)
return -ENODEV;
idev = __in6_dev_get(dev);
if (idev == NULL)
return -ENXIO;
read_lock_bh(&idev->lock);
list_for_each_entry(ifp, &idev->addr_list, if_list) {
if (ifp->prefix_len == plen &&
ipv6_addr_equal(pfx, &ifp->addr)) {
in6_ifa_hold(ifp);
read_unlock_bh(&idev->lock);
if (!(ifp->flags & IFA_F_TEMPORARY) &&
(ifa_flags & IFA_F_MANAGETEMPADDR))
manage_tempaddrs(idev, ifp, 0, 0, false,
jiffies);
ipv6_del_addr(ifp);
addrconf_verify_rtnl();
return 0;
}
}
read_unlock_bh(&idev->lock);
return -EADDRNOTAVAIL;
}
int addrconf_add_ifaddr(struct net *net, void __user *arg)
{
struct in6_ifreq ireq;
int err;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
return -EFAULT;
rtnl_lock();
err = inet6_addr_add(net, ireq.ifr6_ifindex, &ireq.ifr6_addr, NULL,
ireq.ifr6_prefixlen, IFA_F_PERMANENT,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME);
rtnl_unlock();
return err;
}
int addrconf_del_ifaddr(struct net *net, void __user *arg)
{
struct in6_ifreq ireq;
int err;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
return -EFAULT;
rtnl_lock();
err = inet6_addr_del(net, ireq.ifr6_ifindex, 0, &ireq.ifr6_addr,
ireq.ifr6_prefixlen);
rtnl_unlock();
return err;
}
static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
int plen, int scope)
{
struct inet6_ifaddr *ifp;
ifp = ipv6_add_addr(idev, addr, NULL, plen,
scope, IFA_F_PERMANENT,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME);
if (!IS_ERR(ifp)) {
spin_lock_bh(&ifp->lock);
ifp->flags &= ~IFA_F_TENTATIVE;
spin_unlock_bh(&ifp->lock);
ipv6_ifa_notify(RTM_NEWADDR, ifp);
in6_ifa_put(ifp);
}
}
#if IS_ENABLED(CONFIG_IPV6_SIT)
static void sit_add_v4_addrs(struct inet6_dev *idev)
{
struct in6_addr addr;
struct net_device *dev;
struct net *net = dev_net(idev->dev);
int scope, plen;
u32 pflags = 0;
ASSERT_RTNL();
memset(&addr, 0, sizeof(struct in6_addr));
memcpy(&addr.s6_addr32[3], idev->dev->dev_addr, 4);
if (idev->dev->flags&IFF_POINTOPOINT) {
addr.s6_addr32[0] = htonl(0xfe800000);
scope = IFA_LINK;
plen = 64;
} else {
scope = IPV6_ADDR_COMPATv4;
plen = 96;
pflags |= RTF_NONEXTHOP;
}
if (addr.s6_addr32[3]) {
add_addr(idev, &addr, plen, scope);
addrconf_prefix_route(&addr, plen, idev->dev, 0, pflags);
return;
}
for_each_netdev(net, dev) {
struct in_device *in_dev = __in_dev_get_rtnl(dev);
if (in_dev && (dev->flags & IFF_UP)) {
struct in_ifaddr *ifa;
int flag = scope;
for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) {
addr.s6_addr32[3] = ifa->ifa_local;
if (ifa->ifa_scope == RT_SCOPE_LINK)
continue;
if (ifa->ifa_scope >= RT_SCOPE_HOST) {
if (idev->dev->flags&IFF_POINTOPOINT)
continue;
flag |= IFA_HOST;
}
add_addr(idev, &addr, plen, flag);
addrconf_prefix_route(&addr, plen, idev->dev, 0,
pflags);
}
}
}
}
#endif
static void init_loopback(struct net_device *dev)
{
struct inet6_dev *idev;
struct net_device *sp_dev;
struct inet6_ifaddr *sp_ifa;
struct rt6_info *sp_rt;
/* ::1 */
ASSERT_RTNL();
idev = ipv6_find_idev(dev);
if (idev == NULL) {
pr_debug("%s: add_dev failed\n", __func__);
return;
}
add_addr(idev, &in6addr_loopback, 128, IFA_HOST);
/* Add routes to other interface's IPv6 addresses */
for_each_netdev(dev_net(dev), sp_dev) {
if (!strcmp(sp_dev->name, dev->name))
continue;
idev = __in6_dev_get(sp_dev);
if (!idev)
continue;
read_lock_bh(&idev->lock);
list_for_each_entry(sp_ifa, &idev->addr_list, if_list) {
if (sp_ifa->flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE))
continue;
if (sp_ifa->rt) {
/* This dst has been added to garbage list when
* lo device down, release this obsolete dst and
* reallocate a new router for ifa.
*/
if (sp_ifa->rt->dst.obsolete > 0) {
ip6_rt_put(sp_ifa->rt);
sp_ifa->rt = NULL;
} else {
continue;
}
}
sp_rt = addrconf_dst_alloc(idev, &sp_ifa->addr, false);
/* Failure cases are ignored */
if (!IS_ERR(sp_rt)) {
sp_ifa->rt = sp_rt;
ip6_ins_rt(sp_rt);
}
}
read_unlock_bh(&idev->lock);
}
}
static void addrconf_add_linklocal(struct inet6_dev *idev, const struct in6_addr *addr)
{
struct inet6_ifaddr *ifp;
u32 addr_flags = IFA_F_PERMANENT;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
if (idev->cnf.optimistic_dad &&
!dev_net(idev->dev)->ipv6.devconf_all->forwarding)
addr_flags |= IFA_F_OPTIMISTIC;
#endif
ifp = ipv6_add_addr(idev, addr, NULL, 64, IFA_LINK, addr_flags,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME);
if (!IS_ERR(ifp)) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len, idev->dev, 0, 0);
addrconf_dad_start(ifp);
in6_ifa_put(ifp);
}
}
static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route)
{
if (idev->addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64) {
struct in6_addr addr;
ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0);
/* addrconf_add_linklocal also adds a prefix_route and we
* only need to care about prefix routes if ipv6_generate_eui64
* couldn't generate one.
*/
if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0)
addrconf_add_linklocal(idev, &addr);
else if (prefix_route)
addrconf_prefix_route(&addr, 64, idev->dev, 0, 0);
}
}
static void addrconf_dev_config(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
if ((dev->type != ARPHRD_ETHER) &&
(dev->type != ARPHRD_FDDI) &&
(dev->type != ARPHRD_ARCNET) &&
(dev->type != ARPHRD_INFINIBAND) &&
(dev->type != ARPHRD_IEEE802154) &&
(dev->type != ARPHRD_IEEE1394) &&
(dev->type != ARPHRD_TUNNEL6) &&
(dev->type != ARPHRD_6LOWPAN)) {
/* Alas, we support only Ethernet autoconfiguration. */
return;
}
idev = addrconf_add_dev(dev);
if (IS_ERR(idev))
return;
addrconf_addr_gen(idev, false);
}
#if IS_ENABLED(CONFIG_IPV6_SIT)
static void addrconf_sit_config(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
/*
* Configure the tunnel with one of our IPv4
* addresses... we should configure all of
* our v4 addrs in the tunnel
*/
idev = ipv6_find_idev(dev);
if (idev == NULL) {
pr_debug("%s: add_dev failed\n", __func__);
return;
}
if (dev->priv_flags & IFF_ISATAP) {
addrconf_addr_gen(idev, false);
return;
}
sit_add_v4_addrs(idev);
if (dev->flags&IFF_POINTOPOINT)
addrconf_add_mroute(dev);
}
#endif
#if IS_ENABLED(CONFIG_NET_IPGRE)
static void addrconf_gre_config(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = ipv6_find_idev(dev);
if (idev == NULL) {
pr_debug("%s: add_dev failed\n", __func__);
return;
}
addrconf_addr_gen(idev, true);
}
#endif
static int addrconf_notify(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct inet6_dev *idev = __in6_dev_get(dev);
int run_pending = 0;
int err;
switch (event) {
case NETDEV_REGISTER:
if (!idev && dev->mtu >= IPV6_MIN_MTU) {
idev = ipv6_add_dev(dev);
if (IS_ERR(idev))
return notifier_from_errno(PTR_ERR(idev));
}
break;
case NETDEV_UP:
case NETDEV_CHANGE:
if (dev->flags & IFF_SLAVE)
break;
if (idev && idev->cnf.disable_ipv6)
break;
if (event == NETDEV_UP) {
if (!addrconf_qdisc_ok(dev)) {
/* device is not ready yet. */
pr_info("ADDRCONF(NETDEV_UP): %s: link is not ready\n",
dev->name);
break;
}
if (!idev && dev->mtu >= IPV6_MIN_MTU)
idev = ipv6_add_dev(dev);
if (!IS_ERR_OR_NULL(idev)) {
idev->if_flags |= IF_READY;
run_pending = 1;
}
} else {
if (!addrconf_qdisc_ok(dev)) {
/* device is still not ready. */
break;
}
if (idev) {
if (idev->if_flags & IF_READY)
/* device is already configured. */
break;
idev->if_flags |= IF_READY;
}
pr_info("ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\n",
dev->name);
run_pending = 1;
}
switch (dev->type) {
#if IS_ENABLED(CONFIG_IPV6_SIT)
case ARPHRD_SIT:
addrconf_sit_config(dev);
break;
#endif
#if IS_ENABLED(CONFIG_NET_IPGRE)
case ARPHRD_IPGRE:
addrconf_gre_config(dev);
break;
#endif
case ARPHRD_LOOPBACK:
init_loopback(dev);
break;
default:
addrconf_dev_config(dev);
break;
}
if (!IS_ERR_OR_NULL(idev)) {
if (run_pending)
addrconf_dad_run(idev);
/*
* If the MTU changed during the interface down,
* when the interface up, the changed MTU must be
* reflected in the idev as well as routers.
*/
if (idev->cnf.mtu6 != dev->mtu &&
dev->mtu >= IPV6_MIN_MTU) {
rt6_mtu_change(dev, dev->mtu);
idev->cnf.mtu6 = dev->mtu;
}
idev->tstamp = jiffies;
inet6_ifinfo_notify(RTM_NEWLINK, idev);
/*
* If the changed mtu during down is lower than
* IPV6_MIN_MTU stop IPv6 on this interface.
*/
if (dev->mtu < IPV6_MIN_MTU)
addrconf_ifdown(dev, 1);
}
break;
case NETDEV_CHANGEMTU:
if (idev && dev->mtu >= IPV6_MIN_MTU) {
rt6_mtu_change(dev, dev->mtu);
idev->cnf.mtu6 = dev->mtu;
break;
}
if (!idev && dev->mtu >= IPV6_MIN_MTU) {
idev = ipv6_add_dev(dev);
if (!IS_ERR(idev))
break;
}
/*
* if MTU under IPV6_MIN_MTU.
* Stop IPv6 on this interface.
*/
case NETDEV_DOWN:
case NETDEV_UNREGISTER:
/*
* Remove all addresses from this interface.
*/
addrconf_ifdown(dev, event != NETDEV_DOWN);
break;
case NETDEV_CHANGENAME:
if (idev) {
snmp6_unregister_dev(idev);
addrconf_sysctl_unregister(idev);
err = addrconf_sysctl_register(idev);
if (err)
return notifier_from_errno(err);
err = snmp6_register_dev(idev);
if (err) {
addrconf_sysctl_unregister(idev);
return notifier_from_errno(err);
}
}
break;
case NETDEV_PRE_TYPE_CHANGE:
case NETDEV_POST_TYPE_CHANGE:
addrconf_type_change(dev, event);
break;
}
return NOTIFY_OK;
}
/*
* addrconf module should be notified of a device going up
*/
static struct notifier_block ipv6_dev_notf = {
.notifier_call = addrconf_notify,
};
static void addrconf_type_change(struct net_device *dev, unsigned long event)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = __in6_dev_get(dev);
if (event == NETDEV_POST_TYPE_CHANGE)
ipv6_mc_remap(idev);
else if (event == NETDEV_PRE_TYPE_CHANGE)
ipv6_mc_unmap(idev);
}
static int addrconf_ifdown(struct net_device *dev, int how)
{
struct net *net = dev_net(dev);
struct inet6_dev *idev;
struct inet6_ifaddr *ifa;
int state, i;
ASSERT_RTNL();
rt6_ifdown(net, dev);
neigh_ifdown(&nd_tbl, dev);
idev = __in6_dev_get(dev);
if (idev == NULL)
return -ENODEV;
/*
* Step 1: remove reference to ipv6 device from parent device.
* Do not dev_put!
*/
if (how) {
idev->dead = 1;
/* protected by rtnl_lock */
RCU_INIT_POINTER(dev->ip6_ptr, NULL);
/* Step 1.5: remove snmp6 entry */
snmp6_unregister_dev(idev);
}
/* Step 2: clear hash table */
for (i = 0; i < IN6_ADDR_HSIZE; i++) {
struct hlist_head *h = &inet6_addr_lst[i];
spin_lock_bh(&addrconf_hash_lock);
restart:
hlist_for_each_entry_rcu(ifa, h, addr_lst) {
if (ifa->idev == idev) {
hlist_del_init_rcu(&ifa->addr_lst);
addrconf_del_dad_work(ifa);
goto restart;
}
}
spin_unlock_bh(&addrconf_hash_lock);
}
write_lock_bh(&idev->lock);
addrconf_del_rs_timer(idev);
/* Step 2: clear flags for stateless addrconf */
if (!how)
idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY);
if (how && del_timer(&idev->regen_timer))
in6_dev_put(idev);
/* Step 3: clear tempaddr list */
while (!list_empty(&idev->tempaddr_list)) {
ifa = list_first_entry(&idev->tempaddr_list,
struct inet6_ifaddr, tmp_list);
list_del(&ifa->tmp_list);
write_unlock_bh(&idev->lock);
spin_lock_bh(&ifa->lock);
if (ifa->ifpub) {
in6_ifa_put(ifa->ifpub);
ifa->ifpub = NULL;
}
spin_unlock_bh(&ifa->lock);
in6_ifa_put(ifa);
write_lock_bh(&idev->lock);
}
while (!list_empty(&idev->addr_list)) {
ifa = list_first_entry(&idev->addr_list,
struct inet6_ifaddr, if_list);
addrconf_del_dad_work(ifa);
list_del(&ifa->if_list);
write_unlock_bh(&idev->lock);
spin_lock_bh(&ifa->state_lock);
state = ifa->state;
ifa->state = INET6_IFADDR_STATE_DEAD;
spin_unlock_bh(&ifa->state_lock);
if (state != INET6_IFADDR_STATE_DEAD) {
__ipv6_ifa_notify(RTM_DELADDR, ifa);
inet6addr_notifier_call_chain(NETDEV_DOWN, ifa);
}
in6_ifa_put(ifa);
write_lock_bh(&idev->lock);
}
write_unlock_bh(&idev->lock);
/* Step 5: Discard anycast and multicast list */
if (how) {
ipv6_ac_destroy_dev(idev);
ipv6_mc_destroy_dev(idev);
} else {
ipv6_mc_down(idev);
}
idev->tstamp = jiffies;
/* Last: Shot the device (if unregistered) */
if (how) {
addrconf_sysctl_unregister(idev);
neigh_parms_release(&nd_tbl, idev->nd_parms);
neigh_ifdown(&nd_tbl, dev);
in6_dev_put(idev);
}
return 0;
}
static void addrconf_rs_timer(unsigned long data)
{
struct inet6_dev *idev = (struct inet6_dev *)data;
struct net_device *dev = idev->dev;
struct in6_addr lladdr;
write_lock(&idev->lock);
if (idev->dead || !(idev->if_flags & IF_READY))
goto out;
if (!ipv6_accept_ra(idev))
goto out;
/* Announcement received after solicitation was sent */
if (idev->if_flags & IF_RA_RCVD)
goto out;
if (idev->rs_probes++ < idev->cnf.rtr_solicits) {
write_unlock(&idev->lock);
if (!ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
ndisc_send_rs(dev, &lladdr,
&in6addr_linklocal_allrouters);
else
goto put;
write_lock(&idev->lock);
/* The wait after the last probe can be shorter */
addrconf_mod_rs_timer(idev, (idev->rs_probes ==
idev->cnf.rtr_solicits) ?
idev->cnf.rtr_solicit_delay :
idev->cnf.rtr_solicit_interval);
} else {
/*
* Note: we do not support deprecated "all on-link"
* assumption any longer.
*/
pr_debug("%s: no IPv6 routers present\n", idev->dev->name);
}
out:
write_unlock(&idev->lock);
put:
in6_dev_put(idev);
}
/*
* Duplicate Address Detection
*/
static void addrconf_dad_kick(struct inet6_ifaddr *ifp)
{
unsigned long rand_num;
struct inet6_dev *idev = ifp->idev;
if (ifp->flags & IFA_F_OPTIMISTIC)
rand_num = 0;
else
rand_num = prandom_u32() % (idev->cnf.rtr_solicit_delay ? : 1);
ifp->dad_probes = idev->cnf.dad_transmits;
addrconf_mod_dad_work(ifp, rand_num);
}
static void addrconf_dad_begin(struct inet6_ifaddr *ifp)
{
struct inet6_dev *idev = ifp->idev;
struct net_device *dev = idev->dev;
addrconf_join_solict(dev, &ifp->addr);
prandom_seed((__force u32) ifp->addr.s6_addr32[3]);
read_lock_bh(&idev->lock);
spin_lock(&ifp->lock);
if (ifp->state == INET6_IFADDR_STATE_DEAD)
goto out;
if (dev->flags&(IFF_NOARP|IFF_LOOPBACK) ||
idev->cnf.accept_dad < 1 ||
!(ifp->flags&IFA_F_TENTATIVE) ||
ifp->flags & IFA_F_NODAD) {
ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
spin_unlock(&ifp->lock);
read_unlock_bh(&idev->lock);
addrconf_dad_completed(ifp);
return;
}
if (!(idev->if_flags & IF_READY)) {
spin_unlock(&ifp->lock);
read_unlock_bh(&idev->lock);
/*
* If the device is not ready:
* - keep it tentative if it is a permanent address.
* - otherwise, kill it.
*/
in6_ifa_hold(ifp);
addrconf_dad_stop(ifp, 0);
return;
}
/*
* Optimistic nodes can start receiving
* Frames right away
*/
if (ifp->flags & IFA_F_OPTIMISTIC) {
ip6_ins_rt(ifp->rt);
if (ipv6_use_optimistic_addr(idev)) {
/* Because optimistic nodes can use this address,
* notify listeners. If DAD fails, RTM_DELADDR is sent.
*/
ipv6_ifa_notify(RTM_NEWADDR, ifp);
}
}
addrconf_dad_kick(ifp);
out:
spin_unlock(&ifp->lock);
read_unlock_bh(&idev->lock);
}
static void addrconf_dad_start(struct inet6_ifaddr *ifp)
{
bool begin_dad = false;
spin_lock_bh(&ifp->state_lock);
if (ifp->state != INET6_IFADDR_STATE_DEAD) {
ifp->state = INET6_IFADDR_STATE_PREDAD;
begin_dad = true;
}
spin_unlock_bh(&ifp->state_lock);
if (begin_dad)
addrconf_mod_dad_work(ifp, 0);
}
static void addrconf_dad_work(struct work_struct *w)
{
struct inet6_ifaddr *ifp = container_of(to_delayed_work(w),
struct inet6_ifaddr,
dad_work);
struct inet6_dev *idev = ifp->idev;
struct in6_addr mcaddr;
enum {
DAD_PROCESS,
DAD_BEGIN,
DAD_ABORT,
} action = DAD_PROCESS;
rtnl_lock();
spin_lock_bh(&ifp->state_lock);
if (ifp->state == INET6_IFADDR_STATE_PREDAD) {
action = DAD_BEGIN;
ifp->state = INET6_IFADDR_STATE_DAD;
} else if (ifp->state == INET6_IFADDR_STATE_ERRDAD) {
action = DAD_ABORT;
ifp->state = INET6_IFADDR_STATE_POSTDAD;
}
spin_unlock_bh(&ifp->state_lock);
if (action == DAD_BEGIN) {
addrconf_dad_begin(ifp);
goto out;
} else if (action == DAD_ABORT) {
addrconf_dad_stop(ifp, 1);
goto out;
}
if (!ifp->dad_probes && addrconf_dad_end(ifp))
goto out;
write_lock_bh(&idev->lock);
if (idev->dead || !(idev->if_flags & IF_READY)) {
write_unlock_bh(&idev->lock);
goto out;
}
spin_lock(&ifp->lock);
if (ifp->state == INET6_IFADDR_STATE_DEAD) {
spin_unlock(&ifp->lock);
write_unlock_bh(&idev->lock);
goto out;
}
if (ifp->dad_probes == 0) {
/*
* DAD was successful
*/
ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
spin_unlock(&ifp->lock);
write_unlock_bh(&idev->lock);
addrconf_dad_completed(ifp);
goto out;
}
ifp->dad_probes--;
addrconf_mod_dad_work(ifp,
NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME));
spin_unlock(&ifp->lock);
write_unlock_bh(&idev->lock);
/* send a neighbour solicitation for our addr */
addrconf_addr_solict_mult(&ifp->addr, &mcaddr);
ndisc_send_ns(ifp->idev->dev, NULL, &ifp->addr, &mcaddr, &in6addr_any);
out:
in6_ifa_put(ifp);
rtnl_unlock();
}
/* ifp->idev must be at least read locked */
static bool ipv6_lonely_lladdr(struct inet6_ifaddr *ifp)
{
struct inet6_ifaddr *ifpiter;
struct inet6_dev *idev = ifp->idev;
list_for_each_entry_reverse(ifpiter, &idev->addr_list, if_list) {
if (ifpiter->scope > IFA_LINK)
break;
if (ifp != ifpiter && ifpiter->scope == IFA_LINK &&
(ifpiter->flags & (IFA_F_PERMANENT|IFA_F_TENTATIVE|
IFA_F_OPTIMISTIC|IFA_F_DADFAILED)) ==
IFA_F_PERMANENT)
return false;
}
return true;
}
static void addrconf_dad_completed(struct inet6_ifaddr *ifp)
{
struct net_device *dev = ifp->idev->dev;
struct in6_addr lladdr;
bool send_rs, send_mld;
addrconf_del_dad_work(ifp);
/*
* Configure the address for reception. Now it is valid.
*/
ipv6_ifa_notify(RTM_NEWADDR, ifp);
/* If added prefix is link local and we are prepared to process
router advertisements, start sending router solicitations.
*/
read_lock_bh(&ifp->idev->lock);
send_mld = ifp->scope == IFA_LINK && ipv6_lonely_lladdr(ifp);
send_rs = send_mld &&
ipv6_accept_ra(ifp->idev) &&
ifp->idev->cnf.rtr_solicits > 0 &&
(dev->flags&IFF_LOOPBACK) == 0;
read_unlock_bh(&ifp->idev->lock);
/* While dad is in progress mld report's source address is in6_addrany.
* Resend with proper ll now.
*/
if (send_mld)
ipv6_mc_dad_complete(ifp->idev);
if (send_rs) {
/*
* If a host as already performed a random delay
* [...] as part of DAD [...] there is no need
* to delay again before sending the first RS
*/
if (ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
return;
ndisc_send_rs(dev, &lladdr, &in6addr_linklocal_allrouters);
write_lock_bh(&ifp->idev->lock);
spin_lock(&ifp->lock);
ifp->idev->rs_probes = 1;
ifp->idev->if_flags |= IF_RS_SENT;
addrconf_mod_rs_timer(ifp->idev,
ifp->idev->cnf.rtr_solicit_interval);
spin_unlock(&ifp->lock);
write_unlock_bh(&ifp->idev->lock);
}
}
static void addrconf_dad_run(struct inet6_dev *idev)
{
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
list_for_each_entry(ifp, &idev->addr_list, if_list) {
spin_lock(&ifp->lock);
if (ifp->flags & IFA_F_TENTATIVE &&
ifp->state == INET6_IFADDR_STATE_DAD)
addrconf_dad_kick(ifp);
spin_unlock(&ifp->lock);
}
read_unlock_bh(&idev->lock);
}
#ifdef CONFIG_PROC_FS
struct if6_iter_state {
struct seq_net_private p;
int bucket;
int offset;
};
static struct inet6_ifaddr *if6_get_first(struct seq_file *seq, loff_t pos)
{
struct inet6_ifaddr *ifa = NULL;
struct if6_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
int p = 0;
/* initial bucket if pos is 0 */
if (pos == 0) {
state->bucket = 0;
state->offset = 0;
}
for (; state->bucket < IN6_ADDR_HSIZE; ++state->bucket) {
hlist_for_each_entry_rcu_bh(ifa, &inet6_addr_lst[state->bucket],
addr_lst) {
if (!net_eq(dev_net(ifa->idev->dev), net))
continue;
/* sync with offset */
if (p < state->offset) {
p++;
continue;
}
state->offset++;
return ifa;
}
/* prepare for next bucket */
state->offset = 0;
p = 0;
}
return NULL;
}
static struct inet6_ifaddr *if6_get_next(struct seq_file *seq,
struct inet6_ifaddr *ifa)
{
struct if6_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
hlist_for_each_entry_continue_rcu_bh(ifa, addr_lst) {
if (!net_eq(dev_net(ifa->idev->dev), net))
continue;
state->offset++;
return ifa;
}
while (++state->bucket < IN6_ADDR_HSIZE) {
state->offset = 0;
hlist_for_each_entry_rcu_bh(ifa,
&inet6_addr_lst[state->bucket], addr_lst) {
if (!net_eq(dev_net(ifa->idev->dev), net))
continue;
state->offset++;
return ifa;
}
}
return NULL;
}
static void *if6_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(rcu_bh)
{
rcu_read_lock_bh();
return if6_get_first(seq, *pos);
}
static void *if6_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct inet6_ifaddr *ifa;
ifa = if6_get_next(seq, v);
++*pos;
return ifa;
}
static void if6_seq_stop(struct seq_file *seq, void *v)
__releases(rcu_bh)
{
rcu_read_unlock_bh();
}
static int if6_seq_show(struct seq_file *seq, void *v)
{
struct inet6_ifaddr *ifp = (struct inet6_ifaddr *)v;
seq_printf(seq, "%pi6 %02x %02x %02x %02x %8s\n",
&ifp->addr,
ifp->idev->dev->ifindex,
ifp->prefix_len,
ifp->scope,
(u8) ifp->flags,
ifp->idev->dev->name);
return 0;
}
static const struct seq_operations if6_seq_ops = {
.start = if6_seq_start,
.next = if6_seq_next,
.show = if6_seq_show,
.stop = if6_seq_stop,
};
static int if6_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &if6_seq_ops,
sizeof(struct if6_iter_state));
}
static const struct file_operations if6_fops = {
.owner = THIS_MODULE,
.open = if6_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init if6_proc_net_init(struct net *net)
{
if (!proc_create("if_inet6", S_IRUGO, net->proc_net, &if6_fops))
return -ENOMEM;
return 0;
}
static void __net_exit if6_proc_net_exit(struct net *net)
{
remove_proc_entry("if_inet6", net->proc_net);
}
static struct pernet_operations if6_proc_net_ops = {
.init = if6_proc_net_init,
.exit = if6_proc_net_exit,
};
int __init if6_proc_init(void)
{
return register_pernet_subsys(&if6_proc_net_ops);
}
void if6_proc_exit(void)
{
unregister_pernet_subsys(&if6_proc_net_ops);
}
#endif /* CONFIG_PROC_FS */
#if IS_ENABLED(CONFIG_IPV6_MIP6)
/* Check if address is a home address configured on any interface. */
int ipv6_chk_home_addr(struct net *net, const struct in6_addr *addr)
{
int ret = 0;
struct inet6_ifaddr *ifp = NULL;
unsigned int hash = inet6_addr_hash(addr);
rcu_read_lock_bh();
hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[hash], addr_lst) {
if (!net_eq(dev_net(ifp->idev->dev), net))
continue;
if (ipv6_addr_equal(&ifp->addr, addr) &&
(ifp->flags & IFA_F_HOMEADDRESS)) {
ret = 1;
break;
}
}
rcu_read_unlock_bh();
return ret;
}
#endif
/*
* Periodic address status verification
*/
static void addrconf_verify_rtnl(void)
{
unsigned long now, next, next_sec, next_sched;
struct inet6_ifaddr *ifp;
int i;
ASSERT_RTNL();
rcu_read_lock_bh();
now = jiffies;
next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY);
cancel_delayed_work(&addr_chk_work);
for (i = 0; i < IN6_ADDR_HSIZE; i++) {
restart:
hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[i], addr_lst) {
unsigned long age;
/* When setting preferred_lft to a value not zero or
* infinity, while valid_lft is infinity
* IFA_F_PERMANENT has a non-infinity life time.
*/
if ((ifp->flags & IFA_F_PERMANENT) &&
(ifp->prefered_lft == INFINITY_LIFE_TIME))
continue;
spin_lock(&ifp->lock);
/* We try to batch several events at once. */
age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
if (ifp->valid_lft != INFINITY_LIFE_TIME &&
age >= ifp->valid_lft) {
spin_unlock(&ifp->lock);
in6_ifa_hold(ifp);
ipv6_del_addr(ifp);
goto restart;
} else if (ifp->prefered_lft == INFINITY_LIFE_TIME) {
spin_unlock(&ifp->lock);
continue;
} else if (age >= ifp->prefered_lft) {
/* jiffies - ifp->tstamp > age >= ifp->prefered_lft */
int deprecate = 0;
if (!(ifp->flags&IFA_F_DEPRECATED)) {
deprecate = 1;
ifp->flags |= IFA_F_DEPRECATED;
}
if ((ifp->valid_lft != INFINITY_LIFE_TIME) &&
(time_before(ifp->tstamp + ifp->valid_lft * HZ, next)))
next = ifp->tstamp + ifp->valid_lft * HZ;
spin_unlock(&ifp->lock);
if (deprecate) {
in6_ifa_hold(ifp);
ipv6_ifa_notify(0, ifp);
in6_ifa_put(ifp);
goto restart;
}
} else if ((ifp->flags&IFA_F_TEMPORARY) &&
!(ifp->flags&IFA_F_TENTATIVE)) {
unsigned long regen_advance = ifp->idev->cnf.regen_max_retry *
ifp->idev->cnf.dad_transmits *
NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME) / HZ;
if (age >= ifp->prefered_lft - regen_advance) {
struct inet6_ifaddr *ifpub = ifp->ifpub;
if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
next = ifp->tstamp + ifp->prefered_lft * HZ;
if (!ifp->regen_count && ifpub) {
ifp->regen_count++;
in6_ifa_hold(ifp);
in6_ifa_hold(ifpub);
spin_unlock(&ifp->lock);
spin_lock(&ifpub->lock);
ifpub->regen_count = 0;
spin_unlock(&ifpub->lock);
ipv6_create_tempaddr(ifpub, ifp);
in6_ifa_put(ifpub);
in6_ifa_put(ifp);
goto restart;
}
} else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next))
next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ;
spin_unlock(&ifp->lock);
} else {
/* ifp->prefered_lft <= ifp->valid_lft */
if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
next = ifp->tstamp + ifp->prefered_lft * HZ;
spin_unlock(&ifp->lock);
}
}
}
next_sec = round_jiffies_up(next);
next_sched = next;
/* If rounded timeout is accurate enough, accept it. */
if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ))
next_sched = next_sec;
/* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */
if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX))
next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX;
ADBG(KERN_DEBUG "now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n",
now, next, next_sec, next_sched);
mod_delayed_work(addrconf_wq, &addr_chk_work, next_sched - now);
rcu_read_unlock_bh();
}
static void addrconf_verify_work(struct work_struct *w)
{
rtnl_lock();
addrconf_verify_rtnl();
rtnl_unlock();
}
static void addrconf_verify(void)
{
mod_delayed_work(addrconf_wq, &addr_chk_work, 0);
}
static struct in6_addr *extract_addr(struct nlattr *addr, struct nlattr *local,
struct in6_addr **peer_pfx)
{
struct in6_addr *pfx = NULL;
*peer_pfx = NULL;
if (addr)
pfx = nla_data(addr);
if (local) {
if (pfx && nla_memcmp(local, pfx, sizeof(*pfx)))
*peer_pfx = pfx;
pfx = nla_data(local);
}
return pfx;
}
static const struct nla_policy ifa_ipv6_policy[IFA_MAX+1] = {
[IFA_ADDRESS] = { .len = sizeof(struct in6_addr) },
[IFA_LOCAL] = { .len = sizeof(struct in6_addr) },
[IFA_CACHEINFO] = { .len = sizeof(struct ifa_cacheinfo) },
[IFA_FLAGS] = { .len = sizeof(u32) },
};
static int
inet6_rtm_deladdr(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct ifaddrmsg *ifm;
struct nlattr *tb[IFA_MAX+1];
struct in6_addr *pfx, *peer_pfx;
u32 ifa_flags;
int err;
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy);
if (err < 0)
return err;
ifm = nlmsg_data(nlh);
pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
if (pfx == NULL)
return -EINVAL;
ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) : ifm->ifa_flags;
/* We ignore other flags so far. */
ifa_flags &= IFA_F_MANAGETEMPADDR;
return inet6_addr_del(net, ifm->ifa_index, ifa_flags, pfx,
ifm->ifa_prefixlen);
}
static int inet6_addr_modify(struct inet6_ifaddr *ifp, u32 ifa_flags,
u32 prefered_lft, u32 valid_lft)
{
u32 flags;
clock_t expires;
unsigned long timeout;
bool was_managetempaddr;
bool had_prefixroute;
ASSERT_RTNL();
if (!valid_lft || (prefered_lft > valid_lft))
return -EINVAL;
if (ifa_flags & IFA_F_MANAGETEMPADDR &&
(ifp->flags & IFA_F_TEMPORARY || ifp->prefix_len != 64))
return -EINVAL;
timeout = addrconf_timeout_fixup(valid_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
expires = jiffies_to_clock_t(timeout * HZ);
valid_lft = timeout;
flags = RTF_EXPIRES;
} else {
expires = 0;
flags = 0;
ifa_flags |= IFA_F_PERMANENT;
}
timeout = addrconf_timeout_fixup(prefered_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
if (timeout == 0)
ifa_flags |= IFA_F_DEPRECATED;
prefered_lft = timeout;
}
spin_lock_bh(&ifp->lock);
was_managetempaddr = ifp->flags & IFA_F_MANAGETEMPADDR;
had_prefixroute = ifp->flags & IFA_F_PERMANENT &&
!(ifp->flags & IFA_F_NOPREFIXROUTE);
ifp->flags &= ~(IFA_F_DEPRECATED | IFA_F_PERMANENT | IFA_F_NODAD |
IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR |
IFA_F_NOPREFIXROUTE);
ifp->flags |= ifa_flags;
ifp->tstamp = jiffies;
ifp->valid_lft = valid_lft;
ifp->prefered_lft = prefered_lft;
spin_unlock_bh(&ifp->lock);
if (!(ifp->flags&IFA_F_TENTATIVE))
ipv6_ifa_notify(0, ifp);
if (!(ifa_flags & IFA_F_NOPREFIXROUTE)) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len, ifp->idev->dev,
expires, flags);
} else if (had_prefixroute) {
enum cleanup_prefix_rt_t action;
unsigned long rt_expires;
write_lock_bh(&ifp->idev->lock);
action = check_cleanup_prefix_route(ifp, &rt_expires);
write_unlock_bh(&ifp->idev->lock);
if (action != CLEANUP_PREFIX_RT_NOP) {
cleanup_prefix_route(ifp, rt_expires,
action == CLEANUP_PREFIX_RT_DEL);
}
}
if (was_managetempaddr || ifp->flags & IFA_F_MANAGETEMPADDR) {
if (was_managetempaddr && !(ifp->flags & IFA_F_MANAGETEMPADDR))
valid_lft = prefered_lft = 0;
manage_tempaddrs(ifp->idev, ifp, valid_lft, prefered_lft,
!was_managetempaddr, jiffies);
}
addrconf_verify_rtnl();
return 0;
}
static int
inet6_rtm_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct ifaddrmsg *ifm;
struct nlattr *tb[IFA_MAX+1];
struct in6_addr *pfx, *peer_pfx;
struct inet6_ifaddr *ifa;
struct net_device *dev;
u32 valid_lft = INFINITY_LIFE_TIME, preferred_lft = INFINITY_LIFE_TIME;
u32 ifa_flags;
int err;
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy);
if (err < 0)
return err;
ifm = nlmsg_data(nlh);
pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
if (pfx == NULL)
return -EINVAL;
if (tb[IFA_CACHEINFO]) {
struct ifa_cacheinfo *ci;
ci = nla_data(tb[IFA_CACHEINFO]);
valid_lft = ci->ifa_valid;
preferred_lft = ci->ifa_prefered;
} else {
preferred_lft = INFINITY_LIFE_TIME;
valid_lft = INFINITY_LIFE_TIME;
}
dev = __dev_get_by_index(net, ifm->ifa_index);
if (dev == NULL)
return -ENODEV;
ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) : ifm->ifa_flags;
/* We ignore other flags so far. */
ifa_flags &= IFA_F_NODAD | IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR |
IFA_F_NOPREFIXROUTE;
ifa = ipv6_get_ifaddr(net, pfx, dev, 1);
if (ifa == NULL) {
/*
* It would be best to check for !NLM_F_CREATE here but
* userspace already relies on not having to provide this.
*/
return inet6_addr_add(net, ifm->ifa_index, pfx, peer_pfx,
ifm->ifa_prefixlen, ifa_flags,
preferred_lft, valid_lft);
}
if (nlh->nlmsg_flags & NLM_F_EXCL ||
!(nlh->nlmsg_flags & NLM_F_REPLACE))
err = -EEXIST;
else
err = inet6_addr_modify(ifa, ifa_flags, preferred_lft, valid_lft);
in6_ifa_put(ifa);
return err;
}
static void put_ifaddrmsg(struct nlmsghdr *nlh, u8 prefixlen, u32 flags,
u8 scope, int ifindex)
{
struct ifaddrmsg *ifm;
ifm = nlmsg_data(nlh);
ifm->ifa_family = AF_INET6;
ifm->ifa_prefixlen = prefixlen;
ifm->ifa_flags = flags;
ifm->ifa_scope = scope;
ifm->ifa_index = ifindex;
}
static int put_cacheinfo(struct sk_buff *skb, unsigned long cstamp,
unsigned long tstamp, u32 preferred, u32 valid)
{
struct ifa_cacheinfo ci;
ci.cstamp = cstamp_delta(cstamp);
ci.tstamp = cstamp_delta(tstamp);
ci.ifa_prefered = preferred;
ci.ifa_valid = valid;
return nla_put(skb, IFA_CACHEINFO, sizeof(ci), &ci);
}
static inline int rt_scope(int ifa_scope)
{
if (ifa_scope & IFA_HOST)
return RT_SCOPE_HOST;
else if (ifa_scope & IFA_LINK)
return RT_SCOPE_LINK;
else if (ifa_scope & IFA_SITE)
return RT_SCOPE_SITE;
else
return RT_SCOPE_UNIVERSE;
}
static inline int inet6_ifaddr_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct ifaddrmsg))
+ nla_total_size(16) /* IFA_LOCAL */
+ nla_total_size(16) /* IFA_ADDRESS */
+ nla_total_size(sizeof(struct ifa_cacheinfo))
+ nla_total_size(4) /* IFA_FLAGS */;
}
static int inet6_fill_ifaddr(struct sk_buff *skb, struct inet6_ifaddr *ifa,
u32 portid, u32 seq, int event, unsigned int flags)
{
struct nlmsghdr *nlh;
u32 preferred, valid;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags);
if (nlh == NULL)
return -EMSGSIZE;
put_ifaddrmsg(nlh, ifa->prefix_len, ifa->flags, rt_scope(ifa->scope),
ifa->idev->dev->ifindex);
if (!((ifa->flags&IFA_F_PERMANENT) &&
(ifa->prefered_lft == INFINITY_LIFE_TIME))) {
preferred = ifa->prefered_lft;
valid = ifa->valid_lft;
if (preferred != INFINITY_LIFE_TIME) {
long tval = (jiffies - ifa->tstamp)/HZ;
if (preferred > tval)
preferred -= tval;
else
preferred = 0;
if (valid != INFINITY_LIFE_TIME) {
if (valid > tval)
valid -= tval;
else
valid = 0;
}
}
} else {
preferred = INFINITY_LIFE_TIME;
valid = INFINITY_LIFE_TIME;
}
if (!ipv6_addr_any(&ifa->peer_addr)) {
if (nla_put(skb, IFA_LOCAL, 16, &ifa->addr) < 0 ||
nla_put(skb, IFA_ADDRESS, 16, &ifa->peer_addr) < 0)
goto error;
} else
if (nla_put(skb, IFA_ADDRESS, 16, &ifa->addr) < 0)
goto error;
if (put_cacheinfo(skb, ifa->cstamp, ifa->tstamp, preferred, valid) < 0)
goto error;
if (nla_put_u32(skb, IFA_FLAGS, ifa->flags) < 0)
goto error;
nlmsg_end(skb, nlh);
return 0;
error:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int inet6_fill_ifmcaddr(struct sk_buff *skb, struct ifmcaddr6 *ifmca,
u32 portid, u32 seq, int event, u16 flags)
{
struct nlmsghdr *nlh;
u8 scope = RT_SCOPE_UNIVERSE;
int ifindex = ifmca->idev->dev->ifindex;
if (ipv6_addr_scope(&ifmca->mca_addr) & IFA_SITE)
scope = RT_SCOPE_SITE;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags);
if (nlh == NULL)
return -EMSGSIZE;
put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
if (nla_put(skb, IFA_MULTICAST, 16, &ifmca->mca_addr) < 0 ||
put_cacheinfo(skb, ifmca->mca_cstamp, ifmca->mca_tstamp,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
nlmsg_end(skb, nlh);
return 0;
}
static int inet6_fill_ifacaddr(struct sk_buff *skb, struct ifacaddr6 *ifaca,
u32 portid, u32 seq, int event, unsigned int flags)
{
struct nlmsghdr *nlh;
u8 scope = RT_SCOPE_UNIVERSE;
int ifindex = ifaca->aca_idev->dev->ifindex;
if (ipv6_addr_scope(&ifaca->aca_addr) & IFA_SITE)
scope = RT_SCOPE_SITE;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags);
if (nlh == NULL)
return -EMSGSIZE;
put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
if (nla_put(skb, IFA_ANYCAST, 16, &ifaca->aca_addr) < 0 ||
put_cacheinfo(skb, ifaca->aca_cstamp, ifaca->aca_tstamp,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
nlmsg_end(skb, nlh);
return 0;
}
enum addr_type_t {
UNICAST_ADDR,
MULTICAST_ADDR,
ANYCAST_ADDR,
};
/* called with rcu_read_lock() */
static int in6_dump_addrs(struct inet6_dev *idev, struct sk_buff *skb,
struct netlink_callback *cb, enum addr_type_t type,
int s_ip_idx, int *p_ip_idx)
{
struct ifmcaddr6 *ifmca;
struct ifacaddr6 *ifaca;
int err = 1;
int ip_idx = *p_ip_idx;
read_lock_bh(&idev->lock);
switch (type) {
case UNICAST_ADDR: {
struct inet6_ifaddr *ifa;
/* unicast address incl. temp addr */
list_for_each_entry(ifa, &idev->addr_list, if_list) {
if (++ip_idx < s_ip_idx)
continue;
err = inet6_fill_ifaddr(skb, ifa,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_NEWADDR,
NLM_F_MULTI);
if (err < 0)
break;
nl_dump_check_consistent(cb, nlmsg_hdr(skb));
}
break;
}
case MULTICAST_ADDR:
/* multicast address */
for (ifmca = idev->mc_list; ifmca;
ifmca = ifmca->next, ip_idx++) {
if (ip_idx < s_ip_idx)
continue;
err = inet6_fill_ifmcaddr(skb, ifmca,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_GETMULTICAST,
NLM_F_MULTI);
if (err < 0)
break;
}
break;
case ANYCAST_ADDR:
/* anycast address */
for (ifaca = idev->ac_list; ifaca;
ifaca = ifaca->aca_next, ip_idx++) {
if (ip_idx < s_ip_idx)
continue;
err = inet6_fill_ifacaddr(skb, ifaca,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_GETANYCAST,
NLM_F_MULTI);
if (err < 0)
break;
}
break;
default:
break;
}
read_unlock_bh(&idev->lock);
*p_ip_idx = ip_idx;
return err;
}
static int inet6_dump_addr(struct sk_buff *skb, struct netlink_callback *cb,
enum addr_type_t type)
{
struct net *net = sock_net(skb->sk);
int h, s_h;
int idx, ip_idx;
int s_idx, s_ip_idx;
struct net_device *dev;
struct inet6_dev *idev;
struct hlist_head *head;
s_h = cb->args[0];
s_idx = idx = cb->args[1];
s_ip_idx = ip_idx = cb->args[2];
rcu_read_lock();
cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^ net->dev_base_seq;
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &net->dev_index_head[h];
hlist_for_each_entry_rcu(dev, head, index_hlist) {
if (idx < s_idx)
goto cont;
if (h > s_h || idx > s_idx)
s_ip_idx = 0;
ip_idx = 0;
idev = __in6_dev_get(dev);
if (!idev)
goto cont;
if (in6_dump_addrs(idev, skb, cb, type,
s_ip_idx, &ip_idx) < 0)
goto done;
cont:
idx++;
}
}
done:
rcu_read_unlock();
cb->args[0] = h;
cb->args[1] = idx;
cb->args[2] = ip_idx;
return skb->len;
}
static int inet6_dump_ifaddr(struct sk_buff *skb, struct netlink_callback *cb)
{
enum addr_type_t type = UNICAST_ADDR;
return inet6_dump_addr(skb, cb, type);
}
static int inet6_dump_ifmcaddr(struct sk_buff *skb, struct netlink_callback *cb)
{
enum addr_type_t type = MULTICAST_ADDR;
return inet6_dump_addr(skb, cb, type);
}
static int inet6_dump_ifacaddr(struct sk_buff *skb, struct netlink_callback *cb)
{
enum addr_type_t type = ANYCAST_ADDR;
return inet6_dump_addr(skb, cb, type);
}
static int inet6_rtm_getaddr(struct sk_buff *in_skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(in_skb->sk);
struct ifaddrmsg *ifm;
struct nlattr *tb[IFA_MAX+1];
struct in6_addr *addr = NULL, *peer;
struct net_device *dev = NULL;
struct inet6_ifaddr *ifa;
struct sk_buff *skb;
int err;
err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy);
if (err < 0)
goto errout;
addr = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer);
if (addr == NULL) {
err = -EINVAL;
goto errout;
}
ifm = nlmsg_data(nlh);
if (ifm->ifa_index)
dev = __dev_get_by_index(net, ifm->ifa_index);
ifa = ipv6_get_ifaddr(net, addr, dev, 1);
if (!ifa) {
err = -EADDRNOTAVAIL;
goto errout;
}
skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout_ifa;
}
err = inet6_fill_ifaddr(skb, ifa, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWADDR, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout_ifa;
}
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout_ifa:
in6_ifa_put(ifa);
errout:
return err;
}
static void inet6_ifa_notify(int event, struct inet6_ifaddr *ifa)
{
struct sk_buff *skb;
struct net *net = dev_net(ifa->idev->dev);
int err = -ENOBUFS;
skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_ATOMIC);
if (skb == NULL)
goto errout;
err = inet6_fill_ifaddr(skb, ifa, 0, 0, event, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFADDR, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_IFADDR, err);
}
static inline void ipv6_store_devconf(struct ipv6_devconf *cnf,
__s32 *array, int bytes)
{
BUG_ON(bytes < (DEVCONF_MAX * 4));
memset(array, 0, bytes);
array[DEVCONF_FORWARDING] = cnf->forwarding;
array[DEVCONF_HOPLIMIT] = cnf->hop_limit;
array[DEVCONF_MTU6] = cnf->mtu6;
array[DEVCONF_ACCEPT_RA] = cnf->accept_ra;
array[DEVCONF_ACCEPT_REDIRECTS] = cnf->accept_redirects;
array[DEVCONF_AUTOCONF] = cnf->autoconf;
array[DEVCONF_DAD_TRANSMITS] = cnf->dad_transmits;
array[DEVCONF_RTR_SOLICITS] = cnf->rtr_solicits;
array[DEVCONF_RTR_SOLICIT_INTERVAL] =
jiffies_to_msecs(cnf->rtr_solicit_interval);
array[DEVCONF_RTR_SOLICIT_DELAY] =
jiffies_to_msecs(cnf->rtr_solicit_delay);
array[DEVCONF_FORCE_MLD_VERSION] = cnf->force_mld_version;
array[DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL] =
jiffies_to_msecs(cnf->mldv1_unsolicited_report_interval);
array[DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL] =
jiffies_to_msecs(cnf->mldv2_unsolicited_report_interval);
array[DEVCONF_USE_TEMPADDR] = cnf->use_tempaddr;
array[DEVCONF_TEMP_VALID_LFT] = cnf->temp_valid_lft;
array[DEVCONF_TEMP_PREFERED_LFT] = cnf->temp_prefered_lft;
array[DEVCONF_REGEN_MAX_RETRY] = cnf->regen_max_retry;
array[DEVCONF_MAX_DESYNC_FACTOR] = cnf->max_desync_factor;
array[DEVCONF_MAX_ADDRESSES] = cnf->max_addresses;
array[DEVCONF_ACCEPT_RA_DEFRTR] = cnf->accept_ra_defrtr;
array[DEVCONF_ACCEPT_RA_PINFO] = cnf->accept_ra_pinfo;
#ifdef CONFIG_IPV6_ROUTER_PREF
array[DEVCONF_ACCEPT_RA_RTR_PREF] = cnf->accept_ra_rtr_pref;
array[DEVCONF_RTR_PROBE_INTERVAL] =
jiffies_to_msecs(cnf->rtr_probe_interval);
#ifdef CONFIG_IPV6_ROUTE_INFO
array[DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN] = cnf->accept_ra_rt_info_max_plen;
#endif
#endif
array[DEVCONF_PROXY_NDP] = cnf->proxy_ndp;
array[DEVCONF_ACCEPT_SOURCE_ROUTE] = cnf->accept_source_route;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
array[DEVCONF_OPTIMISTIC_DAD] = cnf->optimistic_dad;
array[DEVCONF_USE_OPTIMISTIC] = cnf->use_optimistic;
#endif
#ifdef CONFIG_IPV6_MROUTE
array[DEVCONF_MC_FORWARDING] = cnf->mc_forwarding;
#endif
array[DEVCONF_DISABLE_IPV6] = cnf->disable_ipv6;
array[DEVCONF_ACCEPT_DAD] = cnf->accept_dad;
array[DEVCONF_FORCE_TLLAO] = cnf->force_tllao;
array[DEVCONF_NDISC_NOTIFY] = cnf->ndisc_notify;
array[DEVCONF_SUPPRESS_FRAG_NDISC] = cnf->suppress_frag_ndisc;
array[DEVCONF_ACCEPT_RA_FROM_LOCAL] = cnf->accept_ra_from_local;
array[DEVCONF_ACCEPT_RA_MTU] = cnf->accept_ra_mtu;
}
static inline size_t inet6_ifla6_size(void)
{
return nla_total_size(4) /* IFLA_INET6_FLAGS */
+ nla_total_size(sizeof(struct ifla_cacheinfo))
+ nla_total_size(DEVCONF_MAX * 4) /* IFLA_INET6_CONF */
+ nla_total_size(IPSTATS_MIB_MAX * 8) /* IFLA_INET6_STATS */
+ nla_total_size(ICMP6_MIB_MAX * 8) /* IFLA_INET6_ICMP6STATS */
+ nla_total_size(sizeof(struct in6_addr)); /* IFLA_INET6_TOKEN */
}
static inline size_t inet6_if_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(4) /* IFLA_MTU */
+ nla_total_size(4) /* IFLA_LINK */
+ nla_total_size(inet6_ifla6_size()); /* IFLA_PROTINFO */
}
static inline void __snmp6_fill_statsdev(u64 *stats, atomic_long_t *mib,
int items, int bytes)
{
int i;
int pad = bytes - sizeof(u64) * items;
BUG_ON(pad < 0);
/* Use put_unaligned() because stats may not be aligned for u64. */
put_unaligned(items, &stats[0]);
for (i = 1; i < items; i++)
put_unaligned(atomic_long_read(&mib[i]), &stats[i]);
memset(&stats[items], 0, pad);
}
static inline void __snmp6_fill_stats64(u64 *stats, void __percpu *mib,
int items, int bytes, size_t syncpoff)
{
int i;
int pad = bytes - sizeof(u64) * items;
BUG_ON(pad < 0);
/* Use put_unaligned() because stats may not be aligned for u64. */
put_unaligned(items, &stats[0]);
for (i = 1; i < items; i++)
put_unaligned(snmp_fold_field64(mib, i, syncpoff), &stats[i]);
memset(&stats[items], 0, pad);
}
static void snmp6_fill_stats(u64 *stats, struct inet6_dev *idev, int attrtype,
int bytes)
{
switch (attrtype) {
case IFLA_INET6_STATS:
__snmp6_fill_stats64(stats, idev->stats.ipv6,
IPSTATS_MIB_MAX, bytes, offsetof(struct ipstats_mib, syncp));
break;
case IFLA_INET6_ICMP6STATS:
__snmp6_fill_statsdev(stats, idev->stats.icmpv6dev->mibs, ICMP6_MIB_MAX, bytes);
break;
}
}
static int inet6_fill_ifla6_attrs(struct sk_buff *skb, struct inet6_dev *idev)
{
struct nlattr *nla;
struct ifla_cacheinfo ci;
if (nla_put_u32(skb, IFLA_INET6_FLAGS, idev->if_flags))
goto nla_put_failure;
ci.max_reasm_len = IPV6_MAXPLEN;
ci.tstamp = cstamp_delta(idev->tstamp);
ci.reachable_time = jiffies_to_msecs(idev->nd_parms->reachable_time);
ci.retrans_time = jiffies_to_msecs(NEIGH_VAR(idev->nd_parms, RETRANS_TIME));
if (nla_put(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci))
goto nla_put_failure;
nla = nla_reserve(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(s32));
if (nla == NULL)
goto nla_put_failure;
ipv6_store_devconf(&idev->cnf, nla_data(nla), nla_len(nla));
/* XXX - MC not implemented */
nla = nla_reserve(skb, IFLA_INET6_STATS, IPSTATS_MIB_MAX * sizeof(u64));
if (nla == NULL)
goto nla_put_failure;
snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_STATS, nla_len(nla));
nla = nla_reserve(skb, IFLA_INET6_ICMP6STATS, ICMP6_MIB_MAX * sizeof(u64));
if (nla == NULL)
goto nla_put_failure;
snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_ICMP6STATS, nla_len(nla));
nla = nla_reserve(skb, IFLA_INET6_TOKEN, sizeof(struct in6_addr));
if (nla == NULL)
goto nla_put_failure;
if (nla_put_u8(skb, IFLA_INET6_ADDR_GEN_MODE, idev->addr_gen_mode))
goto nla_put_failure;
read_lock_bh(&idev->lock);
memcpy(nla_data(nla), idev->token.s6_addr, nla_len(nla));
read_unlock_bh(&idev->lock);
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static size_t inet6_get_link_af_size(const struct net_device *dev)
{
if (!__in6_dev_get(dev))
return 0;
return inet6_ifla6_size();
}
static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev)
{
struct inet6_dev *idev = __in6_dev_get(dev);
if (!idev)
return -ENODATA;
if (inet6_fill_ifla6_attrs(skb, idev) < 0)
return -EMSGSIZE;
return 0;
}
static int inet6_set_iftoken(struct inet6_dev *idev, struct in6_addr *token)
{
struct inet6_ifaddr *ifp;
struct net_device *dev = idev->dev;
bool update_rs = false;
struct in6_addr ll_addr;
ASSERT_RTNL();
if (token == NULL)
return -EINVAL;
if (ipv6_addr_any(token))
return -EINVAL;
if (dev->flags & (IFF_LOOPBACK | IFF_NOARP))
return -EINVAL;
if (!ipv6_accept_ra(idev))
return -EINVAL;
if (idev->cnf.rtr_solicits <= 0)
return -EINVAL;
write_lock_bh(&idev->lock);
BUILD_BUG_ON(sizeof(token->s6_addr) != 16);
memcpy(idev->token.s6_addr + 8, token->s6_addr + 8, 8);
write_unlock_bh(&idev->lock);
if (!idev->dead && (idev->if_flags & IF_READY) &&
!ipv6_get_lladdr(dev, &ll_addr, IFA_F_TENTATIVE |
IFA_F_OPTIMISTIC)) {
/* If we're not ready, then normal ifup will take care
* of this. Otherwise, we need to request our rs here.
*/
ndisc_send_rs(dev, &ll_addr, &in6addr_linklocal_allrouters);
update_rs = true;
}
write_lock_bh(&idev->lock);
if (update_rs) {
idev->if_flags |= IF_RS_SENT;
idev->rs_probes = 1;
addrconf_mod_rs_timer(idev, idev->cnf.rtr_solicit_interval);
}
/* Well, that's kinda nasty ... */
list_for_each_entry(ifp, &idev->addr_list, if_list) {
spin_lock(&ifp->lock);
if (ifp->tokenized) {
ifp->valid_lft = 0;
ifp->prefered_lft = 0;
}
spin_unlock(&ifp->lock);
}
write_unlock_bh(&idev->lock);
inet6_ifinfo_notify(RTM_NEWLINK, idev);
addrconf_verify_rtnl();
return 0;
}
static const struct nla_policy inet6_af_policy[IFLA_INET6_MAX + 1] = {
[IFLA_INET6_ADDR_GEN_MODE] = { .type = NLA_U8 },
[IFLA_INET6_TOKEN] = { .len = sizeof(struct in6_addr) },
};
static int inet6_validate_link_af(const struct net_device *dev,
const struct nlattr *nla)
{
struct nlattr *tb[IFLA_INET6_MAX + 1];
if (dev && !__in6_dev_get(dev))
return -EAFNOSUPPORT;
return nla_parse_nested(tb, IFLA_INET6_MAX, nla, inet6_af_policy);
}
static int inet6_set_link_af(struct net_device *dev, const struct nlattr *nla)
{
int err = -EINVAL;
struct inet6_dev *idev = __in6_dev_get(dev);
struct nlattr *tb[IFLA_INET6_MAX + 1];
if (!idev)
return -EAFNOSUPPORT;
if (nla_parse_nested(tb, IFLA_INET6_MAX, nla, NULL) < 0)
BUG();
if (tb[IFLA_INET6_TOKEN]) {
err = inet6_set_iftoken(idev, nla_data(tb[IFLA_INET6_TOKEN]));
if (err)
return err;
}
if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
if (mode != IN6_ADDR_GEN_MODE_EUI64 &&
mode != IN6_ADDR_GEN_MODE_NONE)
return -EINVAL;
idev->addr_gen_mode = mode;
err = 0;
}
return err;
}
static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev,
u32 portid, u32 seq, int event, unsigned int flags)
{
struct net_device *dev = idev->dev;
struct ifinfomsg *hdr;
struct nlmsghdr *nlh;
void *protoinfo;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*hdr), flags);
if (nlh == NULL)
return -EMSGSIZE;
hdr = nlmsg_data(nlh);
hdr->ifi_family = AF_INET6;
hdr->__ifi_pad = 0;
hdr->ifi_type = dev->type;
hdr->ifi_index = dev->ifindex;
hdr->ifi_flags = dev_get_flags(dev);
hdr->ifi_change = 0;
if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
(dev->addr_len &&
nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr)) ||
nla_put_u32(skb, IFLA_MTU, dev->mtu) ||
(dev->ifindex != dev->iflink &&
nla_put_u32(skb, IFLA_LINK, dev->iflink)))
goto nla_put_failure;
protoinfo = nla_nest_start(skb, IFLA_PROTINFO);
if (protoinfo == NULL)
goto nla_put_failure;
if (inet6_fill_ifla6_attrs(skb, idev) < 0)
goto nla_put_failure;
nla_nest_end(skb, protoinfo);
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int inet6_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 inet6_dev *idev;
struct hlist_head *head;
s_h = cb->args[0];
s_idx = cb->args[1];
rcu_read_lock();
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &net->dev_index_head[h];
hlist_for_each_entry_rcu(dev, head, index_hlist) {
if (idx < s_idx)
goto cont;
idev = __in6_dev_get(dev);
if (!idev)
goto cont;
if (inet6_fill_ifinfo(skb, idev,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_NEWLINK, NLM_F_MULTI) < 0)
goto out;
cont:
idx++;
}
}
out:
rcu_read_unlock();
cb->args[1] = idx;
cb->args[0] = h;
return skb->len;
}
void inet6_ifinfo_notify(int event, struct inet6_dev *idev)
{
struct sk_buff *skb;
struct net *net = dev_net(idev->dev);
int err = -ENOBUFS;
skb = nlmsg_new(inet6_if_nlmsg_size(), GFP_ATOMIC);
if (skb == NULL)
goto errout;
err = inet6_fill_ifinfo(skb, idev, 0, 0, event, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_if_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFINFO, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_IFINFO, err);
}
static inline size_t inet6_prefix_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct prefixmsg))
+ nla_total_size(sizeof(struct in6_addr))
+ nla_total_size(sizeof(struct prefix_cacheinfo));
}
static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev,
struct prefix_info *pinfo, u32 portid, u32 seq,
int event, unsigned int flags)
{
struct prefixmsg *pmsg;
struct nlmsghdr *nlh;
struct prefix_cacheinfo ci;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*pmsg), flags);
if (nlh == NULL)
return -EMSGSIZE;
pmsg = nlmsg_data(nlh);
pmsg->prefix_family = AF_INET6;
pmsg->prefix_pad1 = 0;
pmsg->prefix_pad2 = 0;
pmsg->prefix_ifindex = idev->dev->ifindex;
pmsg->prefix_len = pinfo->prefix_len;
pmsg->prefix_type = pinfo->type;
pmsg->prefix_pad3 = 0;
pmsg->prefix_flags = 0;
if (pinfo->onlink)
pmsg->prefix_flags |= IF_PREFIX_ONLINK;
if (pinfo->autoconf)
pmsg->prefix_flags |= IF_PREFIX_AUTOCONF;
if (nla_put(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix))
goto nla_put_failure;
ci.preferred_time = ntohl(pinfo->prefered);
ci.valid_time = ntohl(pinfo->valid);
if (nla_put(skb, PREFIX_CACHEINFO, sizeof(ci), &ci))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static void inet6_prefix_notify(int event, struct inet6_dev *idev,
struct prefix_info *pinfo)
{
struct sk_buff *skb;
struct net *net = dev_net(idev->dev);
int err = -ENOBUFS;
skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC);
if (skb == NULL)
goto errout;
err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err);
}
static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
{
struct net *net = dev_net(ifp->idev->dev);
if (event)
ASSERT_RTNL();
inet6_ifa_notify(event ? : RTM_NEWADDR, ifp);
switch (event) {
case RTM_NEWADDR:
/*
* If the address was optimistic
* we inserted the route at the start of
* our DAD process, so we don't need
* to do it again
*/
if (!(ifp->rt->rt6i_node))
ip6_ins_rt(ifp->rt);
if (ifp->idev->cnf.forwarding)
addrconf_join_anycast(ifp);
if (!ipv6_addr_any(&ifp->peer_addr))
addrconf_prefix_route(&ifp->peer_addr, 128,
ifp->idev->dev, 0, 0);
break;
case RTM_DELADDR:
if (ifp->idev->cnf.forwarding)
addrconf_leave_anycast(ifp);
addrconf_leave_solict(ifp->idev, &ifp->addr);
if (!ipv6_addr_any(&ifp->peer_addr)) {
struct rt6_info *rt;
rt = addrconf_get_prefix_route(&ifp->peer_addr, 128,
ifp->idev->dev, 0, 0);
if (rt && ip6_del_rt(rt))
dst_free(&rt->dst);
}
dst_hold(&ifp->rt->dst);
if (ip6_del_rt(ifp->rt))
dst_free(&ifp->rt->dst);
rt_genid_bump_ipv6(net);
break;
}
atomic_inc(&net->ipv6.dev_addr_genid);
}
static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
{
rcu_read_lock_bh();
if (likely(ifp->idev->dead == 0))
__ipv6_ifa_notify(event, ifp);
rcu_read_unlock_bh();
}
#ifdef CONFIG_SYSCTL
static
int addrconf_sysctl_forward(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int val = *valp;
loff_t pos = *ppos;
struct ctl_table lctl;
int ret;
/*
* ctl->data points to idev->cnf.forwarding, we should
* not modify it until we get the rtnl lock.
*/
lctl = *ctl;
lctl.data = &val;
ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
if (write)
ret = addrconf_fixup_forwarding(ctl, valp, val);
if (ret)
*ppos = pos;
return ret;
}
static void dev_disable_change(struct inet6_dev *idev)
{
struct netdev_notifier_info info;
if (!idev || !idev->dev)
return;
netdev_notifier_info_init(&info, idev->dev);
if (idev->cnf.disable_ipv6)
addrconf_notify(NULL, NETDEV_DOWN, &info);
else
addrconf_notify(NULL, NETDEV_UP, &info);
}
static void addrconf_disable_change(struct net *net, __s32 newf)
{
struct net_device *dev;
struct inet6_dev *idev;
rcu_read_lock();
for_each_netdev_rcu(net, dev) {
idev = __in6_dev_get(dev);
if (idev) {
int changed = (!idev->cnf.disable_ipv6) ^ (!newf);
idev->cnf.disable_ipv6 = newf;
if (changed)
dev_disable_change(idev);
}
}
rcu_read_unlock();
}
static int addrconf_disable_ipv6(struct ctl_table *table, int *p, int newf)
{
struct net *net;
int old;
if (!rtnl_trylock())
return restart_syscall();
net = (struct net *)table->extra2;
old = *p;
*p = newf;
if (p == &net->ipv6.devconf_dflt->disable_ipv6) {
rtnl_unlock();
return 0;
}
if (p == &net->ipv6.devconf_all->disable_ipv6) {
net->ipv6.devconf_dflt->disable_ipv6 = newf;
addrconf_disable_change(net, newf);
} else if ((!newf) ^ (!old))
dev_disable_change((struct inet6_dev *)table->extra1);
rtnl_unlock();
return 0;
}
static
int addrconf_sysctl_disable(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int val = *valp;
loff_t pos = *ppos;
struct ctl_table lctl;
int ret;
/*
* ctl->data points to idev->cnf.disable_ipv6, we should
* not modify it until we get the rtnl lock.
*/
lctl = *ctl;
lctl.data = &val;
ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
if (write)
ret = addrconf_disable_ipv6(ctl, valp, val);
if (ret)
*ppos = pos;
return ret;
}
static
int addrconf_sysctl_proxy_ndp(struct ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int ret;
int old, new;
old = *valp;
ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
new = *valp;
if (write && old != new) {
struct net *net = ctl->extra2;
if (!rtnl_trylock())
return restart_syscall();
if (valp == &net->ipv6.devconf_dflt->proxy_ndp)
inet6_netconf_notify_devconf(net, NETCONFA_PROXY_NEIGH,
NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt);
else if (valp == &net->ipv6.devconf_all->proxy_ndp)
inet6_netconf_notify_devconf(net, NETCONFA_PROXY_NEIGH,
NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all);
else {
struct inet6_dev *idev = ctl->extra1;
inet6_netconf_notify_devconf(net, NETCONFA_PROXY_NEIGH,
idev->dev->ifindex,
&idev->cnf);
}
rtnl_unlock();
}
return ret;
}
static struct addrconf_sysctl_table
{
struct ctl_table_header *sysctl_header;
struct ctl_table addrconf_vars[DEVCONF_MAX+1];
} addrconf_sysctl __read_mostly = {
.sysctl_header = NULL,
.addrconf_vars = {
{
.procname = "forwarding",
.data = &ipv6_devconf.forwarding,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_forward,
},
{
.procname = "hop_limit",
.data = &ipv6_devconf.hop_limit,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mtu",
.data = &ipv6_devconf.mtu6,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra",
.data = &ipv6_devconf.accept_ra,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_redirects",
.data = &ipv6_devconf.accept_redirects,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "autoconf",
.data = &ipv6_devconf.autoconf,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "dad_transmits",
.data = &ipv6_devconf.dad_transmits,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "router_solicitations",
.data = &ipv6_devconf.rtr_solicits,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "router_solicitation_interval",
.data = &ipv6_devconf.rtr_solicit_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "router_solicitation_delay",
.data = &ipv6_devconf.rtr_solicit_delay,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "force_mld_version",
.data = &ipv6_devconf.force_mld_version,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mldv1_unsolicited_report_interval",
.data =
&ipv6_devconf.mldv1_unsolicited_report_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{
.procname = "mldv2_unsolicited_report_interval",
.data =
&ipv6_devconf.mldv2_unsolicited_report_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{
.procname = "use_tempaddr",
.data = &ipv6_devconf.use_tempaddr,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "temp_valid_lft",
.data = &ipv6_devconf.temp_valid_lft,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "temp_prefered_lft",
.data = &ipv6_devconf.temp_prefered_lft,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "regen_max_retry",
.data = &ipv6_devconf.regen_max_retry,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_desync_factor",
.data = &ipv6_devconf.max_desync_factor,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_addresses",
.data = &ipv6_devconf.max_addresses,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_defrtr",
.data = &ipv6_devconf.accept_ra_defrtr,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_pinfo",
.data = &ipv6_devconf.accept_ra_pinfo,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#ifdef CONFIG_IPV6_ROUTER_PREF
{
.procname = "accept_ra_rtr_pref",
.data = &ipv6_devconf.accept_ra_rtr_pref,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "router_probe_interval",
.data = &ipv6_devconf.rtr_probe_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
#ifdef CONFIG_IPV6_ROUTE_INFO
{
.procname = "accept_ra_rt_info_max_plen",
.data = &ipv6_devconf.accept_ra_rt_info_max_plen,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#endif
#endif
{
.procname = "proxy_ndp",
.data = &ipv6_devconf.proxy_ndp,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_proxy_ndp,
},
{
.procname = "accept_source_route",
.data = &ipv6_devconf.accept_source_route,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
{
.procname = "optimistic_dad",
.data = &ipv6_devconf.optimistic_dad,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "use_optimistic",
.data = &ipv6_devconf.use_optimistic,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#endif
#ifdef CONFIG_IPV6_MROUTE
{
.procname = "mc_forwarding",
.data = &ipv6_devconf.mc_forwarding,
.maxlen = sizeof(int),
.mode = 0444,
.proc_handler = proc_dointvec,
},
#endif
{
.procname = "disable_ipv6",
.data = &ipv6_devconf.disable_ipv6,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_disable,
},
{
.procname = "accept_dad",
.data = &ipv6_devconf.accept_dad,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "force_tllao",
.data = &ipv6_devconf.force_tllao,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{
.procname = "ndisc_notify",
.data = &ipv6_devconf.ndisc_notify,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{
.procname = "suppress_frag_ndisc",
.data = &ipv6_devconf.suppress_frag_ndisc,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{
.procname = "accept_ra_from_local",
.data = &ipv6_devconf.accept_ra_from_local,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_mtu",
.data = &ipv6_devconf.accept_ra_mtu,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
/* sentinel */
}
},
};
static int __addrconf_sysctl_register(struct net *net, char *dev_name,
struct inet6_dev *idev, struct ipv6_devconf *p)
{
int i;
struct addrconf_sysctl_table *t;
char path[sizeof("net/ipv6/conf/") + IFNAMSIZ];
t = kmemdup(&addrconf_sysctl, sizeof(*t), GFP_KERNEL);
if (t == NULL)
goto out;
for (i = 0; t->addrconf_vars[i].data; i++) {
t->addrconf_vars[i].data += (char *)p - (char *)&ipv6_devconf;
t->addrconf_vars[i].extra1 = idev; /* embedded; no ref */
t->addrconf_vars[i].extra2 = net;
}
snprintf(path, sizeof(path), "net/ipv6/conf/%s", dev_name);
t->sysctl_header = register_net_sysctl(net, path, t->addrconf_vars);
if (t->sysctl_header == NULL)
goto free;
p->sysctl = t;
return 0;
free:
kfree(t);
out:
return -ENOBUFS;
}
static void __addrconf_sysctl_unregister(struct ipv6_devconf *p)
{
struct addrconf_sysctl_table *t;
if (p->sysctl == NULL)
return;
t = p->sysctl;
p->sysctl = NULL;
unregister_net_sysctl_table(t->sysctl_header);
kfree(t);
}
static int addrconf_sysctl_register(struct inet6_dev *idev)
{
int err;
if (!sysctl_dev_name_is_allowed(idev->dev->name))
return -EINVAL;
err = neigh_sysctl_register(idev->dev, idev->nd_parms,
&ndisc_ifinfo_sysctl_change);
if (err)
return err;
err = __addrconf_sysctl_register(dev_net(idev->dev), idev->dev->name,
idev, &idev->cnf);
if (err)
neigh_sysctl_unregister(idev->nd_parms);
return err;
}
static void addrconf_sysctl_unregister(struct inet6_dev *idev)
{
__addrconf_sysctl_unregister(&idev->cnf);
neigh_sysctl_unregister(idev->nd_parms);
}
#endif
static int __net_init addrconf_init_net(struct net *net)
{
int err = -ENOMEM;
struct ipv6_devconf *all, *dflt;
all = kmemdup(&ipv6_devconf, sizeof(ipv6_devconf), GFP_KERNEL);
if (all == NULL)
goto err_alloc_all;
dflt = kmemdup(&ipv6_devconf_dflt, sizeof(ipv6_devconf_dflt), GFP_KERNEL);
if (dflt == NULL)
goto err_alloc_dflt;
/* these will be inherited by all namespaces */
dflt->autoconf = ipv6_defaults.autoconf;
dflt->disable_ipv6 = ipv6_defaults.disable_ipv6;
net->ipv6.devconf_all = all;
net->ipv6.devconf_dflt = dflt;
#ifdef CONFIG_SYSCTL
err = __addrconf_sysctl_register(net, "all", NULL, all);
if (err < 0)
goto err_reg_all;
err = __addrconf_sysctl_register(net, "default", NULL, dflt);
if (err < 0)
goto err_reg_dflt;
#endif
return 0;
#ifdef CONFIG_SYSCTL
err_reg_dflt:
__addrconf_sysctl_unregister(all);
err_reg_all:
kfree(dflt);
#endif
err_alloc_dflt:
kfree(all);
err_alloc_all:
return err;
}
static void __net_exit addrconf_exit_net(struct net *net)
{
#ifdef CONFIG_SYSCTL
__addrconf_sysctl_unregister(net->ipv6.devconf_dflt);
__addrconf_sysctl_unregister(net->ipv6.devconf_all);
#endif
kfree(net->ipv6.devconf_dflt);
kfree(net->ipv6.devconf_all);
}
static struct pernet_operations addrconf_ops = {
.init = addrconf_init_net,
.exit = addrconf_exit_net,
};
static struct rtnl_af_ops inet6_ops __read_mostly = {
.family = AF_INET6,
.fill_link_af = inet6_fill_link_af,
.get_link_af_size = inet6_get_link_af_size,
.validate_link_af = inet6_validate_link_af,
.set_link_af = inet6_set_link_af,
};
/*
* Init / cleanup code
*/
int __init addrconf_init(void)
{
struct inet6_dev *idev;
int i, err;
err = ipv6_addr_label_init();
if (err < 0) {
pr_crit("%s: cannot initialize default policy table: %d\n",
__func__, err);
goto out;
}
err = register_pernet_subsys(&addrconf_ops);
if (err < 0)
goto out_addrlabel;
addrconf_wq = create_workqueue("ipv6_addrconf");
if (!addrconf_wq) {
err = -ENOMEM;
goto out_nowq;
}
/* The addrconf netdev notifier requires that loopback_dev
* has it's ipv6 private information allocated and setup
* before it can bring up and give link-local addresses
* to other devices which are up.
*
* Unfortunately, loopback_dev is not necessarily the first
* entry in the global dev_base list of net devices. In fact,
* it is likely to be the very last entry on that list.
* So this causes the notifier registry below to try and
* give link-local addresses to all devices besides loopback_dev
* first, then loopback_dev, which cases all the non-loopback_dev
* devices to fail to get a link-local address.
*
* So, as a temporary fix, allocate the ipv6 structure for
* loopback_dev first by hand.
* Longer term, all of the dependencies ipv6 has upon the loopback
* device and it being up should be removed.
*/
rtnl_lock();
idev = ipv6_add_dev(init_net.loopback_dev);
rtnl_unlock();
if (IS_ERR(idev)) {
err = PTR_ERR(idev);
goto errlo;
}
for (i = 0; i < IN6_ADDR_HSIZE; i++)
INIT_HLIST_HEAD(&inet6_addr_lst[i]);
register_netdevice_notifier(&ipv6_dev_notf);
addrconf_verify();
rtnl_af_register(&inet6_ops);
err = __rtnl_register(PF_INET6, RTM_GETLINK, NULL, inet6_dump_ifinfo,
NULL);
if (err < 0)
goto errout;
/* Only the first call to __rtnl_register can fail */
__rtnl_register(PF_INET6, RTM_NEWADDR, inet6_rtm_newaddr, NULL, NULL);
__rtnl_register(PF_INET6, RTM_DELADDR, inet6_rtm_deladdr, NULL, NULL);
__rtnl_register(PF_INET6, RTM_GETADDR, inet6_rtm_getaddr,
inet6_dump_ifaddr, NULL);
__rtnl_register(PF_INET6, RTM_GETMULTICAST, NULL,
inet6_dump_ifmcaddr, NULL);
__rtnl_register(PF_INET6, RTM_GETANYCAST, NULL,
inet6_dump_ifacaddr, NULL);
__rtnl_register(PF_INET6, RTM_GETNETCONF, inet6_netconf_get_devconf,
inet6_netconf_dump_devconf, NULL);
ipv6_addr_label_rtnl_register();
return 0;
errout:
rtnl_af_unregister(&inet6_ops);
unregister_netdevice_notifier(&ipv6_dev_notf);
errlo:
destroy_workqueue(addrconf_wq);
out_nowq:
unregister_pernet_subsys(&addrconf_ops);
out_addrlabel:
ipv6_addr_label_cleanup();
out:
return err;
}
void addrconf_cleanup(void)
{
struct net_device *dev;
int i;
unregister_netdevice_notifier(&ipv6_dev_notf);
unregister_pernet_subsys(&addrconf_ops);
ipv6_addr_label_cleanup();
rtnl_lock();
__rtnl_af_unregister(&inet6_ops);
/* clean dev list */
for_each_netdev(&init_net, dev) {
if (__in6_dev_get(dev) == NULL)
continue;
addrconf_ifdown(dev, 1);
}
addrconf_ifdown(init_net.loopback_dev, 2);
/*
* Check hash table.
*/
spin_lock_bh(&addrconf_hash_lock);
for (i = 0; i < IN6_ADDR_HSIZE; i++)
WARN_ON(!hlist_empty(&inet6_addr_lst[i]));
spin_unlock_bh(&addrconf_hash_lock);
cancel_delayed_work(&addr_chk_work);
rtnl_unlock();
destroy_workqueue(addrconf_wq);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1776_0 |
crossvul-cpp_data_bad_397_0 | #include "cache.h"
#include "object.h"
#include "blob.h"
#include "tree.h"
#include "tree-walk.h"
#include "commit.h"
#include "tag.h"
#include "fsck.h"
#include "refs.h"
#include "utf8.h"
#include "sha1-array.h"
#include "decorate.h"
#include "oidset.h"
#include "packfile.h"
#include "submodule-config.h"
#include "config.h"
static struct oidset gitmodules_found = OIDSET_INIT;
static struct oidset gitmodules_done = OIDSET_INIT;
#define FSCK_FATAL -1
#define FSCK_INFO -2
#define FOREACH_MSG_ID(FUNC) \
/* fatal errors */ \
FUNC(NUL_IN_HEADER, FATAL) \
FUNC(UNTERMINATED_HEADER, FATAL) \
/* errors */ \
FUNC(BAD_DATE, ERROR) \
FUNC(BAD_DATE_OVERFLOW, ERROR) \
FUNC(BAD_EMAIL, ERROR) \
FUNC(BAD_NAME, ERROR) \
FUNC(BAD_OBJECT_SHA1, ERROR) \
FUNC(BAD_PARENT_SHA1, ERROR) \
FUNC(BAD_TAG_OBJECT, ERROR) \
FUNC(BAD_TIMEZONE, ERROR) \
FUNC(BAD_TREE, ERROR) \
FUNC(BAD_TREE_SHA1, ERROR) \
FUNC(BAD_TYPE, ERROR) \
FUNC(DUPLICATE_ENTRIES, ERROR) \
FUNC(MISSING_AUTHOR, ERROR) \
FUNC(MISSING_COMMITTER, ERROR) \
FUNC(MISSING_EMAIL, ERROR) \
FUNC(MISSING_GRAFT, ERROR) \
FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \
FUNC(MISSING_OBJECT, ERROR) \
FUNC(MISSING_PARENT, ERROR) \
FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \
FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \
FUNC(MISSING_TAG, ERROR) \
FUNC(MISSING_TAG_ENTRY, ERROR) \
FUNC(MISSING_TAG_OBJECT, ERROR) \
FUNC(MISSING_TREE, ERROR) \
FUNC(MISSING_TREE_OBJECT, ERROR) \
FUNC(MISSING_TYPE, ERROR) \
FUNC(MISSING_TYPE_ENTRY, ERROR) \
FUNC(MULTIPLE_AUTHORS, ERROR) \
FUNC(TAG_OBJECT_NOT_TAG, ERROR) \
FUNC(TREE_NOT_SORTED, ERROR) \
FUNC(UNKNOWN_TYPE, ERROR) \
FUNC(ZERO_PADDED_DATE, ERROR) \
FUNC(GITMODULES_MISSING, ERROR) \
FUNC(GITMODULES_BLOB, ERROR) \
FUNC(GITMODULES_PARSE, ERROR) \
FUNC(GITMODULES_NAME, ERROR) \
FUNC(GITMODULES_SYMLINK, ERROR) \
/* warnings */ \
FUNC(BAD_FILEMODE, WARN) \
FUNC(EMPTY_NAME, WARN) \
FUNC(FULL_PATHNAME, WARN) \
FUNC(HAS_DOT, WARN) \
FUNC(HAS_DOTDOT, WARN) \
FUNC(HAS_DOTGIT, WARN) \
FUNC(NULL_SHA1, WARN) \
FUNC(ZERO_PADDED_FILEMODE, WARN) \
FUNC(NUL_IN_COMMIT, WARN) \
/* infos (reported as warnings, but ignored by default) */ \
FUNC(BAD_TAG_NAME, INFO) \
FUNC(MISSING_TAGGER_ENTRY, INFO)
#define MSG_ID(id, msg_type) FSCK_MSG_##id,
enum fsck_msg_id {
FOREACH_MSG_ID(MSG_ID)
FSCK_MSG_MAX
};
#undef MSG_ID
#define STR(x) #x
#define MSG_ID(id, msg_type) { STR(id), NULL, FSCK_##msg_type },
static struct {
const char *id_string;
const char *downcased;
int msg_type;
} msg_id_info[FSCK_MSG_MAX + 1] = {
FOREACH_MSG_ID(MSG_ID)
{ NULL, NULL, -1 }
};
#undef MSG_ID
static int parse_msg_id(const char *text)
{
int i;
if (!msg_id_info[0].downcased) {
/* convert id_string to lower case, without underscores. */
for (i = 0; i < FSCK_MSG_MAX; i++) {
const char *p = msg_id_info[i].id_string;
int len = strlen(p);
char *q = xmalloc(len);
msg_id_info[i].downcased = q;
while (*p)
if (*p == '_')
p++;
else
*(q)++ = tolower(*(p)++);
*q = '\0';
}
}
for (i = 0; i < FSCK_MSG_MAX; i++)
if (!strcmp(text, msg_id_info[i].downcased))
return i;
return -1;
}
static int fsck_msg_type(enum fsck_msg_id msg_id,
struct fsck_options *options)
{
int msg_type;
assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX);
if (options->msg_type)
msg_type = options->msg_type[msg_id];
else {
msg_type = msg_id_info[msg_id].msg_type;
if (options->strict && msg_type == FSCK_WARN)
msg_type = FSCK_ERROR;
}
return msg_type;
}
static void init_skiplist(struct fsck_options *options, const char *path)
{
static struct oid_array skiplist = OID_ARRAY_INIT;
int sorted, fd;
char buffer[GIT_MAX_HEXSZ + 1];
struct object_id oid;
if (options->skiplist)
sorted = options->skiplist->sorted;
else {
sorted = 1;
options->skiplist = &skiplist;
}
fd = open(path, O_RDONLY);
if (fd < 0)
die("Could not open skip list: %s", path);
for (;;) {
const char *p;
int result = read_in_full(fd, buffer, sizeof(buffer));
if (result < 0)
die_errno("Could not read '%s'", path);
if (!result)
break;
if (parse_oid_hex(buffer, &oid, &p) || *p != '\n')
die("Invalid SHA-1: %s", buffer);
oid_array_append(&skiplist, &oid);
if (sorted && skiplist.nr > 1 &&
oidcmp(&skiplist.oid[skiplist.nr - 2],
&oid) > 0)
sorted = 0;
}
close(fd);
if (sorted)
skiplist.sorted = 1;
}
static int parse_msg_type(const char *str)
{
if (!strcmp(str, "error"))
return FSCK_ERROR;
else if (!strcmp(str, "warn"))
return FSCK_WARN;
else if (!strcmp(str, "ignore"))
return FSCK_IGNORE;
else
die("Unknown fsck message type: '%s'", str);
}
int is_valid_msg_type(const char *msg_id, const char *msg_type)
{
if (parse_msg_id(msg_id) < 0)
return 0;
parse_msg_type(msg_type);
return 1;
}
void fsck_set_msg_type(struct fsck_options *options,
const char *msg_id, const char *msg_type)
{
int id = parse_msg_id(msg_id), type;
if (id < 0)
die("Unhandled message id: %s", msg_id);
type = parse_msg_type(msg_type);
if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL)
die("Cannot demote %s to %s", msg_id, msg_type);
if (!options->msg_type) {
int i;
int *msg_type;
ALLOC_ARRAY(msg_type, FSCK_MSG_MAX);
for (i = 0; i < FSCK_MSG_MAX; i++)
msg_type[i] = fsck_msg_type(i, options);
options->msg_type = msg_type;
}
options->msg_type[id] = type;
}
void fsck_set_msg_types(struct fsck_options *options, const char *values)
{
char *buf = xstrdup(values), *to_free = buf;
int done = 0;
while (!done) {
int len = strcspn(buf, " ,|"), equal;
done = !buf[len];
if (!len) {
buf++;
continue;
}
buf[len] = '\0';
for (equal = 0;
equal < len && buf[equal] != '=' && buf[equal] != ':';
equal++)
buf[equal] = tolower(buf[equal]);
buf[equal] = '\0';
if (!strcmp(buf, "skiplist")) {
if (equal == len)
die("skiplist requires a path");
init_skiplist(options, buf + equal + 1);
buf += len + 1;
continue;
}
if (equal == len)
die("Missing '=': '%s'", buf);
fsck_set_msg_type(options, buf, buf + equal + 1);
buf += len + 1;
}
free(to_free);
}
static void append_msg_id(struct strbuf *sb, const char *msg_id)
{
for (;;) {
char c = *(msg_id)++;
if (!c)
break;
if (c != '_')
strbuf_addch(sb, tolower(c));
else {
assert(*msg_id);
strbuf_addch(sb, *(msg_id)++);
}
}
strbuf_addstr(sb, ": ");
}
__attribute__((format (printf, 4, 5)))
static int report(struct fsck_options *options, struct object *object,
enum fsck_msg_id id, const char *fmt, ...)
{
va_list ap;
struct strbuf sb = STRBUF_INIT;
int msg_type = fsck_msg_type(id, options), result;
if (msg_type == FSCK_IGNORE)
return 0;
if (options->skiplist && object &&
oid_array_lookup(options->skiplist, &object->oid) >= 0)
return 0;
if (msg_type == FSCK_FATAL)
msg_type = FSCK_ERROR;
else if (msg_type == FSCK_INFO)
msg_type = FSCK_WARN;
append_msg_id(&sb, msg_id_info[id].id_string);
va_start(ap, fmt);
strbuf_vaddf(&sb, fmt, ap);
result = options->error_func(options, object, msg_type, sb.buf);
strbuf_release(&sb);
va_end(ap);
return result;
}
static char *get_object_name(struct fsck_options *options, struct object *obj)
{
if (!options->object_names)
return NULL;
return lookup_decoration(options->object_names, obj);
}
static void put_object_name(struct fsck_options *options, struct object *obj,
const char *fmt, ...)
{
va_list ap;
struct strbuf buf = STRBUF_INIT;
char *existing;
if (!options->object_names)
return;
existing = lookup_decoration(options->object_names, obj);
if (existing)
return;
va_start(ap, fmt);
strbuf_vaddf(&buf, fmt, ap);
add_decoration(options->object_names, obj, strbuf_detach(&buf, NULL));
va_end(ap);
}
static const char *describe_object(struct fsck_options *o, struct object *obj)
{
static struct strbuf buf = STRBUF_INIT;
char *name;
strbuf_reset(&buf);
strbuf_addstr(&buf, oid_to_hex(&obj->oid));
if (o->object_names && (name = lookup_decoration(o->object_names, obj)))
strbuf_addf(&buf, " (%s)", name);
return buf.buf;
}
static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options)
{
struct tree_desc desc;
struct name_entry entry;
int res = 0;
const char *name;
if (parse_tree(tree))
return -1;
name = get_object_name(options, &tree->object);
if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
return -1;
while (tree_entry_gently(&desc, &entry)) {
struct object *obj;
int result;
if (S_ISGITLINK(entry.mode))
continue;
if (S_ISDIR(entry.mode)) {
obj = (struct object *)lookup_tree(entry.oid);
if (name && obj)
put_object_name(options, obj, "%s%s/", name,
entry.path);
result = options->walk(obj, OBJ_TREE, data, options);
}
else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) {
obj = (struct object *)lookup_blob(entry.oid);
if (name && obj)
put_object_name(options, obj, "%s%s", name,
entry.path);
result = options->walk(obj, OBJ_BLOB, data, options);
}
else {
result = error("in tree %s: entry %s has bad mode %.6o",
describe_object(options, &tree->object), entry.path, entry.mode);
}
if (result < 0)
return result;
if (!res)
res = result;
}
return res;
}
static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options)
{
int counter = 0, generation = 0, name_prefix_len = 0;
struct commit_list *parents;
int res;
int result;
const char *name;
if (parse_commit(commit))
return -1;
name = get_object_name(options, &commit->object);
if (name)
put_object_name(options, &commit->tree->object, "%s:", name);
result = options->walk((struct object *)commit->tree, OBJ_TREE, data, options);
if (result < 0)
return result;
res = result;
parents = commit->parents;
if (name && parents) {
int len = strlen(name), power;
if (len && name[len - 1] == '^') {
generation = 1;
name_prefix_len = len - 1;
}
else { /* parse ~<generation> suffix */
for (generation = 0, power = 1;
len && isdigit(name[len - 1]);
power *= 10)
generation += power * (name[--len] - '0');
if (power > 1 && len && name[len - 1] == '~')
name_prefix_len = len - 1;
}
}
while (parents) {
if (name) {
struct object *obj = &parents->item->object;
if (++counter > 1)
put_object_name(options, obj, "%s^%d",
name, counter);
else if (generation > 0)
put_object_name(options, obj, "%.*s~%d",
name_prefix_len, name, generation + 1);
else
put_object_name(options, obj, "%s^", name);
}
result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options);
if (result < 0)
return result;
if (!res)
res = result;
parents = parents->next;
}
return res;
}
static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options)
{
char *name = get_object_name(options, &tag->object);
if (parse_tag(tag))
return -1;
if (name)
put_object_name(options, tag->tagged, "%s", name);
return options->walk(tag->tagged, OBJ_ANY, data, options);
}
int fsck_walk(struct object *obj, void *data, struct fsck_options *options)
{
if (!obj)
return -1;
if (obj->type == OBJ_NONE)
parse_object(&obj->oid);
switch (obj->type) {
case OBJ_BLOB:
return 0;
case OBJ_TREE:
return fsck_walk_tree((struct tree *)obj, data, options);
case OBJ_COMMIT:
return fsck_walk_commit((struct commit *)obj, data, options);
case OBJ_TAG:
return fsck_walk_tag((struct tag *)obj, data, options);
default:
error("Unknown object type for %s", describe_object(options, obj));
return -1;
}
}
/*
* The entries in a tree are ordered in the _path_ order,
* which means that a directory entry is ordered by adding
* a slash to the end of it.
*
* So a directory called "a" is ordered _after_ a file
* called "a.c", because "a/" sorts after "a.c".
*/
#define TREE_UNORDERED (-1)
#define TREE_HAS_DUPS (-2)
static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2)
{
int len1 = strlen(name1);
int len2 = strlen(name2);
int len = len1 < len2 ? len1 : len2;
unsigned char c1, c2;
int cmp;
cmp = memcmp(name1, name2, len);
if (cmp < 0)
return 0;
if (cmp > 0)
return TREE_UNORDERED;
/*
* Ok, the first <len> characters are the same.
* Now we need to order the next one, but turn
* a '\0' into a '/' for a directory entry.
*/
c1 = name1[len];
c2 = name2[len];
if (!c1 && !c2)
/*
* git-write-tree used to write out a nonsense tree that has
* entries with the same name, one blob and one tree. Make
* sure we do not have duplicate entries.
*/
return TREE_HAS_DUPS;
if (!c1 && S_ISDIR(mode1))
c1 = '/';
if (!c2 && S_ISDIR(mode2))
c2 = '/';
return c1 < c2 ? 0 : TREE_UNORDERED;
}
static int fsck_tree(struct tree *item, struct fsck_options *options)
{
int retval = 0;
int has_null_sha1 = 0;
int has_full_path = 0;
int has_empty_name = 0;
int has_dot = 0;
int has_dotdot = 0;
int has_dotgit = 0;
int has_zero_pad = 0;
int has_bad_modes = 0;
int has_dup_entries = 0;
int not_properly_sorted = 0;
struct tree_desc desc;
unsigned o_mode;
const char *o_name;
if (init_tree_desc_gently(&desc, item->buffer, item->size)) {
retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
return retval;
}
o_mode = 0;
o_name = NULL;
while (desc.size) {
unsigned mode;
const char *name;
const struct object_id *oid;
oid = tree_entry_extract(&desc, &name, &mode);
has_null_sha1 |= is_null_oid(oid);
has_full_path |= !!strchr(name, '/');
has_empty_name |= !*name;
has_dot |= !strcmp(name, ".");
has_dotdot |= !strcmp(name, "..");
has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name);
has_zero_pad |= *(char *)desc.buffer == '0';
if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) {
if (!S_ISLNK(mode))
oidset_insert(&gitmodules_found, oid);
else
retval += report(options, &item->object,
FSCK_MSG_GITMODULES_SYMLINK,
".gitmodules is a symbolic link");
}
if (update_tree_entry_gently(&desc)) {
retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
break;
}
switch (mode) {
/*
* Standard modes..
*/
case S_IFREG | 0755:
case S_IFREG | 0644:
case S_IFLNK:
case S_IFDIR:
case S_IFGITLINK:
break;
/*
* This is nonstandard, but we had a few of these
* early on when we honored the full set of mode
* bits..
*/
case S_IFREG | 0664:
if (!options->strict)
break;
/* fallthrough */
default:
has_bad_modes = 1;
}
if (o_name) {
switch (verify_ordered(o_mode, o_name, mode, name)) {
case TREE_UNORDERED:
not_properly_sorted = 1;
break;
case TREE_HAS_DUPS:
has_dup_entries = 1;
break;
default:
break;
}
}
o_mode = mode;
o_name = name;
}
if (has_null_sha1)
retval += report(options, &item->object, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1");
if (has_full_path)
retval += report(options, &item->object, FSCK_MSG_FULL_PATHNAME, "contains full pathnames");
if (has_empty_name)
retval += report(options, &item->object, FSCK_MSG_EMPTY_NAME, "contains empty pathname");
if (has_dot)
retval += report(options, &item->object, FSCK_MSG_HAS_DOT, "contains '.'");
if (has_dotdot)
retval += report(options, &item->object, FSCK_MSG_HAS_DOTDOT, "contains '..'");
if (has_dotgit)
retval += report(options, &item->object, FSCK_MSG_HAS_DOTGIT, "contains '.git'");
if (has_zero_pad)
retval += report(options, &item->object, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes");
if (has_bad_modes)
retval += report(options, &item->object, FSCK_MSG_BAD_FILEMODE, "contains bad file modes");
if (has_dup_entries)
retval += report(options, &item->object, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries");
if (not_properly_sorted)
retval += report(options, &item->object, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted");
return retval;
}
static int verify_headers(const void *data, unsigned long size,
struct object *obj, struct fsck_options *options)
{
const char *buffer = (const char *)data;
unsigned long i;
for (i = 0; i < size; i++) {
switch (buffer[i]) {
case '\0':
return report(options, obj,
FSCK_MSG_NUL_IN_HEADER,
"unterminated header: NUL at offset %ld", i);
case '\n':
if (i + 1 < size && buffer[i + 1] == '\n')
return 0;
}
}
/*
* We did not find double-LF that separates the header
* and the body. Not having a body is not a crime but
* we do want to see the terminating LF for the last header
* line.
*/
if (size && buffer[size - 1] == '\n')
return 0;
return report(options, obj,
FSCK_MSG_UNTERMINATED_HEADER, "unterminated header");
}
static int fsck_ident(const char **ident, struct object *obj, struct fsck_options *options)
{
const char *p = *ident;
char *end;
*ident = strchrnul(*ident, '\n');
if (**ident == '\n')
(*ident)++;
if (*p == '<')
return report(options, obj, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
p += strcspn(p, "<>\n");
if (*p == '>')
return report(options, obj, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name");
if (*p != '<')
return report(options, obj, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email");
if (p[-1] != ' ')
return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
p++;
p += strcspn(p, "<>\n");
if (*p != '>')
return report(options, obj, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email");
p++;
if (*p != ' ')
return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date");
p++;
if (*p == '0' && p[1] != ' ')
return report(options, obj, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date");
if (date_overflows(parse_timestamp(p, &end, 10)))
return report(options, obj, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow");
if ((end == p || *end != ' '))
return report(options, obj, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date");
p = end + 1;
if ((*p != '+' && *p != '-') ||
!isdigit(p[1]) ||
!isdigit(p[2]) ||
!isdigit(p[3]) ||
!isdigit(p[4]) ||
(p[5] != '\n'))
return report(options, obj, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone");
p += 6;
return 0;
}
static int fsck_commit_buffer(struct commit *commit, const char *buffer,
unsigned long size, struct fsck_options *options)
{
unsigned char tree_sha1[20], sha1[20];
struct commit_graft *graft;
unsigned parent_count, parent_line_count = 0, author_count;
int err;
const char *buffer_begin = buffer;
if (verify_headers(buffer, size, &commit->object, options))
return -1;
if (!skip_prefix(buffer, "tree ", &buffer))
return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line");
if (get_sha1_hex(buffer, tree_sha1) || buffer[40] != '\n') {
err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1");
if (err)
return err;
}
buffer += 41;
while (skip_prefix(buffer, "parent ", &buffer)) {
if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1");
if (err)
return err;
}
buffer += 41;
parent_line_count++;
}
graft = lookup_commit_graft(&commit->object.oid);
parent_count = commit_list_count(commit->parents);
if (graft) {
if (graft->nr_parent == -1 && !parent_count)
; /* shallow commit */
else if (graft->nr_parent != parent_count) {
err = report(options, &commit->object, FSCK_MSG_MISSING_GRAFT, "graft objects missing");
if (err)
return err;
}
} else {
if (parent_count != parent_line_count) {
err = report(options, &commit->object, FSCK_MSG_MISSING_PARENT, "parent objects missing");
if (err)
return err;
}
}
author_count = 0;
while (skip_prefix(buffer, "author ", &buffer)) {
author_count++;
err = fsck_ident(&buffer, &commit->object, options);
if (err)
return err;
}
if (author_count < 1)
err = report(options, &commit->object, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line");
else if (author_count > 1)
err = report(options, &commit->object, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines");
if (err)
return err;
if (!skip_prefix(buffer, "committer ", &buffer))
return report(options, &commit->object, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line");
err = fsck_ident(&buffer, &commit->object, options);
if (err)
return err;
if (!commit->tree) {
err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", sha1_to_hex(tree_sha1));
if (err)
return err;
}
if (memchr(buffer_begin, '\0', size)) {
err = report(options, &commit->object, FSCK_MSG_NUL_IN_COMMIT,
"NUL byte in the commit object body");
if (err)
return err;
}
return 0;
}
static int fsck_commit(struct commit *commit, const char *data,
unsigned long size, struct fsck_options *options)
{
const char *buffer = data ? data : get_commit_buffer(commit, &size);
int ret = fsck_commit_buffer(commit, buffer, size, options);
if (!data)
unuse_commit_buffer(commit, buffer);
return ret;
}
static int fsck_tag_buffer(struct tag *tag, const char *data,
unsigned long size, struct fsck_options *options)
{
unsigned char sha1[20];
int ret = 0;
const char *buffer;
char *to_free = NULL, *eol;
struct strbuf sb = STRBUF_INIT;
if (data)
buffer = data;
else {
enum object_type type;
buffer = to_free =
read_sha1_file(tag->object.oid.hash, &type, &size);
if (!buffer)
return report(options, &tag->object,
FSCK_MSG_MISSING_TAG_OBJECT,
"cannot read tag object");
if (type != OBJ_TAG) {
ret = report(options, &tag->object,
FSCK_MSG_TAG_OBJECT_NOT_TAG,
"expected tag got %s",
type_name(type));
goto done;
}
}
ret = verify_headers(buffer, size, &tag->object, options);
if (ret)
goto done;
if (!skip_prefix(buffer, "object ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line");
goto done;
}
if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1");
if (ret)
goto done;
}
buffer += 41;
if (!skip_prefix(buffer, "type ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line");
goto done;
}
eol = strchr(buffer, '\n');
if (!eol) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line");
goto done;
}
if (type_from_string_gently(buffer, eol - buffer, 1) < 0)
ret = report(options, &tag->object, FSCK_MSG_BAD_TYPE, "invalid 'type' value");
if (ret)
goto done;
buffer = eol + 1;
if (!skip_prefix(buffer, "tag ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line");
goto done;
}
eol = strchr(buffer, '\n');
if (!eol) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line");
goto done;
}
strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer);
if (check_refname_format(sb.buf, 0)) {
ret = report(options, &tag->object, FSCK_MSG_BAD_TAG_NAME,
"invalid 'tag' name: %.*s",
(int)(eol - buffer), buffer);
if (ret)
goto done;
}
buffer = eol + 1;
if (!skip_prefix(buffer, "tagger ", &buffer)) {
/* early tags do not contain 'tagger' lines; warn only */
ret = report(options, &tag->object, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line");
if (ret)
goto done;
}
else
ret = fsck_ident(&buffer, &tag->object, options);
done:
strbuf_release(&sb);
free(to_free);
return ret;
}
static int fsck_tag(struct tag *tag, const char *data,
unsigned long size, struct fsck_options *options)
{
struct object *tagged = tag->tagged;
if (!tagged)
return report(options, &tag->object, FSCK_MSG_BAD_TAG_OBJECT, "could not load tagged object");
return fsck_tag_buffer(tag, data, size, options);
}
struct fsck_gitmodules_data {
struct object *obj;
struct fsck_options *options;
int ret;
};
static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
{
struct fsck_gitmodules_data *data = vdata;
const char *subsection, *key;
int subsection_len;
char *name;
if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
!subsection)
return 0;
name = xmemdupz(subsection, subsection_len);
if (check_submodule_name(name) < 0)
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_NAME,
"disallowed submodule name: %s",
name);
free(name);
return 0;
}
static int fsck_blob(struct blob *blob, const char *buf,
unsigned long size, struct fsck_options *options)
{
struct fsck_gitmodules_data data;
if (!oidset_contains(&gitmodules_found, &blob->object.oid))
return 0;
oidset_insert(&gitmodules_done, &blob->object.oid);
if (!buf) {
/*
* A missing buffer here is a sign that the caller found the
* blob too gigantic to load into memory. Let's just consider
* that an error.
*/
return report(options, &blob->object,
FSCK_MSG_GITMODULES_PARSE,
".gitmodules too large to parse");
}
data.obj = &blob->object;
data.options = options;
data.ret = 0;
if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,
".gitmodules", buf, size, &data))
data.ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_PARSE,
"could not parse gitmodules blob");
return data.ret;
}
int fsck_object(struct object *obj, void *data, unsigned long size,
struct fsck_options *options)
{
if (!obj)
return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck");
if (obj->type == OBJ_BLOB)
return fsck_blob((struct blob *)obj, data, size, options);
if (obj->type == OBJ_TREE)
return fsck_tree((struct tree *) obj, options);
if (obj->type == OBJ_COMMIT)
return fsck_commit((struct commit *) obj, (const char *) data,
size, options);
if (obj->type == OBJ_TAG)
return fsck_tag((struct tag *) obj, (const char *) data,
size, options);
return report(options, obj, FSCK_MSG_UNKNOWN_TYPE, "unknown type '%d' (internal fsck error)",
obj->type);
}
int fsck_error_function(struct fsck_options *o,
struct object *obj, int msg_type, const char *message)
{
if (msg_type == FSCK_WARN) {
warning("object %s: %s", describe_object(o, obj), message);
return 0;
}
error("object %s: %s", describe_object(o, obj), message);
return 1;
}
int fsck_finish(struct fsck_options *options)
{
int ret = 0;
struct oidset_iter iter;
const struct object_id *oid;
oidset_iter_init(&gitmodules_found, &iter);
while ((oid = oidset_iter_next(&iter))) {
struct blob *blob;
enum object_type type;
unsigned long size;
char *buf;
if (oidset_contains(&gitmodules_done, oid))
continue;
blob = lookup_blob(oid);
if (!blob) {
ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_BLOB,
"non-blob found at .gitmodules");
continue;
}
buf = read_sha1_file(oid->hash, &type, &size);
if (!buf) {
if (is_promisor_object(&blob->object.oid))
continue;
ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_MISSING,
"unable to read .gitmodules blob");
continue;
}
if (type == OBJ_BLOB)
ret |= fsck_blob(blob, buf, size, options);
else
ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_BLOB,
"non-blob found at .gitmodules");
free(buf);
}
oidset_clear(&gitmodules_found);
oidset_clear(&gitmodules_done);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_397_0 |
crossvul-cpp_data_bad_396_0 | #include "cache.h"
#include "object.h"
#include "blob.h"
#include "tree.h"
#include "tree-walk.h"
#include "commit.h"
#include "tag.h"
#include "fsck.h"
#include "refs.h"
#include "utf8.h"
#include "sha1-array.h"
#include "decorate.h"
#include "oidset.h"
#include "packfile.h"
#include "submodule-config.h"
#include "config.h"
static struct oidset gitmodules_found = OIDSET_INIT;
static struct oidset gitmodules_done = OIDSET_INIT;
#define FSCK_FATAL -1
#define FSCK_INFO -2
#define FOREACH_MSG_ID(FUNC) \
/* fatal errors */ \
FUNC(NUL_IN_HEADER, FATAL) \
FUNC(UNTERMINATED_HEADER, FATAL) \
/* errors */ \
FUNC(BAD_DATE, ERROR) \
FUNC(BAD_DATE_OVERFLOW, ERROR) \
FUNC(BAD_EMAIL, ERROR) \
FUNC(BAD_NAME, ERROR) \
FUNC(BAD_OBJECT_SHA1, ERROR) \
FUNC(BAD_PARENT_SHA1, ERROR) \
FUNC(BAD_TAG_OBJECT, ERROR) \
FUNC(BAD_TIMEZONE, ERROR) \
FUNC(BAD_TREE, ERROR) \
FUNC(BAD_TREE_SHA1, ERROR) \
FUNC(BAD_TYPE, ERROR) \
FUNC(DUPLICATE_ENTRIES, ERROR) \
FUNC(MISSING_AUTHOR, ERROR) \
FUNC(MISSING_COMMITTER, ERROR) \
FUNC(MISSING_EMAIL, ERROR) \
FUNC(MISSING_GRAFT, ERROR) \
FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \
FUNC(MISSING_OBJECT, ERROR) \
FUNC(MISSING_PARENT, ERROR) \
FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \
FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \
FUNC(MISSING_TAG, ERROR) \
FUNC(MISSING_TAG_ENTRY, ERROR) \
FUNC(MISSING_TAG_OBJECT, ERROR) \
FUNC(MISSING_TREE, ERROR) \
FUNC(MISSING_TREE_OBJECT, ERROR) \
FUNC(MISSING_TYPE, ERROR) \
FUNC(MISSING_TYPE_ENTRY, ERROR) \
FUNC(MULTIPLE_AUTHORS, ERROR) \
FUNC(TAG_OBJECT_NOT_TAG, ERROR) \
FUNC(TREE_NOT_SORTED, ERROR) \
FUNC(UNKNOWN_TYPE, ERROR) \
FUNC(ZERO_PADDED_DATE, ERROR) \
FUNC(GITMODULES_MISSING, ERROR) \
FUNC(GITMODULES_BLOB, ERROR) \
FUNC(GITMODULES_PARSE, ERROR) \
FUNC(GITMODULES_NAME, ERROR) \
FUNC(GITMODULES_SYMLINK, ERROR) \
FUNC(GITMODULES_URL, ERROR) \
/* warnings */ \
FUNC(BAD_FILEMODE, WARN) \
FUNC(EMPTY_NAME, WARN) \
FUNC(FULL_PATHNAME, WARN) \
FUNC(HAS_DOT, WARN) \
FUNC(HAS_DOTDOT, WARN) \
FUNC(HAS_DOTGIT, WARN) \
FUNC(NULL_SHA1, WARN) \
FUNC(ZERO_PADDED_FILEMODE, WARN) \
FUNC(NUL_IN_COMMIT, WARN) \
/* infos (reported as warnings, but ignored by default) */ \
FUNC(BAD_TAG_NAME, INFO) \
FUNC(MISSING_TAGGER_ENTRY, INFO)
#define MSG_ID(id, msg_type) FSCK_MSG_##id,
enum fsck_msg_id {
FOREACH_MSG_ID(MSG_ID)
FSCK_MSG_MAX
};
#undef MSG_ID
#define STR(x) #x
#define MSG_ID(id, msg_type) { STR(id), NULL, FSCK_##msg_type },
static struct {
const char *id_string;
const char *downcased;
int msg_type;
} msg_id_info[FSCK_MSG_MAX + 1] = {
FOREACH_MSG_ID(MSG_ID)
{ NULL, NULL, -1 }
};
#undef MSG_ID
static int parse_msg_id(const char *text)
{
int i;
if (!msg_id_info[0].downcased) {
/* convert id_string to lower case, without underscores. */
for (i = 0; i < FSCK_MSG_MAX; i++) {
const char *p = msg_id_info[i].id_string;
int len = strlen(p);
char *q = xmalloc(len);
msg_id_info[i].downcased = q;
while (*p)
if (*p == '_')
p++;
else
*(q)++ = tolower(*(p)++);
*q = '\0';
}
}
for (i = 0; i < FSCK_MSG_MAX; i++)
if (!strcmp(text, msg_id_info[i].downcased))
return i;
return -1;
}
static int fsck_msg_type(enum fsck_msg_id msg_id,
struct fsck_options *options)
{
int msg_type;
assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX);
if (options->msg_type)
msg_type = options->msg_type[msg_id];
else {
msg_type = msg_id_info[msg_id].msg_type;
if (options->strict && msg_type == FSCK_WARN)
msg_type = FSCK_ERROR;
}
return msg_type;
}
static void init_skiplist(struct fsck_options *options, const char *path)
{
static struct oid_array skiplist = OID_ARRAY_INIT;
int sorted, fd;
char buffer[GIT_MAX_HEXSZ + 1];
struct object_id oid;
if (options->skiplist)
sorted = options->skiplist->sorted;
else {
sorted = 1;
options->skiplist = &skiplist;
}
fd = open(path, O_RDONLY);
if (fd < 0)
die("Could not open skip list: %s", path);
for (;;) {
const char *p;
int result = read_in_full(fd, buffer, sizeof(buffer));
if (result < 0)
die_errno("Could not read '%s'", path);
if (!result)
break;
if (parse_oid_hex(buffer, &oid, &p) || *p != '\n')
die("Invalid SHA-1: %s", buffer);
oid_array_append(&skiplist, &oid);
if (sorted && skiplist.nr > 1 &&
oidcmp(&skiplist.oid[skiplist.nr - 2],
&oid) > 0)
sorted = 0;
}
close(fd);
if (sorted)
skiplist.sorted = 1;
}
static int parse_msg_type(const char *str)
{
if (!strcmp(str, "error"))
return FSCK_ERROR;
else if (!strcmp(str, "warn"))
return FSCK_WARN;
else if (!strcmp(str, "ignore"))
return FSCK_IGNORE;
else
die("Unknown fsck message type: '%s'", str);
}
int is_valid_msg_type(const char *msg_id, const char *msg_type)
{
if (parse_msg_id(msg_id) < 0)
return 0;
parse_msg_type(msg_type);
return 1;
}
void fsck_set_msg_type(struct fsck_options *options,
const char *msg_id, const char *msg_type)
{
int id = parse_msg_id(msg_id), type;
if (id < 0)
die("Unhandled message id: %s", msg_id);
type = parse_msg_type(msg_type);
if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL)
die("Cannot demote %s to %s", msg_id, msg_type);
if (!options->msg_type) {
int i;
int *msg_type;
ALLOC_ARRAY(msg_type, FSCK_MSG_MAX);
for (i = 0; i < FSCK_MSG_MAX; i++)
msg_type[i] = fsck_msg_type(i, options);
options->msg_type = msg_type;
}
options->msg_type[id] = type;
}
void fsck_set_msg_types(struct fsck_options *options, const char *values)
{
char *buf = xstrdup(values), *to_free = buf;
int done = 0;
while (!done) {
int len = strcspn(buf, " ,|"), equal;
done = !buf[len];
if (!len) {
buf++;
continue;
}
buf[len] = '\0';
for (equal = 0;
equal < len && buf[equal] != '=' && buf[equal] != ':';
equal++)
buf[equal] = tolower(buf[equal]);
buf[equal] = '\0';
if (!strcmp(buf, "skiplist")) {
if (equal == len)
die("skiplist requires a path");
init_skiplist(options, buf + equal + 1);
buf += len + 1;
continue;
}
if (equal == len)
die("Missing '=': '%s'", buf);
fsck_set_msg_type(options, buf, buf + equal + 1);
buf += len + 1;
}
free(to_free);
}
static void append_msg_id(struct strbuf *sb, const char *msg_id)
{
for (;;) {
char c = *(msg_id)++;
if (!c)
break;
if (c != '_')
strbuf_addch(sb, tolower(c));
else {
assert(*msg_id);
strbuf_addch(sb, *(msg_id)++);
}
}
strbuf_addstr(sb, ": ");
}
__attribute__((format (printf, 4, 5)))
static int report(struct fsck_options *options, struct object *object,
enum fsck_msg_id id, const char *fmt, ...)
{
va_list ap;
struct strbuf sb = STRBUF_INIT;
int msg_type = fsck_msg_type(id, options), result;
if (msg_type == FSCK_IGNORE)
return 0;
if (options->skiplist && object &&
oid_array_lookup(options->skiplist, &object->oid) >= 0)
return 0;
if (msg_type == FSCK_FATAL)
msg_type = FSCK_ERROR;
else if (msg_type == FSCK_INFO)
msg_type = FSCK_WARN;
append_msg_id(&sb, msg_id_info[id].id_string);
va_start(ap, fmt);
strbuf_vaddf(&sb, fmt, ap);
result = options->error_func(options, object, msg_type, sb.buf);
strbuf_release(&sb);
va_end(ap);
return result;
}
static char *get_object_name(struct fsck_options *options, struct object *obj)
{
if (!options->object_names)
return NULL;
return lookup_decoration(options->object_names, obj);
}
static void put_object_name(struct fsck_options *options, struct object *obj,
const char *fmt, ...)
{
va_list ap;
struct strbuf buf = STRBUF_INIT;
char *existing;
if (!options->object_names)
return;
existing = lookup_decoration(options->object_names, obj);
if (existing)
return;
va_start(ap, fmt);
strbuf_vaddf(&buf, fmt, ap);
add_decoration(options->object_names, obj, strbuf_detach(&buf, NULL));
va_end(ap);
}
static const char *describe_object(struct fsck_options *o, struct object *obj)
{
static struct strbuf buf = STRBUF_INIT;
char *name;
strbuf_reset(&buf);
strbuf_addstr(&buf, oid_to_hex(&obj->oid));
if (o->object_names && (name = lookup_decoration(o->object_names, obj)))
strbuf_addf(&buf, " (%s)", name);
return buf.buf;
}
static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options)
{
struct tree_desc desc;
struct name_entry entry;
int res = 0;
const char *name;
if (parse_tree(tree))
return -1;
name = get_object_name(options, &tree->object);
if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
return -1;
while (tree_entry_gently(&desc, &entry)) {
struct object *obj;
int result;
if (S_ISGITLINK(entry.mode))
continue;
if (S_ISDIR(entry.mode)) {
obj = (struct object *)lookup_tree(entry.oid);
if (name && obj)
put_object_name(options, obj, "%s%s/", name,
entry.path);
result = options->walk(obj, OBJ_TREE, data, options);
}
else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) {
obj = (struct object *)lookup_blob(entry.oid);
if (name && obj)
put_object_name(options, obj, "%s%s", name,
entry.path);
result = options->walk(obj, OBJ_BLOB, data, options);
}
else {
result = error("in tree %s: entry %s has bad mode %.6o",
describe_object(options, &tree->object), entry.path, entry.mode);
}
if (result < 0)
return result;
if (!res)
res = result;
}
return res;
}
static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options)
{
int counter = 0, generation = 0, name_prefix_len = 0;
struct commit_list *parents;
int res;
int result;
const char *name;
if (parse_commit(commit))
return -1;
name = get_object_name(options, &commit->object);
if (name)
put_object_name(options, &commit->tree->object, "%s:", name);
result = options->walk((struct object *)commit->tree, OBJ_TREE, data, options);
if (result < 0)
return result;
res = result;
parents = commit->parents;
if (name && parents) {
int len = strlen(name), power;
if (len && name[len - 1] == '^') {
generation = 1;
name_prefix_len = len - 1;
}
else { /* parse ~<generation> suffix */
for (generation = 0, power = 1;
len && isdigit(name[len - 1]);
power *= 10)
generation += power * (name[--len] - '0');
if (power > 1 && len && name[len - 1] == '~')
name_prefix_len = len - 1;
}
}
while (parents) {
if (name) {
struct object *obj = &parents->item->object;
if (++counter > 1)
put_object_name(options, obj, "%s^%d",
name, counter);
else if (generation > 0)
put_object_name(options, obj, "%.*s~%d",
name_prefix_len, name, generation + 1);
else
put_object_name(options, obj, "%s^", name);
}
result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options);
if (result < 0)
return result;
if (!res)
res = result;
parents = parents->next;
}
return res;
}
static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options)
{
char *name = get_object_name(options, &tag->object);
if (parse_tag(tag))
return -1;
if (name)
put_object_name(options, tag->tagged, "%s", name);
return options->walk(tag->tagged, OBJ_ANY, data, options);
}
int fsck_walk(struct object *obj, void *data, struct fsck_options *options)
{
if (!obj)
return -1;
if (obj->type == OBJ_NONE)
parse_object(&obj->oid);
switch (obj->type) {
case OBJ_BLOB:
return 0;
case OBJ_TREE:
return fsck_walk_tree((struct tree *)obj, data, options);
case OBJ_COMMIT:
return fsck_walk_commit((struct commit *)obj, data, options);
case OBJ_TAG:
return fsck_walk_tag((struct tag *)obj, data, options);
default:
error("Unknown object type for %s", describe_object(options, obj));
return -1;
}
}
/*
* The entries in a tree are ordered in the _path_ order,
* which means that a directory entry is ordered by adding
* a slash to the end of it.
*
* So a directory called "a" is ordered _after_ a file
* called "a.c", because "a/" sorts after "a.c".
*/
#define TREE_UNORDERED (-1)
#define TREE_HAS_DUPS (-2)
static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2)
{
int len1 = strlen(name1);
int len2 = strlen(name2);
int len = len1 < len2 ? len1 : len2;
unsigned char c1, c2;
int cmp;
cmp = memcmp(name1, name2, len);
if (cmp < 0)
return 0;
if (cmp > 0)
return TREE_UNORDERED;
/*
* Ok, the first <len> characters are the same.
* Now we need to order the next one, but turn
* a '\0' into a '/' for a directory entry.
*/
c1 = name1[len];
c2 = name2[len];
if (!c1 && !c2)
/*
* git-write-tree used to write out a nonsense tree that has
* entries with the same name, one blob and one tree. Make
* sure we do not have duplicate entries.
*/
return TREE_HAS_DUPS;
if (!c1 && S_ISDIR(mode1))
c1 = '/';
if (!c2 && S_ISDIR(mode2))
c2 = '/';
return c1 < c2 ? 0 : TREE_UNORDERED;
}
static int fsck_tree(struct tree *item, struct fsck_options *options)
{
int retval = 0;
int has_null_sha1 = 0;
int has_full_path = 0;
int has_empty_name = 0;
int has_dot = 0;
int has_dotdot = 0;
int has_dotgit = 0;
int has_zero_pad = 0;
int has_bad_modes = 0;
int has_dup_entries = 0;
int not_properly_sorted = 0;
struct tree_desc desc;
unsigned o_mode;
const char *o_name;
if (init_tree_desc_gently(&desc, item->buffer, item->size)) {
retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
return retval;
}
o_mode = 0;
o_name = NULL;
while (desc.size) {
unsigned mode;
const char *name;
const struct object_id *oid;
oid = tree_entry_extract(&desc, &name, &mode);
has_null_sha1 |= is_null_oid(oid);
has_full_path |= !!strchr(name, '/');
has_empty_name |= !*name;
has_dot |= !strcmp(name, ".");
has_dotdot |= !strcmp(name, "..");
has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name);
has_zero_pad |= *(char *)desc.buffer == '0';
if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) {
if (!S_ISLNK(mode))
oidset_insert(&gitmodules_found, oid);
else
retval += report(options, &item->object,
FSCK_MSG_GITMODULES_SYMLINK,
".gitmodules is a symbolic link");
}
if (update_tree_entry_gently(&desc)) {
retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
break;
}
switch (mode) {
/*
* Standard modes..
*/
case S_IFREG | 0755:
case S_IFREG | 0644:
case S_IFLNK:
case S_IFDIR:
case S_IFGITLINK:
break;
/*
* This is nonstandard, but we had a few of these
* early on when we honored the full set of mode
* bits..
*/
case S_IFREG | 0664:
if (!options->strict)
break;
/* fallthrough */
default:
has_bad_modes = 1;
}
if (o_name) {
switch (verify_ordered(o_mode, o_name, mode, name)) {
case TREE_UNORDERED:
not_properly_sorted = 1;
break;
case TREE_HAS_DUPS:
has_dup_entries = 1;
break;
default:
break;
}
}
o_mode = mode;
o_name = name;
}
if (has_null_sha1)
retval += report(options, &item->object, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1");
if (has_full_path)
retval += report(options, &item->object, FSCK_MSG_FULL_PATHNAME, "contains full pathnames");
if (has_empty_name)
retval += report(options, &item->object, FSCK_MSG_EMPTY_NAME, "contains empty pathname");
if (has_dot)
retval += report(options, &item->object, FSCK_MSG_HAS_DOT, "contains '.'");
if (has_dotdot)
retval += report(options, &item->object, FSCK_MSG_HAS_DOTDOT, "contains '..'");
if (has_dotgit)
retval += report(options, &item->object, FSCK_MSG_HAS_DOTGIT, "contains '.git'");
if (has_zero_pad)
retval += report(options, &item->object, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes");
if (has_bad_modes)
retval += report(options, &item->object, FSCK_MSG_BAD_FILEMODE, "contains bad file modes");
if (has_dup_entries)
retval += report(options, &item->object, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries");
if (not_properly_sorted)
retval += report(options, &item->object, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted");
return retval;
}
static int verify_headers(const void *data, unsigned long size,
struct object *obj, struct fsck_options *options)
{
const char *buffer = (const char *)data;
unsigned long i;
for (i = 0; i < size; i++) {
switch (buffer[i]) {
case '\0':
return report(options, obj,
FSCK_MSG_NUL_IN_HEADER,
"unterminated header: NUL at offset %ld", i);
case '\n':
if (i + 1 < size && buffer[i + 1] == '\n')
return 0;
}
}
/*
* We did not find double-LF that separates the header
* and the body. Not having a body is not a crime but
* we do want to see the terminating LF for the last header
* line.
*/
if (size && buffer[size - 1] == '\n')
return 0;
return report(options, obj,
FSCK_MSG_UNTERMINATED_HEADER, "unterminated header");
}
static int fsck_ident(const char **ident, struct object *obj, struct fsck_options *options)
{
const char *p = *ident;
char *end;
*ident = strchrnul(*ident, '\n');
if (**ident == '\n')
(*ident)++;
if (*p == '<')
return report(options, obj, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
p += strcspn(p, "<>\n");
if (*p == '>')
return report(options, obj, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name");
if (*p != '<')
return report(options, obj, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email");
if (p[-1] != ' ')
return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email");
p++;
p += strcspn(p, "<>\n");
if (*p != '>')
return report(options, obj, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email");
p++;
if (*p != ' ')
return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date");
p++;
if (*p == '0' && p[1] != ' ')
return report(options, obj, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date");
if (date_overflows(parse_timestamp(p, &end, 10)))
return report(options, obj, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow");
if ((end == p || *end != ' '))
return report(options, obj, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date");
p = end + 1;
if ((*p != '+' && *p != '-') ||
!isdigit(p[1]) ||
!isdigit(p[2]) ||
!isdigit(p[3]) ||
!isdigit(p[4]) ||
(p[5] != '\n'))
return report(options, obj, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone");
p += 6;
return 0;
}
static int fsck_commit_buffer(struct commit *commit, const char *buffer,
unsigned long size, struct fsck_options *options)
{
unsigned char tree_sha1[20], sha1[20];
struct commit_graft *graft;
unsigned parent_count, parent_line_count = 0, author_count;
int err;
const char *buffer_begin = buffer;
if (verify_headers(buffer, size, &commit->object, options))
return -1;
if (!skip_prefix(buffer, "tree ", &buffer))
return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line");
if (get_sha1_hex(buffer, tree_sha1) || buffer[40] != '\n') {
err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1");
if (err)
return err;
}
buffer += 41;
while (skip_prefix(buffer, "parent ", &buffer)) {
if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1");
if (err)
return err;
}
buffer += 41;
parent_line_count++;
}
graft = lookup_commit_graft(&commit->object.oid);
parent_count = commit_list_count(commit->parents);
if (graft) {
if (graft->nr_parent == -1 && !parent_count)
; /* shallow commit */
else if (graft->nr_parent != parent_count) {
err = report(options, &commit->object, FSCK_MSG_MISSING_GRAFT, "graft objects missing");
if (err)
return err;
}
} else {
if (parent_count != parent_line_count) {
err = report(options, &commit->object, FSCK_MSG_MISSING_PARENT, "parent objects missing");
if (err)
return err;
}
}
author_count = 0;
while (skip_prefix(buffer, "author ", &buffer)) {
author_count++;
err = fsck_ident(&buffer, &commit->object, options);
if (err)
return err;
}
if (author_count < 1)
err = report(options, &commit->object, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line");
else if (author_count > 1)
err = report(options, &commit->object, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines");
if (err)
return err;
if (!skip_prefix(buffer, "committer ", &buffer))
return report(options, &commit->object, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line");
err = fsck_ident(&buffer, &commit->object, options);
if (err)
return err;
if (!commit->tree) {
err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", sha1_to_hex(tree_sha1));
if (err)
return err;
}
if (memchr(buffer_begin, '\0', size)) {
err = report(options, &commit->object, FSCK_MSG_NUL_IN_COMMIT,
"NUL byte in the commit object body");
if (err)
return err;
}
return 0;
}
static int fsck_commit(struct commit *commit, const char *data,
unsigned long size, struct fsck_options *options)
{
const char *buffer = data ? data : get_commit_buffer(commit, &size);
int ret = fsck_commit_buffer(commit, buffer, size, options);
if (!data)
unuse_commit_buffer(commit, buffer);
return ret;
}
static int fsck_tag_buffer(struct tag *tag, const char *data,
unsigned long size, struct fsck_options *options)
{
unsigned char sha1[20];
int ret = 0;
const char *buffer;
char *to_free = NULL, *eol;
struct strbuf sb = STRBUF_INIT;
if (data)
buffer = data;
else {
enum object_type type;
buffer = to_free =
read_sha1_file(tag->object.oid.hash, &type, &size);
if (!buffer)
return report(options, &tag->object,
FSCK_MSG_MISSING_TAG_OBJECT,
"cannot read tag object");
if (type != OBJ_TAG) {
ret = report(options, &tag->object,
FSCK_MSG_TAG_OBJECT_NOT_TAG,
"expected tag got %s",
type_name(type));
goto done;
}
}
ret = verify_headers(buffer, size, &tag->object, options);
if (ret)
goto done;
if (!skip_prefix(buffer, "object ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line");
goto done;
}
if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1");
if (ret)
goto done;
}
buffer += 41;
if (!skip_prefix(buffer, "type ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line");
goto done;
}
eol = strchr(buffer, '\n');
if (!eol) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line");
goto done;
}
if (type_from_string_gently(buffer, eol - buffer, 1) < 0)
ret = report(options, &tag->object, FSCK_MSG_BAD_TYPE, "invalid 'type' value");
if (ret)
goto done;
buffer = eol + 1;
if (!skip_prefix(buffer, "tag ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line");
goto done;
}
eol = strchr(buffer, '\n');
if (!eol) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line");
goto done;
}
strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer);
if (check_refname_format(sb.buf, 0)) {
ret = report(options, &tag->object, FSCK_MSG_BAD_TAG_NAME,
"invalid 'tag' name: %.*s",
(int)(eol - buffer), buffer);
if (ret)
goto done;
}
buffer = eol + 1;
if (!skip_prefix(buffer, "tagger ", &buffer)) {
/* early tags do not contain 'tagger' lines; warn only */
ret = report(options, &tag->object, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line");
if (ret)
goto done;
}
else
ret = fsck_ident(&buffer, &tag->object, options);
done:
strbuf_release(&sb);
free(to_free);
return ret;
}
static int fsck_tag(struct tag *tag, const char *data,
unsigned long size, struct fsck_options *options)
{
struct object *tagged = tag->tagged;
if (!tagged)
return report(options, &tag->object, FSCK_MSG_BAD_TAG_OBJECT, "could not load tagged object");
return fsck_tag_buffer(tag, data, size, options);
}
struct fsck_gitmodules_data {
struct object *obj;
struct fsck_options *options;
int ret;
};
static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
{
struct fsck_gitmodules_data *data = vdata;
const char *subsection, *key;
int subsection_len;
char *name;
if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
!subsection)
return 0;
name = xmemdupz(subsection, subsection_len);
if (check_submodule_name(name) < 0)
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_NAME,
"disallowed submodule name: %s",
name);
if (!strcmp(key, "url") && value &&
looks_like_command_line_option(value))
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_URL,
"disallowed submodule url: %s",
value);
free(name);
return 0;
}
static int fsck_blob(struct blob *blob, const char *buf,
unsigned long size, struct fsck_options *options)
{
struct fsck_gitmodules_data data;
if (!oidset_contains(&gitmodules_found, &blob->object.oid))
return 0;
oidset_insert(&gitmodules_done, &blob->object.oid);
if (!buf) {
/*
* A missing buffer here is a sign that the caller found the
* blob too gigantic to load into memory. Let's just consider
* that an error.
*/
return report(options, &blob->object,
FSCK_MSG_GITMODULES_PARSE,
".gitmodules too large to parse");
}
data.obj = &blob->object;
data.options = options;
data.ret = 0;
if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,
".gitmodules", buf, size, &data))
data.ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_PARSE,
"could not parse gitmodules blob");
return data.ret;
}
int fsck_object(struct object *obj, void *data, unsigned long size,
struct fsck_options *options)
{
if (!obj)
return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck");
if (obj->type == OBJ_BLOB)
return fsck_blob((struct blob *)obj, data, size, options);
if (obj->type == OBJ_TREE)
return fsck_tree((struct tree *) obj, options);
if (obj->type == OBJ_COMMIT)
return fsck_commit((struct commit *) obj, (const char *) data,
size, options);
if (obj->type == OBJ_TAG)
return fsck_tag((struct tag *) obj, (const char *) data,
size, options);
return report(options, obj, FSCK_MSG_UNKNOWN_TYPE, "unknown type '%d' (internal fsck error)",
obj->type);
}
int fsck_error_function(struct fsck_options *o,
struct object *obj, int msg_type, const char *message)
{
if (msg_type == FSCK_WARN) {
warning("object %s: %s", describe_object(o, obj), message);
return 0;
}
error("object %s: %s", describe_object(o, obj), message);
return 1;
}
int fsck_finish(struct fsck_options *options)
{
int ret = 0;
struct oidset_iter iter;
const struct object_id *oid;
oidset_iter_init(&gitmodules_found, &iter);
while ((oid = oidset_iter_next(&iter))) {
struct blob *blob;
enum object_type type;
unsigned long size;
char *buf;
if (oidset_contains(&gitmodules_done, oid))
continue;
blob = lookup_blob(oid);
if (!blob) {
ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_BLOB,
"non-blob found at .gitmodules");
continue;
}
buf = read_sha1_file(oid->hash, &type, &size);
if (!buf) {
if (is_promisor_object(&blob->object.oid))
continue;
ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_MISSING,
"unable to read .gitmodules blob");
continue;
}
if (type == OBJ_BLOB)
ret |= fsck_blob(blob, buf, size, options);
else
ret |= report(options, &blob->object,
FSCK_MSG_GITMODULES_BLOB,
"non-blob found at .gitmodules");
free(buf);
}
oidset_clear(&gitmodules_found);
oidset_clear(&gitmodules_done);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_396_0 |
crossvul-cpp_data_bad_2802_0 | /*
* nautilus-directory-async.c: Nautilus directory model state machine.
*
* Copyright (C) 1999, 2000, 2001 Eazel, 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, see <http://www.gnu.org/licenses/>.
*
* Author: Darin Adler <darin@bentspoon.com>
*/
#include <config.h>
#include "nautilus-directory-notify.h"
#include "nautilus-directory-private.h"
#include "nautilus-file-attributes.h"
#include "nautilus-file-private.h"
#include "nautilus-file-utilities.h"
#include "nautilus-signaller.h"
#include "nautilus-global-preferences.h"
#include "nautilus-link.h"
#include "nautilus-profile.h"
#include <eel/eel-glib-extensions.h>
#include <gtk/gtk.h>
#include <libxml/parser.h>
#include <stdio.h>
#include <stdlib.h>
/* turn this on to see messages about each load_directory call: */
#if 0
#define DEBUG_LOAD_DIRECTORY
#endif
/* turn this on to check if async. job calls are balanced */
#if 0
#define DEBUG_ASYNC_JOBS
#endif
/* turn this on to log things starting and stopping */
#if 0
#define DEBUG_START_STOP
#endif
#define DIRECTORY_LOAD_ITEMS_PER_CALLBACK 100
/* Keep async. jobs down to this number for all directories. */
#define MAX_ASYNC_JOBS 10
struct TopLeftTextReadState
{
NautilusDirectory *directory;
NautilusFile *file;
gboolean large;
GCancellable *cancellable;
};
struct LinkInfoReadState
{
NautilusDirectory *directory;
GCancellable *cancellable;
NautilusFile *file;
};
struct ThumbnailState
{
NautilusDirectory *directory;
GCancellable *cancellable;
NautilusFile *file;
gboolean trying_original;
gboolean tried_original;
};
struct MountState
{
NautilusDirectory *directory;
GCancellable *cancellable;
NautilusFile *file;
};
struct FilesystemInfoState
{
NautilusDirectory *directory;
GCancellable *cancellable;
NautilusFile *file;
};
struct DirectoryLoadState
{
NautilusDirectory *directory;
GCancellable *cancellable;
GFileEnumerator *enumerator;
GHashTable *load_mime_list_hash;
NautilusFile *load_directory_file;
int load_file_count;
};
struct MimeListState
{
NautilusDirectory *directory;
NautilusFile *mime_list_file;
GCancellable *cancellable;
GFileEnumerator *enumerator;
GHashTable *mime_list_hash;
};
struct GetInfoState
{
NautilusDirectory *directory;
GCancellable *cancellable;
};
struct NewFilesState
{
NautilusDirectory *directory;
GCancellable *cancellable;
int count;
};
struct DirectoryCountState
{
NautilusDirectory *directory;
NautilusFile *count_file;
GCancellable *cancellable;
GFileEnumerator *enumerator;
int file_count;
};
struct DeepCountState
{
NautilusDirectory *directory;
GCancellable *cancellable;
GFileEnumerator *enumerator;
GFile *deep_count_location;
GList *deep_count_subdirectories;
GArray *seen_deep_count_inodes;
char *fs_id;
};
typedef struct
{
NautilusFile *file; /* Which file, NULL means all. */
union
{
NautilusDirectoryCallback directory;
NautilusFileCallback file;
} callback;
gpointer callback_data;
Request request;
gboolean active; /* Set to FALSE when the callback is triggered and
* scheduled to be called at idle, its still kept
* in the list so we can kill it when the file
* goes away.
*/
} ReadyCallback;
typedef struct
{
NautilusFile *file; /* Which file, NULL means all. */
gboolean monitor_hidden_files; /* defines whether "all" includes hidden files */
gconstpointer client;
Request request;
} Monitor;
typedef struct
{
NautilusDirectory *directory;
NautilusInfoProvider *provider;
NautilusOperationHandle *handle;
NautilusOperationResult result;
} InfoProviderResponse;
typedef gboolean (*RequestCheck) (Request);
typedef gboolean (*FileCheck) (NautilusFile *);
/* Current number of async. jobs. */
static int async_job_count;
static GHashTable *waiting_directories;
#ifdef DEBUG_ASYNC_JOBS
static GHashTable *async_jobs;
#endif
/* Forward declarations for functions that need them. */
static void deep_count_load (DeepCountState *state,
GFile *location);
static gboolean request_is_satisfied (NautilusDirectory *directory,
NautilusFile *file,
Request request);
static void cancel_loading_attributes (NautilusDirectory *directory,
NautilusFileAttributes file_attributes);
static void add_all_files_to_work_queue (NautilusDirectory *directory);
static void link_info_done (NautilusDirectory *directory,
NautilusFile *file,
const char *uri,
const char *name,
GIcon *icon,
gboolean is_launcher,
gboolean is_foreign);
static void move_file_to_low_priority_queue (NautilusDirectory *directory,
NautilusFile *file);
static void move_file_to_extension_queue (NautilusDirectory *directory,
NautilusFile *file);
static void nautilus_directory_invalidate_file_attributes (NautilusDirectory *directory,
NautilusFileAttributes file_attributes);
/* Some helpers for case-insensitive strings.
* Move to nautilus-glib-extensions?
*/
static gboolean
istr_equal (gconstpointer v,
gconstpointer v2)
{
return g_ascii_strcasecmp (v, v2) == 0;
}
static guint
istr_hash (gconstpointer key)
{
const char *p;
guint h;
h = 0;
for (p = key; *p != '\0'; p++)
{
h = (h << 5) - h + g_ascii_tolower (*p);
}
return h;
}
static GHashTable *
istr_set_new (void)
{
return g_hash_table_new_full (istr_hash, istr_equal, g_free, NULL);
}
static void
istr_set_insert (GHashTable *table,
const char *istr)
{
char *key;
key = g_strdup (istr);
g_hash_table_replace (table, key, key);
}
static void
add_istr_to_list (gpointer key,
gpointer value,
gpointer callback_data)
{
GList **list;
list = callback_data;
*list = g_list_prepend (*list, g_strdup (key));
}
static GList *
istr_set_get_as_list (GHashTable *table)
{
GList *list;
list = NULL;
g_hash_table_foreach (table, add_istr_to_list, &list);
return list;
}
static void
istr_set_destroy (GHashTable *table)
{
g_hash_table_destroy (table);
}
static void
request_counter_add_request (RequestCounter counter,
Request request)
{
guint i;
for (i = 0; i < REQUEST_TYPE_LAST; i++)
{
if (REQUEST_WANTS_TYPE (request, i))
{
counter[i]++;
}
}
}
static void
request_counter_remove_request (RequestCounter counter,
Request request)
{
guint i;
for (i = 0; i < REQUEST_TYPE_LAST; i++)
{
if (REQUEST_WANTS_TYPE (request, i))
{
counter[i]--;
}
}
}
#if 0
static void
nautilus_directory_verify_request_counts (NautilusDirectory *directory)
{
GList *l;
RequestCounter counters;
int i;
gboolean fail;
fail = FALSE;
for (i = 0; i < REQUEST_TYPE_LAST; i++)
{
counters[i] = 0;
}
for (l = directory->details->monitor_list; l != NULL; l = l->next)
{
Monitor *monitor = l->data;
request_counter_add_request (counters, monitor->request);
}
for (i = 0; i < REQUEST_TYPE_LAST; i++)
{
if (counters[i] != directory->details->monitor_counters[i])
{
g_warning ("monitor counter for %i is wrong, expecting %d but found %d",
i, counters[i], directory->details->monitor_counters[i]);
fail = TRUE;
}
}
for (i = 0; i < REQUEST_TYPE_LAST; i++)
{
counters[i] = 0;
}
for (l = directory->details->call_when_ready_list; l != NULL; l = l->next)
{
ReadyCallback *callback = l->data;
request_counter_add_request (counters, callback->request);
}
for (i = 0; i < REQUEST_TYPE_LAST; i++)
{
if (counters[i] != directory->details->call_when_ready_counters[i])
{
g_warning ("call when ready counter for %i is wrong, expecting %d but found %d",
i, counters[i], directory->details->call_when_ready_counters[i]);
fail = TRUE;
}
}
g_assert (!fail);
}
#endif
/* Start a job. This is really just a way of limiting the number of
* async. requests that we issue at any given time. Without this, the
* number of requests is unbounded.
*/
static gboolean
async_job_start (NautilusDirectory *directory,
const char *job)
{
#ifdef DEBUG_ASYNC_JOBS
char *key;
#endif
#ifdef DEBUG_START_STOP
g_message ("starting %s in %p", job, directory->details->location);
#endif
g_assert (async_job_count >= 0);
g_assert (async_job_count <= MAX_ASYNC_JOBS);
if (async_job_count >= MAX_ASYNC_JOBS)
{
if (waiting_directories == NULL)
{
waiting_directories = g_hash_table_new (NULL, NULL);
}
g_hash_table_insert (waiting_directories,
directory,
directory);
return FALSE;
}
#ifdef DEBUG_ASYNC_JOBS
{
char *uri;
if (async_jobs == NULL)
{
async_jobs = g_hash_table_new (g_str_hash, g_str_equal);
}
uri = nautilus_directory_get_uri (directory);
key = g_strconcat (uri, ": ", job, NULL);
if (g_hash_table_lookup (async_jobs, key) != NULL)
{
g_warning ("same job twice: %s in %s",
job, uri);
}
g_free (uri);
g_hash_table_insert (async_jobs, key, directory);
}
#endif
async_job_count += 1;
return TRUE;
}
/* End a job. */
static void
async_job_end (NautilusDirectory *directory,
const char *job)
{
#ifdef DEBUG_ASYNC_JOBS
char *key;
gpointer table_key, value;
#endif
#ifdef DEBUG_START_STOP
g_message ("stopping %s in %p", job, directory->details->location);
#endif
g_assert (async_job_count > 0);
#ifdef DEBUG_ASYNC_JOBS
{
char *uri;
uri = nautilus_directory_get_uri (directory);
g_assert (async_jobs != NULL);
key = g_strconcat (uri, ": ", job, NULL);
if (!g_hash_table_lookup_extended (async_jobs, key, &table_key, &value))
{
g_warning ("ending job we didn't start: %s in %s",
job, uri);
}
else
{
g_hash_table_remove (async_jobs, key);
g_free (table_key);
}
g_free (uri);
g_free (key);
}
#endif
async_job_count -= 1;
}
/* Helper to get one value from a hash table. */
static void
get_one_value_callback (gpointer key,
gpointer value,
gpointer callback_data)
{
gpointer *returned_value;
returned_value = callback_data;
*returned_value = value;
}
/* return a single value from a hash table. */
static gpointer
get_one_value (GHashTable *table)
{
gpointer value;
value = NULL;
if (table != NULL)
{
g_hash_table_foreach (table, get_one_value_callback, &value);
}
return value;
}
/* Wake up directories that are "blocked" as long as there are job
* slots available.
*/
static void
async_job_wake_up (void)
{
static gboolean already_waking_up = FALSE;
gpointer value;
g_assert (async_job_count >= 0);
g_assert (async_job_count <= MAX_ASYNC_JOBS);
if (already_waking_up)
{
return;
}
already_waking_up = TRUE;
while (async_job_count < MAX_ASYNC_JOBS)
{
value = get_one_value (waiting_directories);
if (value == NULL)
{
break;
}
g_hash_table_remove (waiting_directories, value);
nautilus_directory_async_state_changed
(NAUTILUS_DIRECTORY (value));
}
already_waking_up = FALSE;
}
static void
directory_count_cancel (NautilusDirectory *directory)
{
if (directory->details->count_in_progress != NULL)
{
g_cancellable_cancel (directory->details->count_in_progress->cancellable);
directory->details->count_in_progress = NULL;
}
}
static void
deep_count_cancel (NautilusDirectory *directory)
{
if (directory->details->deep_count_in_progress != NULL)
{
g_assert (NAUTILUS_IS_FILE (directory->details->deep_count_file));
g_cancellable_cancel (directory->details->deep_count_in_progress->cancellable);
directory->details->deep_count_file->details->deep_counts_status = NAUTILUS_REQUEST_NOT_STARTED;
directory->details->deep_count_in_progress->directory = NULL;
directory->details->deep_count_in_progress = NULL;
directory->details->deep_count_file = NULL;
async_job_end (directory, "deep count");
}
}
static void
mime_list_cancel (NautilusDirectory *directory)
{
if (directory->details->mime_list_in_progress != NULL)
{
g_cancellable_cancel (directory->details->mime_list_in_progress->cancellable);
}
}
static void
link_info_cancel (NautilusDirectory *directory)
{
if (directory->details->link_info_read_state != NULL)
{
g_cancellable_cancel (directory->details->link_info_read_state->cancellable);
directory->details->link_info_read_state->directory = NULL;
directory->details->link_info_read_state = NULL;
async_job_end (directory, "link info");
}
}
static void
thumbnail_cancel (NautilusDirectory *directory)
{
if (directory->details->thumbnail_state != NULL)
{
g_cancellable_cancel (directory->details->thumbnail_state->cancellable);
directory->details->thumbnail_state->directory = NULL;
directory->details->thumbnail_state = NULL;
async_job_end (directory, "thumbnail");
}
}
static void
mount_cancel (NautilusDirectory *directory)
{
if (directory->details->mount_state != NULL)
{
g_cancellable_cancel (directory->details->mount_state->cancellable);
directory->details->mount_state->directory = NULL;
directory->details->mount_state = NULL;
async_job_end (directory, "mount");
}
}
static void
file_info_cancel (NautilusDirectory *directory)
{
if (directory->details->get_info_in_progress != NULL)
{
g_cancellable_cancel (directory->details->get_info_in_progress->cancellable);
directory->details->get_info_in_progress->directory = NULL;
directory->details->get_info_in_progress = NULL;
directory->details->get_info_file = NULL;
async_job_end (directory, "file info");
}
}
static void
new_files_cancel (NautilusDirectory *directory)
{
GList *l;
NewFilesState *state;
if (directory->details->new_files_in_progress != NULL)
{
for (l = directory->details->new_files_in_progress; l != NULL; l = l->next)
{
state = l->data;
g_cancellable_cancel (state->cancellable);
state->directory = NULL;
}
g_list_free (directory->details->new_files_in_progress);
directory->details->new_files_in_progress = NULL;
}
}
static int
monitor_key_compare (gconstpointer a,
gconstpointer data)
{
const Monitor *monitor;
const Monitor *compare_monitor;
monitor = a;
compare_monitor = data;
if (monitor->client < compare_monitor->client)
{
return -1;
}
if (monitor->client > compare_monitor->client)
{
return +1;
}
if (monitor->file < compare_monitor->file)
{
return -1;
}
if (monitor->file > compare_monitor->file)
{
return +1;
}
return 0;
}
static GList *
find_monitor (NautilusDirectory *directory,
NautilusFile *file,
gconstpointer client)
{
Monitor monitor;
monitor.client = client;
monitor.file = file;
return g_list_find_custom (directory->details->monitor_list,
&monitor,
monitor_key_compare);
}
static void
remove_monitor_link (NautilusDirectory *directory,
GList *link)
{
Monitor *monitor;
if (link != NULL)
{
monitor = link->data;
request_counter_remove_request (directory->details->monitor_counters,
monitor->request);
directory->details->monitor_list =
g_list_remove_link (directory->details->monitor_list, link);
g_free (monitor);
g_list_free_1 (link);
}
}
static void
remove_monitor (NautilusDirectory *directory,
NautilusFile *file,
gconstpointer client)
{
remove_monitor_link (directory, find_monitor (directory, file, client));
}
Request
nautilus_directory_set_up_request (NautilusFileAttributes file_attributes)
{
Request request;
request = 0;
if ((file_attributes & NAUTILUS_FILE_ATTRIBUTE_DIRECTORY_ITEM_COUNT) != 0)
{
REQUEST_SET_TYPE (request, REQUEST_DIRECTORY_COUNT);
}
if ((file_attributes & NAUTILUS_FILE_ATTRIBUTE_DEEP_COUNTS) != 0)
{
REQUEST_SET_TYPE (request, REQUEST_DEEP_COUNT);
}
if ((file_attributes & NAUTILUS_FILE_ATTRIBUTE_DIRECTORY_ITEM_MIME_TYPES) != 0)
{
REQUEST_SET_TYPE (request, REQUEST_MIME_LIST);
}
if ((file_attributes & NAUTILUS_FILE_ATTRIBUTE_INFO) != 0)
{
REQUEST_SET_TYPE (request, REQUEST_FILE_INFO);
}
if (file_attributes & NAUTILUS_FILE_ATTRIBUTE_LINK_INFO)
{
REQUEST_SET_TYPE (request, REQUEST_FILE_INFO);
REQUEST_SET_TYPE (request, REQUEST_LINK_INFO);
}
if ((file_attributes & NAUTILUS_FILE_ATTRIBUTE_EXTENSION_INFO) != 0)
{
REQUEST_SET_TYPE (request, REQUEST_EXTENSION_INFO);
}
if (file_attributes & NAUTILUS_FILE_ATTRIBUTE_THUMBNAIL)
{
REQUEST_SET_TYPE (request, REQUEST_THUMBNAIL);
REQUEST_SET_TYPE (request, REQUEST_FILE_INFO);
}
if (file_attributes & NAUTILUS_FILE_ATTRIBUTE_MOUNT)
{
REQUEST_SET_TYPE (request, REQUEST_MOUNT);
REQUEST_SET_TYPE (request, REQUEST_FILE_INFO);
}
if (file_attributes & NAUTILUS_FILE_ATTRIBUTE_FILESYSTEM_INFO)
{
REQUEST_SET_TYPE (request, REQUEST_FILESYSTEM_INFO);
}
return request;
}
static void
mime_db_changed_callback (GObject *ignore,
NautilusDirectory *dir)
{
NautilusFileAttributes attrs;
g_assert (dir != NULL);
g_assert (dir->details != NULL);
attrs = NAUTILUS_FILE_ATTRIBUTE_INFO |
NAUTILUS_FILE_ATTRIBUTE_LINK_INFO |
NAUTILUS_FILE_ATTRIBUTE_DIRECTORY_ITEM_MIME_TYPES;
nautilus_directory_force_reload_internal (dir, attrs);
}
void
nautilus_directory_monitor_add_internal (NautilusDirectory *directory,
NautilusFile *file,
gconstpointer client,
gboolean monitor_hidden_files,
NautilusFileAttributes file_attributes,
NautilusDirectoryCallback callback,
gpointer callback_data)
{
Monitor *monitor;
GList *file_list;
char *file_uri = NULL;
char *dir_uri = NULL;
g_assert (NAUTILUS_IS_DIRECTORY (directory));
if (file != NULL)
{
file_uri = nautilus_file_get_uri (file);
}
if (directory != NULL)
{
dir_uri = nautilus_directory_get_uri (directory);
}
nautilus_profile_start ("uri %s file-uri %s client %p", dir_uri, file_uri, client);
g_free (dir_uri);
g_free (file_uri);
/* Replace any current monitor for this client/file pair. */
remove_monitor (directory, file, client);
/* Add the new monitor. */
monitor = g_new (Monitor, 1);
monitor->file = file;
monitor->monitor_hidden_files = monitor_hidden_files;
monitor->client = client;
monitor->request = nautilus_directory_set_up_request (file_attributes);
if (file == NULL)
{
REQUEST_SET_TYPE (monitor->request, REQUEST_FILE_LIST);
}
directory->details->monitor_list =
g_list_prepend (directory->details->monitor_list, monitor);
request_counter_add_request (directory->details->monitor_counters,
monitor->request);
if (callback != NULL)
{
file_list = nautilus_directory_get_file_list (directory);
(*callback)(directory, file_list, callback_data);
nautilus_file_list_free (file_list);
}
/* Start the "real" monitoring (FAM or whatever). */
/* We always monitor the whole directory since in practice
* nautilus almost always shows the whole directory anyway, and
* it allows us to avoid one file monitor per file in a directory.
*/
if (directory->details->monitor == NULL)
{
directory->details->monitor = nautilus_monitor_directory (directory->details->location);
}
if (REQUEST_WANTS_TYPE (monitor->request, REQUEST_FILE_INFO) &&
directory->details->mime_db_monitor == 0)
{
directory->details->mime_db_monitor =
g_signal_connect_object (nautilus_signaller_get_current (),
"mime-data-changed",
G_CALLBACK (mime_db_changed_callback), directory, 0);
}
/* Put the monitor file or all the files on the work queue. */
if (file != NULL)
{
nautilus_directory_add_file_to_work_queue (directory, file);
}
else
{
add_all_files_to_work_queue (directory);
}
/* Kick off I/O. */
nautilus_directory_async_state_changed (directory);
nautilus_profile_end (NULL);
}
static void
set_file_unconfirmed (NautilusFile *file,
gboolean unconfirmed)
{
NautilusDirectory *directory;
g_assert (NAUTILUS_IS_FILE (file));
g_assert (unconfirmed == FALSE || unconfirmed == TRUE);
if (file->details->unconfirmed == unconfirmed)
{
return;
}
file->details->unconfirmed = unconfirmed;
directory = file->details->directory;
if (unconfirmed)
{
directory->details->confirmed_file_count--;
}
else
{
directory->details->confirmed_file_count++;
}
}
static gboolean show_hidden_files = TRUE;
static void
show_hidden_files_changed_callback (gpointer callback_data)
{
show_hidden_files = g_settings_get_boolean (gtk_filechooser_preferences, NAUTILUS_PREFERENCES_SHOW_HIDDEN_FILES);
}
static gboolean
should_skip_file (NautilusDirectory *directory,
GFileInfo *info)
{
static gboolean show_hidden_files_changed_callback_installed = FALSE;
/* Add the callback once for the life of our process */
if (!show_hidden_files_changed_callback_installed)
{
g_signal_connect_swapped (gtk_filechooser_preferences,
"changed::" NAUTILUS_PREFERENCES_SHOW_HIDDEN_FILES,
G_CALLBACK (show_hidden_files_changed_callback),
NULL);
show_hidden_files_changed_callback_installed = TRUE;
/* Peek for the first time */
show_hidden_files_changed_callback (NULL);
}
if (!show_hidden_files &&
(g_file_info_get_is_hidden (info) ||
g_file_info_get_is_backup (info)))
{
return TRUE;
}
return FALSE;
}
static gboolean
dequeue_pending_idle_callback (gpointer callback_data)
{
NautilusDirectory *directory;
GList *pending_file_info;
GList *node, *next;
NautilusFile *file;
GList *changed_files, *added_files;
GFileInfo *file_info;
const char *mimetype, *name;
DirectoryLoadState *dir_load_state;
directory = NAUTILUS_DIRECTORY (callback_data);
nautilus_directory_ref (directory);
nautilus_profile_start ("nitems %d", g_list_length (directory->details->pending_file_info));
directory->details->dequeue_pending_idle_id = 0;
/* Handle the files in the order we saw them. */
pending_file_info = g_list_reverse (directory->details->pending_file_info);
directory->details->pending_file_info = NULL;
/* If we are no longer monitoring, then throw away these. */
if (!nautilus_directory_is_file_list_monitored (directory))
{
nautilus_directory_async_state_changed (directory);
goto drain;
}
added_files = NULL;
changed_files = NULL;
dir_load_state = directory->details->directory_load_in_progress;
/* Build a list of NautilusFile objects. */
for (node = pending_file_info; node != NULL; node = node->next)
{
file_info = node->data;
name = g_file_info_get_name (file_info);
/* Update the file count. */
/* FIXME bugzilla.gnome.org 45063: This could count a
* file twice if we get it from both load_directory
* and from new_files_callback. Not too hard to fix by
* moving this into the actual callback instead of
* waiting for the idle function.
*/
if (dir_load_state &&
!should_skip_file (directory, file_info))
{
dir_load_state->load_file_count += 1;
/* Add the MIME type to the set. */
mimetype = g_file_info_get_content_type (file_info);
if (mimetype != NULL)
{
istr_set_insert (dir_load_state->load_mime_list_hash,
mimetype);
}
}
/* check if the file already exists */
file = nautilus_directory_find_file_by_name (directory, name);
if (file != NULL)
{
/* file already exists in dir, check if we still need to
* emit file_added or if it changed */
set_file_unconfirmed (file, FALSE);
if (!file->details->is_added)
{
/* We consider this newly added even if its in the list.
* This can happen if someone called nautilus_file_get_by_uri()
* on a file in the folder before the add signal was
* emitted */
nautilus_file_ref (file);
file->details->is_added = TRUE;
added_files = g_list_prepend (added_files, file);
}
else if (nautilus_file_update_info (file, file_info))
{
/* File changed, notify about the change. */
nautilus_file_ref (file);
changed_files = g_list_prepend (changed_files, file);
}
}
else
{
/* new file, create a nautilus file object and add it to the list */
file = nautilus_file_new_from_info (directory, file_info);
nautilus_directory_add_file (directory, file);
file->details->is_added = TRUE;
added_files = g_list_prepend (added_files, file);
}
}
/* If we are done loading, then we assume that any unconfirmed
* files are gone.
*/
if (directory->details->directory_loaded)
{
for (node = directory->details->file_list;
node != NULL; node = next)
{
file = NAUTILUS_FILE (node->data);
next = node->next;
if (file->details->unconfirmed)
{
nautilus_file_ref (file);
changed_files = g_list_prepend (changed_files, file);
nautilus_file_mark_gone (file);
}
}
}
/* Send the changed and added signals. */
nautilus_directory_emit_change_signals (directory, changed_files);
nautilus_file_list_free (changed_files);
nautilus_directory_emit_files_added (directory, added_files);
nautilus_file_list_free (added_files);
if (directory->details->directory_loaded &&
!directory->details->directory_loaded_sent_notification)
{
/* Send the done_loading signal. */
nautilus_directory_emit_done_loading (directory);
if (dir_load_state)
{
file = dir_load_state->load_directory_file;
file->details->directory_count = dir_load_state->load_file_count;
file->details->directory_count_is_up_to_date = TRUE;
file->details->got_directory_count = TRUE;
file->details->got_mime_list = TRUE;
file->details->mime_list_is_up_to_date = TRUE;
g_list_free_full (file->details->mime_list, g_free);
file->details->mime_list = istr_set_get_as_list
(dir_load_state->load_mime_list_hash);
nautilus_file_changed (file);
}
nautilus_directory_async_state_changed (directory);
directory->details->directory_loaded_sent_notification = TRUE;
}
drain:
g_list_free_full (pending_file_info, g_object_unref);
/* Get the state machine running again. */
nautilus_directory_async_state_changed (directory);
nautilus_profile_end (NULL);
nautilus_directory_unref (directory);
return FALSE;
}
void
nautilus_directory_schedule_dequeue_pending (NautilusDirectory *directory)
{
if (directory->details->dequeue_pending_idle_id == 0)
{
directory->details->dequeue_pending_idle_id
= g_idle_add (dequeue_pending_idle_callback, directory);
}
}
static void
directory_load_one (NautilusDirectory *directory,
GFileInfo *info)
{
if (info == NULL)
{
return;
}
if (g_file_info_get_name (info) == NULL)
{
char *uri;
uri = nautilus_directory_get_uri (directory);
g_warning ("Got GFileInfo with NULL name in %s, ignoring. This shouldn't happen unless the gvfs backend is broken.\n", uri);
g_free (uri);
return;
}
/* Arrange for the "loading" part of the work. */
g_object_ref (info);
directory->details->pending_file_info
= g_list_prepend (directory->details->pending_file_info, info);
nautilus_directory_schedule_dequeue_pending (directory);
}
static void
directory_load_cancel (NautilusDirectory *directory)
{
NautilusFile *file;
DirectoryLoadState *state;
state = directory->details->directory_load_in_progress;
if (state != NULL)
{
file = state->load_directory_file;
file->details->loading_directory = FALSE;
if (file->details->directory != directory)
{
nautilus_directory_async_state_changed (file->details->directory);
}
g_cancellable_cancel (state->cancellable);
state->directory = NULL;
directory->details->directory_load_in_progress = NULL;
async_job_end (directory, "file list");
}
}
static void
file_list_cancel (NautilusDirectory *directory)
{
directory_load_cancel (directory);
if (directory->details->dequeue_pending_idle_id != 0)
{
g_source_remove (directory->details->dequeue_pending_idle_id);
directory->details->dequeue_pending_idle_id = 0;
}
if (directory->details->pending_file_info != NULL)
{
g_list_free_full (directory->details->pending_file_info, g_object_unref);
directory->details->pending_file_info = NULL;
}
}
static void
directory_load_done (NautilusDirectory *directory,
GError *error)
{
GList *node;
nautilus_profile_start (NULL);
g_object_ref (directory);
directory->details->directory_loaded = TRUE;
directory->details->directory_loaded_sent_notification = FALSE;
if (error != NULL)
{
/* The load did not complete successfully. This means
* we don't know the status of the files in this directory.
* We clear the unconfirmed bit on each file here so that
* they won't be marked "gone" later -- we don't know enough
* about them to know whether they are really gone.
*/
for (node = directory->details->file_list;
node != NULL; node = node->next)
{
set_file_unconfirmed (NAUTILUS_FILE (node->data), FALSE);
}
nautilus_directory_emit_load_error (directory, error);
}
/* Call the idle function right away. */
if (directory->details->dequeue_pending_idle_id != 0)
{
g_source_remove (directory->details->dequeue_pending_idle_id);
}
dequeue_pending_idle_callback (directory);
directory_load_cancel (directory);
g_object_unref (directory);
nautilus_profile_end (NULL);
}
void
nautilus_directory_monitor_remove_internal (NautilusDirectory *directory,
NautilusFile *file,
gconstpointer client)
{
g_assert (NAUTILUS_IS_DIRECTORY (directory));
g_assert (file == NULL || NAUTILUS_IS_FILE (file));
g_assert (client != NULL);
remove_monitor (directory, file, client);
if (directory->details->monitor != NULL
&& directory->details->monitor_list == NULL)
{
nautilus_monitor_cancel (directory->details->monitor);
directory->details->monitor = NULL;
}
/* XXX - do we need to remove anything from the work queue? */
nautilus_directory_async_state_changed (directory);
}
FileMonitors *
nautilus_directory_remove_file_monitors (NautilusDirectory *directory,
NautilusFile *file)
{
GList *result, **list, *node, *next;
Monitor *monitor;
g_assert (NAUTILUS_IS_DIRECTORY (directory));
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
result = NULL;
list = &directory->details->monitor_list;
for (node = directory->details->monitor_list; node != NULL; node = next)
{
next = node->next;
monitor = node->data;
if (monitor->file == file)
{
*list = g_list_remove_link (*list, node);
result = g_list_concat (node, result);
request_counter_remove_request (directory->details->monitor_counters,
monitor->request);
}
}
/* XXX - do we need to remove anything from the work queue? */
nautilus_directory_async_state_changed (directory);
return (FileMonitors *) result;
}
void
nautilus_directory_add_file_monitors (NautilusDirectory *directory,
NautilusFile *file,
FileMonitors *monitors)
{
GList **list;
GList *l;
Monitor *monitor;
g_assert (NAUTILUS_IS_DIRECTORY (directory));
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (monitors == NULL)
{
return;
}
for (l = (GList *) monitors; l != NULL; l = l->next)
{
monitor = l->data;
request_counter_add_request (directory->details->monitor_counters,
monitor->request);
}
list = &directory->details->monitor_list;
*list = g_list_concat (*list, (GList *) monitors);
nautilus_directory_add_file_to_work_queue (directory, file);
nautilus_directory_async_state_changed (directory);
}
static int
ready_callback_key_compare (gconstpointer a,
gconstpointer b)
{
const ReadyCallback *callback_a, *callback_b;
callback_a = a;
callback_b = b;
if (callback_a->file < callback_b->file)
{
return -1;
}
if (callback_a->file > callback_b->file)
{
return 1;
}
if (callback_a->file == NULL)
{
/* ANSI C doesn't allow ordered compares of function pointers, so we cast them to
* normal pointers to make some overly pedantic compilers (*cough* HP-UX *cough*)
* compile this. Of course, on any compiler where ordered function pointers actually
* break this probably won't work, but at least it will compile on platforms where it
* works, but stupid compilers won't let you use it.
*/
if ((void *) callback_a->callback.directory < (void *) callback_b->callback.directory)
{
return -1;
}
if ((void *) callback_a->callback.directory > (void *) callback_b->callback.directory)
{
return 1;
}
}
else
{
if ((void *) callback_a->callback.file < (void *) callback_b->callback.file)
{
return -1;
}
if ((void *) callback_a->callback.file > (void *) callback_b->callback.file)
{
return 1;
}
}
if (callback_a->callback_data < callback_b->callback_data)
{
return -1;
}
if (callback_a->callback_data > callback_b->callback_data)
{
return 1;
}
return 0;
}
static int
ready_callback_key_compare_only_active (gconstpointer a,
gconstpointer b)
{
const ReadyCallback *callback_a;
callback_a = a;
/* Non active callbacks never match */
if (!callback_a->active)
{
return -1;
}
return ready_callback_key_compare (a, b);
}
static void
ready_callback_call (NautilusDirectory *directory,
const ReadyCallback *callback)
{
GList *file_list;
/* Call the callback. */
if (callback->file != NULL)
{
if (callback->callback.file)
{
(*callback->callback.file)(callback->file,
callback->callback_data);
}
}
else if (callback->callback.directory != NULL)
{
if (directory == NULL ||
!REQUEST_WANTS_TYPE (callback->request, REQUEST_FILE_LIST))
{
file_list = NULL;
}
else
{
file_list = nautilus_directory_get_file_list (directory);
}
/* Pass back the file list if the user was waiting for it. */
(*callback->callback.directory)(directory,
file_list,
callback->callback_data);
nautilus_file_list_free (file_list);
}
}
void
nautilus_directory_call_when_ready_internal (NautilusDirectory *directory,
NautilusFile *file,
NautilusFileAttributes file_attributes,
gboolean wait_for_file_list,
NautilusDirectoryCallback directory_callback,
NautilusFileCallback file_callback,
gpointer callback_data)
{
ReadyCallback callback;
g_assert (directory == NULL || NAUTILUS_IS_DIRECTORY (directory));
g_assert (file == NULL || NAUTILUS_IS_FILE (file));
g_assert (file != NULL || directory_callback != NULL);
/* Construct a callback object. */
callback.active = TRUE;
callback.file = file;
if (file == NULL)
{
callback.callback.directory = directory_callback;
}
else
{
callback.callback.file = file_callback;
}
callback.callback_data = callback_data;
callback.request = nautilus_directory_set_up_request (file_attributes);
if (wait_for_file_list)
{
REQUEST_SET_TYPE (callback.request, REQUEST_FILE_LIST);
}
/* Handle the NULL case. */
if (directory == NULL)
{
ready_callback_call (NULL, &callback);
return;
}
/* Check if the callback is already there. */
if (g_list_find_custom (directory->details->call_when_ready_list,
&callback,
ready_callback_key_compare_only_active) != NULL)
{
if (file_callback != NULL && directory_callback != NULL)
{
g_warning ("tried to add a new callback while an old one was pending");
}
/* NULL callback means, just read it. Conflicts are ok. */
return;
}
/* Add the new callback to the list. */
directory->details->call_when_ready_list = g_list_prepend
(directory->details->call_when_ready_list,
g_memdup (&callback, sizeof (callback)));
request_counter_add_request (directory->details->call_when_ready_counters,
callback.request);
/* Put the callback file or all the files on the work queue. */
if (file != NULL)
{
nautilus_directory_add_file_to_work_queue (directory, file);
}
else
{
add_all_files_to_work_queue (directory);
}
nautilus_directory_async_state_changed (directory);
}
gboolean
nautilus_directory_check_if_ready_internal (NautilusDirectory *directory,
NautilusFile *file,
NautilusFileAttributes file_attributes)
{
Request request;
g_assert (NAUTILUS_IS_DIRECTORY (directory));
request = nautilus_directory_set_up_request (file_attributes);
return request_is_satisfied (directory, file, request);
}
static void
remove_callback_link_keep_data (NautilusDirectory *directory,
GList *link)
{
ReadyCallback *callback;
callback = link->data;
directory->details->call_when_ready_list = g_list_remove_link
(directory->details->call_when_ready_list, link);
request_counter_remove_request (directory->details->call_when_ready_counters,
callback->request);
g_list_free_1 (link);
}
static void
remove_callback_link (NautilusDirectory *directory,
GList *link)
{
ReadyCallback *callback;
callback = link->data;
remove_callback_link_keep_data (directory, link);
g_free (callback);
}
void
nautilus_directory_cancel_callback_internal (NautilusDirectory *directory,
NautilusFile *file,
NautilusDirectoryCallback directory_callback,
NautilusFileCallback file_callback,
gpointer callback_data)
{
ReadyCallback callback;
GList *node;
if (directory == NULL)
{
return;
}
g_assert (NAUTILUS_IS_DIRECTORY (directory));
g_assert (file == NULL || NAUTILUS_IS_FILE (file));
g_assert (file != NULL || directory_callback != NULL);
g_assert (file == NULL || file_callback != NULL);
/* Construct a callback object. */
callback.file = file;
if (file == NULL)
{
callback.callback.directory = directory_callback;
}
else
{
callback.callback.file = file_callback;
}
callback.callback_data = callback_data;
/* Remove all queued callback from the list (including non-active). */
do
{
node = g_list_find_custom (directory->details->call_when_ready_list,
&callback,
ready_callback_key_compare);
if (node != NULL)
{
remove_callback_link (directory, node);
nautilus_directory_async_state_changed (directory);
}
}
while (node != NULL);
}
static void
new_files_state_unref (NewFilesState *state)
{
state->count--;
if (state->count == 0)
{
if (state->directory)
{
state->directory->details->new_files_in_progress =
g_list_remove (state->directory->details->new_files_in_progress,
state);
}
g_object_unref (state->cancellable);
g_free (state);
}
}
static void
new_files_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
NautilusDirectory *directory;
GFileInfo *info;
NewFilesState *state;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
new_files_state_unref (state);
return;
}
directory = nautilus_directory_ref (state->directory);
/* Queue up the new file. */
info = g_file_query_info_finish (G_FILE (source_object), res, NULL);
if (info != NULL)
{
directory_load_one (directory, info);
g_object_unref (info);
}
new_files_state_unref (state);
nautilus_directory_unref (directory);
}
void
nautilus_directory_get_info_for_new_files (NautilusDirectory *directory,
GList *location_list)
{
NewFilesState *state;
GFile *location;
GList *l;
if (location_list == NULL)
{
return;
}
state = g_new (NewFilesState, 1);
state->directory = directory;
state->cancellable = g_cancellable_new ();
state->count = 0;
for (l = location_list; l != NULL; l = l->next)
{
location = l->data;
state->count++;
g_file_query_info_async (location,
NAUTILUS_FILE_DEFAULT_ATTRIBUTES,
0,
G_PRIORITY_DEFAULT,
state->cancellable,
new_files_callback, state);
}
directory->details->new_files_in_progress
= g_list_prepend (directory->details->new_files_in_progress,
state);
}
void
nautilus_async_destroying_file (NautilusFile *file)
{
NautilusDirectory *directory;
gboolean changed;
GList *node, *next;
ReadyCallback *callback;
Monitor *monitor;
directory = file->details->directory;
changed = FALSE;
/* Check for callbacks. */
for (node = directory->details->call_when_ready_list; node != NULL; node = next)
{
next = node->next;
callback = node->data;
if (callback->file == file)
{
/* Client should have cancelled callback. */
if (callback->active)
{
g_warning ("destroyed file has call_when_ready pending");
}
remove_callback_link (directory, node);
changed = TRUE;
}
}
/* Check for monitors. */
for (node = directory->details->monitor_list; node != NULL; node = next)
{
next = node->next;
monitor = node->data;
if (monitor->file == file)
{
/* Client should have removed monitor earlier. */
g_warning ("destroyed file still being monitored");
remove_monitor_link (directory, node);
changed = TRUE;
}
}
/* Check if it's a file that's currently being worked on.
* If so, make that NULL so it gets canceled right away.
*/
if (directory->details->count_in_progress != NULL &&
directory->details->count_in_progress->count_file == file)
{
directory->details->count_in_progress->count_file = NULL;
changed = TRUE;
}
if (directory->details->deep_count_file == file)
{
directory->details->deep_count_file = NULL;
changed = TRUE;
}
if (directory->details->mime_list_in_progress != NULL &&
directory->details->mime_list_in_progress->mime_list_file == file)
{
directory->details->mime_list_in_progress->mime_list_file = NULL;
changed = TRUE;
}
if (directory->details->get_info_file == file)
{
directory->details->get_info_file = NULL;
changed = TRUE;
}
if (directory->details->link_info_read_state != NULL &&
directory->details->link_info_read_state->file == file)
{
directory->details->link_info_read_state->file = NULL;
changed = TRUE;
}
if (directory->details->extension_info_file == file)
{
directory->details->extension_info_file = NULL;
changed = TRUE;
}
if (directory->details->thumbnail_state != NULL &&
directory->details->thumbnail_state->file == file)
{
directory->details->thumbnail_state->file = NULL;
changed = TRUE;
}
if (directory->details->mount_state != NULL &&
directory->details->mount_state->file == file)
{
directory->details->mount_state->file = NULL;
changed = TRUE;
}
if (directory->details->filesystem_info_state != NULL &&
directory->details->filesystem_info_state->file == file)
{
directory->details->filesystem_info_state->file = NULL;
changed = TRUE;
}
/* Let the directory take care of the rest. */
if (changed)
{
nautilus_directory_async_state_changed (directory);
}
}
static gboolean
lacks_directory_count (NautilusFile *file)
{
return !file->details->directory_count_is_up_to_date
&& nautilus_file_should_show_directory_item_count (file);
}
static gboolean
should_get_directory_count_now (NautilusFile *file)
{
return lacks_directory_count (file)
&& !file->details->loading_directory;
}
static gboolean
lacks_info (NautilusFile *file)
{
return !file->details->file_info_is_up_to_date
&& !file->details->is_gone;
}
static gboolean
lacks_filesystem_info (NautilusFile *file)
{
return !file->details->filesystem_info_is_up_to_date;
}
static gboolean
lacks_deep_count (NautilusFile *file)
{
return file->details->deep_counts_status != NAUTILUS_REQUEST_DONE;
}
static gboolean
lacks_mime_list (NautilusFile *file)
{
return !file->details->mime_list_is_up_to_date;
}
static gboolean
should_get_mime_list (NautilusFile *file)
{
return lacks_mime_list (file)
&& !file->details->loading_directory;
}
static gboolean
lacks_link_info (NautilusFile *file)
{
if (file->details->file_info_is_up_to_date &&
!file->details->link_info_is_up_to_date)
{
if (nautilus_file_is_nautilus_link (file))
{
return TRUE;
}
else
{
link_info_done (file->details->directory, file, NULL, NULL, NULL, FALSE, FALSE);
return FALSE;
}
}
else
{
return FALSE;
}
}
static gboolean
lacks_extension_info (NautilusFile *file)
{
return file->details->pending_info_providers != NULL;
}
static gboolean
lacks_thumbnail (NautilusFile *file)
{
return nautilus_file_should_show_thumbnail (file) &&
file->details->thumbnail_path != NULL &&
!file->details->thumbnail_is_up_to_date;
}
static gboolean
lacks_mount (NautilusFile *file)
{
return (!file->details->mount_is_up_to_date &&
(
/* Unix mountpoint, could be a GMount */
file->details->is_mountpoint ||
/* The toplevel directory of something */
(file->details->type == G_FILE_TYPE_DIRECTORY &&
nautilus_file_is_self_owned (file)) ||
/* Mountable, could be a mountpoint */
(file->details->type == G_FILE_TYPE_MOUNTABLE)
)
);
}
static gboolean
has_problem (NautilusDirectory *directory,
NautilusFile *file,
FileCheck problem)
{
GList *node;
if (file != NULL)
{
return (*problem)(file);
}
for (node = directory->details->file_list; node != NULL; node = node->next)
{
if ((*problem)(node->data))
{
return TRUE;
}
}
return FALSE;
}
static gboolean
request_is_satisfied (NautilusDirectory *directory,
NautilusFile *file,
Request request)
{
if (REQUEST_WANTS_TYPE (request, REQUEST_FILE_LIST) &&
!(directory->details->directory_loaded &&
directory->details->directory_loaded_sent_notification))
{
return FALSE;
}
if (REQUEST_WANTS_TYPE (request, REQUEST_DIRECTORY_COUNT))
{
if (has_problem (directory, file, lacks_directory_count))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_FILE_INFO))
{
if (has_problem (directory, file, lacks_info))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_FILESYSTEM_INFO))
{
if (has_problem (directory, file, lacks_filesystem_info))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_DEEP_COUNT))
{
if (has_problem (directory, file, lacks_deep_count))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_THUMBNAIL))
{
if (has_problem (directory, file, lacks_thumbnail))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_MOUNT))
{
if (has_problem (directory, file, lacks_mount))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_MIME_LIST))
{
if (has_problem (directory, file, lacks_mime_list))
{
return FALSE;
}
}
if (REQUEST_WANTS_TYPE (request, REQUEST_LINK_INFO))
{
if (has_problem (directory, file, lacks_link_info))
{
return FALSE;
}
}
return TRUE;
}
static gboolean
call_ready_callbacks_at_idle (gpointer callback_data)
{
NautilusDirectory *directory;
GList *node, *next;
ReadyCallback *callback;
directory = NAUTILUS_DIRECTORY (callback_data);
directory->details->call_ready_idle_id = 0;
nautilus_directory_ref (directory);
callback = NULL;
while (1)
{
/* Check if any callbacks are non-active and call them if they are. */
for (node = directory->details->call_when_ready_list;
node != NULL; node = next)
{
next = node->next;
callback = node->data;
if (!callback->active)
{
/* Non-active, remove and call */
break;
}
}
if (node == NULL)
{
break;
}
/* Callbacks are one-shots, so remove it now. */
remove_callback_link_keep_data (directory, node);
/* Call the callback. */
ready_callback_call (directory, callback);
g_free (callback);
}
nautilus_directory_async_state_changed (directory);
nautilus_directory_unref (directory);
return FALSE;
}
static void
schedule_call_ready_callbacks (NautilusDirectory *directory)
{
if (directory->details->call_ready_idle_id == 0)
{
directory->details->call_ready_idle_id
= g_idle_add (call_ready_callbacks_at_idle, directory);
}
}
/* Marks all callbacks that are ready as non-active and
* calls them at idle time, unless they are removed
* before then */
static gboolean
call_ready_callbacks (NautilusDirectory *directory)
{
gboolean found_any;
GList *node, *next;
ReadyCallback *callback;
found_any = FALSE;
/* Check if any callbacks are satisifed and mark them for call them if they are. */
for (node = directory->details->call_when_ready_list;
node != NULL; node = next)
{
next = node->next;
callback = node->data;
if (callback->active &&
request_is_satisfied (directory, callback->file, callback->request))
{
callback->active = FALSE;
found_any = TRUE;
}
}
if (found_any)
{
schedule_call_ready_callbacks (directory);
}
return found_any;
}
gboolean
nautilus_directory_has_active_request_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
GList *node;
ReadyCallback *callback;
Monitor *monitor;
for (node = directory->details->call_when_ready_list;
node != NULL; node = node->next)
{
callback = node->data;
if (callback->file == file ||
callback->file == NULL)
{
return TRUE;
}
}
for (node = directory->details->monitor_list;
node != NULL; node = node->next)
{
monitor = node->data;
if (monitor->file == file ||
monitor->file == NULL)
{
return TRUE;
}
}
return FALSE;
}
/* This checks if there's a request for monitoring the file list. */
gboolean
nautilus_directory_is_anyone_monitoring_file_list (NautilusDirectory *directory)
{
if (directory->details->call_when_ready_counters[REQUEST_FILE_LIST] > 0)
{
return TRUE;
}
if (directory->details->monitor_counters[REQUEST_FILE_LIST] > 0)
{
return TRUE;
}
return FALSE;
}
/* This checks if the file list being monitored. */
gboolean
nautilus_directory_is_file_list_monitored (NautilusDirectory *directory)
{
return directory->details->file_list_monitored;
}
static void
mark_all_files_unconfirmed (NautilusDirectory *directory)
{
GList *node;
NautilusFile *file;
for (node = directory->details->file_list; node != NULL; node = node->next)
{
file = node->data;
set_file_unconfirmed (file, TRUE);
}
}
static void
directory_load_state_free (DirectoryLoadState *state)
{
if (state->enumerator)
{
if (!g_file_enumerator_is_closed (state->enumerator))
{
g_file_enumerator_close_async (state->enumerator,
0, NULL, NULL, NULL);
}
g_object_unref (state->enumerator);
}
if (state->load_mime_list_hash != NULL)
{
istr_set_destroy (state->load_mime_list_hash);
}
nautilus_file_unref (state->load_directory_file);
g_object_unref (state->cancellable);
g_free (state);
}
static void
more_files_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DirectoryLoadState *state;
NautilusDirectory *directory;
GError *error;
GList *files, *l;
GFileInfo *info;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
directory_load_state_free (state);
return;
}
directory = nautilus_directory_ref (state->directory);
g_assert (directory->details->directory_load_in_progress != NULL);
g_assert (directory->details->directory_load_in_progress == state);
error = NULL;
files = g_file_enumerator_next_files_finish (state->enumerator,
res, &error);
for (l = files; l != NULL; l = l->next)
{
info = l->data;
directory_load_one (directory, info);
g_object_unref (info);
}
if (files == NULL)
{
directory_load_done (directory, error);
directory_load_state_free (state);
}
else
{
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_DEFAULT,
state->cancellable,
more_files_callback,
state);
}
nautilus_directory_unref (directory);
if (error)
{
g_error_free (error);
}
g_list_free (files);
}
static void
enumerate_children_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DirectoryLoadState *state;
GFileEnumerator *enumerator;
GError *error;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
directory_load_state_free (state);
return;
}
error = NULL;
enumerator = g_file_enumerate_children_finish (G_FILE (source_object),
res, &error);
if (enumerator == NULL)
{
directory_load_done (state->directory, error);
g_error_free (error);
directory_load_state_free (state);
return;
}
else
{
state->enumerator = enumerator;
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_DEFAULT,
state->cancellable,
more_files_callback,
state);
}
}
/* Start monitoring the file list if it isn't already. */
static void
start_monitoring_file_list (NautilusDirectory *directory)
{
DirectoryLoadState *state;
if (!directory->details->file_list_monitored)
{
g_assert (!directory->details->directory_load_in_progress);
directory->details->file_list_monitored = TRUE;
nautilus_file_list_ref (directory->details->file_list);
}
if (directory->details->directory_loaded ||
directory->details->directory_load_in_progress != NULL)
{
return;
}
if (!async_job_start (directory, "file list"))
{
return;
}
mark_all_files_unconfirmed (directory);
state = g_new0 (DirectoryLoadState, 1);
state->directory = directory;
state->cancellable = g_cancellable_new ();
state->load_mime_list_hash = istr_set_new ();
state->load_file_count = 0;
g_assert (directory->details->location != NULL);
state->load_directory_file =
nautilus_directory_get_corresponding_file (directory);
state->load_directory_file->details->loading_directory = TRUE;
#ifdef DEBUG_LOAD_DIRECTORY
g_message ("load_directory called to monitor file list of %p", directory->details->location);
#endif
directory->details->directory_load_in_progress = state;
g_file_enumerate_children_async (directory->details->location,
NAUTILUS_FILE_DEFAULT_ATTRIBUTES,
0, /* flags */
G_PRIORITY_DEFAULT, /* prio */
state->cancellable,
enumerate_children_callback,
state);
}
/* Stop monitoring the file list if it is being monitored. */
void
nautilus_directory_stop_monitoring_file_list (NautilusDirectory *directory)
{
if (!directory->details->file_list_monitored)
{
g_assert (directory->details->directory_load_in_progress == NULL);
return;
}
directory->details->file_list_monitored = FALSE;
file_list_cancel (directory);
nautilus_file_list_unref (directory->details->file_list);
directory->details->directory_loaded = FALSE;
}
static void
file_list_start_or_stop (NautilusDirectory *directory)
{
if (nautilus_directory_is_anyone_monitoring_file_list (directory))
{
start_monitoring_file_list (directory);
}
else
{
nautilus_directory_stop_monitoring_file_list (directory);
}
}
void
nautilus_file_invalidate_count_and_mime_list (NautilusFile *file)
{
NautilusFileAttributes attributes;
attributes = NAUTILUS_FILE_ATTRIBUTE_DIRECTORY_ITEM_COUNT |
NAUTILUS_FILE_ATTRIBUTE_DIRECTORY_ITEM_MIME_TYPES;
nautilus_file_invalidate_attributes (file, attributes);
}
/* Reset count and mime list. Invalidating deep counts is handled by
* itself elsewhere because it's a relatively heavyweight and
* special-purpose operation (see bug 5863). Also, the shallow count
* needs to be refreshed when filtering changes, but the deep count
* deliberately does not take filtering into account.
*/
void
nautilus_directory_invalidate_count_and_mime_list (NautilusDirectory *directory)
{
NautilusFile *file;
file = nautilus_directory_get_existing_corresponding_file (directory);
if (file != NULL)
{
nautilus_file_invalidate_count_and_mime_list (file);
}
nautilus_file_unref (file);
}
static void
nautilus_directory_invalidate_file_attributes (NautilusDirectory *directory,
NautilusFileAttributes file_attributes)
{
GList *node;
cancel_loading_attributes (directory, file_attributes);
for (node = directory->details->file_list; node != NULL; node = node->next)
{
nautilus_file_invalidate_attributes_internal (NAUTILUS_FILE (node->data),
file_attributes);
}
if (directory->details->as_file != NULL)
{
nautilus_file_invalidate_attributes_internal (directory->details->as_file,
file_attributes);
}
}
void
nautilus_directory_force_reload_internal (NautilusDirectory *directory,
NautilusFileAttributes file_attributes)
{
nautilus_profile_start (NULL);
/* invalidate attributes that are getting reloaded for all files */
nautilus_directory_invalidate_file_attributes (directory, file_attributes);
/* Start a new directory load. */
file_list_cancel (directory);
directory->details->directory_loaded = FALSE;
/* Start a new directory count. */
nautilus_directory_invalidate_count_and_mime_list (directory);
add_all_files_to_work_queue (directory);
nautilus_directory_async_state_changed (directory);
nautilus_profile_end (NULL);
}
static gboolean
monitor_includes_file (const Monitor *monitor,
NautilusFile *file)
{
if (monitor->file == file)
{
return TRUE;
}
if (monitor->file != NULL)
{
return FALSE;
}
if (file == file->details->directory->details->as_file)
{
return FALSE;
}
return nautilus_file_should_show (file,
monitor->monitor_hidden_files,
TRUE);
}
static gboolean
is_needy (NautilusFile *file,
FileCheck check_missing,
RequestType request_type_wanted)
{
NautilusDirectory *directory;
GList *node;
ReadyCallback *callback;
Monitor *monitor;
if (!(*check_missing)(file))
{
return FALSE;
}
directory = file->details->directory;
if (directory->details->call_when_ready_counters[request_type_wanted] > 0)
{
for (node = directory->details->call_when_ready_list;
node != NULL; node = node->next)
{
callback = node->data;
if (callback->active &&
REQUEST_WANTS_TYPE (callback->request, request_type_wanted))
{
if (callback->file == file)
{
return TRUE;
}
if (callback->file == NULL
&& file != directory->details->as_file)
{
return TRUE;
}
}
}
}
if (directory->details->monitor_counters[request_type_wanted] > 0)
{
for (node = directory->details->monitor_list;
node != NULL; node = node->next)
{
monitor = node->data;
if (REQUEST_WANTS_TYPE (monitor->request, request_type_wanted))
{
if (monitor_includes_file (monitor, file))
{
return TRUE;
}
}
}
}
return FALSE;
}
static void
directory_count_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->count_in_progress != NULL)
{
file = directory->details->count_in_progress->count_file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
should_get_directory_count_now,
REQUEST_DIRECTORY_COUNT))
{
return;
}
}
/* The count is not wanted, so stop it. */
directory_count_cancel (directory);
}
}
static guint
count_non_skipped_files (GList *list)
{
guint count;
GList *node;
GFileInfo *info;
count = 0;
for (node = list; node != NULL; node = node->next)
{
info = node->data;
if (!should_skip_file (NULL, info))
{
count += 1;
}
}
return count;
}
static void
count_children_done (NautilusDirectory *directory,
NautilusFile *count_file,
gboolean succeeded,
int count)
{
g_assert (NAUTILUS_IS_FILE (count_file));
count_file->details->directory_count_is_up_to_date = TRUE;
/* Record either a failure or success. */
if (!succeeded)
{
count_file->details->directory_count_failed = TRUE;
count_file->details->got_directory_count = FALSE;
count_file->details->directory_count = 0;
}
else
{
count_file->details->directory_count_failed = FALSE;
count_file->details->got_directory_count = TRUE;
count_file->details->directory_count = count;
}
directory->details->count_in_progress = NULL;
/* Send file-changed even if count failed, so interested parties can
* distinguish between unknowable and not-yet-known cases.
*/
nautilus_file_changed (count_file);
/* Start up the next one. */
async_job_end (directory, "directory count");
nautilus_directory_async_state_changed (directory);
}
static void
directory_count_state_free (DirectoryCountState *state)
{
if (state->enumerator)
{
if (!g_file_enumerator_is_closed (state->enumerator))
{
g_file_enumerator_close_async (state->enumerator,
0, NULL, NULL, NULL);
}
g_object_unref (state->enumerator);
}
g_object_unref (state->cancellable);
nautilus_directory_unref (state->directory);
g_free (state);
}
static void
count_more_files_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DirectoryCountState *state;
NautilusDirectory *directory;
GError *error;
GList *files;
state = user_data;
directory = state->directory;
if (g_cancellable_is_cancelled (state->cancellable))
{
/* Operation was cancelled. Bail out */
async_job_end (directory, "directory count");
nautilus_directory_async_state_changed (directory);
directory_count_state_free (state);
return;
}
g_assert (directory->details->count_in_progress != NULL);
g_assert (directory->details->count_in_progress == state);
error = NULL;
files = g_file_enumerator_next_files_finish (state->enumerator,
res, &error);
state->file_count += count_non_skipped_files (files);
if (files == NULL)
{
count_children_done (directory, state->count_file,
TRUE, state->file_count);
directory_count_state_free (state);
}
else
{
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_DEFAULT,
state->cancellable,
count_more_files_callback,
state);
}
g_list_free_full (files, g_object_unref);
if (error)
{
g_error_free (error);
}
}
static void
count_children_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DirectoryCountState *state;
GFileEnumerator *enumerator;
NautilusDirectory *directory;
GError *error;
state = user_data;
if (g_cancellable_is_cancelled (state->cancellable))
{
/* Operation was cancelled. Bail out */
directory = state->directory;
async_job_end (directory, "directory count");
nautilus_directory_async_state_changed (directory);
directory_count_state_free (state);
return;
}
error = NULL;
enumerator = g_file_enumerate_children_finish (G_FILE (source_object),
res, &error);
if (enumerator == NULL)
{
count_children_done (state->directory,
state->count_file,
FALSE, 0);
g_error_free (error);
directory_count_state_free (state);
return;
}
else
{
state->enumerator = enumerator;
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_DEFAULT,
state->cancellable,
count_more_files_callback,
state);
}
}
static void
directory_count_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
DirectoryCountState *state;
GFile *location;
if (directory->details->count_in_progress != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file,
should_get_directory_count_now,
REQUEST_DIRECTORY_COUNT))
{
return;
}
*doing_io = TRUE;
if (!nautilus_file_is_directory (file))
{
file->details->directory_count_is_up_to_date = TRUE;
file->details->directory_count_failed = FALSE;
file->details->got_directory_count = FALSE;
nautilus_directory_async_state_changed (directory);
return;
}
if (!async_job_start (directory, "directory count"))
{
return;
}
/* Start counting. */
state = g_new0 (DirectoryCountState, 1);
state->count_file = file;
state->directory = nautilus_directory_ref (directory);
state->cancellable = g_cancellable_new ();
directory->details->count_in_progress = state;
location = nautilus_file_get_location (file);
#ifdef DEBUG_LOAD_DIRECTORY
{
char *uri;
uri = g_file_get_uri (location);
g_message ("load_directory called to get shallow file count for %s", uri);
g_free (uri);
}
#endif
g_file_enumerate_children_async (location,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN ","
G_FILE_ATTRIBUTE_STANDARD_IS_BACKUP,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, /* flags */
G_PRIORITY_DEFAULT, /* prio */
state->cancellable,
count_children_callback,
state);
g_object_unref (location);
}
static inline gboolean
seen_inode (DeepCountState *state,
GFileInfo *info)
{
guint64 inode, inode2;
guint i;
inode = g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_UNIX_INODE);
if (inode != 0)
{
for (i = 0; i < state->seen_deep_count_inodes->len; i++)
{
inode2 = g_array_index (state->seen_deep_count_inodes, guint64, i);
if (inode == inode2)
{
return TRUE;
}
}
}
return FALSE;
}
static inline void
mark_inode_as_seen (DeepCountState *state,
GFileInfo *info)
{
guint64 inode;
inode = g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_UNIX_INODE);
if (inode != 0)
{
g_array_append_val (state->seen_deep_count_inodes, inode);
}
}
static void
deep_count_one (DeepCountState *state,
GFileInfo *info)
{
NautilusFile *file;
GFile *subdir;
gboolean is_seen_inode;
const char *fs_id;
if (should_skip_file (NULL, info))
{
return;
}
is_seen_inode = seen_inode (state, info);
if (!is_seen_inode)
{
mark_inode_as_seen (state, info);
}
file = state->directory->details->deep_count_file;
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
/* Count the directory. */
file->details->deep_directory_count += 1;
/* Record the fact that we have to descend into this directory. */
fs_id = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_ID_FILESYSTEM);
if (g_strcmp0 (fs_id, state->fs_id) == 0)
{
/* only if it is on the same filesystem */
subdir = g_file_get_child (state->deep_count_location, g_file_info_get_name (info));
state->deep_count_subdirectories = g_list_prepend
(state->deep_count_subdirectories, subdir);
}
}
else
{
/* Even non-regular files count as files. */
file->details->deep_file_count += 1;
}
/* Count the size. */
if (!is_seen_inode && g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_SIZE))
{
file->details->deep_size += g_file_info_get_size (info);
}
}
static void
deep_count_state_free (DeepCountState *state)
{
if (state->enumerator)
{
if (!g_file_enumerator_is_closed (state->enumerator))
{
g_file_enumerator_close_async (state->enumerator,
0, NULL, NULL, NULL);
}
g_object_unref (state->enumerator);
}
g_object_unref (state->cancellable);
if (state->deep_count_location)
{
g_object_unref (state->deep_count_location);
}
g_list_free_full (state->deep_count_subdirectories, g_object_unref);
g_array_free (state->seen_deep_count_inodes, TRUE);
g_free (state->fs_id);
g_free (state);
}
static void
deep_count_next_dir (DeepCountState *state)
{
GFile *location;
NautilusFile *file;
NautilusDirectory *directory;
gboolean done;
directory = state->directory;
g_object_unref (state->deep_count_location);
state->deep_count_location = NULL;
done = FALSE;
file = directory->details->deep_count_file;
if (state->deep_count_subdirectories != NULL)
{
/* Work on a new directory. */
location = state->deep_count_subdirectories->data;
state->deep_count_subdirectories = g_list_remove
(state->deep_count_subdirectories, location);
deep_count_load (state, location);
g_object_unref (location);
}
else
{
file->details->deep_counts_status = NAUTILUS_REQUEST_DONE;
directory->details->deep_count_file = NULL;
directory->details->deep_count_in_progress = NULL;
deep_count_state_free (state);
done = TRUE;
}
nautilus_file_updated_deep_count_in_progress (file);
if (done)
{
nautilus_file_changed (file);
async_job_end (directory, "deep count");
nautilus_directory_async_state_changed (directory);
}
}
static void
deep_count_more_files_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DeepCountState *state;
NautilusDirectory *directory;
GList *files, *l;
GFileInfo *info;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
deep_count_state_free (state);
return;
}
directory = nautilus_directory_ref (state->directory);
g_assert (directory->details->deep_count_in_progress != NULL);
g_assert (directory->details->deep_count_in_progress == state);
files = g_file_enumerator_next_files_finish (state->enumerator,
res, NULL);
for (l = files; l != NULL; l = l->next)
{
info = l->data;
deep_count_one (state, info);
g_object_unref (info);
}
if (files == NULL)
{
g_file_enumerator_close_async (state->enumerator, 0, NULL, NULL, NULL);
g_object_unref (state->enumerator);
state->enumerator = NULL;
deep_count_next_dir (state);
}
else
{
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_LOW,
state->cancellable,
deep_count_more_files_callback,
state);
}
g_list_free (files);
nautilus_directory_unref (directory);
}
static void
deep_count_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DeepCountState *state;
GFileEnumerator *enumerator;
NautilusFile *file;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
deep_count_state_free (state);
return;
}
file = state->directory->details->deep_count_file;
enumerator = g_file_enumerate_children_finish (G_FILE (source_object), res, NULL);
if (enumerator == NULL)
{
file->details->deep_unreadable_count += 1;
deep_count_next_dir (state);
}
else
{
state->enumerator = enumerator;
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_LOW,
state->cancellable,
deep_count_more_files_callback,
state);
}
}
static void
deep_count_load (DeepCountState *state,
GFile *location)
{
state->deep_count_location = g_object_ref (location);
#ifdef DEBUG_LOAD_DIRECTORY
g_message ("load_directory called to get deep file count for %p", location);
#endif
g_file_enumerate_children_async (state->deep_count_location,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE ","
G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN ","
G_FILE_ATTRIBUTE_STANDARD_IS_BACKUP ","
G_FILE_ATTRIBUTE_ID_FILESYSTEM ","
G_FILE_ATTRIBUTE_UNIX_INODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, /* flags */
G_PRIORITY_LOW, /* prio */
state->cancellable,
deep_count_callback,
state);
}
static void
deep_count_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->deep_count_in_progress != NULL)
{
file = directory->details->deep_count_file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
lacks_deep_count,
REQUEST_DEEP_COUNT))
{
return;
}
}
/* The count is not wanted, so stop it. */
deep_count_cancel (directory);
}
}
static void
deep_count_got_info (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
GFileInfo *info;
const char *id;
GFile *file = (GFile *) source_object;
DeepCountState *state = (DeepCountState *) user_data;
info = g_file_query_info_finish (file, res, NULL);
if (info != NULL)
{
id = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_ID_FILESYSTEM);
state->fs_id = g_strdup (id);
g_object_unref (info);
}
deep_count_load (state, file);
}
static void
deep_count_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
GFile *location;
DeepCountState *state;
if (directory->details->deep_count_in_progress != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file,
lacks_deep_count,
REQUEST_DEEP_COUNT))
{
return;
}
*doing_io = TRUE;
if (!nautilus_file_is_directory (file))
{
file->details->deep_counts_status = NAUTILUS_REQUEST_DONE;
nautilus_directory_async_state_changed (directory);
return;
}
if (!async_job_start (directory, "deep count"))
{
return;
}
/* Start counting. */
file->details->deep_counts_status = NAUTILUS_REQUEST_IN_PROGRESS;
file->details->deep_directory_count = 0;
file->details->deep_file_count = 0;
file->details->deep_unreadable_count = 0;
file->details->deep_size = 0;
directory->details->deep_count_file = file;
state = g_new0 (DeepCountState, 1);
state->directory = directory;
state->cancellable = g_cancellable_new ();
state->seen_deep_count_inodes = g_array_new (FALSE, TRUE, sizeof (guint64));
state->fs_id = NULL;
directory->details->deep_count_in_progress = state;
location = nautilus_file_get_location (file);
g_file_query_info_async (location,
G_FILE_ATTRIBUTE_ID_FILESYSTEM,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
G_PRIORITY_DEFAULT,
NULL,
deep_count_got_info,
state);
g_object_unref (location);
}
static void
mime_list_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->mime_list_in_progress != NULL)
{
file = directory->details->mime_list_in_progress->mime_list_file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
should_get_mime_list,
REQUEST_MIME_LIST))
{
return;
}
}
/* The count is not wanted, so stop it. */
mime_list_cancel (directory);
}
}
static void
mime_list_state_free (MimeListState *state)
{
if (state->enumerator)
{
if (!g_file_enumerator_is_closed (state->enumerator))
{
g_file_enumerator_close_async (state->enumerator,
0, NULL, NULL, NULL);
}
g_object_unref (state->enumerator);
}
g_object_unref (state->cancellable);
istr_set_destroy (state->mime_list_hash);
nautilus_directory_unref (state->directory);
g_free (state);
}
static void
mime_list_done (MimeListState *state,
gboolean success)
{
NautilusFile *file;
NautilusDirectory *directory;
directory = state->directory;
g_assert (directory != NULL);
file = state->mime_list_file;
file->details->mime_list_is_up_to_date = TRUE;
g_list_free_full (file->details->mime_list, g_free);
if (success)
{
file->details->mime_list_failed = TRUE;
file->details->mime_list = NULL;
}
else
{
file->details->got_mime_list = TRUE;
file->details->mime_list = istr_set_get_as_list (state->mime_list_hash);
}
directory->details->mime_list_in_progress = NULL;
/* Send file-changed even if getting the item type list
* failed, so interested parties can distinguish between
* unknowable and not-yet-known cases.
*/
nautilus_file_changed (file);
/* Start up the next one. */
async_job_end (directory, "MIME list");
nautilus_directory_async_state_changed (directory);
}
static void
mime_list_one (MimeListState *state,
GFileInfo *info)
{
const char *mime_type;
if (should_skip_file (NULL, info))
{
g_object_unref (info);
return;
}
mime_type = g_file_info_get_content_type (info);
if (mime_type != NULL)
{
istr_set_insert (state->mime_list_hash, mime_type);
}
}
static void
mime_list_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MimeListState *state;
NautilusDirectory *directory;
GError *error;
GList *files, *l;
GFileInfo *info;
state = user_data;
directory = state->directory;
if (g_cancellable_is_cancelled (state->cancellable))
{
/* Operation was cancelled. Bail out */
directory->details->mime_list_in_progress = NULL;
async_job_end (directory, "MIME list");
nautilus_directory_async_state_changed (directory);
mime_list_state_free (state);
return;
}
g_assert (directory->details->mime_list_in_progress != NULL);
g_assert (directory->details->mime_list_in_progress == state);
error = NULL;
files = g_file_enumerator_next_files_finish (state->enumerator,
res, &error);
for (l = files; l != NULL; l = l->next)
{
info = l->data;
mime_list_one (state, info);
g_object_unref (info);
}
if (files == NULL)
{
mime_list_done (state, error != NULL);
mime_list_state_free (state);
}
else
{
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_DEFAULT,
state->cancellable,
mime_list_callback,
state);
}
g_list_free (files);
if (error)
{
g_error_free (error);
}
}
static void
list_mime_enum_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MimeListState *state;
GFileEnumerator *enumerator;
NautilusDirectory *directory;
GError *error;
state = user_data;
if (g_cancellable_is_cancelled (state->cancellable))
{
/* Operation was cancelled. Bail out */
directory = state->directory;
directory->details->mime_list_in_progress = NULL;
async_job_end (directory, "MIME list");
nautilus_directory_async_state_changed (directory);
mime_list_state_free (state);
return;
}
error = NULL;
enumerator = g_file_enumerate_children_finish (G_FILE (source_object),
res, &error);
if (enumerator == NULL)
{
mime_list_done (state, FALSE);
g_error_free (error);
mime_list_state_free (state);
return;
}
else
{
state->enumerator = enumerator;
g_file_enumerator_next_files_async (state->enumerator,
DIRECTORY_LOAD_ITEMS_PER_CALLBACK,
G_PRIORITY_DEFAULT,
state->cancellable,
mime_list_callback,
state);
}
}
static void
mime_list_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
MimeListState *state;
GFile *location;
mime_list_stop (directory);
if (directory->details->mime_list_in_progress != NULL)
{
*doing_io = TRUE;
return;
}
/* Figure out which file to get a mime list for. */
if (!is_needy (file,
should_get_mime_list,
REQUEST_MIME_LIST))
{
return;
}
*doing_io = TRUE;
if (!nautilus_file_is_directory (file))
{
g_list_free (file->details->mime_list);
file->details->mime_list_failed = FALSE;
file->details->got_mime_list = FALSE;
file->details->mime_list_is_up_to_date = TRUE;
nautilus_directory_async_state_changed (directory);
return;
}
if (!async_job_start (directory, "MIME list"))
{
return;
}
state = g_new0 (MimeListState, 1);
state->mime_list_file = file;
state->directory = nautilus_directory_ref (directory);
state->cancellable = g_cancellable_new ();
state->mime_list_hash = istr_set_new ();
directory->details->mime_list_in_progress = state;
location = nautilus_file_get_location (file);
#ifdef DEBUG_LOAD_DIRECTORY
{
char *uri;
uri = g_file_get_uri (location);
g_message ("load_directory called to get MIME list of %s", uri);
g_free (uri);
}
#endif
g_file_enumerate_children_async (location,
G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
0, /* flags */
G_PRIORITY_LOW, /* prio */
state->cancellable,
list_mime_enum_callback,
state);
g_object_unref (location);
}
static void
get_info_state_free (GetInfoState *state)
{
g_object_unref (state->cancellable);
g_free (state);
}
static void
query_info_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
NautilusDirectory *directory;
NautilusFile *get_info_file;
GFileInfo *info;
GetInfoState *state;
GError *error;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
get_info_state_free (state);
return;
}
directory = nautilus_directory_ref (state->directory);
get_info_file = directory->details->get_info_file;
g_assert (NAUTILUS_IS_FILE (get_info_file));
directory->details->get_info_file = NULL;
directory->details->get_info_in_progress = NULL;
/* ref here because we might be removing the last ref when we
* mark the file gone below, but we need to keep a ref at
* least long enough to send the change notification.
*/
nautilus_file_ref (get_info_file);
error = NULL;
info = g_file_query_info_finish (G_FILE (source_object), res, &error);
if (info == NULL)
{
if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_NOT_FOUND)
{
/* mark file as gone */
nautilus_file_mark_gone (get_info_file);
}
get_info_file->details->file_info_is_up_to_date = TRUE;
nautilus_file_clear_info (get_info_file);
get_info_file->details->get_info_failed = TRUE;
get_info_file->details->get_info_error = error;
}
else
{
nautilus_file_update_info (get_info_file, info);
g_object_unref (info);
}
nautilus_file_changed (get_info_file);
nautilus_file_unref (get_info_file);
async_job_end (directory, "file info");
nautilus_directory_async_state_changed (directory);
nautilus_directory_unref (directory);
get_info_state_free (state);
}
static void
file_info_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->get_info_in_progress != NULL)
{
file = directory->details->get_info_file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file, lacks_info, REQUEST_FILE_INFO))
{
return;
}
}
/* The info is not wanted, so stop it. */
file_info_cancel (directory);
}
}
static void
file_info_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
GFile *location;
GetInfoState *state;
file_info_stop (directory);
if (directory->details->get_info_in_progress != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file, lacks_info, REQUEST_FILE_INFO))
{
return;
}
*doing_io = TRUE;
if (!async_job_start (directory, "file info"))
{
return;
}
directory->details->get_info_file = file;
file->details->get_info_failed = FALSE;
if (file->details->get_info_error)
{
g_error_free (file->details->get_info_error);
file->details->get_info_error = NULL;
}
state = g_new (GetInfoState, 1);
state->directory = directory;
state->cancellable = g_cancellable_new ();
directory->details->get_info_in_progress = state;
location = nautilus_file_get_location (file);
g_file_query_info_async (location,
NAUTILUS_FILE_DEFAULT_ATTRIBUTES,
0,
G_PRIORITY_DEFAULT,
state->cancellable, query_info_callback, state);
g_object_unref (location);
}
static gboolean
is_link_trusted (NautilusFile *file,
gboolean is_launcher)
{
GFile *location;
gboolean res;
if (!is_launcher)
{
return TRUE;
}
if (nautilus_file_can_execute (file))
{
return TRUE;
}
res = FALSE;
if (nautilus_file_is_local (file))
{
location = nautilus_file_get_location (file);
res = nautilus_is_in_system_dir (location);
g_object_unref (location);
}
return res;
}
static void
link_info_done (NautilusDirectory *directory,
NautilusFile *file,
const char *uri,
const char *name,
GIcon *icon,
gboolean is_launcher,
gboolean is_foreign)
{
gboolean is_trusted;
file->details->link_info_is_up_to_date = TRUE;
is_trusted = is_link_trusted (file, is_launcher);
if (is_trusted)
{
nautilus_file_set_display_name (file, name, name, TRUE);
}
else
{
nautilus_file_set_display_name (file, NULL, NULL, TRUE);
}
file->details->got_link_info = TRUE;
g_clear_object (&file->details->custom_icon);
if (uri)
{
g_free (file->details->activation_uri);
file->details->activation_uri = NULL;
file->details->got_custom_activation_uri = TRUE;
file->details->activation_uri = g_strdup (uri);
}
if (is_trusted && (icon != NULL))
{
file->details->custom_icon = g_object_ref (icon);
}
file->details->is_launcher = is_launcher;
file->details->is_foreign_link = is_foreign;
file->details->is_trusted_link = is_trusted;
nautilus_directory_async_state_changed (directory);
}
static void
link_info_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->link_info_read_state != NULL)
{
file = directory->details->link_info_read_state->file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
lacks_link_info,
REQUEST_LINK_INFO))
{
return;
}
}
/* The link info is not wanted, so stop it. */
link_info_cancel (directory);
}
}
static void
link_info_got_data (NautilusDirectory *directory,
NautilusFile *file,
gboolean result,
goffset bytes_read,
char *file_contents)
{
char *link_uri, *uri, *name;
GIcon *icon;
gboolean is_launcher;
gboolean is_foreign;
nautilus_directory_ref (directory);
uri = NULL;
name = NULL;
icon = NULL;
is_launcher = FALSE;
is_foreign = FALSE;
/* Handle the case where we read the Nautilus link. */
if (result)
{
link_uri = nautilus_file_get_uri (file);
nautilus_link_get_link_info_given_file_contents (file_contents, bytes_read, link_uri,
&uri, &name, &icon, &is_launcher, &is_foreign);
g_free (link_uri);
}
else
{
/* FIXME bugzilla.gnome.org 42433: We should report this error to the user. */
}
nautilus_file_ref (file);
link_info_done (directory, file, uri, name, icon, is_launcher, is_foreign);
nautilus_file_changed (file);
nautilus_file_unref (file);
g_free (uri);
g_free (name);
if (icon != NULL)
{
g_object_unref (icon);
}
nautilus_directory_unref (directory);
}
static void
link_info_read_state_free (LinkInfoReadState *state)
{
g_object_unref (state->cancellable);
g_free (state);
}
static void
link_info_nautilus_link_read_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
LinkInfoReadState *state;
gsize file_size;
char *file_contents;
gboolean result;
NautilusDirectory *directory;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
link_info_read_state_free (state);
return;
}
directory = nautilus_directory_ref (state->directory);
result = g_file_load_contents_finish (G_FILE (source_object),
res,
&file_contents, &file_size,
NULL, NULL);
state->directory->details->link_info_read_state = NULL;
async_job_end (state->directory, "link info");
link_info_got_data (state->directory, state->file, result, file_size, file_contents);
if (result)
{
g_free (file_contents);
}
link_info_read_state_free (state);
nautilus_directory_unref (directory);
}
static void
link_info_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
GFile *location;
gboolean nautilus_style_link;
LinkInfoReadState *state;
if (directory->details->link_info_read_state != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file,
lacks_link_info,
REQUEST_LINK_INFO))
{
return;
}
*doing_io = TRUE;
/* Figure out if it is a link. */
nautilus_style_link = nautilus_file_is_nautilus_link (file);
location = nautilus_file_get_location (file);
/* If it's not a link we are done. If it is, we need to read it. */
if (!nautilus_style_link)
{
link_info_done (directory, file, NULL, NULL, NULL, FALSE, FALSE);
}
else
{
if (!async_job_start (directory, "link info"))
{
g_object_unref (location);
return;
}
state = g_new0 (LinkInfoReadState, 1);
state->directory = directory;
state->file = file;
state->cancellable = g_cancellable_new ();
directory->details->link_info_read_state = state;
g_file_load_contents_async (location,
state->cancellable,
link_info_nautilus_link_read_callback,
state);
}
g_object_unref (location);
}
static void
thumbnail_done (NautilusDirectory *directory,
NautilusFile *file,
GdkPixbuf *pixbuf,
gboolean tried_original)
{
const char *thumb_mtime_str;
time_t thumb_mtime = 0;
file->details->thumbnail_is_up_to_date = TRUE;
file->details->thumbnail_tried_original = tried_original;
if (file->details->thumbnail)
{
g_object_unref (file->details->thumbnail);
file->details->thumbnail = NULL;
}
if (file->details->scaled_thumbnail)
{
g_object_unref (file->details->scaled_thumbnail);
file->details->scaled_thumbnail = NULL;
}
if (pixbuf)
{
if (tried_original)
{
thumb_mtime = file->details->mtime;
}
else
{
thumb_mtime_str = gdk_pixbuf_get_option (pixbuf, "tEXt::Thumb::MTime");
if (thumb_mtime_str)
{
thumb_mtime = atol (thumb_mtime_str);
}
}
if (thumb_mtime == 0 ||
thumb_mtime == file->details->mtime)
{
file->details->thumbnail = g_object_ref (pixbuf);
file->details->thumbnail_mtime = thumb_mtime;
}
else
{
g_free (file->details->thumbnail_path);
file->details->thumbnail_path = NULL;
}
}
nautilus_directory_async_state_changed (directory);
}
static void
thumbnail_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->thumbnail_state != NULL)
{
file = directory->details->thumbnail_state->file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
lacks_thumbnail,
REQUEST_THUMBNAIL))
{
return;
}
}
/* The link info is not wanted, so stop it. */
thumbnail_cancel (directory);
}
}
static void
thumbnail_got_pixbuf (NautilusDirectory *directory,
NautilusFile *file,
GdkPixbuf *pixbuf,
gboolean tried_original)
{
nautilus_directory_ref (directory);
nautilus_file_ref (file);
thumbnail_done (directory, file, pixbuf, tried_original);
nautilus_file_changed (file);
nautilus_file_unref (file);
if (pixbuf)
{
g_object_unref (pixbuf);
}
nautilus_directory_unref (directory);
}
static void
thumbnail_state_free (ThumbnailState *state)
{
g_object_unref (state->cancellable);
g_free (state);
}
extern int cached_thumbnail_size;
/* scale very large images down to the max. size we need */
static void
thumbnail_loader_size_prepared (GdkPixbufLoader *loader,
int width,
int height,
gpointer user_data)
{
int max_thumbnail_size;
double aspect_ratio;
aspect_ratio = ((double) width) / height;
/* cf. nautilus_file_get_icon() */
max_thumbnail_size = NAUTILUS_CANVAS_ICON_SIZE_LARGER * cached_thumbnail_size / NAUTILUS_CANVAS_ICON_SIZE_SMALL;
if (MAX (width, height) > max_thumbnail_size)
{
if (width > height)
{
width = max_thumbnail_size;
height = width / aspect_ratio;
}
else
{
height = max_thumbnail_size;
width = height * aspect_ratio;
}
gdk_pixbuf_loader_set_size (loader, width, height);
}
}
static GdkPixbuf *
get_pixbuf_for_content (goffset file_len,
char *file_contents)
{
gboolean res;
GdkPixbuf *pixbuf, *pixbuf2;
GdkPixbufLoader *loader;
gsize chunk_len;
pixbuf = NULL;
loader = gdk_pixbuf_loader_new ();
g_signal_connect (loader, "size-prepared",
G_CALLBACK (thumbnail_loader_size_prepared),
NULL);
/* For some reason we have to write in chunks, or gdk-pixbuf fails */
res = TRUE;
while (res && file_len > 0)
{
chunk_len = file_len;
res = gdk_pixbuf_loader_write (loader, (guchar *) file_contents, chunk_len, NULL);
file_contents += chunk_len;
file_len -= chunk_len;
}
if (res)
{
res = gdk_pixbuf_loader_close (loader, NULL);
}
if (res)
{
pixbuf = g_object_ref (gdk_pixbuf_loader_get_pixbuf (loader));
}
g_object_unref (G_OBJECT (loader));
if (pixbuf)
{
pixbuf2 = gdk_pixbuf_apply_embedded_orientation (pixbuf);
g_object_unref (pixbuf);
pixbuf = pixbuf2;
}
return pixbuf;
}
static void
thumbnail_read_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
ThumbnailState *state;
gsize file_size;
char *file_contents;
gboolean result;
NautilusDirectory *directory;
GdkPixbuf *pixbuf;
GFile *location;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
thumbnail_state_free (state);
return;
}
directory = nautilus_directory_ref (state->directory);
result = g_file_load_contents_finish (G_FILE (source_object),
res,
&file_contents, &file_size,
NULL, NULL);
pixbuf = NULL;
if (result)
{
pixbuf = get_pixbuf_for_content (file_size, file_contents);
g_free (file_contents);
}
if (pixbuf == NULL && state->trying_original)
{
state->trying_original = FALSE;
location = g_file_new_for_path (state->file->details->thumbnail_path);
g_file_load_contents_async (location,
state->cancellable,
thumbnail_read_callback,
state);
g_object_unref (location);
}
else
{
state->directory->details->thumbnail_state = NULL;
async_job_end (state->directory, "thumbnail");
thumbnail_got_pixbuf (state->directory, state->file, pixbuf, state->tried_original);
thumbnail_state_free (state);
}
nautilus_directory_unref (directory);
}
static void
thumbnail_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
GFile *location;
ThumbnailState *state;
if (directory->details->thumbnail_state != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file,
lacks_thumbnail,
REQUEST_THUMBNAIL))
{
return;
}
*doing_io = TRUE;
if (!async_job_start (directory, "thumbnail"))
{
return;
}
state = g_new0 (ThumbnailState, 1);
state->directory = directory;
state->file = file;
state->cancellable = g_cancellable_new ();
if (file->details->thumbnail_wants_original)
{
state->tried_original = TRUE;
state->trying_original = TRUE;
location = nautilus_file_get_location (file);
}
else
{
location = g_file_new_for_path (file->details->thumbnail_path);
}
directory->details->thumbnail_state = state;
g_file_load_contents_async (location,
state->cancellable,
thumbnail_read_callback,
state);
g_object_unref (location);
}
static void
mount_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->mount_state != NULL)
{
file = directory->details->mount_state->file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
lacks_mount,
REQUEST_MOUNT))
{
return;
}
}
/* The link info is not wanted, so stop it. */
mount_cancel (directory);
}
}
static void
mount_state_free (MountState *state)
{
g_object_unref (state->cancellable);
g_free (state);
}
static void
got_mount (MountState *state,
GMount *mount)
{
NautilusDirectory *directory;
NautilusFile *file;
directory = nautilus_directory_ref (state->directory);
state->directory->details->mount_state = NULL;
async_job_end (state->directory, "mount");
file = nautilus_file_ref (state->file);
file->details->mount_is_up_to_date = TRUE;
nautilus_file_set_mount (file, mount);
nautilus_directory_async_state_changed (directory);
nautilus_file_changed (file);
nautilus_file_unref (file);
nautilus_directory_unref (directory);
mount_state_free (state);
}
static void
find_enclosing_mount_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
GMount *mount;
MountState *state;
GFile *location, *root;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
mount_state_free (state);
return;
}
mount = g_file_find_enclosing_mount_finish (G_FILE (source_object),
res, NULL);
if (mount)
{
root = g_mount_get_root (mount);
location = nautilus_file_get_location (state->file);
if (!g_file_equal (location, root))
{
g_object_unref (mount);
mount = NULL;
}
g_object_unref (root);
g_object_unref (location);
}
got_mount (state, mount);
if (mount)
{
g_object_unref (mount);
}
}
static GMount *
get_mount_at (GFile *target)
{
GVolumeMonitor *monitor;
GFile *root;
GList *mounts, *l;
GMount *found;
monitor = g_volume_monitor_get ();
mounts = g_volume_monitor_get_mounts (monitor);
found = NULL;
for (l = mounts; l != NULL; l = l->next)
{
GMount *mount = G_MOUNT (l->data);
if (g_mount_is_shadowed (mount))
{
continue;
}
root = g_mount_get_root (mount);
if (g_file_equal (target, root))
{
found = g_object_ref (mount);
break;
}
g_object_unref (root);
}
g_list_free_full (mounts, g_object_unref);
g_object_unref (monitor);
return found;
}
static void
mount_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
GFile *location;
MountState *state;
if (directory->details->mount_state != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file,
lacks_mount,
REQUEST_MOUNT))
{
return;
}
*doing_io = TRUE;
if (!async_job_start (directory, "mount"))
{
return;
}
state = g_new0 (MountState, 1);
state->directory = directory;
state->file = file;
state->cancellable = g_cancellable_new ();
location = nautilus_file_get_location (file);
directory->details->mount_state = state;
if (file->details->type == G_FILE_TYPE_MOUNTABLE)
{
GFile *target;
GMount *mount;
mount = NULL;
target = nautilus_file_get_activation_location (file);
if (target != NULL)
{
mount = get_mount_at (target);
g_object_unref (target);
}
got_mount (state, mount);
if (mount)
{
g_object_unref (mount);
}
}
else
{
g_file_find_enclosing_mount_async (location,
G_PRIORITY_DEFAULT,
state->cancellable,
find_enclosing_mount_callback,
state);
}
g_object_unref (location);
}
static void
filesystem_info_cancel (NautilusDirectory *directory)
{
if (directory->details->filesystem_info_state != NULL)
{
g_cancellable_cancel (directory->details->filesystem_info_state->cancellable);
directory->details->filesystem_info_state->directory = NULL;
directory->details->filesystem_info_state = NULL;
async_job_end (directory, "filesystem info");
}
}
static void
filesystem_info_stop (NautilusDirectory *directory)
{
NautilusFile *file;
if (directory->details->filesystem_info_state != NULL)
{
file = directory->details->filesystem_info_state->file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file,
lacks_filesystem_info,
REQUEST_FILESYSTEM_INFO))
{
return;
}
}
/* The filesystem info is not wanted, so stop it. */
filesystem_info_cancel (directory);
}
}
static void
filesystem_info_state_free (FilesystemInfoState *state)
{
g_object_unref (state->cancellable);
g_free (state);
}
static void
got_filesystem_info (FilesystemInfoState *state,
GFileInfo *info)
{
NautilusDirectory *directory;
NautilusFile *file;
const char *filesystem_type;
/* careful here, info may be NULL */
directory = nautilus_directory_ref (state->directory);
state->directory->details->filesystem_info_state = NULL;
async_job_end (state->directory, "filesystem info");
file = nautilus_file_ref (state->file);
file->details->filesystem_info_is_up_to_date = TRUE;
if (info != NULL)
{
file->details->filesystem_use_preview =
g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_FILESYSTEM_USE_PREVIEW);
file->details->filesystem_readonly =
g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY);
filesystem_type = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE);
if (g_strcmp0 (eel_ref_str_peek (file->details->filesystem_type), filesystem_type) != 0)
{
eel_ref_str_unref (file->details->filesystem_type);
file->details->filesystem_type = eel_ref_str_get_unique (filesystem_type);
}
}
nautilus_directory_async_state_changed (directory);
nautilus_file_changed (file);
nautilus_file_unref (file);
nautilus_directory_unref (directory);
filesystem_info_state_free (state);
}
static void
query_filesystem_info_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
GFileInfo *info;
FilesystemInfoState *state;
state = user_data;
if (state->directory == NULL)
{
/* Operation was cancelled. Bail out */
filesystem_info_state_free (state);
return;
}
info = g_file_query_filesystem_info_finish (G_FILE (source_object), res, NULL);
got_filesystem_info (state, info);
if (info != NULL)
{
g_object_unref (info);
}
}
static void
filesystem_info_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
GFile *location;
FilesystemInfoState *state;
if (directory->details->filesystem_info_state != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file,
lacks_filesystem_info,
REQUEST_FILESYSTEM_INFO))
{
return;
}
*doing_io = TRUE;
if (!async_job_start (directory, "filesystem info"))
{
return;
}
state = g_new0 (FilesystemInfoState, 1);
state->directory = directory;
state->file = file;
state->cancellable = g_cancellable_new ();
location = nautilus_file_get_location (file);
directory->details->filesystem_info_state = state;
g_file_query_filesystem_info_async (location,
G_FILE_ATTRIBUTE_FILESYSTEM_READONLY ","
G_FILE_ATTRIBUTE_FILESYSTEM_USE_PREVIEW ","
G_FILE_ATTRIBUTE_FILESYSTEM_TYPE,
G_PRIORITY_DEFAULT,
state->cancellable,
query_filesystem_info_callback,
state);
g_object_unref (location);
}
static void
extension_info_cancel (NautilusDirectory *directory)
{
if (directory->details->extension_info_in_progress != NULL)
{
if (directory->details->extension_info_idle)
{
g_source_remove (directory->details->extension_info_idle);
}
else
{
nautilus_info_provider_cancel_update
(directory->details->extension_info_provider,
directory->details->extension_info_in_progress);
}
directory->details->extension_info_in_progress = NULL;
directory->details->extension_info_file = NULL;
directory->details->extension_info_provider = NULL;
directory->details->extension_info_idle = 0;
async_job_end (directory, "extension info");
}
}
static void
extension_info_stop (NautilusDirectory *directory)
{
if (directory->details->extension_info_in_progress != NULL)
{
NautilusFile *file;
file = directory->details->extension_info_file;
if (file != NULL)
{
g_assert (NAUTILUS_IS_FILE (file));
g_assert (file->details->directory == directory);
if (is_needy (file, lacks_extension_info, REQUEST_EXTENSION_INFO))
{
return;
}
}
/* The info is not wanted, so stop it. */
extension_info_cancel (directory);
}
}
static void
finish_info_provider (NautilusDirectory *directory,
NautilusFile *file,
NautilusInfoProvider *provider)
{
file->details->pending_info_providers =
g_list_remove (file->details->pending_info_providers,
provider);
g_object_unref (provider);
nautilus_directory_async_state_changed (directory);
if (file->details->pending_info_providers == NULL)
{
nautilus_file_info_providers_done (file);
}
}
static gboolean
info_provider_idle_callback (gpointer user_data)
{
InfoProviderResponse *response;
NautilusDirectory *directory;
response = user_data;
directory = response->directory;
if (response->handle != directory->details->extension_info_in_progress
|| response->provider != directory->details->extension_info_provider)
{
g_warning ("Unexpected plugin response. This probably indicates a bug in a Nautilus extension: handle=%p", response->handle);
}
else
{
NautilusFile *file;
async_job_end (directory, "extension info");
file = directory->details->extension_info_file;
directory->details->extension_info_file = NULL;
directory->details->extension_info_provider = NULL;
directory->details->extension_info_in_progress = NULL;
directory->details->extension_info_idle = 0;
finish_info_provider (directory, file, response->provider);
}
return FALSE;
}
static void
info_provider_callback (NautilusInfoProvider *provider,
NautilusOperationHandle *handle,
NautilusOperationResult result,
gpointer user_data)
{
InfoProviderResponse *response;
response = g_new0 (InfoProviderResponse, 1);
response->provider = provider;
response->handle = handle;
response->result = result;
response->directory = NAUTILUS_DIRECTORY (user_data);
response->directory->details->extension_info_idle =
g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
info_provider_idle_callback, response,
g_free);
}
static void
extension_info_start (NautilusDirectory *directory,
NautilusFile *file,
gboolean *doing_io)
{
NautilusInfoProvider *provider;
NautilusOperationResult result;
NautilusOperationHandle *handle;
GClosure *update_complete;
if (directory->details->extension_info_in_progress != NULL)
{
*doing_io = TRUE;
return;
}
if (!is_needy (file, lacks_extension_info, REQUEST_EXTENSION_INFO))
{
return;
}
*doing_io = TRUE;
if (!async_job_start (directory, "extension info"))
{
return;
}
provider = file->details->pending_info_providers->data;
update_complete = g_cclosure_new (G_CALLBACK (info_provider_callback),
directory,
NULL);
g_closure_set_marshal (update_complete,
g_cclosure_marshal_generic);
result = nautilus_info_provider_update_file_info
(provider,
NAUTILUS_FILE_INFO (file),
update_complete,
&handle);
g_closure_unref (update_complete);
if (result == NAUTILUS_OPERATION_COMPLETE ||
result == NAUTILUS_OPERATION_FAILED)
{
finish_info_provider (directory, file, provider);
async_job_end (directory, "extension info");
}
else
{
directory->details->extension_info_in_progress = handle;
directory->details->extension_info_provider = provider;
directory->details->extension_info_file = file;
}
}
static void
start_or_stop_io (NautilusDirectory *directory)
{
NautilusFile *file;
gboolean doing_io;
/* Start or stop reading files. */
file_list_start_or_stop (directory);
/* Stop any no longer wanted attribute fetches. */
file_info_stop (directory);
directory_count_stop (directory);
deep_count_stop (directory);
mime_list_stop (directory);
link_info_stop (directory);
extension_info_stop (directory);
mount_stop (directory);
thumbnail_stop (directory);
filesystem_info_stop (directory);
doing_io = FALSE;
/* Take files that are all done off the queue. */
while (!nautilus_file_queue_is_empty (directory->details->high_priority_queue))
{
file = nautilus_file_queue_head (directory->details->high_priority_queue);
/* Start getting attributes if possible */
file_info_start (directory, file, &doing_io);
link_info_start (directory, file, &doing_io);
if (doing_io)
{
return;
}
move_file_to_low_priority_queue (directory, file);
}
/* High priority queue must be empty */
while (!nautilus_file_queue_is_empty (directory->details->low_priority_queue))
{
file = nautilus_file_queue_head (directory->details->low_priority_queue);
/* Start getting attributes if possible */
mount_start (directory, file, &doing_io);
directory_count_start (directory, file, &doing_io);
deep_count_start (directory, file, &doing_io);
mime_list_start (directory, file, &doing_io);
thumbnail_start (directory, file, &doing_io);
filesystem_info_start (directory, file, &doing_io);
if (doing_io)
{
return;
}
move_file_to_extension_queue (directory, file);
}
/* Low priority queue must be empty */
while (!nautilus_file_queue_is_empty (directory->details->extension_queue))
{
file = nautilus_file_queue_head (directory->details->extension_queue);
/* Start getting attributes if possible */
extension_info_start (directory, file, &doing_io);
if (doing_io)
{
return;
}
nautilus_directory_remove_file_from_work_queue (directory, file);
}
}
/* Call this when the monitor or call when ready list changes,
* or when some I/O is completed.
*/
void
nautilus_directory_async_state_changed (NautilusDirectory *directory)
{
/* Check if any callbacks are satisfied and call them if they
* are. Do this last so that any changes done in start or stop
* I/O functions immediately (not in callbacks) are taken into
* consideration. If any callbacks are called, consider the
* I/O state again so that we can release or cancel I/O that
* is not longer needed once the callbacks are satisfied.
*/
if (directory->details->in_async_service_loop)
{
directory->details->state_changed = TRUE;
return;
}
directory->details->in_async_service_loop = TRUE;
nautilus_directory_ref (directory);
do
{
directory->details->state_changed = FALSE;
start_or_stop_io (directory);
if (call_ready_callbacks (directory))
{
directory->details->state_changed = TRUE;
}
}
while (directory->details->state_changed);
directory->details->in_async_service_loop = FALSE;
nautilus_directory_unref (directory);
/* Check if any directories should wake up. */
async_job_wake_up ();
}
void
nautilus_directory_cancel (NautilusDirectory *directory)
{
/* Arbitrary order (kept alphabetical). */
deep_count_cancel (directory);
directory_count_cancel (directory);
file_info_cancel (directory);
file_list_cancel (directory);
link_info_cancel (directory);
mime_list_cancel (directory);
new_files_cancel (directory);
extension_info_cancel (directory);
thumbnail_cancel (directory);
mount_cancel (directory);
filesystem_info_cancel (directory);
/* We aren't waiting for anything any more. */
if (waiting_directories != NULL)
{
g_hash_table_remove (waiting_directories, directory);
}
/* Check if any directories should wake up. */
async_job_wake_up ();
}
static void
cancel_directory_count_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->count_in_progress != NULL &&
directory->details->count_in_progress->count_file == file)
{
directory_count_cancel (directory);
}
}
static void
cancel_deep_counts_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->deep_count_file == file)
{
deep_count_cancel (directory);
}
}
static void
cancel_mime_list_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->mime_list_in_progress != NULL &&
directory->details->mime_list_in_progress->mime_list_file == file)
{
mime_list_cancel (directory);
}
}
static void
cancel_file_info_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->get_info_file == file)
{
file_info_cancel (directory);
}
}
static void
cancel_thumbnail_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->thumbnail_state != NULL &&
directory->details->thumbnail_state->file == file)
{
thumbnail_cancel (directory);
}
}
static void
cancel_mount_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->mount_state != NULL &&
directory->details->mount_state->file == file)
{
mount_cancel (directory);
}
}
static void
cancel_filesystem_info_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->filesystem_info_state != NULL &&
directory->details->filesystem_info_state->file == file)
{
filesystem_info_cancel (directory);
}
}
static void
cancel_link_info_for_file (NautilusDirectory *directory,
NautilusFile *file)
{
if (directory->details->link_info_read_state != NULL &&
directory->details->link_info_read_state->file == file)
{
link_info_cancel (directory);
}
}
static void
cancel_loading_attributes (NautilusDirectory *directory,
NautilusFileAttributes file_attributes)
{
Request request;
request = nautilus_directory_set_up_request (file_attributes);
if (REQUEST_WANTS_TYPE (request, REQUEST_DIRECTORY_COUNT))
{
directory_count_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_DEEP_COUNT))
{
deep_count_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_MIME_LIST))
{
mime_list_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_FILE_INFO))
{
file_info_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_FILESYSTEM_INFO))
{
filesystem_info_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_LINK_INFO))
{
link_info_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_EXTENSION_INFO))
{
extension_info_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_THUMBNAIL))
{
thumbnail_cancel (directory);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_MOUNT))
{
mount_cancel (directory);
}
nautilus_directory_async_state_changed (directory);
}
void
nautilus_directory_cancel_loading_file_attributes (NautilusDirectory *directory,
NautilusFile *file,
NautilusFileAttributes file_attributes)
{
Request request;
nautilus_directory_remove_file_from_work_queue (directory, file);
request = nautilus_directory_set_up_request (file_attributes);
if (REQUEST_WANTS_TYPE (request, REQUEST_DIRECTORY_COUNT))
{
cancel_directory_count_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_DEEP_COUNT))
{
cancel_deep_counts_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_MIME_LIST))
{
cancel_mime_list_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_FILE_INFO))
{
cancel_file_info_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_FILESYSTEM_INFO))
{
cancel_filesystem_info_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_LINK_INFO))
{
cancel_link_info_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_THUMBNAIL))
{
cancel_thumbnail_for_file (directory, file);
}
if (REQUEST_WANTS_TYPE (request, REQUEST_MOUNT))
{
cancel_mount_for_file (directory, file);
}
nautilus_directory_async_state_changed (directory);
}
void
nautilus_directory_add_file_to_work_queue (NautilusDirectory *directory,
NautilusFile *file)
{
g_return_if_fail (file->details->directory == directory);
nautilus_file_queue_enqueue (directory->details->high_priority_queue,
file);
}
static void
add_all_files_to_work_queue (NautilusDirectory *directory)
{
GList *node;
NautilusFile *file;
for (node = directory->details->file_list; node != NULL; node = node->next)
{
file = NAUTILUS_FILE (node->data);
nautilus_directory_add_file_to_work_queue (directory, file);
}
}
void
nautilus_directory_remove_file_from_work_queue (NautilusDirectory *directory,
NautilusFile *file)
{
nautilus_file_queue_remove (directory->details->high_priority_queue,
file);
nautilus_file_queue_remove (directory->details->low_priority_queue,
file);
nautilus_file_queue_remove (directory->details->extension_queue,
file);
}
static void
move_file_to_low_priority_queue (NautilusDirectory *directory,
NautilusFile *file)
{
/* Must add before removing to avoid ref underflow */
nautilus_file_queue_enqueue (directory->details->low_priority_queue,
file);
nautilus_file_queue_remove (directory->details->high_priority_queue,
file);
}
static void
move_file_to_extension_queue (NautilusDirectory *directory,
NautilusFile *file)
{
/* Must add before removing to avoid ref underflow */
nautilus_file_queue_enqueue (directory->details->extension_queue,
file);
nautilus_file_queue_remove (directory->details->low_priority_queue,
file);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2802_0 |
crossvul-cpp_data_bad_2035_1 | /*
* linux/fs/proc/base.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* proc base directory handling functions
*
* 1999, Al Viro. Rewritten. Now it covers the whole per-process part.
* Instead of using magical inumbers to determine the kind of object
* we allocate and fill in-core inodes upon lookup. They don't even
* go into icache. We cache the reference to task_struct upon lookup too.
* Eventually it should become a filesystem in its own. We don't use the
* rest of procfs anymore.
*
*
* Changelog:
* 17-Jan-2005
* Allan Bezerra
* Bruna Moreira <bruna.moreira@indt.org.br>
* Edjard Mota <edjard.mota@indt.org.br>
* Ilias Biris <ilias.biris@indt.org.br>
* Mauricio Lin <mauricio.lin@indt.org.br>
*
* Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
*
* A new process specific entry (smaps) included in /proc. It shows the
* size of rss for each memory area. The maps entry lacks information
* about physical memory size (rss) for each mapped file, i.e.,
* rss information for executables and library files.
* This additional information is useful for any tools that need to know
* about physical memory consumption for a process specific library.
*
* Changelog:
* 21-Feb-2005
* Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
* Pud inclusion in the page table walking.
*
* ChangeLog:
* 10-Mar-2005
* 10LE Instituto Nokia de Tecnologia - INdT:
* A better way to walks through the page table as suggested by Hugh Dickins.
*
* Simo Piiroinen <simo.piiroinen@nokia.com>:
* Smaps information related to shared, private, clean and dirty pages.
*
* Paul Mundt <paul.mundt@nokia.com>:
* Overall revision about smaps.
*/
#include <asm/uaccess.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/init.h>
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <linux/namei.h>
#include <linux/mnt_namespace.h>
#include <linux/mm.h>
#include <linux/rcupdate.h>
#include <linux/kallsyms.h>
#include <linux/stacktrace.h>
#include <linux/resource.h>
#include <linux/module.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/ptrace.h>
#include <linux/tracehook.h>
#include <linux/cgroup.h>
#include <linux/cpuset.h>
#include <linux/audit.h>
#include <linux/poll.h>
#include <linux/nsproxy.h>
#include <linux/oom.h>
#include <linux/elf.h>
#include <linux/pid_namespace.h>
#include <linux/fs_struct.h>
#include "internal.h"
/* NOTE:
* Implementing inode permission operations in /proc is almost
* certainly an error. Permission checks need to happen during
* each system call not at open time. The reason is that most of
* what we wish to check for permissions in /proc varies at runtime.
*
* The classic example of a problem is opening file descriptors
* in /proc for a task before it execs a suid executable.
*/
struct pid_entry {
char *name;
int len;
mode_t mode;
const struct inode_operations *iop;
const struct file_operations *fop;
union proc_op op;
};
#define NOD(NAME, MODE, IOP, FOP, OP) { \
.name = (NAME), \
.len = sizeof(NAME) - 1, \
.mode = MODE, \
.iop = IOP, \
.fop = FOP, \
.op = OP, \
}
#define DIR(NAME, MODE, iops, fops) \
NOD(NAME, (S_IFDIR|(MODE)), &iops, &fops, {} )
#define LNK(NAME, get_link) \
NOD(NAME, (S_IFLNK|S_IRWXUGO), \
&proc_pid_link_inode_operations, NULL, \
{ .proc_get_link = get_link } )
#define REG(NAME, MODE, fops) \
NOD(NAME, (S_IFREG|(MODE)), NULL, &fops, {})
#define INF(NAME, MODE, read) \
NOD(NAME, (S_IFREG|(MODE)), \
NULL, &proc_info_file_operations, \
{ .proc_read = read } )
#define ONE(NAME, MODE, show) \
NOD(NAME, (S_IFREG|(MODE)), \
NULL, &proc_single_file_operations, \
{ .proc_show = show } )
/*
* Count the number of hardlinks for the pid_entry table, excluding the .
* and .. links.
*/
static unsigned int pid_entry_count_dirs(const struct pid_entry *entries,
unsigned int n)
{
unsigned int i;
unsigned int count;
count = 0;
for (i = 0; i < n; ++i) {
if (S_ISDIR(entries[i].mode))
++count;
}
return count;
}
static int get_fs_path(struct task_struct *task, struct path *path, bool root)
{
struct fs_struct *fs;
int result = -ENOENT;
task_lock(task);
fs = task->fs;
if (fs) {
read_lock(&fs->lock);
*path = root ? fs->root : fs->pwd;
path_get(path);
read_unlock(&fs->lock);
result = 0;
}
task_unlock(task);
return result;
}
static int get_nr_threads(struct task_struct *tsk)
{
unsigned long flags;
int count = 0;
if (lock_task_sighand(tsk, &flags)) {
count = atomic_read(&tsk->signal->count);
unlock_task_sighand(tsk, &flags);
}
return count;
}
static int proc_cwd_link(struct inode *inode, struct path *path)
{
struct task_struct *task = get_proc_task(inode);
int result = -ENOENT;
if (task) {
result = get_fs_path(task, path, 0);
put_task_struct(task);
}
return result;
}
static int proc_root_link(struct inode *inode, struct path *path)
{
struct task_struct *task = get_proc_task(inode);
int result = -ENOENT;
if (task) {
result = get_fs_path(task, path, 1);
put_task_struct(task);
}
return result;
}
/*
* Return zero if current may access user memory in @task, -error if not.
*/
static int check_mem_permission(struct task_struct *task)
{
/*
* A task can always look at itself, in case it chooses
* to use system calls instead of load instructions.
*/
if (task == current)
return 0;
/*
* If current is actively ptrace'ing, and would also be
* permitted to freshly attach with ptrace now, permit it.
*/
if (task_is_stopped_or_traced(task)) {
int match;
rcu_read_lock();
match = (tracehook_tracer_task(task) == current);
rcu_read_unlock();
if (match && ptrace_may_access(task, PTRACE_MODE_ATTACH))
return 0;
}
/*
* Noone else is allowed.
*/
return -EPERM;
}
struct mm_struct *mm_for_maps(struct task_struct *task)
{
struct mm_struct *mm;
if (mutex_lock_killable(&task->cred_guard_mutex))
return NULL;
mm = get_task_mm(task);
if (mm && mm != current->mm &&
!ptrace_may_access(task, PTRACE_MODE_READ)) {
mmput(mm);
mm = NULL;
}
mutex_unlock(&task->cred_guard_mutex);
return mm;
}
static int proc_pid_cmdline(struct task_struct *task, char * buffer)
{
int res = 0;
unsigned int len;
struct mm_struct *mm = get_task_mm(task);
if (!mm)
goto out;
if (!mm->arg_end)
goto out_mm; /* Shh! No looking before we're done */
len = mm->arg_end - mm->arg_start;
if (len > PAGE_SIZE)
len = PAGE_SIZE;
res = access_process_vm(task, mm->arg_start, buffer, len, 0);
// If the nul at the end of args has been overwritten, then
// assume application is using setproctitle(3).
if (res > 0 && buffer[res-1] != '\0' && len < PAGE_SIZE) {
len = strnlen(buffer, res);
if (len < res) {
res = len;
} else {
len = mm->env_end - mm->env_start;
if (len > PAGE_SIZE - res)
len = PAGE_SIZE - res;
res += access_process_vm(task, mm->env_start, buffer+res, len, 0);
res = strnlen(buffer, res);
}
}
out_mm:
mmput(mm);
out:
return res;
}
static int proc_pid_auxv(struct task_struct *task, char *buffer)
{
int res = 0;
struct mm_struct *mm = get_task_mm(task);
if (mm) {
unsigned int nwords = 0;
do {
nwords += 2;
} while (mm->saved_auxv[nwords - 2] != 0); /* AT_NULL */
res = nwords * sizeof(mm->saved_auxv[0]);
if (res > PAGE_SIZE)
res = PAGE_SIZE;
memcpy(buffer, mm->saved_auxv, res);
mmput(mm);
}
return res;
}
#ifdef CONFIG_KALLSYMS
/*
* Provides a wchan file via kallsyms in a proper one-value-per-file format.
* Returns the resolved symbol. If that fails, simply return the address.
*/
static int proc_pid_wchan(struct task_struct *task, char *buffer)
{
unsigned long wchan;
char symname[KSYM_NAME_LEN];
wchan = get_wchan(task);
if (lookup_symbol_name(wchan, symname) < 0)
if (!ptrace_may_access(task, PTRACE_MODE_READ))
return 0;
else
return sprintf(buffer, "%lu", wchan);
else
return sprintf(buffer, "%s", symname);
}
#endif /* CONFIG_KALLSYMS */
#ifdef CONFIG_STACKTRACE
#define MAX_STACK_TRACE_DEPTH 64
static int proc_pid_stack(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
struct stack_trace trace;
unsigned long *entries;
int i;
entries = kmalloc(MAX_STACK_TRACE_DEPTH * sizeof(*entries), GFP_KERNEL);
if (!entries)
return -ENOMEM;
trace.nr_entries = 0;
trace.max_entries = MAX_STACK_TRACE_DEPTH;
trace.entries = entries;
trace.skip = 0;
save_stack_trace_tsk(task, &trace);
for (i = 0; i < trace.nr_entries; i++) {
seq_printf(m, "[<%p>] %pS\n",
(void *)entries[i], (void *)entries[i]);
}
kfree(entries);
return 0;
}
#endif
#ifdef CONFIG_SCHEDSTATS
/*
* Provides /proc/PID/schedstat
*/
static int proc_pid_schedstat(struct task_struct *task, char *buffer)
{
return sprintf(buffer, "%llu %llu %lu\n",
(unsigned long long)task->se.sum_exec_runtime,
(unsigned long long)task->sched_info.run_delay,
task->sched_info.pcount);
}
#endif
#ifdef CONFIG_LATENCYTOP
static int lstats_show_proc(struct seq_file *m, void *v)
{
int i;
struct inode *inode = m->private;
struct task_struct *task = get_proc_task(inode);
if (!task)
return -ESRCH;
seq_puts(m, "Latency Top version : v0.1\n");
for (i = 0; i < 32; i++) {
if (task->latency_record[i].backtrace[0]) {
int q;
seq_printf(m, "%i %li %li ",
task->latency_record[i].count,
task->latency_record[i].time,
task->latency_record[i].max);
for (q = 0; q < LT_BACKTRACEDEPTH; q++) {
char sym[KSYM_SYMBOL_LEN];
char *c;
if (!task->latency_record[i].backtrace[q])
break;
if (task->latency_record[i].backtrace[q] == ULONG_MAX)
break;
sprint_symbol(sym, task->latency_record[i].backtrace[q]);
c = strchr(sym, '+');
if (c)
*c = 0;
seq_printf(m, "%s ", sym);
}
seq_printf(m, "\n");
}
}
put_task_struct(task);
return 0;
}
static int lstats_open(struct inode *inode, struct file *file)
{
return single_open(file, lstats_show_proc, inode);
}
static ssize_t lstats_write(struct file *file, const char __user *buf,
size_t count, loff_t *offs)
{
struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
if (!task)
return -ESRCH;
clear_all_latency_tracing(task);
put_task_struct(task);
return count;
}
static const struct file_operations proc_lstats_operations = {
.open = lstats_open,
.read = seq_read,
.write = lstats_write,
.llseek = seq_lseek,
.release = single_release,
};
#endif
/* The badness from the OOM killer */
unsigned long badness(struct task_struct *p, unsigned long uptime);
static int proc_oom_score(struct task_struct *task, char *buffer)
{
unsigned long points;
struct timespec uptime;
do_posix_clock_monotonic_gettime(&uptime);
read_lock(&tasklist_lock);
points = badness(task->group_leader, uptime.tv_sec);
read_unlock(&tasklist_lock);
return sprintf(buffer, "%lu\n", points);
}
struct limit_names {
char *name;
char *unit;
};
static const struct limit_names lnames[RLIM_NLIMITS] = {
[RLIMIT_CPU] = {"Max cpu time", "seconds"},
[RLIMIT_FSIZE] = {"Max file size", "bytes"},
[RLIMIT_DATA] = {"Max data size", "bytes"},
[RLIMIT_STACK] = {"Max stack size", "bytes"},
[RLIMIT_CORE] = {"Max core file size", "bytes"},
[RLIMIT_RSS] = {"Max resident set", "bytes"},
[RLIMIT_NPROC] = {"Max processes", "processes"},
[RLIMIT_NOFILE] = {"Max open files", "files"},
[RLIMIT_MEMLOCK] = {"Max locked memory", "bytes"},
[RLIMIT_AS] = {"Max address space", "bytes"},
[RLIMIT_LOCKS] = {"Max file locks", "locks"},
[RLIMIT_SIGPENDING] = {"Max pending signals", "signals"},
[RLIMIT_MSGQUEUE] = {"Max msgqueue size", "bytes"},
[RLIMIT_NICE] = {"Max nice priority", NULL},
[RLIMIT_RTPRIO] = {"Max realtime priority", NULL},
[RLIMIT_RTTIME] = {"Max realtime timeout", "us"},
};
/* Display limits for a process */
static int proc_pid_limits(struct task_struct *task, char *buffer)
{
unsigned int i;
int count = 0;
unsigned long flags;
char *bufptr = buffer;
struct rlimit rlim[RLIM_NLIMITS];
if (!lock_task_sighand(task, &flags))
return 0;
memcpy(rlim, task->signal->rlim, sizeof(struct rlimit) * RLIM_NLIMITS);
unlock_task_sighand(task, &flags);
/*
* print the file header
*/
count += sprintf(&bufptr[count], "%-25s %-20s %-20s %-10s\n",
"Limit", "Soft Limit", "Hard Limit", "Units");
for (i = 0; i < RLIM_NLIMITS; i++) {
if (rlim[i].rlim_cur == RLIM_INFINITY)
count += sprintf(&bufptr[count], "%-25s %-20s ",
lnames[i].name, "unlimited");
else
count += sprintf(&bufptr[count], "%-25s %-20lu ",
lnames[i].name, rlim[i].rlim_cur);
if (rlim[i].rlim_max == RLIM_INFINITY)
count += sprintf(&bufptr[count], "%-20s ", "unlimited");
else
count += sprintf(&bufptr[count], "%-20lu ",
rlim[i].rlim_max);
if (lnames[i].unit)
count += sprintf(&bufptr[count], "%-10s\n",
lnames[i].unit);
else
count += sprintf(&bufptr[count], "\n");
}
return count;
}
#ifdef CONFIG_HAVE_ARCH_TRACEHOOK
static int proc_pid_syscall(struct task_struct *task, char *buffer)
{
long nr;
unsigned long args[6], sp, pc;
if (task_current_syscall(task, &nr, args, 6, &sp, &pc))
return sprintf(buffer, "running\n");
if (nr < 0)
return sprintf(buffer, "%ld 0x%lx 0x%lx\n", nr, sp, pc);
return sprintf(buffer,
"%ld 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx\n",
nr,
args[0], args[1], args[2], args[3], args[4], args[5],
sp, pc);
}
#endif /* CONFIG_HAVE_ARCH_TRACEHOOK */
/************************************************************************/
/* Here the fs part begins */
/************************************************************************/
/* permission checks */
static int proc_fd_access_allowed(struct inode *inode)
{
struct task_struct *task;
int allowed = 0;
/* Allow access to a task's file descriptors if it is us or we
* may use ptrace attach to the process and find out that
* information.
*/
task = get_proc_task(inode);
if (task) {
allowed = ptrace_may_access(task, PTRACE_MODE_READ);
put_task_struct(task);
}
return allowed;
}
static int proc_setattr(struct dentry *dentry, struct iattr *attr)
{
int error;
struct inode *inode = dentry->d_inode;
if (attr->ia_valid & ATTR_MODE)
return -EPERM;
error = inode_change_ok(inode, attr);
if (!error)
error = inode_setattr(inode, attr);
return error;
}
static const struct inode_operations proc_def_inode_operations = {
.setattr = proc_setattr,
};
static int mounts_open_common(struct inode *inode, struct file *file,
const struct seq_operations *op)
{
struct task_struct *task = get_proc_task(inode);
struct nsproxy *nsp;
struct mnt_namespace *ns = NULL;
struct path root;
struct proc_mounts *p;
int ret = -EINVAL;
if (task) {
rcu_read_lock();
nsp = task_nsproxy(task);
if (nsp) {
ns = nsp->mnt_ns;
if (ns)
get_mnt_ns(ns);
}
rcu_read_unlock();
if (ns && get_fs_path(task, &root, 1) == 0)
ret = 0;
put_task_struct(task);
}
if (!ns)
goto err;
if (ret)
goto err_put_ns;
ret = -ENOMEM;
p = kmalloc(sizeof(struct proc_mounts), GFP_KERNEL);
if (!p)
goto err_put_path;
file->private_data = &p->m;
ret = seq_open(file, op);
if (ret)
goto err_free;
p->m.private = p;
p->ns = ns;
p->root = root;
p->event = ns->event;
return 0;
err_free:
kfree(p);
err_put_path:
path_put(&root);
err_put_ns:
put_mnt_ns(ns);
err:
return ret;
}
static int mounts_release(struct inode *inode, struct file *file)
{
struct proc_mounts *p = file->private_data;
path_put(&p->root);
put_mnt_ns(p->ns);
return seq_release(inode, file);
}
static unsigned mounts_poll(struct file *file, poll_table *wait)
{
struct proc_mounts *p = file->private_data;
struct mnt_namespace *ns = p->ns;
unsigned res = POLLIN | POLLRDNORM;
poll_wait(file, &ns->poll, wait);
spin_lock(&vfsmount_lock);
if (p->event != ns->event) {
p->event = ns->event;
res |= POLLERR | POLLPRI;
}
spin_unlock(&vfsmount_lock);
return res;
}
static int mounts_open(struct inode *inode, struct file *file)
{
return mounts_open_common(inode, file, &mounts_op);
}
static const struct file_operations proc_mounts_operations = {
.open = mounts_open,
.read = seq_read,
.llseek = seq_lseek,
.release = mounts_release,
.poll = mounts_poll,
};
static int mountinfo_open(struct inode *inode, struct file *file)
{
return mounts_open_common(inode, file, &mountinfo_op);
}
static const struct file_operations proc_mountinfo_operations = {
.open = mountinfo_open,
.read = seq_read,
.llseek = seq_lseek,
.release = mounts_release,
.poll = mounts_poll,
};
static int mountstats_open(struct inode *inode, struct file *file)
{
return mounts_open_common(inode, file, &mountstats_op);
}
static const struct file_operations proc_mountstats_operations = {
.open = mountstats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = mounts_release,
};
#define PROC_BLOCK_SIZE (3*1024) /* 4K page size but our output routines use some slack for overruns */
static ssize_t proc_info_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
unsigned long page;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
length = -ESRCH;
if (!task)
goto out_no_task;
if (count > PROC_BLOCK_SIZE)
count = PROC_BLOCK_SIZE;
length = -ENOMEM;
if (!(page = __get_free_page(GFP_TEMPORARY)))
goto out;
length = PROC_I(inode)->op.proc_read(task, (char*)page);
if (length >= 0)
length = simple_read_from_buffer(buf, count, ppos, (char *)page, length);
free_page(page);
out:
put_task_struct(task);
out_no_task:
return length;
}
static const struct file_operations proc_info_file_operations = {
.read = proc_info_read,
};
static int proc_single_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct pid_namespace *ns;
struct pid *pid;
struct task_struct *task;
int ret;
ns = inode->i_sb->s_fs_info;
pid = proc_pid(inode);
task = get_pid_task(pid, PIDTYPE_PID);
if (!task)
return -ESRCH;
ret = PROC_I(inode)->op.proc_show(m, ns, pid, task);
put_task_struct(task);
return ret;
}
static int proc_single_open(struct inode *inode, struct file *filp)
{
int ret;
ret = single_open(filp, proc_single_show, NULL);
if (!ret) {
struct seq_file *m = filp->private_data;
m->private = inode;
}
return ret;
}
static const struct file_operations proc_single_file_operations = {
.open = proc_single_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int mem_open(struct inode* inode, struct file* file)
{
file->private_data = (void*)((long)current->self_exec_id);
return 0;
}
static ssize_t mem_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
char *page;
unsigned long src = *ppos;
int ret = -ESRCH;
struct mm_struct *mm;
if (!task)
goto out_no_task;
if (check_mem_permission(task))
goto out;
ret = -ENOMEM;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
goto out;
ret = 0;
mm = get_task_mm(task);
if (!mm)
goto out_free;
ret = -EIO;
if (file->private_data != (void*)((long)current->self_exec_id))
goto out_put;
ret = 0;
while (count > 0) {
int this_len, retval;
this_len = (count > PAGE_SIZE) ? PAGE_SIZE : count;
retval = access_process_vm(task, src, page, this_len, 0);
if (!retval || check_mem_permission(task)) {
if (!ret)
ret = -EIO;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
out_put:
mmput(mm);
out_free:
free_page((unsigned long) page);
out:
put_task_struct(task);
out_no_task:
return ret;
}
#define mem_write NULL
#ifndef mem_write
/* This is a security hazard */
static ssize_t mem_write(struct file * file, const char __user *buf,
size_t count, loff_t *ppos)
{
int copied;
char *page;
struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
unsigned long dst = *ppos;
copied = -ESRCH;
if (!task)
goto out_no_task;
if (check_mem_permission(task))
goto out;
copied = -ENOMEM;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
goto out;
copied = 0;
while (count > 0) {
int this_len, retval;
this_len = (count > PAGE_SIZE) ? PAGE_SIZE : count;
if (copy_from_user(page, buf, this_len)) {
copied = -EFAULT;
break;
}
retval = access_process_vm(task, dst, page, this_len, 1);
if (!retval) {
if (!copied)
copied = -EIO;
break;
}
copied += retval;
buf += retval;
dst += retval;
count -= retval;
}
*ppos = dst;
free_page((unsigned long) page);
out:
put_task_struct(task);
out_no_task:
return copied;
}
#endif
loff_t mem_lseek(struct file *file, loff_t offset, int orig)
{
switch (orig) {
case 0:
file->f_pos = offset;
break;
case 1:
file->f_pos += offset;
break;
default:
return -EINVAL;
}
force_successful_syscall_return();
return file->f_pos;
}
static const struct file_operations proc_mem_operations = {
.llseek = mem_lseek,
.read = mem_read,
.write = mem_write,
.open = mem_open,
};
static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
char *page;
unsigned long src = *ppos;
int ret = -ESRCH;
struct mm_struct *mm;
if (!task)
goto out_no_task;
if (!ptrace_may_access(task, PTRACE_MODE_READ))
goto out;
ret = -ENOMEM;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
goto out;
ret = 0;
mm = get_task_mm(task);
if (!mm)
goto out_free;
while (count > 0) {
int this_len, retval, max_len;
this_len = mm->env_end - (mm->env_start + src);
if (this_len <= 0)
break;
max_len = (count > PAGE_SIZE) ? PAGE_SIZE : count;
this_len = (this_len > max_len) ? max_len : this_len;
retval = access_process_vm(task, (mm->env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
out_free:
free_page((unsigned long) page);
out:
put_task_struct(task);
out_no_task:
return ret;
}
static const struct file_operations proc_environ_operations = {
.read = environ_read,
};
static ssize_t oom_adjust_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
char buffer[PROC_NUMBUF];
size_t len;
int oom_adjust = OOM_DISABLE;
unsigned long flags;
if (!task)
return -ESRCH;
if (lock_task_sighand(task, &flags)) {
oom_adjust = task->signal->oom_adj;
unlock_task_sighand(task, &flags);
}
put_task_struct(task);
len = snprintf(buffer, sizeof(buffer), "%i\n", oom_adjust);
return simple_read_from_buffer(buf, count, ppos, buffer, len);
}
static ssize_t oom_adjust_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
long oom_adjust;
unsigned long flags;
int err;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
err = strict_strtol(strstrip(buffer), 0, &oom_adjust);
if (err)
return -EINVAL;
if ((oom_adjust < OOM_ADJUST_MIN || oom_adjust > OOM_ADJUST_MAX) &&
oom_adjust != OOM_DISABLE)
return -EINVAL;
task = get_proc_task(file->f_path.dentry->d_inode);
if (!task)
return -ESRCH;
if (!lock_task_sighand(task, &flags)) {
put_task_struct(task);
return -ESRCH;
}
if (oom_adjust < task->signal->oom_adj && !capable(CAP_SYS_RESOURCE)) {
unlock_task_sighand(task, &flags);
put_task_struct(task);
return -EACCES;
}
task->signal->oom_adj = oom_adjust;
unlock_task_sighand(task, &flags);
put_task_struct(task);
return count;
}
static const struct file_operations proc_oom_adjust_operations = {
.read = oom_adjust_read,
.write = oom_adjust_write,
};
#ifdef CONFIG_AUDITSYSCALL
#define TMPBUFLEN 21
static ssize_t proc_loginuid_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
ssize_t length;
char tmpbuf[TMPBUFLEN];
if (!task)
return -ESRCH;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
audit_get_loginuid(task));
put_task_struct(task);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static ssize_t proc_loginuid_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
char *page, *tmp;
ssize_t length;
uid_t loginuid;
if (!capable(CAP_AUDIT_CONTROL))
return -EPERM;
if (current != pid_task(proc_pid(inode), PIDTYPE_PID))
return -EPERM;
if (count >= PAGE_SIZE)
count = PAGE_SIZE - 1;
if (*ppos != 0) {
/* No partial writes. */
return -EINVAL;
}
page = (char*)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out_free_page;
page[count] = '\0';
loginuid = simple_strtoul(page, &tmp, 10);
if (tmp == page) {
length = -EINVAL;
goto out_free_page;
}
length = audit_set_loginuid(current, loginuid);
if (likely(length == 0))
length = count;
out_free_page:
free_page((unsigned long) page);
return length;
}
static const struct file_operations proc_loginuid_operations = {
.read = proc_loginuid_read,
.write = proc_loginuid_write,
};
static ssize_t proc_sessionid_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
ssize_t length;
char tmpbuf[TMPBUFLEN];
if (!task)
return -ESRCH;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
audit_get_sessionid(task));
put_task_struct(task);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static const struct file_operations proc_sessionid_operations = {
.read = proc_sessionid_read,
};
#endif
#ifdef CONFIG_FAULT_INJECTION
static ssize_t proc_fault_inject_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
char buffer[PROC_NUMBUF];
size_t len;
int make_it_fail;
if (!task)
return -ESRCH;
make_it_fail = task->make_it_fail;
put_task_struct(task);
len = snprintf(buffer, sizeof(buffer), "%i\n", make_it_fail);
return simple_read_from_buffer(buf, count, ppos, buffer, len);
}
static ssize_t proc_fault_inject_write(struct file * file,
const char __user * buf, size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF], *end;
int make_it_fail;
if (!capable(CAP_SYS_RESOURCE))
return -EPERM;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
make_it_fail = simple_strtol(strstrip(buffer), &end, 0);
if (*end)
return -EINVAL;
task = get_proc_task(file->f_dentry->d_inode);
if (!task)
return -ESRCH;
task->make_it_fail = make_it_fail;
put_task_struct(task);
return count;
}
static const struct file_operations proc_fault_inject_operations = {
.read = proc_fault_inject_read,
.write = proc_fault_inject_write,
};
#endif
#ifdef CONFIG_SCHED_DEBUG
/*
* Print out various scheduling related per-task fields:
*/
static int sched_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
proc_sched_show_task(p, m);
put_task_struct(p);
return 0;
}
static ssize_t
sched_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
proc_sched_set_task(p);
put_task_struct(p);
return count;
}
static int sched_open(struct inode *inode, struct file *filp)
{
int ret;
ret = single_open(filp, sched_show, NULL);
if (!ret) {
struct seq_file *m = filp->private_data;
m->private = inode;
}
return ret;
}
static const struct file_operations proc_pid_sched_operations = {
.open = sched_open,
.read = seq_read,
.write = sched_write,
.llseek = seq_lseek,
.release = single_release,
};
#endif
static ssize_t comm_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct task_struct *p;
char buffer[TASK_COMM_LEN];
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
if (same_thread_group(current, p))
set_task_comm(p, buffer);
else
count = -EINVAL;
put_task_struct(p);
return count;
}
static int comm_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
task_lock(p);
seq_printf(m, "%s\n", p->comm);
task_unlock(p);
put_task_struct(p);
return 0;
}
static int comm_open(struct inode *inode, struct file *filp)
{
int ret;
ret = single_open(filp, comm_show, NULL);
if (!ret) {
struct seq_file *m = filp->private_data;
m->private = inode;
}
return ret;
}
static const struct file_operations proc_pid_set_comm_operations = {
.open = comm_open,
.read = seq_read,
.write = comm_write,
.llseek = seq_lseek,
.release = single_release,
};
/*
* We added or removed a vma mapping the executable. The vmas are only mapped
* during exec and are not mapped with the mmap system call.
* Callers must hold down_write() on the mm's mmap_sem for these
*/
void added_exe_file_vma(struct mm_struct *mm)
{
mm->num_exe_file_vmas++;
}
void removed_exe_file_vma(struct mm_struct *mm)
{
mm->num_exe_file_vmas--;
if ((mm->num_exe_file_vmas == 0) && mm->exe_file){
fput(mm->exe_file);
mm->exe_file = NULL;
}
}
void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
{
if (new_exe_file)
get_file(new_exe_file);
if (mm->exe_file)
fput(mm->exe_file);
mm->exe_file = new_exe_file;
mm->num_exe_file_vmas = 0;
}
struct file *get_mm_exe_file(struct mm_struct *mm)
{
struct file *exe_file;
/* We need mmap_sem to protect against races with removal of
* VM_EXECUTABLE vmas */
down_read(&mm->mmap_sem);
exe_file = mm->exe_file;
if (exe_file)
get_file(exe_file);
up_read(&mm->mmap_sem);
return exe_file;
}
void dup_mm_exe_file(struct mm_struct *oldmm, struct mm_struct *newmm)
{
/* It's safe to write the exe_file pointer without exe_file_lock because
* this is called during fork when the task is not yet in /proc */
newmm->exe_file = get_mm_exe_file(oldmm);
}
static int proc_exe_link(struct inode *inode, struct path *exe_path)
{
struct task_struct *task;
struct mm_struct *mm;
struct file *exe_file;
task = get_proc_task(inode);
if (!task)
return -ENOENT;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm)
return -ENOENT;
exe_file = get_mm_exe_file(mm);
mmput(mm);
if (exe_file) {
*exe_path = exe_file->f_path;
path_get(&exe_file->f_path);
fput(exe_file);
return 0;
} else
return -ENOENT;
}
static void *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct inode *inode = dentry->d_inode;
int error = -EACCES;
/* We don't need a base pointer in the /proc filesystem */
path_put(&nd->path);
/* Are we allowed to snoop on the tasks file descriptors? */
if (!proc_fd_access_allowed(inode))
goto out;
error = PROC_I(inode)->op.proc_get_link(inode, &nd->path);
nd->last_type = LAST_BIND;
out:
return ERR_PTR(error);
}
static int do_proc_readlink(struct path *path, char __user *buffer, int buflen)
{
char *tmp = (char*)__get_free_page(GFP_TEMPORARY);
char *pathname;
int len;
if (!tmp)
return -ENOMEM;
pathname = d_path(path, tmp, PAGE_SIZE);
len = PTR_ERR(pathname);
if (IS_ERR(pathname))
goto out;
len = tmp + PAGE_SIZE - 1 - pathname;
if (len > buflen)
len = buflen;
if (copy_to_user(buffer, pathname, len))
len = -EFAULT;
out:
free_page((unsigned long)tmp);
return len;
}
static int proc_pid_readlink(struct dentry * dentry, char __user * buffer, int buflen)
{
int error = -EACCES;
struct inode *inode = dentry->d_inode;
struct path path;
/* Are we allowed to snoop on the tasks file descriptors? */
if (!proc_fd_access_allowed(inode))
goto out;
error = PROC_I(inode)->op.proc_get_link(inode, &path);
if (error)
goto out;
error = do_proc_readlink(&path, buffer, buflen);
path_put(&path);
out:
return error;
}
static const struct inode_operations proc_pid_link_inode_operations = {
.readlink = proc_pid_readlink,
.follow_link = proc_pid_follow_link,
.setattr = proc_setattr,
};
/* building an inode */
static int task_dumpable(struct task_struct *task)
{
int dumpable = 0;
struct mm_struct *mm;
task_lock(task);
mm = task->mm;
if (mm)
dumpable = get_dumpable(mm);
task_unlock(task);
if(dumpable == 1)
return 1;
return 0;
}
static struct inode *proc_pid_make_inode(struct super_block * sb, struct task_struct *task)
{
struct inode * inode;
struct proc_inode *ei;
const struct cred *cred;
/* We need a new inode */
inode = new_inode(sb);
if (!inode)
goto out;
/* Common stuff */
ei = PROC_I(inode);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
inode->i_op = &proc_def_inode_operations;
/*
* grab the reference to task.
*/
ei->pid = get_task_pid(task, PIDTYPE_PID);
if (!ei->pid)
goto out_unlock;
if (task_dumpable(task)) {
rcu_read_lock();
cred = __task_cred(task);
inode->i_uid = cred->euid;
inode->i_gid = cred->egid;
rcu_read_unlock();
}
security_task_to_inode(task, inode);
out:
return inode;
out_unlock:
iput(inode);
return NULL;
}
static int pid_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
struct task_struct *task;
const struct cred *cred;
generic_fillattr(inode, stat);
rcu_read_lock();
stat->uid = 0;
stat->gid = 0;
task = pid_task(proc_pid(inode), PIDTYPE_PID);
if (task) {
if ((inode->i_mode == (S_IFDIR|S_IRUGO|S_IXUGO)) ||
task_dumpable(task)) {
cred = __task_cred(task);
stat->uid = cred->euid;
stat->gid = cred->egid;
}
}
rcu_read_unlock();
return 0;
}
/* dentry stuff */
/*
* Exceptional case: normally we are not allowed to unhash a busy
* directory. In this case, however, we can do it - no aliasing problems
* due to the way we treat inodes.
*
* Rewrite the inode's ownerships here because the owning task may have
* performed a setuid(), etc.
*
* Before the /proc/pid/status file was created the only way to read
* the effective uid of a /process was to stat /proc/pid. Reading
* /proc/pid/status is slow enough that procps and other packages
* kept stating /proc/pid. To keep the rules in /proc simple I have
* made this apply to all per process world readable and executable
* directories.
*/
static int pid_revalidate(struct dentry *dentry, struct nameidata *nd)
{
struct inode *inode = dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
const struct cred *cred;
if (task) {
if ((inode->i_mode == (S_IFDIR|S_IRUGO|S_IXUGO)) ||
task_dumpable(task)) {
rcu_read_lock();
cred = __task_cred(task);
inode->i_uid = cred->euid;
inode->i_gid = cred->egid;
rcu_read_unlock();
} else {
inode->i_uid = 0;
inode->i_gid = 0;
}
inode->i_mode &= ~(S_ISUID | S_ISGID);
security_task_to_inode(task, inode);
put_task_struct(task);
return 1;
}
d_drop(dentry);
return 0;
}
static int pid_delete_dentry(struct dentry * dentry)
{
/* Is the task we represent dead?
* If so, then don't put the dentry on the lru list,
* kill it immediately.
*/
return !proc_pid(dentry->d_inode)->tasks[PIDTYPE_PID].first;
}
static const struct dentry_operations pid_dentry_operations =
{
.d_revalidate = pid_revalidate,
.d_delete = pid_delete_dentry,
};
/* Lookups */
typedef struct dentry *instantiate_t(struct inode *, struct dentry *,
struct task_struct *, const void *);
/*
* Fill a directory entry.
*
* If possible create the dcache entry and derive our inode number and
* file type from dcache entry.
*
* Since all of the proc inode numbers are dynamically generated, the inode
* numbers do not exist until the inode is cache. This means creating the
* the dcache entry in readdir is necessary to keep the inode numbers
* reported by readdir in sync with the inode numbers reported
* by stat.
*/
static int proc_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
char *name, int len,
instantiate_t instantiate, struct task_struct *task, const void *ptr)
{
struct dentry *child, *dir = filp->f_path.dentry;
struct inode *inode;
struct qstr qname;
ino_t ino = 0;
unsigned type = DT_UNKNOWN;
qname.name = name;
qname.len = len;
qname.hash = full_name_hash(name, len);
child = d_lookup(dir, &qname);
if (!child) {
struct dentry *new;
new = d_alloc(dir, &qname);
if (new) {
child = instantiate(dir->d_inode, new, task, ptr);
if (child)
dput(new);
else
child = new;
}
}
if (!child || IS_ERR(child) || !child->d_inode)
goto end_instantiate;
inode = child->d_inode;
if (inode) {
ino = inode->i_ino;
type = inode->i_mode >> 12;
}
dput(child);
end_instantiate:
if (!ino)
ino = find_inode_number(dir, &qname);
if (!ino)
ino = 1;
return filldir(dirent, name, len, filp->f_pos, ino, type);
}
static unsigned name_to_int(struct dentry *dentry)
{
const char *name = dentry->d_name.name;
int len = dentry->d_name.len;
unsigned n = 0;
if (len > 1 && *name == '0')
goto out;
while (len-- > 0) {
unsigned c = *name++ - '0';
if (c > 9)
goto out;
if (n >= (~0U-9)/10)
goto out;
n *= 10;
n += c;
}
return n;
out:
return ~0U;
}
#define PROC_FDINFO_MAX 64
static int proc_fd_info(struct inode *inode, struct path *path, char *info)
{
struct task_struct *task = get_proc_task(inode);
struct files_struct *files = NULL;
struct file *file;
int fd = proc_fd(inode);
if (task) {
files = get_files_struct(task);
put_task_struct(task);
}
if (files) {
/*
* We are not taking a ref to the file structure, so we must
* hold ->file_lock.
*/
spin_lock(&files->file_lock);
file = fcheck_files(files, fd);
if (file) {
if (path) {
*path = file->f_path;
path_get(&file->f_path);
}
if (info)
snprintf(info, PROC_FDINFO_MAX,
"pos:\t%lli\n"
"flags:\t0%o\n",
(long long) file->f_pos,
file->f_flags);
spin_unlock(&files->file_lock);
put_files_struct(files);
return 0;
}
spin_unlock(&files->file_lock);
put_files_struct(files);
}
return -ENOENT;
}
static int proc_fd_link(struct inode *inode, struct path *path)
{
return proc_fd_info(inode, path, NULL);
}
static int tid_fd_revalidate(struct dentry *dentry, struct nameidata *nd)
{
struct inode *inode = dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
int fd = proc_fd(inode);
struct files_struct *files;
const struct cred *cred;
if (task) {
files = get_files_struct(task);
if (files) {
rcu_read_lock();
if (fcheck_files(files, fd)) {
rcu_read_unlock();
put_files_struct(files);
if (task_dumpable(task)) {
rcu_read_lock();
cred = __task_cred(task);
inode->i_uid = cred->euid;
inode->i_gid = cred->egid;
rcu_read_unlock();
} else {
inode->i_uid = 0;
inode->i_gid = 0;
}
inode->i_mode &= ~(S_ISUID | S_ISGID);
security_task_to_inode(task, inode);
put_task_struct(task);
return 1;
}
rcu_read_unlock();
put_files_struct(files);
}
put_task_struct(task);
}
d_drop(dentry);
return 0;
}
static const struct dentry_operations tid_fd_dentry_operations =
{
.d_revalidate = tid_fd_revalidate,
.d_delete = pid_delete_dentry,
};
static struct dentry *proc_fd_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
unsigned fd = *(const unsigned *)ptr;
struct file *file;
struct files_struct *files;
struct inode *inode;
struct proc_inode *ei;
struct dentry *error = ERR_PTR(-ENOENT);
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
ei = PROC_I(inode);
ei->fd = fd;
files = get_files_struct(task);
if (!files)
goto out_iput;
inode->i_mode = S_IFLNK;
/*
* We are not taking a ref to the file structure, so we must
* hold ->file_lock.
*/
spin_lock(&files->file_lock);
file = fcheck_files(files, fd);
if (!file)
goto out_unlock;
if (file->f_mode & FMODE_READ)
inode->i_mode |= S_IRUSR | S_IXUSR;
if (file->f_mode & FMODE_WRITE)
inode->i_mode |= S_IWUSR | S_IXUSR;
spin_unlock(&files->file_lock);
put_files_struct(files);
inode->i_op = &proc_pid_link_inode_operations;
inode->i_size = 64;
ei->op.proc_get_link = proc_fd_link;
dentry->d_op = &tid_fd_dentry_operations;
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (tid_fd_revalidate(dentry, NULL))
error = NULL;
out:
return error;
out_unlock:
spin_unlock(&files->file_lock);
put_files_struct(files);
out_iput:
iput(inode);
goto out;
}
static struct dentry *proc_lookupfd_common(struct inode *dir,
struct dentry *dentry,
instantiate_t instantiate)
{
struct task_struct *task = get_proc_task(dir);
unsigned fd = name_to_int(dentry);
struct dentry *result = ERR_PTR(-ENOENT);
if (!task)
goto out_no_task;
if (fd == ~0U)
goto out;
result = instantiate(dir, dentry, task, &fd);
out:
put_task_struct(task);
out_no_task:
return result;
}
static int proc_readfd_common(struct file * filp, void * dirent,
filldir_t filldir, instantiate_t instantiate)
{
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct task_struct *p = get_proc_task(inode);
unsigned int fd, ino;
int retval;
struct files_struct * files;
retval = -ENOENT;
if (!p)
goto out_no_task;
retval = 0;
fd = filp->f_pos;
switch (fd) {
case 0:
if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR) < 0)
goto out;
filp->f_pos++;
case 1:
ino = parent_ino(dentry);
if (filldir(dirent, "..", 2, 1, ino, DT_DIR) < 0)
goto out;
filp->f_pos++;
default:
files = get_files_struct(p);
if (!files)
goto out;
rcu_read_lock();
for (fd = filp->f_pos-2;
fd < files_fdtable(files)->max_fds;
fd++, filp->f_pos++) {
char name[PROC_NUMBUF];
int len;
if (!fcheck_files(files, fd))
continue;
rcu_read_unlock();
len = snprintf(name, sizeof(name), "%d", fd);
if (proc_fill_cache(filp, dirent, filldir,
name, len, instantiate,
p, &fd) < 0) {
rcu_read_lock();
break;
}
rcu_read_lock();
}
rcu_read_unlock();
put_files_struct(files);
}
out:
put_task_struct(p);
out_no_task:
return retval;
}
static struct dentry *proc_lookupfd(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
return proc_lookupfd_common(dir, dentry, proc_fd_instantiate);
}
static int proc_readfd(struct file *filp, void *dirent, filldir_t filldir)
{
return proc_readfd_common(filp, dirent, filldir, proc_fd_instantiate);
}
static ssize_t proc_fdinfo_read(struct file *file, char __user *buf,
size_t len, loff_t *ppos)
{
char tmp[PROC_FDINFO_MAX];
int err = proc_fd_info(file->f_path.dentry->d_inode, NULL, tmp);
if (!err)
err = simple_read_from_buffer(buf, len, ppos, tmp, strlen(tmp));
return err;
}
static const struct file_operations proc_fdinfo_file_operations = {
.open = nonseekable_open,
.read = proc_fdinfo_read,
};
static const struct file_operations proc_fd_operations = {
.read = generic_read_dir,
.readdir = proc_readfd,
};
/*
* /proc/pid/fd needs a special permission handler so that a process can still
* access /proc/self/fd after it has executed a setuid().
*/
static int proc_fd_permission(struct inode *inode, int mask)
{
int rv;
rv = generic_permission(inode, mask, NULL);
if (rv == 0)
return 0;
if (task_pid(current) == proc_pid(inode))
rv = 0;
return rv;
}
/*
* proc directories can do almost nothing..
*/
static const struct inode_operations proc_fd_inode_operations = {
.lookup = proc_lookupfd,
.permission = proc_fd_permission,
.setattr = proc_setattr,
};
static struct dentry *proc_fdinfo_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
unsigned fd = *(unsigned *)ptr;
struct inode *inode;
struct proc_inode *ei;
struct dentry *error = ERR_PTR(-ENOENT);
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
ei = PROC_I(inode);
ei->fd = fd;
inode->i_mode = S_IFREG | S_IRUSR;
inode->i_fop = &proc_fdinfo_file_operations;
dentry->d_op = &tid_fd_dentry_operations;
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (tid_fd_revalidate(dentry, NULL))
error = NULL;
out:
return error;
}
static struct dentry *proc_lookupfdinfo(struct inode *dir,
struct dentry *dentry,
struct nameidata *nd)
{
return proc_lookupfd_common(dir, dentry, proc_fdinfo_instantiate);
}
static int proc_readfdinfo(struct file *filp, void *dirent, filldir_t filldir)
{
return proc_readfd_common(filp, dirent, filldir,
proc_fdinfo_instantiate);
}
static const struct file_operations proc_fdinfo_operations = {
.read = generic_read_dir,
.readdir = proc_readfdinfo,
};
/*
* proc directories can do almost nothing..
*/
static const struct inode_operations proc_fdinfo_inode_operations = {
.lookup = proc_lookupfdinfo,
.setattr = proc_setattr,
};
static struct dentry *proc_pident_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
const struct pid_entry *p = ptr;
struct inode *inode;
struct proc_inode *ei;
struct dentry *error = ERR_PTR(-ENOENT);
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
ei = PROC_I(inode);
inode->i_mode = p->mode;
if (S_ISDIR(inode->i_mode))
inode->i_nlink = 2; /* Use getattr to fix if necessary */
if (p->iop)
inode->i_op = p->iop;
if (p->fop)
inode->i_fop = p->fop;
ei->op = p->op;
dentry->d_op = &pid_dentry_operations;
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (pid_revalidate(dentry, NULL))
error = NULL;
out:
return error;
}
static struct dentry *proc_pident_lookup(struct inode *dir,
struct dentry *dentry,
const struct pid_entry *ents,
unsigned int nents)
{
struct dentry *error;
struct task_struct *task = get_proc_task(dir);
const struct pid_entry *p, *last;
error = ERR_PTR(-ENOENT);
if (!task)
goto out_no_task;
/*
* Yes, it does not scale. And it should not. Don't add
* new entries into /proc/<tgid>/ without very good reasons.
*/
last = &ents[nents - 1];
for (p = ents; p <= last; p++) {
if (p->len != dentry->d_name.len)
continue;
if (!memcmp(dentry->d_name.name, p->name, p->len))
break;
}
if (p > last)
goto out;
error = proc_pident_instantiate(dir, dentry, task, p);
out:
put_task_struct(task);
out_no_task:
return error;
}
static int proc_pident_fill_cache(struct file *filp, void *dirent,
filldir_t filldir, struct task_struct *task, const struct pid_entry *p)
{
return proc_fill_cache(filp, dirent, filldir, p->name, p->len,
proc_pident_instantiate, task, p);
}
static int proc_pident_readdir(struct file *filp,
void *dirent, filldir_t filldir,
const struct pid_entry *ents, unsigned int nents)
{
int i;
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
const struct pid_entry *p, *last;
ino_t ino;
int ret;
ret = -ENOENT;
if (!task)
goto out_no_task;
ret = 0;
i = filp->f_pos;
switch (i) {
case 0:
ino = inode->i_ino;
if (filldir(dirent, ".", 1, i, ino, DT_DIR) < 0)
goto out;
i++;
filp->f_pos++;
/* fall through */
case 1:
ino = parent_ino(dentry);
if (filldir(dirent, "..", 2, i, ino, DT_DIR) < 0)
goto out;
i++;
filp->f_pos++;
/* fall through */
default:
i -= 2;
if (i >= nents) {
ret = 1;
goto out;
}
p = ents + i;
last = &ents[nents - 1];
while (p <= last) {
if (proc_pident_fill_cache(filp, dirent, filldir, task, p) < 0)
goto out;
filp->f_pos++;
p++;
}
}
ret = 1;
out:
put_task_struct(task);
out_no_task:
return ret;
}
#ifdef CONFIG_SECURITY
static ssize_t proc_pid_attr_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
char *p = NULL;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
if (!task)
return -ESRCH;
length = security_getprocattr(task,
(char*)file->f_path.dentry->d_name.name,
&p);
put_task_struct(task);
if (length > 0)
length = simple_read_from_buffer(buf, count, ppos, p, length);
kfree(p);
return length;
}
static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
char *page;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
length = -ESRCH;
if (!task)
goto out_no_task;
if (count > PAGE_SIZE)
count = PAGE_SIZE;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char*)__get_free_page(GFP_TEMPORARY);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out_free;
/* Guard against adverse ptrace interaction */
length = mutex_lock_interruptible(&task->cred_guard_mutex);
if (length < 0)
goto out_free;
length = security_setprocattr(task,
(char*)file->f_path.dentry->d_name.name,
(void*)page, count);
mutex_unlock(&task->cred_guard_mutex);
out_free:
free_page((unsigned long) page);
out:
put_task_struct(task);
out_no_task:
return length;
}
static const struct file_operations proc_pid_attr_operations = {
.read = proc_pid_attr_read,
.write = proc_pid_attr_write,
};
static const struct pid_entry attr_dir_stuff[] = {
REG("current", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("prev", S_IRUGO, proc_pid_attr_operations),
REG("exec", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("fscreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("keycreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("sockcreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
};
static int proc_attr_dir_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
return proc_pident_readdir(filp,dirent,filldir,
attr_dir_stuff,ARRAY_SIZE(attr_dir_stuff));
}
static const struct file_operations proc_attr_dir_operations = {
.read = generic_read_dir,
.readdir = proc_attr_dir_readdir,
};
static struct dentry *proc_attr_dir_lookup(struct inode *dir,
struct dentry *dentry, struct nameidata *nd)
{
return proc_pident_lookup(dir, dentry,
attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
}
static const struct inode_operations proc_attr_dir_inode_operations = {
.lookup = proc_attr_dir_lookup,
.getattr = pid_getattr,
.setattr = proc_setattr,
};
#endif
#ifdef CONFIG_ELF_CORE
static ssize_t proc_coredump_filter_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
struct mm_struct *mm;
char buffer[PROC_NUMBUF];
size_t len;
int ret;
if (!task)
return -ESRCH;
ret = 0;
mm = get_task_mm(task);
if (mm) {
len = snprintf(buffer, sizeof(buffer), "%08lx\n",
((mm->flags & MMF_DUMP_FILTER_MASK) >>
MMF_DUMP_FILTER_SHIFT));
mmput(mm);
ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
}
put_task_struct(task);
return ret;
}
static ssize_t proc_coredump_filter_write(struct file *file,
const char __user *buf,
size_t count,
loff_t *ppos)
{
struct task_struct *task;
struct mm_struct *mm;
char buffer[PROC_NUMBUF], *end;
unsigned int val;
int ret;
int i;
unsigned long mask;
ret = -EFAULT;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
goto out_no_task;
ret = -EINVAL;
val = (unsigned int)simple_strtoul(buffer, &end, 0);
if (*end == '\n')
end++;
if (end - buffer == 0)
goto out_no_task;
ret = -ESRCH;
task = get_proc_task(file->f_dentry->d_inode);
if (!task)
goto out_no_task;
ret = end - buffer;
mm = get_task_mm(task);
if (!mm)
goto out_no_mm;
for (i = 0, mask = 1; i < MMF_DUMP_FILTER_BITS; i++, mask <<= 1) {
if (val & mask)
set_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
else
clear_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
}
mmput(mm);
out_no_mm:
put_task_struct(task);
out_no_task:
return ret;
}
static const struct file_operations proc_coredump_filter_operations = {
.read = proc_coredump_filter_read,
.write = proc_coredump_filter_write,
};
#endif
/*
* /proc/self:
*/
static int proc_self_readlink(struct dentry *dentry, char __user *buffer,
int buflen)
{
struct pid_namespace *ns = dentry->d_sb->s_fs_info;
pid_t tgid = task_tgid_nr_ns(current, ns);
char tmp[PROC_NUMBUF];
if (!tgid)
return -ENOENT;
sprintf(tmp, "%d", tgid);
return vfs_readlink(dentry,buffer,buflen,tmp);
}
static void *proc_self_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct pid_namespace *ns = dentry->d_sb->s_fs_info;
pid_t tgid = task_tgid_nr_ns(current, ns);
char tmp[PROC_NUMBUF];
if (!tgid)
return ERR_PTR(-ENOENT);
sprintf(tmp, "%d", task_tgid_nr_ns(current, ns));
return ERR_PTR(vfs_follow_link(nd,tmp));
}
static const struct inode_operations proc_self_inode_operations = {
.readlink = proc_self_readlink,
.follow_link = proc_self_follow_link,
};
/*
* proc base
*
* These are the directory entries in the root directory of /proc
* that properly belong to the /proc filesystem, as they describe
* describe something that is process related.
*/
static const struct pid_entry proc_base_stuff[] = {
NOD("self", S_IFLNK|S_IRWXUGO,
&proc_self_inode_operations, NULL, {}),
};
/*
* Exceptional case: normally we are not allowed to unhash a busy
* directory. In this case, however, we can do it - no aliasing problems
* due to the way we treat inodes.
*/
static int proc_base_revalidate(struct dentry *dentry, struct nameidata *nd)
{
struct inode *inode = dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
if (task) {
put_task_struct(task);
return 1;
}
d_drop(dentry);
return 0;
}
static const struct dentry_operations proc_base_dentry_operations =
{
.d_revalidate = proc_base_revalidate,
.d_delete = pid_delete_dentry,
};
static struct dentry *proc_base_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
const struct pid_entry *p = ptr;
struct inode *inode;
struct proc_inode *ei;
struct dentry *error = ERR_PTR(-EINVAL);
/* Allocate the inode */
error = ERR_PTR(-ENOMEM);
inode = new_inode(dir->i_sb);
if (!inode)
goto out;
/* Initialize the inode */
ei = PROC_I(inode);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
/*
* grab the reference to the task.
*/
ei->pid = get_task_pid(task, PIDTYPE_PID);
if (!ei->pid)
goto out_iput;
inode->i_mode = p->mode;
if (S_ISDIR(inode->i_mode))
inode->i_nlink = 2;
if (S_ISLNK(inode->i_mode))
inode->i_size = 64;
if (p->iop)
inode->i_op = p->iop;
if (p->fop)
inode->i_fop = p->fop;
ei->op = p->op;
dentry->d_op = &proc_base_dentry_operations;
d_add(dentry, inode);
error = NULL;
out:
return error;
out_iput:
iput(inode);
goto out;
}
static struct dentry *proc_base_lookup(struct inode *dir, struct dentry *dentry)
{
struct dentry *error;
struct task_struct *task = get_proc_task(dir);
const struct pid_entry *p, *last;
error = ERR_PTR(-ENOENT);
if (!task)
goto out_no_task;
/* Lookup the directory entry */
last = &proc_base_stuff[ARRAY_SIZE(proc_base_stuff) - 1];
for (p = proc_base_stuff; p <= last; p++) {
if (p->len != dentry->d_name.len)
continue;
if (!memcmp(dentry->d_name.name, p->name, p->len))
break;
}
if (p > last)
goto out;
error = proc_base_instantiate(dir, dentry, task, p);
out:
put_task_struct(task);
out_no_task:
return error;
}
static int proc_base_fill_cache(struct file *filp, void *dirent,
filldir_t filldir, struct task_struct *task, const struct pid_entry *p)
{
return proc_fill_cache(filp, dirent, filldir, p->name, p->len,
proc_base_instantiate, task, p);
}
#ifdef CONFIG_TASK_IO_ACCOUNTING
static int do_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
return sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
}
static int proc_tid_io_accounting(struct task_struct *task, char *buffer)
{
return do_io_accounting(task, buffer, 0);
}
static int proc_tgid_io_accounting(struct task_struct *task, char *buffer)
{
return do_io_accounting(task, buffer, 1);
}
#endif /* CONFIG_TASK_IO_ACCOUNTING */
static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
seq_printf(m, "%08x\n", task->personality);
return 0;
}
/*
* Thread groups
*/
static const struct file_operations proc_task_operations;
static const struct inode_operations proc_task_inode_operations;
static const struct pid_entry tgid_base_stuff[] = {
DIR("task", S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
DIR("fd", S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
DIR("fdinfo", S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
#ifdef CONFIG_NET
DIR("net", S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
#endif
REG("environ", S_IRUSR, proc_environ_operations),
INF("auxv", S_IRUSR, proc_pid_auxv),
ONE("status", S_IRUGO, proc_pid_status),
ONE("personality", S_IRUSR, proc_pid_personality),
INF("limits", S_IRUSR, proc_pid_limits),
#ifdef CONFIG_SCHED_DEBUG
REG("sched", S_IRUGO|S_IWUSR, proc_pid_sched_operations),
#endif
REG("comm", S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
#ifdef CONFIG_HAVE_ARCH_TRACEHOOK
INF("syscall", S_IRUSR, proc_pid_syscall),
#endif
INF("cmdline", S_IRUGO, proc_pid_cmdline),
ONE("stat", S_IRUGO, proc_tgid_stat),
ONE("statm", S_IRUGO, proc_pid_statm),
REG("maps", S_IRUGO, proc_maps_operations),
#ifdef CONFIG_NUMA
REG("numa_maps", S_IRUGO, proc_numa_maps_operations),
#endif
REG("mem", S_IRUSR|S_IWUSR, proc_mem_operations),
LNK("cwd", proc_cwd_link),
LNK("root", proc_root_link),
LNK("exe", proc_exe_link),
REG("mounts", S_IRUGO, proc_mounts_operations),
REG("mountinfo", S_IRUGO, proc_mountinfo_operations),
REG("mountstats", S_IRUSR, proc_mountstats_operations),
#ifdef CONFIG_PROC_PAGE_MONITOR
REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
REG("smaps", S_IRUGO, proc_smaps_operations),
REG("pagemap", S_IRUSR, proc_pagemap_operations),
#endif
#ifdef CONFIG_SECURITY
DIR("attr", S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
#endif
#ifdef CONFIG_KALLSYMS
INF("wchan", S_IRUGO, proc_pid_wchan),
#endif
#ifdef CONFIG_STACKTRACE
ONE("stack", S_IRUSR, proc_pid_stack),
#endif
#ifdef CONFIG_SCHEDSTATS
INF("schedstat", S_IRUGO, proc_pid_schedstat),
#endif
#ifdef CONFIG_LATENCYTOP
REG("latency", S_IRUGO, proc_lstats_operations),
#endif
#ifdef CONFIG_PROC_PID_CPUSET
REG("cpuset", S_IRUGO, proc_cpuset_operations),
#endif
#ifdef CONFIG_CGROUPS
REG("cgroup", S_IRUGO, proc_cgroup_operations),
#endif
INF("oom_score", S_IRUGO, proc_oom_score),
REG("oom_adj", S_IRUGO|S_IWUSR, proc_oom_adjust_operations),
#ifdef CONFIG_AUDITSYSCALL
REG("loginuid", S_IWUSR|S_IRUGO, proc_loginuid_operations),
REG("sessionid", S_IRUGO, proc_sessionid_operations),
#endif
#ifdef CONFIG_FAULT_INJECTION
REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
#endif
#ifdef CONFIG_ELF_CORE
REG("coredump_filter", S_IRUGO|S_IWUSR, proc_coredump_filter_operations),
#endif
#ifdef CONFIG_TASK_IO_ACCOUNTING
INF("io", S_IRUGO, proc_tgid_io_accounting),
#endif
};
static int proc_tgid_base_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
return proc_pident_readdir(filp,dirent,filldir,
tgid_base_stuff,ARRAY_SIZE(tgid_base_stuff));
}
static const struct file_operations proc_tgid_base_operations = {
.read = generic_read_dir,
.readdir = proc_tgid_base_readdir,
};
static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd){
return proc_pident_lookup(dir, dentry,
tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
}
static const struct inode_operations proc_tgid_base_inode_operations = {
.lookup = proc_tgid_base_lookup,
.getattr = pid_getattr,
.setattr = proc_setattr,
};
static void proc_flush_task_mnt(struct vfsmount *mnt, pid_t pid, pid_t tgid)
{
struct dentry *dentry, *leader, *dir;
char buf[PROC_NUMBUF];
struct qstr name;
name.name = buf;
name.len = snprintf(buf, sizeof(buf), "%d", pid);
dentry = d_hash_and_lookup(mnt->mnt_root, &name);
if (dentry) {
shrink_dcache_parent(dentry);
d_drop(dentry);
dput(dentry);
}
name.name = buf;
name.len = snprintf(buf, sizeof(buf), "%d", tgid);
leader = d_hash_and_lookup(mnt->mnt_root, &name);
if (!leader)
goto out;
name.name = "task";
name.len = strlen(name.name);
dir = d_hash_and_lookup(leader, &name);
if (!dir)
goto out_put_leader;
name.name = buf;
name.len = snprintf(buf, sizeof(buf), "%d", pid);
dentry = d_hash_and_lookup(dir, &name);
if (dentry) {
shrink_dcache_parent(dentry);
d_drop(dentry);
dput(dentry);
}
dput(dir);
out_put_leader:
dput(leader);
out:
return;
}
/**
* proc_flush_task - Remove dcache entries for @task from the /proc dcache.
* @task: task that should be flushed.
*
* When flushing dentries from proc, one needs to flush them from global
* proc (proc_mnt) and from all the namespaces' procs this task was seen
* in. This call is supposed to do all of this job.
*
* Looks in the dcache for
* /proc/@pid
* /proc/@tgid/task/@pid
* if either directory is present flushes it and all of it'ts children
* from the dcache.
*
* It is safe and reasonable to cache /proc entries for a task until
* that task exits. After that they just clog up the dcache with
* useless entries, possibly causing useful dcache entries to be
* flushed instead. This routine is proved to flush those useless
* dcache entries at process exit time.
*
* NOTE: This routine is just an optimization so it does not guarantee
* that no dcache entries will exist at process exit time it
* just makes it very unlikely that any will persist.
*/
void proc_flush_task(struct task_struct *task)
{
int i;
struct pid *pid, *tgid;
struct upid *upid;
pid = task_pid(task);
tgid = task_tgid(task);
for (i = 0; i <= pid->level; i++) {
upid = &pid->numbers[i];
proc_flush_task_mnt(upid->ns->proc_mnt, upid->nr,
tgid->numbers[i].nr);
}
upid = &pid->numbers[pid->level];
if (upid->nr == 1)
pid_ns_release_proc(upid->ns);
}
static struct dentry *proc_pid_instantiate(struct inode *dir,
struct dentry * dentry,
struct task_struct *task, const void *ptr)
{
struct dentry *error = ERR_PTR(-ENOENT);
struct inode *inode;
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
inode->i_mode = S_IFDIR|S_IRUGO|S_IXUGO;
inode->i_op = &proc_tgid_base_inode_operations;
inode->i_fop = &proc_tgid_base_operations;
inode->i_flags|=S_IMMUTABLE;
inode->i_nlink = 2 + pid_entry_count_dirs(tgid_base_stuff,
ARRAY_SIZE(tgid_base_stuff));
dentry->d_op = &pid_dentry_operations;
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (pid_revalidate(dentry, NULL))
error = NULL;
out:
return error;
}
struct dentry *proc_pid_lookup(struct inode *dir, struct dentry * dentry, struct nameidata *nd)
{
struct dentry *result = ERR_PTR(-ENOENT);
struct task_struct *task;
unsigned tgid;
struct pid_namespace *ns;
result = proc_base_lookup(dir, dentry);
if (!IS_ERR(result) || PTR_ERR(result) != -ENOENT)
goto out;
tgid = name_to_int(dentry);
if (tgid == ~0U)
goto out;
ns = dentry->d_sb->s_fs_info;
rcu_read_lock();
task = find_task_by_pid_ns(tgid, ns);
if (task)
get_task_struct(task);
rcu_read_unlock();
if (!task)
goto out;
result = proc_pid_instantiate(dir, dentry, task, NULL);
put_task_struct(task);
out:
return result;
}
/*
* Find the first task with tgid >= tgid
*
*/
struct tgid_iter {
unsigned int tgid;
struct task_struct *task;
};
static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
{
struct pid *pid;
if (iter.task)
put_task_struct(iter.task);
rcu_read_lock();
retry:
iter.task = NULL;
pid = find_ge_pid(iter.tgid, ns);
if (pid) {
iter.tgid = pid_nr_ns(pid, ns);
iter.task = pid_task(pid, PIDTYPE_PID);
/* What we to know is if the pid we have find is the
* pid of a thread_group_leader. Testing for task
* being a thread_group_leader is the obvious thing
* todo but there is a window when it fails, due to
* the pid transfer logic in de_thread.
*
* So we perform the straight forward test of seeing
* if the pid we have found is the pid of a thread
* group leader, and don't worry if the task we have
* found doesn't happen to be a thread group leader.
* As we don't care in the case of readdir.
*/
if (!iter.task || !has_group_leader_pid(iter.task)) {
iter.tgid += 1;
goto retry;
}
get_task_struct(iter.task);
}
rcu_read_unlock();
return iter;
}
#define TGID_OFFSET (FIRST_PROCESS_ENTRY + ARRAY_SIZE(proc_base_stuff))
static int proc_pid_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
struct tgid_iter iter)
{
char name[PROC_NUMBUF];
int len = snprintf(name, sizeof(name), "%d", iter.tgid);
return proc_fill_cache(filp, dirent, filldir, name, len,
proc_pid_instantiate, iter.task, NULL);
}
/* for the /proc/ directory itself, after non-process stuff has been done */
int proc_pid_readdir(struct file * filp, void * dirent, filldir_t filldir)
{
unsigned int nr = filp->f_pos - FIRST_PROCESS_ENTRY;
struct task_struct *reaper = get_proc_task(filp->f_path.dentry->d_inode);
struct tgid_iter iter;
struct pid_namespace *ns;
if (!reaper)
goto out_no_task;
for (; nr < ARRAY_SIZE(proc_base_stuff); filp->f_pos++, nr++) {
const struct pid_entry *p = &proc_base_stuff[nr];
if (proc_base_fill_cache(filp, dirent, filldir, reaper, p) < 0)
goto out;
}
ns = filp->f_dentry->d_sb->s_fs_info;
iter.task = NULL;
iter.tgid = filp->f_pos - TGID_OFFSET;
for (iter = next_tgid(ns, iter);
iter.task;
iter.tgid += 1, iter = next_tgid(ns, iter)) {
filp->f_pos = iter.tgid + TGID_OFFSET;
if (proc_pid_fill_cache(filp, dirent, filldir, iter) < 0) {
put_task_struct(iter.task);
goto out;
}
}
filp->f_pos = PID_MAX_LIMIT + TGID_OFFSET;
out:
put_task_struct(reaper);
out_no_task:
return 0;
}
/*
* Tasks
*/
static const struct pid_entry tid_base_stuff[] = {
DIR("fd", S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
DIR("fdinfo", S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fd_operations),
REG("environ", S_IRUSR, proc_environ_operations),
INF("auxv", S_IRUSR, proc_pid_auxv),
ONE("status", S_IRUGO, proc_pid_status),
ONE("personality", S_IRUSR, proc_pid_personality),
INF("limits", S_IRUSR, proc_pid_limits),
#ifdef CONFIG_SCHED_DEBUG
REG("sched", S_IRUGO|S_IWUSR, proc_pid_sched_operations),
#endif
REG("comm", S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
#ifdef CONFIG_HAVE_ARCH_TRACEHOOK
INF("syscall", S_IRUSR, proc_pid_syscall),
#endif
INF("cmdline", S_IRUGO, proc_pid_cmdline),
ONE("stat", S_IRUGO, proc_tid_stat),
ONE("statm", S_IRUGO, proc_pid_statm),
REG("maps", S_IRUGO, proc_maps_operations),
#ifdef CONFIG_NUMA
REG("numa_maps", S_IRUGO, proc_numa_maps_operations),
#endif
REG("mem", S_IRUSR|S_IWUSR, proc_mem_operations),
LNK("cwd", proc_cwd_link),
LNK("root", proc_root_link),
LNK("exe", proc_exe_link),
REG("mounts", S_IRUGO, proc_mounts_operations),
REG("mountinfo", S_IRUGO, proc_mountinfo_operations),
#ifdef CONFIG_PROC_PAGE_MONITOR
REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
REG("smaps", S_IRUGO, proc_smaps_operations),
REG("pagemap", S_IRUSR, proc_pagemap_operations),
#endif
#ifdef CONFIG_SECURITY
DIR("attr", S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
#endif
#ifdef CONFIG_KALLSYMS
INF("wchan", S_IRUGO, proc_pid_wchan),
#endif
#ifdef CONFIG_STACKTRACE
ONE("stack", S_IRUSR, proc_pid_stack),
#endif
#ifdef CONFIG_SCHEDSTATS
INF("schedstat", S_IRUGO, proc_pid_schedstat),
#endif
#ifdef CONFIG_LATENCYTOP
REG("latency", S_IRUGO, proc_lstats_operations),
#endif
#ifdef CONFIG_PROC_PID_CPUSET
REG("cpuset", S_IRUGO, proc_cpuset_operations),
#endif
#ifdef CONFIG_CGROUPS
REG("cgroup", S_IRUGO, proc_cgroup_operations),
#endif
INF("oom_score", S_IRUGO, proc_oom_score),
REG("oom_adj", S_IRUGO|S_IWUSR, proc_oom_adjust_operations),
#ifdef CONFIG_AUDITSYSCALL
REG("loginuid", S_IWUSR|S_IRUGO, proc_loginuid_operations),
REG("sessionid", S_IRUSR, proc_sessionid_operations),
#endif
#ifdef CONFIG_FAULT_INJECTION
REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
#endif
#ifdef CONFIG_TASK_IO_ACCOUNTING
INF("io", S_IRUGO, proc_tid_io_accounting),
#endif
};
static int proc_tid_base_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
return proc_pident_readdir(filp,dirent,filldir,
tid_base_stuff,ARRAY_SIZE(tid_base_stuff));
}
static struct dentry *proc_tid_base_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd){
return proc_pident_lookup(dir, dentry,
tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
}
static const struct file_operations proc_tid_base_operations = {
.read = generic_read_dir,
.readdir = proc_tid_base_readdir,
};
static const struct inode_operations proc_tid_base_inode_operations = {
.lookup = proc_tid_base_lookup,
.getattr = pid_getattr,
.setattr = proc_setattr,
};
static struct dentry *proc_task_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
struct dentry *error = ERR_PTR(-ENOENT);
struct inode *inode;
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
inode->i_mode = S_IFDIR|S_IRUGO|S_IXUGO;
inode->i_op = &proc_tid_base_inode_operations;
inode->i_fop = &proc_tid_base_operations;
inode->i_flags|=S_IMMUTABLE;
inode->i_nlink = 2 + pid_entry_count_dirs(tid_base_stuff,
ARRAY_SIZE(tid_base_stuff));
dentry->d_op = &pid_dentry_operations;
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (pid_revalidate(dentry, NULL))
error = NULL;
out:
return error;
}
static struct dentry *proc_task_lookup(struct inode *dir, struct dentry * dentry, struct nameidata *nd)
{
struct dentry *result = ERR_PTR(-ENOENT);
struct task_struct *task;
struct task_struct *leader = get_proc_task(dir);
unsigned tid;
struct pid_namespace *ns;
if (!leader)
goto out_no_task;
tid = name_to_int(dentry);
if (tid == ~0U)
goto out;
ns = dentry->d_sb->s_fs_info;
rcu_read_lock();
task = find_task_by_pid_ns(tid, ns);
if (task)
get_task_struct(task);
rcu_read_unlock();
if (!task)
goto out;
if (!same_thread_group(leader, task))
goto out_drop_task;
result = proc_task_instantiate(dir, dentry, task, NULL);
out_drop_task:
put_task_struct(task);
out:
put_task_struct(leader);
out_no_task:
return result;
}
/*
* Find the first tid of a thread group to return to user space.
*
* Usually this is just the thread group leader, but if the users
* buffer was too small or there was a seek into the middle of the
* directory we have more work todo.
*
* In the case of a short read we start with find_task_by_pid.
*
* In the case of a seek we start with the leader and walk nr
* threads past it.
*/
static struct task_struct *first_tid(struct task_struct *leader,
int tid, int nr, struct pid_namespace *ns)
{
struct task_struct *pos;
rcu_read_lock();
/* Attempt to start with the pid of a thread */
if (tid && (nr > 0)) {
pos = find_task_by_pid_ns(tid, ns);
if (pos && (pos->group_leader == leader))
goto found;
}
/* If nr exceeds the number of threads there is nothing todo */
pos = NULL;
if (nr && nr >= get_nr_threads(leader))
goto out;
/* If we haven't found our starting place yet start
* with the leader and walk nr threads forward.
*/
for (pos = leader; nr > 0; --nr) {
pos = next_thread(pos);
if (pos == leader) {
pos = NULL;
goto out;
}
}
found:
get_task_struct(pos);
out:
rcu_read_unlock();
return pos;
}
/*
* Find the next thread in the thread list.
* Return NULL if there is an error or no next thread.
*
* The reference to the input task_struct is released.
*/
static struct task_struct *next_tid(struct task_struct *start)
{
struct task_struct *pos = NULL;
rcu_read_lock();
if (pid_alive(start)) {
pos = next_thread(start);
if (thread_group_leader(pos))
pos = NULL;
else
get_task_struct(pos);
}
rcu_read_unlock();
put_task_struct(start);
return pos;
}
static int proc_task_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
struct task_struct *task, int tid)
{
char name[PROC_NUMBUF];
int len = snprintf(name, sizeof(name), "%d", tid);
return proc_fill_cache(filp, dirent, filldir, name, len,
proc_task_instantiate, task, NULL);
}
/* for the /proc/TGID/task/ directories */
static int proc_task_readdir(struct file * filp, void * dirent, filldir_t filldir)
{
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct task_struct *leader = NULL;
struct task_struct *task;
int retval = -ENOENT;
ino_t ino;
int tid;
struct pid_namespace *ns;
task = get_proc_task(inode);
if (!task)
goto out_no_task;
rcu_read_lock();
if (pid_alive(task)) {
leader = task->group_leader;
get_task_struct(leader);
}
rcu_read_unlock();
put_task_struct(task);
if (!leader)
goto out_no_task;
retval = 0;
switch ((unsigned long)filp->f_pos) {
case 0:
ino = inode->i_ino;
if (filldir(dirent, ".", 1, filp->f_pos, ino, DT_DIR) < 0)
goto out;
filp->f_pos++;
/* fall through */
case 1:
ino = parent_ino(dentry);
if (filldir(dirent, "..", 2, filp->f_pos, ino, DT_DIR) < 0)
goto out;
filp->f_pos++;
/* fall through */
}
/* f_version caches the tgid value that the last readdir call couldn't
* return. lseek aka telldir automagically resets f_version to 0.
*/
ns = filp->f_dentry->d_sb->s_fs_info;
tid = (int)filp->f_version;
filp->f_version = 0;
for (task = first_tid(leader, tid, filp->f_pos - 2, ns);
task;
task = next_tid(task), filp->f_pos++) {
tid = task_pid_nr_ns(task, ns);
if (proc_task_fill_cache(filp, dirent, filldir, task, tid) < 0) {
/* returning this tgid failed, save it as the first
* pid for the next readir call */
filp->f_version = (u64)tid;
put_task_struct(task);
break;
}
}
out:
put_task_struct(leader);
out_no_task:
return retval;
}
static int proc_task_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
struct task_struct *p = get_proc_task(inode);
generic_fillattr(inode, stat);
if (p) {
stat->nlink += get_nr_threads(p);
put_task_struct(p);
}
return 0;
}
static const struct inode_operations proc_task_inode_operations = {
.lookup = proc_task_lookup,
.getattr = proc_task_getattr,
.setattr = proc_setattr,
};
static const struct file_operations proc_task_operations = {
.read = generic_read_dir,
.readdir = proc_task_readdir,
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2035_1 |
crossvul-cpp_data_good_5608_2 | /*
* ModSecurity for Apache 2.x, http://www.modsecurity.org/
* Copyright (c) 2004-2011 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* You may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*/
#include "msc_xml.h"
static xmlParserInputBufferPtr
xml_unload_external_entity(const char *URI, xmlCharEncoding enc) {
return NULL;
}
/**
* Initialise XML parser.
*/
int xml_init(modsec_rec *msr, char **error_msg) {
xmlParserInputBufferCreateFilenameFunc entity;
if (error_msg == NULL) return -1;
*error_msg = NULL;
msr->xml = apr_pcalloc(msr->mp, sizeof(xml_data));
if (msr->xml == NULL) return -1;
if(msr->txcfg->xml_external_entity == 0) {
entity = xmlParserInputBufferCreateFilenameDefault(xml_unload_external_entity);
}
return 1;
}
#if 0
static void xml_receive_sax_error(void *data, const char *msg, ...) {
modsec_rec *msr = (modsec_rec *)data;
char message[256];
if (msr == NULL) return;
apr_snprintf(message, sizeof(message), "%s (line %d offset %d)",
log_escape_nq(msr->mp, msr->xml->parsing_ctx->lastError.message),
msr->xml->parsing_ctx->lastError.line,
msr->xml->parsing_ctx->lastError.int2);
msr_log(msr, 5, "XML: Parsing error: %s", message);
}
#endif
/**
* Feed one chunk of data to the XML parser.
*/
int xml_process_chunk(modsec_rec *msr, const char *buf, unsigned int size, char **error_msg) {
if (error_msg == NULL) return -1;
*error_msg = NULL;
/* We want to initialise our parsing context here, to
* enable us to pass it the first chunk of data so that
* it can attempt to auto-detect the encoding.
*/
if (msr->xml->parsing_ctx == NULL) {
/* First invocation. */
msr_log(msr, 4, "XML: Initialising parser.");
/* NOTE When Sax interface is used libxml will not
* create the document object, but we need it.
msr->xml->sax_handler = (xmlSAXHandler *)apr_pcalloc(msr->mp, sizeof(xmlSAXHandler));
if (msr->xml->sax_handler == NULL) return -1;
msr->xml->sax_handler->error = xml_receive_sax_error;
msr->xml->sax_handler->warning = xml_receive_sax_error;
msr->xml->parsing_ctx = xmlCreatePushParserCtxt(msr->xml->sax_handler, msr,
buf, size, "body.xml");
*/
msr->xml->parsing_ctx = xmlCreatePushParserCtxt(NULL, NULL, buf, size, "body.xml");
if (msr->xml->parsing_ctx == NULL) {
*error_msg = apr_psprintf(msr->mp, "XML: Failed to create parsing context.");
return -1;
}
} else {
/* Not a first invocation. */
xmlParseChunk(msr->xml->parsing_ctx, buf, size, 0);
if (msr->xml->parsing_ctx->wellFormed != 1) {
*error_msg = apr_psprintf(msr->mp, "XML: Failed parsing document.");
return -1;
}
}
return 1;
}
/**
* Finalise XML parsing.
*/
int xml_complete(modsec_rec *msr, char **error_msg) {
if (error_msg == NULL) return -1;
*error_msg = NULL;
/* Only if we have a context, meaning we've done some work. */
if (msr->xml->parsing_ctx != NULL) {
/* This is how we signalise the end of parsing to libxml. */
xmlParseChunk(msr->xml->parsing_ctx, NULL, 0, 1);
/* Preserve the results for our reference. */
msr->xml->well_formed = msr->xml->parsing_ctx->wellFormed;
msr->xml->doc = msr->xml->parsing_ctx->myDoc;
/* Clean up everything else. */
xmlFreeParserCtxt(msr->xml->parsing_ctx);
msr->xml->parsing_ctx = NULL;
msr_log(msr, 4, "XML: Parsing complete (well_formed %u).", msr->xml->well_formed);
if (msr->xml->well_formed != 1) {
*error_msg = apr_psprintf(msr->mp, "XML: Failed parsing document.");
return -1;
}
}
return 1;
}
/**
* Frees the resources used for XML parsing.
*/
apr_status_t xml_cleanup(modsec_rec *msr) {
if (msr->xml->doc != NULL) {
xmlFreeDoc(msr->xml->doc);
msr->xml->doc = NULL;
}
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5608_2 |
crossvul-cpp_data_bad_4717_0 | /*
* reflection.c: Routines for creating an image at runtime.
*
* Author:
* Paolo Molaro (lupus@ximian.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*
*/
#include <config.h>
#include "mono/utils/mono-digest.h"
#include "mono/utils/mono-membar.h"
#include "mono/metadata/reflection.h"
#include "mono/metadata/tabledefs.h"
#include "mono/metadata/metadata-internals.h"
#include <mono/metadata/profiler-private.h>
#include "mono/metadata/class-internals.h"
#include "mono/metadata/gc-internal.h"
#include "mono/metadata/tokentype.h"
#include "mono/metadata/domain-internals.h"
#include "mono/metadata/opcodes.h"
#include "mono/metadata/assembly.h"
#include "mono/metadata/object-internals.h"
#include <mono/metadata/exception.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/security-manager.h>
#include <stdio.h>
#include <glib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include "image.h"
#include "cil-coff.h"
#include "mono-endian.h"
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/mono-ptr-array.h>
#include <mono/utils/mono-string.h>
#include <mono/utils/mono-error-internals.h>
#if HAVE_SGEN_GC
static void* reflection_info_desc = NULL;
#define MOVING_GC_REGISTER(addr) do { \
if (!reflection_info_desc) { \
gsize bmap = 1; \
reflection_info_desc = mono_gc_make_descr_from_bitmap (&bmap, 1); \
} \
mono_gc_register_root ((char*)(addr), sizeof (gpointer), reflection_info_desc); \
} while (0)
#else
#define MOVING_GC_REGISTER(addr)
#endif
static gboolean is_usertype (MonoReflectionType *ref);
static MonoReflectionType *mono_reflection_type_resolve_user_types (MonoReflectionType *type);
typedef struct {
char *p;
char *buf;
char *end;
} SigBuffer;
#define TEXT_OFFSET 512
#define CLI_H_SIZE 136
#define FILE_ALIGN 512
#define VIRT_ALIGN 8192
#define START_TEXT_RVA 0x00002000
typedef struct {
MonoReflectionILGen *ilgen;
MonoReflectionType *rtype;
MonoArray *parameters;
MonoArray *generic_params;
MonoGenericContainer *generic_container;
MonoArray *pinfo;
MonoArray *opt_types;
guint32 attrs;
guint32 iattrs;
guint32 call_conv;
guint32 *table_idx; /* note: it's a pointer */
MonoArray *code;
MonoObject *type;
MonoString *name;
MonoBoolean init_locals;
MonoBoolean skip_visibility;
MonoArray *return_modreq;
MonoArray *return_modopt;
MonoArray *param_modreq;
MonoArray *param_modopt;
MonoArray *permissions;
MonoMethod *mhandle;
guint32 nrefs;
gpointer *refs;
/* for PInvoke */
int charset, extra_flags, native_cc;
MonoString *dll, *dllentry;
} ReflectionMethodBuilder;
typedef struct {
guint32 owner;
MonoReflectionGenericParam *gparam;
} GenericParamTableEntry;
const unsigned char table_sizes [MONO_TABLE_NUM] = {
MONO_MODULE_SIZE,
MONO_TYPEREF_SIZE,
MONO_TYPEDEF_SIZE,
0,
MONO_FIELD_SIZE,
0,
MONO_METHOD_SIZE,
0,
MONO_PARAM_SIZE,
MONO_INTERFACEIMPL_SIZE,
MONO_MEMBERREF_SIZE, /* 0x0A */
MONO_CONSTANT_SIZE,
MONO_CUSTOM_ATTR_SIZE,
MONO_FIELD_MARSHAL_SIZE,
MONO_DECL_SECURITY_SIZE,
MONO_CLASS_LAYOUT_SIZE,
MONO_FIELD_LAYOUT_SIZE, /* 0x10 */
MONO_STAND_ALONE_SIGNATURE_SIZE,
MONO_EVENT_MAP_SIZE,
0,
MONO_EVENT_SIZE,
MONO_PROPERTY_MAP_SIZE,
0,
MONO_PROPERTY_SIZE,
MONO_METHOD_SEMA_SIZE,
MONO_METHODIMPL_SIZE,
MONO_MODULEREF_SIZE, /* 0x1A */
MONO_TYPESPEC_SIZE,
MONO_IMPLMAP_SIZE,
MONO_FIELD_RVA_SIZE,
0,
0,
MONO_ASSEMBLY_SIZE, /* 0x20 */
MONO_ASSEMBLY_PROCESSOR_SIZE,
MONO_ASSEMBLYOS_SIZE,
MONO_ASSEMBLYREF_SIZE,
MONO_ASSEMBLYREFPROC_SIZE,
MONO_ASSEMBLYREFOS_SIZE,
MONO_FILE_SIZE,
MONO_EXP_TYPE_SIZE,
MONO_MANIFEST_SIZE,
MONO_NESTED_CLASS_SIZE,
MONO_GENERICPARAM_SIZE, /* 0x2A */
MONO_METHODSPEC_SIZE,
MONO_GENPARCONSTRAINT_SIZE
};
#ifndef DISABLE_REFLECTION_EMIT
static guint32 mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec);
static guint32 mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec);
static guint32 mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *cb);
static guint32 mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper);
static void ensure_runtime_vtable (MonoClass *klass);
static gpointer resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context);
static guint32 mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method);
static guint32 encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context);
static gpointer register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly);
static void reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb);
static void reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb);
static guint32 create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb);
#endif
static guint32 mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type);
static guint32 mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec);
static void mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly);
static guint32 encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo);
static guint32 encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type);
static char* type_get_qualified_name (MonoType *type, MonoAssembly *ass);
static void encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf);
static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types);
static MonoReflectionType *mono_reflection_type_get_underlying_system_type (MonoReflectionType* t);
static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve);
static MonoReflectionType* mono_reflection_type_resolve_user_types (MonoReflectionType *type);
static gboolean is_sre_array (MonoClass *class);
static gboolean is_sre_byref (MonoClass *class);
static gboolean is_sre_pointer (MonoClass *class);
static gboolean is_sre_type_builder (MonoClass *class);
static gboolean is_sre_method_builder (MonoClass *class);
static gboolean is_sre_ctor_builder (MonoClass *class);
static gboolean is_sre_field_builder (MonoClass *class);
static gboolean is_sr_mono_method (MonoClass *class);
static gboolean is_sr_mono_cmethod (MonoClass *class);
static gboolean is_sr_mono_generic_method (MonoClass *class);
static gboolean is_sr_mono_generic_cmethod (MonoClass *class);
static gboolean is_sr_mono_field (MonoClass *class);
static gboolean is_sr_mono_property (MonoClass *class);
static gboolean is_sre_method_on_tb_inst (MonoClass *class);
static gboolean is_sre_ctor_on_tb_inst (MonoClass *class);
static guint32 mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method);
static guint32 mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m);
static MonoMethod * inflate_method (MonoReflectionType *type, MonoObject *obj);
#define RESOLVE_TYPE(type) do { type = (void*)mono_reflection_type_resolve_user_types ((MonoReflectionType*)type); } while (0)
#define RESOLVE_ARRAY_TYPE_ELEMENT(array, index) do { \
MonoReflectionType *__type = mono_array_get (array, MonoReflectionType*, index); \
__type = mono_reflection_type_resolve_user_types (__type); \
mono_array_set (arr, MonoReflectionType*, index, __type); \
} while (0)
#define mono_type_array_get_and_resolve(array, index) mono_reflection_type_get_handle ((MonoReflectionType*)mono_array_get (array, gpointer, index))
void
mono_reflection_init (void)
{
}
static void
sigbuffer_init (SigBuffer *buf, int size)
{
buf->buf = g_malloc (size);
buf->p = buf->buf;
buf->end = buf->buf + size;
}
static void
sigbuffer_make_room (SigBuffer *buf, int size)
{
if (buf->end - buf->p < size) {
int new_size = buf->end - buf->buf + size + 32;
char *p = g_realloc (buf->buf, new_size);
size = buf->p - buf->buf;
buf->buf = p;
buf->p = p + size;
buf->end = buf->buf + new_size;
}
}
static void
sigbuffer_add_value (SigBuffer *buf, guint32 val)
{
sigbuffer_make_room (buf, 6);
mono_metadata_encode_value (val, buf->p, &buf->p);
}
static void
sigbuffer_add_byte (SigBuffer *buf, guint8 val)
{
sigbuffer_make_room (buf, 1);
buf->p [0] = val;
buf->p++;
}
static void
sigbuffer_add_mem (SigBuffer *buf, char *p, guint32 size)
{
sigbuffer_make_room (buf, size);
memcpy (buf->p, p, size);
buf->p += size;
}
static void
sigbuffer_free (SigBuffer *buf)
{
g_free (buf->buf);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mp_g_alloc:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc (image, size);
else
return g_malloc (size);
}
#endif /* !DISABLE_REFLECTION_EMIT */
/**
* image_g_alloc0:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc0 (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc0 (image, size);
else
return g_malloc0 (size);
}
#ifndef DISABLE_REFLECTION_EMIT
static char*
image_strdup (MonoImage *image, const char *s)
{
if (image)
return mono_image_strdup (image, s);
else
return g_strdup (s);
}
#endif
#define image_g_new(image,struct_type, n_structs) \
((struct_type *) image_g_malloc (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
#define image_g_new0(image,struct_type, n_structs) \
((struct_type *) image_g_malloc0 (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
static void
alloc_table (MonoDynamicTable *table, guint nrows)
{
table->rows = nrows;
g_assert (table->columns);
if (nrows + 1 >= table->alloc_rows) {
while (nrows + 1 >= table->alloc_rows) {
if (table->alloc_rows == 0)
table->alloc_rows = 16;
else
table->alloc_rows *= 2;
}
table->values = g_renew (guint32, table->values, (table->alloc_rows) * table->columns);
}
}
static void
make_room_in_stream (MonoDynamicStream *stream, int size)
{
if (size <= stream->alloc_size)
return;
while (stream->alloc_size <= size) {
if (stream->alloc_size < 4096)
stream->alloc_size = 4096;
else
stream->alloc_size *= 2;
}
stream->data = g_realloc (stream->data, stream->alloc_size);
}
static guint32
string_heap_insert (MonoDynamicStream *sh, const char *str)
{
guint32 idx;
guint32 len;
gpointer oldkey, oldval;
if (g_hash_table_lookup_extended (sh->hash, str, &oldkey, &oldval))
return GPOINTER_TO_UINT (oldval);
len = strlen (str) + 1;
idx = sh->index;
make_room_in_stream (sh, idx + len);
/*
* We strdup the string even if we already copy them in sh->data
* so that the string pointers in the hash remain valid even if
* we need to realloc sh->data. We may want to avoid that later.
*/
g_hash_table_insert (sh->hash, g_strdup (str), GUINT_TO_POINTER (idx));
memcpy (sh->data + idx, str, len);
sh->index += len;
return idx;
}
static guint32
string_heap_insert_mstring (MonoDynamicStream *sh, MonoString *str)
{
char *name = mono_string_to_utf8 (str);
guint32 idx;
idx = string_heap_insert (sh, name);
g_free (name);
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
string_heap_init (MonoDynamicStream *sh)
{
sh->index = 0;
sh->alloc_size = 4096;
sh->data = g_malloc (4096);
sh->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
string_heap_insert (sh, "");
}
#endif
static guint32
mono_image_add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memcpy (stream->data + stream->index, data, len);
idx = stream->index;
stream->index += len;
/*
* align index? Not without adding an additional param that controls it since
* we may store a blob value in pieces.
*/
return idx;
}
static guint32
mono_image_add_stream_zero (MonoDynamicStream *stream, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memset (stream->data + stream->index, 0, len);
idx = stream->index;
stream->index += len;
return idx;
}
static void
stream_data_align (MonoDynamicStream *stream)
{
char buf [4] = {0};
guint32 count = stream->index % 4;
/* we assume the stream data will be aligned */
if (count)
mono_image_add_stream_data (stream, buf, 4 - count);
}
#ifndef DISABLE_REFLECTION_EMIT
static int
mono_blob_entry_hash (const char* str)
{
guint len, h;
const char *end;
len = mono_metadata_decode_blob_size (str, &str);
if (len > 0) {
end = str + len;
h = *str;
for (str += 1; str < end; str++)
h = (h << 5) - h + *str;
return h;
} else {
return 0;
}
}
static gboolean
mono_blob_entry_equal (const char *str1, const char *str2) {
int len, len2;
const char *end1;
const char *end2;
len = mono_metadata_decode_blob_size (str1, &end1);
len2 = mono_metadata_decode_blob_size (str2, &end2);
if (len != len2)
return 0;
return memcmp (end1, end2, len) == 0;
}
#endif
static guint32
add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2)
{
guint32 idx;
char *copy;
gpointer oldkey, oldval;
copy = g_malloc (s1+s2);
memcpy (copy, b1, s1);
memcpy (copy + s1, b2, s2);
if (g_hash_table_lookup_extended (assembly->blob_cache, copy, &oldkey, &oldval)) {
g_free (copy);
idx = GPOINTER_TO_UINT (oldval);
} else {
idx = mono_image_add_stream_data (&assembly->blob, b1, s1);
mono_image_add_stream_data (&assembly->blob, b2, s2);
g_hash_table_insert (assembly->blob_cache, copy, GUINT_TO_POINTER (idx));
}
return idx;
}
static guint32
sigbuffer_add_to_blob_cached (MonoDynamicImage *assembly, SigBuffer *buf)
{
char blob_size [8];
char *b = blob_size;
guint32 size = buf->p - buf->buf;
/* store length */
g_assert (size <= (buf->end - buf->buf));
mono_metadata_encode_value (size, b, &b);
return add_to_blob_cached (assembly, blob_size, b-blob_size, buf->buf, size);
}
/*
* Copy len * nelem bytes from val to dest, swapping bytes to LE if necessary.
* dest may be misaligned.
*/
static void
swap_with_size (char *dest, const char* val, int len, int nelem) {
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
int elem;
for (elem = 0; elem < nelem; ++elem) {
switch (len) {
case 1:
*dest = *val;
break;
case 2:
dest [0] = val [1];
dest [1] = val [0];
break;
case 4:
dest [0] = val [3];
dest [1] = val [2];
dest [2] = val [1];
dest [3] = val [0];
break;
case 8:
dest [0] = val [7];
dest [1] = val [6];
dest [2] = val [5];
dest [3] = val [4];
dest [4] = val [3];
dest [5] = val [2];
dest [6] = val [1];
dest [7] = val [0];
break;
default:
g_assert_not_reached ();
}
dest += len;
val += len;
}
#else
memcpy (dest, val, len * nelem);
#endif
}
static guint32
add_mono_string_to_blob_cached (MonoDynamicImage *assembly, MonoString *str)
{
char blob_size [64];
char *b = blob_size;
guint32 idx = 0, len;
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoClass *
default_class_from_mono_type (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_OBJECT:
return mono_defaults.object_class;
case MONO_TYPE_VOID:
return mono_defaults.void_class;
case MONO_TYPE_BOOLEAN:
return mono_defaults.boolean_class;
case MONO_TYPE_CHAR:
return mono_defaults.char_class;
case MONO_TYPE_I1:
return mono_defaults.sbyte_class;
case MONO_TYPE_U1:
return mono_defaults.byte_class;
case MONO_TYPE_I2:
return mono_defaults.int16_class;
case MONO_TYPE_U2:
return mono_defaults.uint16_class;
case MONO_TYPE_I4:
return mono_defaults.int32_class;
case MONO_TYPE_U4:
return mono_defaults.uint32_class;
case MONO_TYPE_I:
return mono_defaults.int_class;
case MONO_TYPE_U:
return mono_defaults.uint_class;
case MONO_TYPE_I8:
return mono_defaults.int64_class;
case MONO_TYPE_U8:
return mono_defaults.uint64_class;
case MONO_TYPE_R4:
return mono_defaults.single_class;
case MONO_TYPE_R8:
return mono_defaults.double_class;
case MONO_TYPE_STRING:
return mono_defaults.string_class;
default:
g_warning ("default_class_from_mono_type: implement me 0x%02x\n", type->type);
g_assert_not_reached ();
}
return NULL;
}
#endif
/*
* mono_class_get_ref_info:
*
* Return the type builder/generic param builder corresponding to KLASS, if it exists.
*/
gpointer
mono_class_get_ref_info (MonoClass *klass)
{
if (klass->ref_info_handle == 0)
return NULL;
else
return mono_gchandle_get_target (klass->ref_info_handle);
}
void
mono_class_set_ref_info (MonoClass *klass, gpointer obj)
{
klass->ref_info_handle = mono_gchandle_new ((MonoObject*)obj, FALSE);
g_assert (klass->ref_info_handle != 0);
}
void
mono_class_free_ref_info (MonoClass *klass)
{
if (klass->ref_info_handle) {
mono_gchandle_free (klass->ref_info_handle);
klass->ref_info_handle = 0;
}
}
static void
encode_generic_class (MonoDynamicImage *assembly, MonoGenericClass *gclass, SigBuffer *buf)
{
int i;
MonoGenericInst *class_inst;
MonoClass *klass;
g_assert (gclass);
class_inst = gclass->context.class_inst;
sigbuffer_add_value (buf, MONO_TYPE_GENERICINST);
klass = gclass->container_class;
sigbuffer_add_value (buf, klass->byval_arg.type);
sigbuffer_add_value (buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
sigbuffer_add_value (buf, class_inst->type_argc);
for (i = 0; i < class_inst->type_argc; ++i)
encode_type (assembly, class_inst->type_argv [i], buf);
}
static void
encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf)
{
if (!type) {
g_assert_not_reached ();
return;
}
if (type->byref)
sigbuffer_add_value (buf, MONO_TYPE_BYREF);
switch (type->type){
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
sigbuffer_add_value (buf, type->type);
break;
case MONO_TYPE_PTR:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, type->data.type, buf);
break;
case MONO_TYPE_SZARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.klass->byval_arg, buf);
break;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS: {
MonoClass *k = mono_class_from_mono_type (type);
if (k->generic_container) {
MonoGenericClass *gclass = mono_metadata_lookup_generic_class (k, k->generic_container->context.class_inst, TRUE);
encode_generic_class (assembly, gclass, buf);
} else {
/*
* Make sure we use the correct type.
*/
sigbuffer_add_value (buf, k->byval_arg.type);
/*
* ensure only non-byref gets passed to mono_image_typedef_or_ref(),
* otherwise two typerefs could point to the same type, leading to
* verification errors.
*/
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, &k->byval_arg));
}
break;
}
case MONO_TYPE_ARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.array->eklass->byval_arg, buf);
sigbuffer_add_value (buf, type->data.array->rank);
sigbuffer_add_value (buf, 0); /* FIXME: set to 0 for now */
sigbuffer_add_value (buf, 0);
break;
case MONO_TYPE_GENERICINST:
encode_generic_class (assembly, type->data.generic_class, buf);
break;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
sigbuffer_add_value (buf, type->type);
sigbuffer_add_value (buf, mono_type_get_generic_param_num (type));
break;
default:
g_error ("need to encode type %x", type->type);
}
}
static void
encode_reflection_type (MonoDynamicImage *assembly, MonoReflectionType *type, SigBuffer *buf)
{
if (!type) {
sigbuffer_add_value (buf, MONO_TYPE_VOID);
return;
}
encode_type (assembly, mono_reflection_type_get_handle (type), buf);
}
static void
encode_custom_modifiers (MonoDynamicImage *assembly, MonoArray *modreq, MonoArray *modopt, SigBuffer *buf)
{
int i;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_REQD);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
method_encode_signature (MonoDynamicImage *assembly, MonoMethodSignature *sig)
{
SigBuffer buf;
int i;
guint32 nparams = sig->param_count;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
idx = sig->call_convention;
if (sig->hasthis)
idx |= 0x20; /* hasthis */
if (sig->generic_param_count)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (sig->generic_param_count)
sigbuffer_add_value (&buf, sig->generic_param_count);
sigbuffer_add_value (&buf, nparams);
encode_type (assembly, sig->ret, &buf);
for (i = 0; i < nparams; ++i) {
if (i == sig->sentinelpos)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
encode_type (assembly, sig->params [i], &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
method_builder_encode_signature (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
/*
* FIXME: reuse code from method_encode_signature().
*/
SigBuffer buf;
int i;
guint32 nparams = mb->parameters ? mono_array_length (mb->parameters): 0;
guint32 ngparams = mb->generic_params ? mono_array_length (mb->generic_params): 0;
guint32 notypes = mb->opt_types ? mono_array_length (mb->opt_types): 0;
guint32 idx;
sigbuffer_init (&buf, 32);
/* LAMESPEC: all the call conv spec is foobared */
idx = mb->call_conv & 0x60; /* has-this, explicit-this */
if (mb->call_conv & 2)
idx |= 0x5; /* vararg */
if (!(mb->attrs & METHOD_ATTRIBUTE_STATIC))
idx |= 0x20; /* hasthis */
if (ngparams)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (ngparams)
sigbuffer_add_value (&buf, ngparams);
sigbuffer_add_value (&buf, nparams + notypes);
encode_custom_modifiers (assembly, mb->return_modreq, mb->return_modopt, &buf);
encode_reflection_type (assembly, mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoArray *modreq = NULL;
MonoArray *modopt = NULL;
MonoReflectionType *pt;
if (mb->param_modreq && (i < mono_array_length (mb->param_modreq)))
modreq = mono_array_get (mb->param_modreq, MonoArray*, i);
if (mb->param_modopt && (i < mono_array_length (mb->param_modopt)))
modopt = mono_array_get (mb->param_modopt, MonoArray*, i);
encode_custom_modifiers (assembly, modreq, modopt, &buf);
pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
if (notypes)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
for (i = 0; i < notypes; ++i) {
MonoReflectionType *pt;
pt = mono_array_get (mb->opt_types, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_locals (MonoDynamicImage *assembly, MonoReflectionILGen *ilgen)
{
MonoDynamicTable *table;
guint32 *values;
guint32 idx, sig_idx;
guint nl = mono_array_length (ilgen->locals);
SigBuffer buf;
int i;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, nl);
for (i = 0; i < nl; ++i) {
MonoReflectionLocalBuilder *lb = mono_array_get (ilgen->locals, MonoReflectionLocalBuilder*, i);
if (lb->is_pinned)
sigbuffer_add_value (&buf, MONO_TYPE_PINNED);
encode_reflection_type (assembly, (MonoReflectionType*)lb->type, &buf);
}
sig_idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
if (assembly->standalonesig_cache == NULL)
assembly->standalonesig_cache = g_hash_table_new (NULL, NULL);
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx)));
if (idx)
return idx;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] = sig_idx;
g_hash_table_insert (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx), GUINT_TO_POINTER (idx));
return idx;
}
static guint32
method_count_clauses (MonoReflectionILGen *ilgen)
{
guint32 num_clauses = 0;
int i;
MonoILExceptionInfo *ex_info;
for (i = 0; i < mono_array_length (ilgen->ex_handlers); ++i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers)
num_clauses += mono_array_length (ex_info->handlers);
else
num_clauses++;
}
return num_clauses;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoExceptionClause*
method_encode_clauses (MonoImage *image, MonoDynamicImage *assembly, MonoReflectionILGen *ilgen, guint32 num_clauses)
{
MonoExceptionClause *clauses;
MonoExceptionClause *clause;
MonoILExceptionInfo *ex_info;
MonoILExceptionBlock *ex_block;
guint32 finally_start;
int i, j, clause_index;;
clauses = image_g_new0 (image, MonoExceptionClause, num_clauses);
clause_index = 0;
for (i = mono_array_length (ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
finally_start = ex_info->start + ex_info->len;
if (!ex_info->handlers)
continue;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
clause = &(clauses [clause_index]);
clause->flags = ex_block->type;
clause->try_offset = ex_info->start;
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
clause->try_len = finally_start - ex_info->start;
else
clause->try_len = ex_info->len;
clause->handler_offset = ex_block->start;
clause->handler_len = ex_block->len;
if (ex_block->extype) {
clause->data.catch_class = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
clause->data.filter_offset = ex_block->filter_offset;
else
clause->data.filter_offset = 0;
}
finally_start = ex_block->start + ex_block->len;
clause_index ++;
}
}
return clauses;
}
#endif /* !DISABLE_REFLECTION_EMIT */
static guint32
method_encode_code (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
char flags = 0;
guint32 idx;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_exception = 0;
gint maybe_small;
guint32 fat_flags;
char fat_header [12];
guint32 int_value;
guint16 short_value;
guint32 local_sig = 0;
guint32 header_size = 12;
MonoArray *code;
if ((mb->attrs & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT)) ||
(mb->iattrs & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)))
return 0;
/*if (mb->name)
g_print ("Encode method %s\n", mono_string_to_utf8 (mb->name));*/
if (mb->ilgen) {
code = mb->ilgen->code;
code_size = mb->ilgen->code_len;
max_stack = mb->ilgen->max_stack;
num_locals = mb->ilgen->locals ? mono_array_length (mb->ilgen->locals) : 0;
if (mb->ilgen->ex_handlers)
num_exception = method_count_clauses (mb->ilgen);
} else {
code = mb->code;
if (code == NULL){
char *name = mono_string_to_utf8 (mb->name);
char *str = g_strdup_printf ("Method %s does not have any IL associated", name);
MonoException *exception = mono_get_exception_argument (NULL, "a method does not have any IL associated");
g_free (str);
g_free (name);
mono_raise_exception (exception);
}
code_size = mono_array_length (code);
max_stack = 8; /* we probably need to run a verifier on the code... */
}
stream_data_align (&assembly->code);
/* check for exceptions, maxstack, locals */
maybe_small = (max_stack <= 8) && (!num_locals) && (!num_exception);
if (maybe_small) {
if (code_size < 64 && !(code_size & 1)) {
flags = (code_size << 2) | 0x2;
} else if (code_size < 32 && (code_size & 1)) {
flags = (code_size << 2) | 0x6; /* LAMESPEC: see metadata.c */
} else {
goto fat_header;
}
idx = mono_image_add_stream_data (&assembly->code, &flags, 1);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 1));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
return assembly->text_rva + idx;
}
fat_header:
if (num_locals)
local_sig = MONO_TOKEN_SIGNATURE | encode_locals (assembly, mb->ilgen);
/*
* FIXME: need to set also the header size in fat_flags.
* (and more sects and init locals flags)
*/
fat_flags = 0x03;
if (num_exception)
fat_flags |= METHOD_HEADER_MORE_SECTS;
if (mb->init_locals)
fat_flags |= METHOD_HEADER_INIT_LOCALS;
fat_header [0] = fat_flags;
fat_header [1] = (header_size / 4 ) << 4;
short_value = GUINT16_TO_LE (max_stack);
memcpy (fat_header + 2, &short_value, 2);
int_value = GUINT32_TO_LE (code_size);
memcpy (fat_header + 4, &int_value, 4);
int_value = GUINT32_TO_LE (local_sig);
memcpy (fat_header + 8, &int_value, 4);
idx = mono_image_add_stream_data (&assembly->code, fat_header, 12);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 12));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
if (num_exception) {
unsigned char sheader [4];
MonoILExceptionInfo * ex_info;
MonoILExceptionBlock * ex_block;
int j;
stream_data_align (&assembly->code);
/* always use fat format for now */
sheader [0] = METHOD_HEADER_SECTION_FAT_FORMAT | METHOD_HEADER_SECTION_EHTABLE;
num_exception *= 6 * sizeof (guint32);
num_exception += 4; /* include the size of the header */
sheader [1] = num_exception & 0xff;
sheader [2] = (num_exception >> 8) & 0xff;
sheader [3] = (num_exception >> 16) & 0xff;
mono_image_add_stream_data (&assembly->code, (char*)sheader, 4);
/* fat header, so we are already aligned */
/* reverse order */
for (i = mono_array_length (mb->ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo *)mono_array_addr (mb->ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers) {
int finally_start = ex_info->start + ex_info->len;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
guint32 val;
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
/* the flags */
val = GUINT32_TO_LE (ex_block->type);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* try offset */
val = GUINT32_TO_LE (ex_info->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* need fault, too, probably */
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
val = GUINT32_TO_LE (finally_start - ex_info->start);
else
val = GUINT32_TO_LE (ex_info->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler offset */
val = GUINT32_TO_LE (ex_block->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler len */
val = GUINT32_TO_LE (ex_block->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
finally_start = ex_block->start + ex_block->len;
if (ex_block->extype) {
val = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype)));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
val = ex_block->filter_offset;
else
val = 0;
}
val = GUINT32_TO_LE (val);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/*g_print ("out clause %d: from %d len=%d, handler at %d, %d, finally_start=%d, ex_info->start=%d, ex_info->len=%d, ex_block->type=%d, j=%d, i=%d\n",
clause.flags, clause.try_offset, clause.try_len, clause.handler_offset, clause.handler_len, finally_start, ex_info->start, ex_info->len, ex_block->type, j, i);*/
}
} else {
g_error ("No clauses for ex info block %d", i);
}
}
}
return assembly->text_rva + idx;
}
static guint32
find_index_in_table (MonoDynamicImage *assembly, int table_idx, int col, guint32 token)
{
int i;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [table_idx];
g_assert (col < table->columns);
values = table->values + table->columns;
for (i = 1; i <= table->rows; ++i) {
if (values [col] == token)
return i;
values += table->columns;
}
return 0;
}
/*
* LOCKING: Acquires the loader lock.
*/
static MonoCustomAttrInfo*
lookup_custom_attr (MonoImage *image, gpointer member)
{
MonoCustomAttrInfo* res;
res = mono_image_property_lookup (image, member, MONO_PROP_DYNAMIC_CATTR);
if (!res)
return NULL;
return g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
}
static gboolean
custom_attr_visible (MonoImage *image, MonoReflectionCustomAttr *cattr)
{
/* FIXME: Need to do more checks */
if (cattr->ctor->method && (cattr->ctor->method->klass->image != image)) {
int visibility = cattr->ctor->method->klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if ((visibility != TYPE_ATTRIBUTE_PUBLIC) && (visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC))
return FALSE;
}
return TRUE;
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArray *cattrs)
{
int i, index, count, not_visible;
MonoCustomAttrInfo *ainfo;
MonoReflectionCustomAttr *cattr;
if (!cattrs)
return NULL;
/* FIXME: check in assembly the Run flag is set */
count = mono_array_length (cattrs);
/* Skip nonpublic attributes since MS.NET seems to do the same */
/* FIXME: This needs to be done more globally */
not_visible = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (!custom_attr_visible (image, cattr))
not_visible ++;
}
count -= not_visible;
ainfo = image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count);
ainfo->image = image;
ainfo->num_attrs = count;
ainfo->cached = alloc_img != NULL;
index = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (custom_attr_visible (image, cattr)) {
unsigned char *saved = mono_image_alloc (image, mono_array_length (cattr->data));
memcpy (saved, mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
ainfo->attrs [index].ctor = cattr->ctor->method;
ainfo->attrs [index].data = saved;
ainfo->attrs [index].data_size = mono_array_length (cattr->data);
index ++;
}
}
return ainfo;
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* LOCKING: Acquires the loader lock.
*/
static void
mono_save_custom_attrs (MonoImage *image, void *obj, MonoArray *cattrs)
{
MonoCustomAttrInfo *ainfo, *tmp;
if (!cattrs || !mono_array_length (cattrs))
return;
ainfo = mono_custom_attrs_from_builders (image, image, cattrs);
mono_loader_lock ();
tmp = mono_image_property_lookup (image, obj, MONO_PROP_DYNAMIC_CATTR);
if (tmp)
mono_custom_attrs_free (tmp);
mono_image_property_insert (image, obj, MONO_PROP_DYNAMIC_CATTR, ainfo);
mono_loader_unlock ();
}
#endif
void
mono_custom_attrs_free (MonoCustomAttrInfo *ainfo)
{
if (!ainfo->cached)
g_free (ainfo);
}
/*
* idx is the table index of the object
* type is one of MONO_CUSTOM_ATTR_*
*/
static void
mono_image_add_cattrs (MonoDynamicImage *assembly, guint32 idx, guint32 type, MonoArray *cattrs)
{
MonoDynamicTable *table;
MonoReflectionCustomAttr *cattr;
guint32 *values;
guint32 count, i, token;
char blob_size [6];
char *p = blob_size;
/* it is legal to pass a NULL cattrs: we avoid to use the if in a lot of places */
if (!cattrs)
return;
count = mono_array_length (cattrs);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_CUSTOM_ATTR_SIZE;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= type;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
values [MONO_CUSTOM_ATTR_PARENT] = idx;
token = mono_image_create_token (assembly, (MonoObject*)cattr->ctor, FALSE, FALSE);
type = mono_metadata_token_index (token);
type <<= MONO_CUSTOM_ATTR_TYPE_BITS;
switch (mono_metadata_token_table (token)) {
case MONO_TABLE_METHOD:
type |= MONO_CUSTOM_ATTR_TYPE_METHODDEF;
break;
case MONO_TABLE_MEMBERREF:
type |= MONO_CUSTOM_ATTR_TYPE_MEMBERREF;
break;
default:
g_warning ("got wrong token in custom attr");
continue;
}
values [MONO_CUSTOM_ATTR_TYPE] = type;
p = blob_size;
mono_metadata_encode_value (mono_array_length (cattr->data), p, &p);
values [MONO_CUSTOM_ATTR_VALUE] = add_to_blob_cached (assembly, blob_size, p - blob_size,
mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
values += MONO_CUSTOM_ATTR_SIZE;
++table->next_idx;
}
}
static void
mono_image_add_decl_security (MonoDynamicImage *assembly, guint32 parent_token, MonoArray *permissions)
{
MonoDynamicTable *table;
guint32 *values;
guint32 count, i, idx;
MonoReflectionPermissionSet *perm;
if (!permissions)
return;
count = mono_array_length (permissions);
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
table->rows += count;
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (permissions); ++i) {
perm = (MonoReflectionPermissionSet*)mono_array_addr (permissions, MonoReflectionPermissionSet, i);
values = table->values + table->next_idx * MONO_DECL_SECURITY_SIZE;
idx = mono_metadata_token_index (parent_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
switch (mono_metadata_token_table (parent_token)) {
case MONO_TABLE_TYPEDEF:
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
break;
case MONO_TABLE_METHOD:
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
break;
case MONO_TABLE_ASSEMBLY:
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
break;
default:
g_assert_not_reached ();
}
values [MONO_DECL_SECURITY_ACTION] = perm->action;
values [MONO_DECL_SECURITY_PARENT] = idx;
values [MONO_DECL_SECURITY_PERMISSIONSET] = add_mono_string_to_blob_cached (assembly, perm->pset);
++table->next_idx;
}
}
/*
* Fill in the MethodDef and ParamDef tables for a method.
* This is used for both normal methods and constructors.
*/
static void
mono_image_basic_method (ReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint i, count;
/* room in this table is already allocated */
table = &assembly->tables [MONO_TABLE_METHOD];
*mb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->method_to_table_idx, mb->mhandle, GUINT_TO_POINTER ((*mb->table_idx)));
values = table->values + *mb->table_idx * MONO_METHOD_SIZE;
values [MONO_METHOD_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
values [MONO_METHOD_FLAGS] = mb->attrs;
values [MONO_METHOD_IMPLFLAGS] = mb->iattrs;
values [MONO_METHOD_SIGNATURE] = method_builder_encode_signature (assembly, mb);
values [MONO_METHOD_RVA] = method_encode_code (assembly, mb);
table = &assembly->tables [MONO_TABLE_PARAM];
values [MONO_METHOD_PARAMLIST] = table->next_idx;
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_METHOD, *mb->table_idx), mb->permissions);
if (mb->pinfo) {
MonoDynamicTable *mtable;
guint32 *mvalues;
mtable = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
mvalues = mtable->values + mtable->next_idx * MONO_FIELD_MARSHAL_SIZE;
count = 0;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
if (mono_array_get (mb->pinfo, gpointer, i))
count++;
}
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_PARAM_SIZE;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (mb->pinfo, MonoReflectionParamBuilder*, i))) {
values [MONO_PARAM_FLAGS] = pb->attrs;
values [MONO_PARAM_SEQUENCE] = i;
if (pb->name != NULL) {
values [MONO_PARAM_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
} else {
values [MONO_PARAM_NAME] = 0;
}
values += MONO_PARAM_SIZE;
if (pb->marshal_info) {
mtable->rows++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_FIELD_MARSHAL_SIZE;
mvalues [MONO_FIELD_MARSHAL_PARENT] = (table->next_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_PARAMDEF;
mvalues [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, pb->marshal_info);
}
pb->table_idx = table->next_idx++;
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
mtable = &assembly->tables [MONO_TABLE_CONSTANT];
mtable->rows ++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_CONSTANT_SIZE;
mvalues [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PARAM | (pb->table_idx << MONO_HASCONSTANT_BITS);
mvalues [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
mvalues [MONO_CONSTANT_TYPE] = field_type;
mvalues [MONO_CONSTANT_PADDING] = 0;
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static void
reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_reflection_type_resolve_user_types ((MonoReflectionType*)mb->rtype);
rmb->parameters = mb->parameters;
rmb->generic_params = mb->generic_params;
rmb->generic_container = mb->generic_container;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = mb->code;
rmb->type = mb->type;
rmb->name = mb->name;
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = mb->return_modreq;
rmb->return_modopt = mb->return_modopt;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
if (mb->dll) {
rmb->charset = mb->charset;
rmb->extra_flags = mb->extra_flags;
rmb->native_cc = mb->native_cc;
rmb->dllentry = mb->dllentry;
rmb->dll = mb->dll;
}
}
static void
reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb)
{
const char *name = mb->attrs & METHOD_ATTRIBUTE_STATIC ? ".cctor": ".ctor";
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_type_get_object (mono_domain_get (), &mono_defaults.void_class->byval_arg);
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = mb->type;
rmb->name = mono_string_new (mono_domain_get (), name);
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
static void
reflection_methodbuilder_from_dynamic_method (ReflectionMethodBuilder *rmb, MonoReflectionDynamicMethod *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mb->rtype;
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = NULL;
rmb->attrs = mb->attrs;
rmb->iattrs = 0;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = (MonoObject *) mb->owner;
rmb->name = mb->name;
rmb->table_idx = NULL;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = mb->skip_visibility;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = NULL;
rmb->param_modopt = NULL;
rmb->permissions = NULL;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
#endif
static void
mono_image_add_methodimpl (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
MonoDynamicTable *table;
guint32 *values;
guint32 tok;
if (!mb->override_method)
return;
table = &assembly->tables [MONO_TABLE_METHODIMPL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_METHODIMPL_SIZE;
values [MONO_METHODIMPL_CLASS] = tb->table_idx;
values [MONO_METHODIMPL_BODY] = MONO_METHODDEFORREF_METHODDEF | (mb->table_idx << MONO_METHODDEFORREF_BITS);
tok = mono_image_create_token (assembly, (MonoObject*)mb->override_method, FALSE, FALSE);
switch (mono_metadata_token_table (tok)) {
case MONO_TABLE_MEMBERREF:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
values [MONO_METHODIMPL_DECLARATION] = tok;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
mono_image_get_method_info (MonoReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
ReflectionMethodBuilder rmb;
int i;
reflection_methodbuilder_from_method_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
if (mb->dll) { /* It's a P/Invoke method */
guint32 moduleref;
/* map CharSet values to on-disk values */
int ncharset = (mb->charset ? (mb->charset - 1) * 2 : 0);
int extra_flags = mb->extra_flags;
table = &assembly->tables [MONO_TABLE_IMPLMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_IMPLMAP_SIZE;
values [MONO_IMPLMAP_FLAGS] = (mb->native_cc << 8) | ncharset | extra_flags;
values [MONO_IMPLMAP_MEMBER] = (mb->table_idx << 1) | 1; /* memberforwarded: method */
if (mb->dllentry)
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->dllentry);
else
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
moduleref = string_heap_insert_mstring (&assembly->sheap, mb->dll);
if (!(values [MONO_IMPLMAP_SCOPE] = find_index_in_table (assembly, MONO_TABLE_MODULEREF, MONO_MODULEREF_NAME, moduleref))) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
table->rows ++;
alloc_table (table, table->rows);
table->values [table->rows * MONO_MODULEREF_SIZE + MONO_MODULEREF_NAME] = moduleref;
values [MONO_IMPLMAP_SCOPE] = table->rows;
}
}
if (mb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (mb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (mb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_METHOD | (mb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (mb->generic_params, gpointer, i), owner, assembly);
}
}
}
static void
mono_image_get_ctor_info (MonoDomain *domain, MonoReflectionCtorBuilder *mb, MonoDynamicImage *assembly)
{
ReflectionMethodBuilder rmb;
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
}
#endif
static char*
type_get_fully_qualified_name (MonoType *type)
{
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
static char*
type_get_qualified_name (MonoType *type, MonoAssembly *ass) {
MonoClass *klass;
MonoAssembly *ta;
klass = mono_class_from_mono_type (type);
if (!klass)
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
ta = klass->image->assembly;
if (ta->dynamic || (ta == ass)) {
if (klass->generic_class || klass->generic_container)
/* For generic type definitions, we want T, while REFLECTION returns T<K> */
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_FULL_NAME);
else
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
}
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
#ifndef DISABLE_REFLECTION_EMIT
/*field_image is the image to which the eventual custom mods have been encoded against*/
static guint32
fieldref_encode_signature (MonoDynamicImage *assembly, MonoImage *field_image, MonoType *type)
{
SigBuffer buf;
guint32 idx, i, token;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
/* encode custom attributes before the type */
if (type->num_mods) {
for (i = 0; i < type->num_mods; ++i) {
if (field_image) {
MonoClass *class = mono_class_get (field_image, type->modifiers [i].token);
g_assert (class);
token = mono_image_typedef_or_ref (assembly, &class->byval_arg);
} else {
token = type->modifiers [i].token;
}
if (type->modifiers [i].required)
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_REQD);
else
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (&buf, token);
}
}
encode_type (assembly, type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
field_encode_signature (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
SigBuffer buf;
guint32 idx;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
encode_custom_modifiers (assembly, fb->modreq, fb->modopt, &buf);
/* encode custom attributes before the type */
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type) {
char blob_size [64];
char *b = blob_size;
char *p, *box_val;
char* buf;
guint32 idx = 0, len = 0, dummy = 0;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
guint32 fpa_double [2];
guint32 *fpa_p;
#endif
#endif
p = buf = g_malloc (64);
if (!val) {
*ret_type = MONO_TYPE_CLASS;
len = 4;
box_val = (char*)&dummy;
} else {
box_val = ((char*)val) + sizeof (MonoObject);
*ret_type = val->vtable->klass->byval_arg.type;
}
handle_enum:
switch (*ret_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
len = 1;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
len = 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
len = 4;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
len = 8;
break;
case MONO_TYPE_R8:
len = 8;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
fpa_p = (guint32*)box_val;
fpa_double [0] = fpa_p [1];
fpa_double [1] = fpa_p [0];
box_val = (char*)fpa_double;
#endif
#endif
break;
case MONO_TYPE_VALUETYPE: {
MonoClass *klass = val->vtable->klass;
if (klass->enumtype) {
*ret_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
} else if (mono_is_corlib_image (klass->image) && strcmp (klass->name_space, "System") == 0 && strcmp (klass->name, "DateTime") == 0) {
len = 8;
} else
g_error ("we can't encode valuetypes, we should have never reached this line");
break;
}
case MONO_TYPE_CLASS:
break;
case MONO_TYPE_STRING: {
MonoString *str = (MonoString*)val;
/* there is no signature */
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
g_free (buf);
return idx;
}
case MONO_TYPE_GENERICINST:
*ret_type = val->vtable->klass->generic_class->container_class->byval_arg.type;
goto handle_enum;
default:
g_error ("we don't encode constant type 0x%02x yet", *ret_type);
}
/* there is no signature */
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
idx = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
swap_with_size (blob_size, box_val, len, 1);
mono_image_add_stream_data (&assembly->blob, blob_size, len);
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, box_val, len);
#endif
g_free (buf);
return idx;
}
static guint32
encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo) {
char *str;
SigBuffer buf;
guint32 idx, len;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, minfo->type);
switch (minfo->type) {
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
sigbuffer_add_value (&buf, minfo->count);
break;
case MONO_NATIVE_LPARRAY:
if (minfo->eltype || minfo->has_size) {
sigbuffer_add_value (&buf, minfo->eltype);
if (minfo->has_size) {
sigbuffer_add_value (&buf, minfo->param_num != -1? minfo->param_num: 0);
sigbuffer_add_value (&buf, minfo->count != -1? minfo->count: 0);
/* LAMESPEC: ElemMult is undocumented */
sigbuffer_add_value (&buf, minfo->param_num != -1? 1: 0);
}
}
break;
case MONO_NATIVE_SAFEARRAY:
if (minfo->eltype)
sigbuffer_add_value (&buf, minfo->eltype);
break;
case MONO_NATIVE_CUSTOM:
if (minfo->guid) {
str = mono_string_to_utf8 (minfo->guid);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
/* native type name */
sigbuffer_add_value (&buf, 0);
/* custom marshaler type name */
if (minfo->marshaltype || minfo->marshaltyperef) {
if (minfo->marshaltyperef)
str = type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
else
str = mono_string_to_utf8 (minfo->marshaltype);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
/* FIXME: Actually a bug, since this field is required. Punting for now ... */
sigbuffer_add_value (&buf, 0);
}
if (minfo->mcookie) {
str = mono_string_to_utf8 (minfo->mcookie);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
break;
default:
break;
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_field_info (MonoReflectionFieldBuilder *fb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
/* maybe this fixup should be done in the C# code */
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL)
fb->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
table = &assembly->tables [MONO_TABLE_FIELD];
fb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->field_to_table_idx, fb->handle, GUINT_TO_POINTER (fb->table_idx));
values = table->values + fb->table_idx * MONO_FIELD_SIZE;
values [MONO_FIELD_NAME] = string_heap_insert_mstring (&assembly->sheap, fb->name);
values [MONO_FIELD_FLAGS] = fb->attrs;
values [MONO_FIELD_SIGNATURE] = field_encode_signature (assembly, fb);
if (fb->offset != -1) {
table = &assembly->tables [MONO_TABLE_FIELDLAYOUT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_LAYOUT_SIZE;
values [MONO_FIELD_LAYOUT_FIELD] = fb->table_idx;
values [MONO_FIELD_LAYOUT_OFFSET] = fb->offset;
}
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_FIEDDEF | (fb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, fb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
if (fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
guint32 rva_idx;
table = &assembly->tables [MONO_TABLE_FIELDRVA];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_RVA_SIZE;
values [MONO_FIELD_RVA_FIELD] = fb->table_idx;
/*
* We store it in the code section because it's simpler for now.
*/
if (fb->rva_data) {
if (mono_array_length (fb->rva_data) >= 10)
stream_data_align (&assembly->code);
rva_idx = mono_image_add_stream_data (&assembly->code, mono_array_addr (fb->rva_data, char, 0), mono_array_length (fb->rva_data));
} else
rva_idx = mono_image_add_stream_zero (&assembly->code, mono_class_value_size (fb->handle->parent, NULL));
values [MONO_FIELD_RVA_RVA] = rva_idx + assembly->text_rva;
}
if (fb->marshal_info) {
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_MARSHAL_SIZE;
values [MONO_FIELD_MARSHAL_PARENT] = (fb->table_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_FIELDSREF;
values [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, fb->marshal_info);
}
}
static guint32
property_encode_signature (MonoDynamicImage *assembly, MonoReflectionPropertyBuilder *fb)
{
SigBuffer buf;
guint32 nparams = 0;
MonoReflectionMethodBuilder *mb = fb->get_method;
MonoReflectionMethodBuilder *smb = fb->set_method;
guint32 idx, i;
if (mb && mb->parameters)
nparams = mono_array_length (mb->parameters);
if (!mb && smb && smb->parameters)
nparams = mono_array_length (smb->parameters) - 1;
sigbuffer_init (&buf, 32);
if (fb->call_conv & 0x20)
sigbuffer_add_byte (&buf, 0x28);
else
sigbuffer_add_byte (&buf, 0x08);
sigbuffer_add_value (&buf, nparams);
if (mb) {
encode_reflection_type (assembly, (MonoReflectionType*)mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else if (smb && smb->parameters) {
/* the property type is the last param */
encode_reflection_type (assembly, mono_array_get (smb->parameters, MonoReflectionType*, nparams), &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (smb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else {
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_property_info (MonoReflectionPropertyBuilder *pb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* PROPERTYMAP (info already filled in _get_type_info ())
* PROPERTY (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
* CONSTANT
*/
table = &assembly->tables [MONO_TABLE_PROPERTY];
pb->table_idx = table->next_idx ++;
values = table->values + pb->table_idx * MONO_PROPERTY_SIZE;
values [MONO_PROPERTY_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
values [MONO_PROPERTY_FLAGS] = pb->attrs;
values [MONO_PROPERTY_TYPE] = property_encode_signature (assembly, pb);
/* FIXME: we still don't handle 'other' methods */
if (pb->get_method) num_methods ++;
if (pb->set_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (pb->get_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_GETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->get_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->set_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_SETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->set_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PROPERTY | (pb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
}
static void
mono_image_get_event_info (MonoReflectionEventBuilder *eb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* EVENTMAP (info already filled in _get_type_info ())
* EVENT (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
*/
table = &assembly->tables [MONO_TABLE_EVENT];
eb->table_idx = table->next_idx ++;
values = table->values + eb->table_idx * MONO_EVENT_SIZE;
values [MONO_EVENT_NAME] = string_heap_insert_mstring (&assembly->sheap, eb->name);
values [MONO_EVENT_FLAGS] = eb->attrs;
values [MONO_EVENT_TYPE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (eb->type));
/*
* FIXME: we still don't handle 'other' methods
*/
if (eb->add_method) num_methods ++;
if (eb->remove_method) num_methods ++;
if (eb->raise_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (eb->add_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_ADD_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->add_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->remove_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_REMOVE_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->remove_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->raise_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_FIRE;
values [MONO_METHOD_SEMA_METHOD] = eb->raise_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
}
static void
encode_constraints (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 num_constraints, i;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
num_constraints = gparam->iface_constraints ?
mono_array_length (gparam->iface_constraints) : 0;
table->rows += num_constraints;
if (gparam->base_type)
table->rows++;
alloc_table (table, table->rows);
if (gparam->base_type) {
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (gparam->base_type));
}
for (i = 0; i < num_constraints; i++) {
MonoReflectionType *constraint = mono_array_get (
gparam->iface_constraints, gpointer, i);
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (constraint));
}
}
static void
mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
GenericParamTableEntry *entry;
/*
* The GenericParam table must be sorted according to the `owner' field.
* We need to do this sorting prior to writing the GenericParamConstraint
* table, since we have to use the final GenericParam table indices there
* and they must also be sorted.
*/
entry = g_new0 (GenericParamTableEntry, 1);
entry->owner = owner;
/* FIXME: track where gen_params should be freed and remove the GC root as well */
MOVING_GC_REGISTER (&entry->gparam);
entry->gparam = gparam;
g_ptr_array_add (assembly->gen_params, entry);
}
static void
write_generic_param_entry (MonoDynamicImage *assembly, GenericParamTableEntry *entry)
{
MonoDynamicTable *table;
MonoGenericParam *param;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENERICPARAM_SIZE;
param = mono_reflection_type_get_handle ((MonoReflectionType*)entry->gparam)->data.generic_param;
values [MONO_GENERICPARAM_OWNER] = entry->owner;
values [MONO_GENERICPARAM_FLAGS] = entry->gparam->attrs;
values [MONO_GENERICPARAM_NUMBER] = mono_generic_param_num (param);
values [MONO_GENERICPARAM_NAME] = string_heap_insert (&assembly->sheap, mono_generic_param_info (param)->name);
mono_image_add_cattrs (assembly, table_idx, MONO_CUSTOM_ATTR_GENERICPAR, entry->gparam->cattrs);
encode_constraints (entry->gparam, table_idx, assembly);
}
static guint32
resolution_scope_from_image (MonoDynamicImage *assembly, MonoImage *image)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
guint32 cols [MONO_ASSEMBLY_SIZE];
const char *pubkey;
guint32 publen;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, image))))
return token;
if (image->assembly->dynamic && (image->assembly == assembly->image.assembly)) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_MODULEREF_SIZE;
values [MONO_MODULEREF_NAME] = string_heap_insert (&assembly->sheap, image->module_name);
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_MODULEREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
if (image->assembly->dynamic)
/* FIXME: */
memset (cols, 0, sizeof (cols));
else {
/* image->assembly->image is the manifest module */
image = image->assembly->image;
mono_metadata_decode_row (&image->tables [MONO_TABLE_ASSEMBLY], 0, cols, MONO_ASSEMBLY_SIZE);
}
table = &assembly->tables [MONO_TABLE_ASSEMBLYREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_ASSEMBLYREF_SIZE;
values [MONO_ASSEMBLYREF_NAME] = string_heap_insert (&assembly->sheap, image->assembly_name);
values [MONO_ASSEMBLYREF_MAJOR_VERSION] = cols [MONO_ASSEMBLY_MAJOR_VERSION];
values [MONO_ASSEMBLYREF_MINOR_VERSION] = cols [MONO_ASSEMBLY_MINOR_VERSION];
values [MONO_ASSEMBLYREF_BUILD_NUMBER] = cols [MONO_ASSEMBLY_BUILD_NUMBER];
values [MONO_ASSEMBLYREF_REV_NUMBER] = cols [MONO_ASSEMBLY_REV_NUMBER];
values [MONO_ASSEMBLYREF_FLAGS] = 0;
values [MONO_ASSEMBLYREF_CULTURE] = 0;
values [MONO_ASSEMBLYREF_HASH_VALUE] = 0;
if (strcmp ("", image->assembly->aname.culture)) {
values [MONO_ASSEMBLYREF_CULTURE] = string_heap_insert (&assembly->sheap,
image->assembly->aname.culture);
}
if ((pubkey = mono_image_get_public_key (image, &publen))) {
guchar pubtoken [9];
pubtoken [0] = 8;
mono_digest_get_public_token (pubtoken + 1, (guchar*)pubkey, publen);
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = mono_image_add_stream_data (&assembly->blob, (char*)pubtoken, 9);
} else {
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = 0;
}
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_ASSEMBLYREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
static guint32
create_typespec (MonoDynamicImage *assembly, MonoType *type)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token;
SigBuffer buf;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type))))
return token;
sigbuffer_init (&buf, 32);
switch (type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_GENERICINST:
encode_type (assembly, type, &buf);
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE: {
MonoClass *k = mono_class_from_mono_type (type);
if (!k || !k->generic_container) {
sigbuffer_free (&buf);
return 0;
}
encode_type (assembly, type, &buf);
break;
}
default:
sigbuffer_free (&buf);
return 0;
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
static guint32
mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, scope, enclosing;
MonoClass *klass;
/* if the type requires a typespec, we must try that first*/
if (try_typespec && (token = create_typespec (assembly, type)))
return token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typeref, type));
if (token)
return token;
klass = mono_class_from_mono_type (type);
if (!klass)
klass = mono_class_from_mono_type (type);
/*
* If it's in the same module and not a generic type parameter:
*/
if ((klass->image == &assembly->image) && (type->type != MONO_TYPE_VAR) &&
(type->type != MONO_TYPE_MVAR)) {
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
token = MONO_TYPEDEFORREF_TYPEDEF | (tb->table_idx << MONO_TYPEDEFORREF_BITS);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), mono_class_get_ref_info (klass));
return token;
}
if (klass->nested_in) {
enclosing = mono_image_typedef_or_ref_full (assembly, &klass->nested_in->byval_arg, FALSE);
/* get the typeref idx of the enclosing type */
enclosing >>= MONO_TYPEDEFORREF_BITS;
scope = (enclosing << MONO_RESOLTION_SCOPE_BITS) | MONO_RESOLTION_SCOPE_TYPEREF;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
}
table = &assembly->tables [MONO_TABLE_TYPEREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPEREF_SIZE;
values [MONO_TYPEREF_SCOPE] = scope;
values [MONO_TYPEREF_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_TYPEREF_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
}
token = MONO_TYPEDEFORREF_TYPEREF | (table->next_idx << MONO_TYPEDEFORREF_BITS); /* typeref */
g_hash_table_insert (assembly->typeref, type, GUINT_TO_POINTER(token));
table->next_idx ++;
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), mono_class_get_ref_info (klass));
return token;
}
/*
* Despite the name, we handle also TypeSpec (with the above helper).
*/
static guint32
mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type)
{
return mono_image_typedef_or_ref_full (assembly, type, TRUE);
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_add_memberef_row (MonoDynamicImage *assembly, guint32 parent, const char *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, pclass;
switch (parent & MONO_TYPEDEFORREF_MASK) {
case MONO_TYPEDEFORREF_TYPEREF:
pclass = MONO_MEMBERREF_PARENT_TYPEREF;
break;
case MONO_TYPEDEFORREF_TYPESPEC:
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
break;
case MONO_TYPEDEFORREF_TYPEDEF:
pclass = MONO_MEMBERREF_PARENT_TYPEDEF;
break;
default:
g_warning ("unknown typeref or def token 0x%08x for %s", parent, name);
return 0;
}
/* extract the index */
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
/*
* Insert a memberef row into the metadata: the token that point to the memberref
* is returned. Caching is done in the caller (mono_image_get_methodref_token() or
* mono_image_get_fieldref_token()).
* The sig param is an index to an already built signature.
*/
static guint32
mono_image_get_memberref_token (MonoDynamicImage *assembly, MonoType *type, const char *name, guint32 sig)
{
guint32 parent = mono_image_typedef_or_ref (assembly, type);
return mono_image_add_memberef_row (assembly, parent, name, sig);
}
static guint32
mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec)
{
guint32 token;
MonoMethodSignature *sig;
create_typespec = create_typespec && method->is_generic && method->klass->image != &assembly->image;
if (create_typespec) {
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1)));
if (token)
return token;
}
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token && !create_typespec)
return token;
g_assert (!method->is_inflated);
if (!token) {
/*
* A methodref signature can't contain an unmanaged calling convention.
*/
sig = mono_metadata_signature_dup (mono_method_signature (method));
if ((sig->call_convention != MONO_CALL_DEFAULT) && (sig->call_convention != MONO_CALL_VARARG))
sig->call_convention = MONO_CALL_DEFAULT;
token = mono_image_get_memberref_token (assembly, &method->klass->byval_arg,
method->name, method_encode_signature (assembly, sig));
g_free (sig);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
}
if (create_typespec) {
MonoDynamicTable *table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF);
token = (mono_metadata_token_index (token) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
if (assembly->save) {
guint32 *values;
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = token;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_sig (assembly, &mono_method_get_generic_container (method)->context);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
/*methodspec and memberef tokens are diferent, */
g_hash_table_insert (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1), GUINT_TO_POINTER (token));
return token;
}
return token;
}
static guint32
mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method)
{
guint32 token, parent, sig;
ReflectionMethodBuilder rmb;
char *name;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)method->type;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
name = mono_string_to_utf8 (method->name);
reflection_methodbuilder_from_method_builder (&rmb, method);
/*
* A methodref signature can't contain an unmanaged calling convention.
* Since some flags are encoded as part of call_conv, we need to check against it.
*/
if ((rmb.call_conv & ~0x60) != MONO_CALL_DEFAULT && (rmb.call_conv & ~0x60) != MONO_CALL_VARARG)
rmb.call_conv = (rmb.call_conv & 0x60) | MONO_CALL_DEFAULT;
sig = method_builder_encode_signature (assembly, &rmb);
if (tb->generic_params)
parent = create_generic_typespec (assembly, tb);
else
parent = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type));
token = mono_image_add_memberef_row (assembly, parent, name, sig);
g_free (name);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_varargs_method_token (MonoDynamicImage *assembly, guint32 original,
const gchar *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = original;
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
encode_generic_method_definition_sig (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
SigBuffer buf;
int i;
guint32 nparams = mono_array_length (mb->generic_params);
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0xa);
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++) {
sigbuffer_add_value (&buf, MONO_TYPE_MVAR);
sigbuffer_add_value (&buf, i);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_methodspec_token_for_generic_method_definition (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->methodspec, mb));
if (token)
return token;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
mtoken = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_definition_sig (assembly, mb);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->methodspec, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec)
{
guint32 token;
if (mb->generic_params && create_methodspec)
return mono_image_get_methodspec_token_for_generic_method_definition (assembly, mb);
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
if (token)
return token;
token = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *mb)
{
guint32 token, parent, sig;
ReflectionMethodBuilder rmb;
char *name;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
if (token)
return token;
g_assert (tb->generic_params);
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
parent = create_generic_typespec (assembly, tb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_add_memberef_row (assembly, parent, name, sig);
g_free (name);
mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
return token;
}
#endif
static gboolean
is_field_on_inst (MonoClassField *field)
{
return (field->parent->generic_class && field->parent->generic_class->is_dynamic && ((MonoDynamicGenericClass*)field->parent->generic_class)->fields);
}
/*
* If FIELD is a field of a MonoDynamicGenericClass, return its non-inflated type.
*/
static MonoType*
get_field_on_inst_generic_type (MonoClassField *field)
{
MonoClass *class, *gtd;
MonoDynamicGenericClass *dgclass;
int field_index;
g_assert (is_field_on_inst (field));
dgclass = (MonoDynamicGenericClass*)field->parent->generic_class;
if (field >= dgclass->fields && field - dgclass->fields < dgclass->count_fields) {
field_index = field - dgclass->fields;
return dgclass->field_generic_types [field_index];
}
class = field->parent;
gtd = class->generic_class->container_class;
if (field >= class->fields && field - class->fields < class->field.count) {
field_index = field - class->fields;
return gtd->fields [field_index].type;
}
g_assert_not_reached ();
return 0;
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoObject *f, MonoClassField *field)
{
MonoType *type;
guint32 token;
g_assert (field);
g_assert (field->parent);
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
if (token)
return token;
if (field->parent->generic_class && field->parent->generic_class->container_class && field->parent->generic_class->container_class->fields) {
int index = field - field->parent->fields;
type = field->parent->generic_class->container_class->fields [index].type;
} else {
if (is_field_on_inst (field))
type = get_field_on_inst_generic_type (field);
else
type = field->type;
}
token = mono_image_get_memberref_token (assembly, &field->parent->byval_arg,
mono_field_get_name (field),
fieldref_encode_signature (assembly, field->parent->image, type));
mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFieldOnTypeBuilderInst *f)
{
guint32 token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoType *type;
char *name;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
if (token)
return token;
if (is_sre_field_builder (mono_object_class (f->fb))) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)f->fb;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
name = mono_string_to_utf8 (fb->name);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name,
field_encode_signature (assembly, fb));
g_free (name);
} else if (is_sr_mono_field (mono_object_class (f->fb))) {
guint32 sig;
MonoClassField *field = ((MonoReflectionField *)f->fb)->field;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
sig = fieldref_encode_signature (assembly, field->parent->image, field->type);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, field->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (f->fb));
g_error ("mono_image_get_field_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER (token));
return token;
}
static guint32
mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCtorOnTypeBuilderInst *c, gboolean create_methodspec)
{
guint32 sig, token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoType *type;
/* A ctor cannot be a generic method, so we can ignore create_methodspec */
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, c));
if (token)
return token;
if (is_sre_ctor_builder (mono_object_class (c->cb))) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder *)c->cb;
MonoDynamicGenericClass *dgclass;
ReflectionMethodBuilder rmb;
char *name;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
reflection_methodbuilder_from_ctor_builder (&rmb, cb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
} else if (is_sr_mono_cmethod (mono_object_class (c->cb))) {
MonoMethod *mm = ((MonoReflectionMethod *)c->cb)->method;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
sig = method_encode_signature (assembly, mono_method_signature (mm));
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (c->cb));
g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, c, GUINT_TO_POINTER (token));
return token;
}
static MonoMethod*
mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m)
{
MonoClass *klass;
MonoGenericContext tmp_context;
MonoType **type_argv;
MonoGenericInst *ginst;
MonoMethod *method, *inflated;
int count, i;
method = inflate_method (m->inst, (MonoObject*)m->mb);
klass = method->klass;
if (m->method_args == NULL)
return method;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_array_length (m->method_args);
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (m->method_args, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
return inflated;
}
static guint32
mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec)
{
guint32 sig, token = 0;
MonoType *type;
MonoClass *klass;
if (m->method_args) {
MonoMethod *inflated;
inflated = mono_reflection_method_on_tb_inst_get_handle (m);
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, inflated);
else
token = mono_image_get_inflated_method_token (assembly, inflated);
return token;
}
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, m));
if (token)
return token;
if (is_sre_method_builder (mono_object_class (m->mb))) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)m->mb;
MonoGenericClass *gclass;
ReflectionMethodBuilder rmb;
char *name;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
reflection_methodbuilder_from_method_builder (&rmb, mb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
} else if (is_sr_mono_method (mono_object_class (m->mb))) {
MonoMethod *mm = ((MonoReflectionMethod *)m->mb)->method;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
sig = method_encode_signature (assembly, mono_method_signature (mm));
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (m->mb));
g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, m, GUINT_TO_POINTER (token));
return token;
}
static guint32
encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context)
{
SigBuffer buf;
int i;
guint32 nparams = context->method_inst->type_argc;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
sigbuffer_add_value (&buf, 0xa); /* FIXME FIXME FIXME */
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++)
encode_type (assembly, context->method_inst->type_argv [i], &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
method_encode_methodspec (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0, sig;
MonoMethodInflated *imethod;
MonoMethod *declaring;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
declaring = imethod->declaring;
sig = method_encode_signature (assembly, mono_method_signature (declaring));
mtoken = mono_image_get_memberref_token (assembly, &method->klass->byval_arg, declaring->name, sig);
if (!mono_method_signature (declaring)->generic_param_count)
return mtoken;
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
sig = encode_generic_method_sig (assembly, mono_method_get_context (method));
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = sig;
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoMethodInflated *imethod;
guint32 token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
if (mono_method_signature (imethod->declaring)->generic_param_count) {
token = method_encode_methodspec (assembly, method);
} else {
guint32 sig = method_encode_signature (
assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &method->klass->byval_arg, method->name, sig);
}
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m)
{
MonoMethodInflated *imethod = (MonoMethodInflated *) m;
guint32 sig, token;
sig = method_encode_signature (assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &m->klass->byval_arg, m->name, sig);
return token;
}
static guint32
create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *type;
guint32 *values;
guint32 token;
SigBuffer buf;
int count, i;
/*
* We're creating a TypeSpec for the TypeBuilder of a generic type declaration,
* ie. what we'd normally use as the generic type in a TypeSpec signature.
* Because of this, we must not insert it into the `typeref' hash table.
*/
type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type));
if (token)
return token;
sigbuffer_init (&buf, 32);
g_assert (tb->generic_params);
klass = mono_class_from_mono_type (type);
if (tb->generic_container)
mono_reflection_create_generic_class (tb);
sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST);
g_assert (klass->generic_container);
sigbuffer_add_value (&buf, klass->byval_arg.type);
sigbuffer_add_value (&buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
count = mono_array_length (tb->generic_params);
sigbuffer_add_value (&buf, count);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam;
gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i);
encode_type (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)gparam), &buf);
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
/*
* Return a copy of TYPE, adding the custom modifiers in MODREQ and MODOPT.
*/
static MonoType*
add_custom_modifiers (MonoDynamicImage *assembly, MonoType *type, MonoArray *modreq, MonoArray *modopt)
{
int i, count, len, pos;
MonoType *t;
count = 0;
if (modreq)
count += mono_array_length (modreq);
if (modopt)
count += mono_array_length (modopt);
if (count == 0)
return mono_metadata_type_dup (NULL, type);
len = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
t = g_malloc (len);
memcpy (t, type, MONO_SIZEOF_TYPE);
t->num_mods = count;
pos = 0;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
t->modifiers [pos].required = 1;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
t->modifiers [pos].required = 0;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
return t;
}
static guint32
mono_image_get_generic_field_token (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *custom = NULL;
guint32 *values;
guint32 token, pclass, parent, sig;
gchar *name;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, fb));
if (token)
return token;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (fb->typeb));
name = mono_string_to_utf8 (fb->name);
/* fb->type does not include the custom modifiers */
/* FIXME: We should do this in one place when a fieldbuilder is created */
if (fb->modreq || fb->modopt) {
custom = add_custom_modifiers (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type), fb->modreq, fb->modopt);
sig = fieldref_encode_signature (assembly, NULL, custom);
g_free (custom);
} else {
sig = fieldref_encode_signature (assembly, NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
}
parent = create_generic_typespec (assembly, (MonoReflectionTypeBuilder *) fb->typeb);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_TYPEDEFORREF_TYPESPEC);
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->handleref_managed, fb, GUINT_TO_POINTER(token));
g_free (name);
return token;
}
static guint32
mono_reflection_encode_sighelper (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
SigBuffer buf;
guint32 nargs;
guint32 size;
guint32 i, idx;
if (!assembly->save)
return 0;
/* FIXME: this means SignatureHelper.SignatureHelpType.HELPER_METHOD */
g_assert (helper->type == 2);
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
size = 10 + (nargs * 10);
sigbuffer_init (&buf, 32);
/* Encode calling convention */
/* Change Any to Standard */
if ((helper->call_conv & 0x03) == 0x03)
helper->call_conv = 0x01;
/* explicit_this implies has_this */
if (helper->call_conv & 0x40)
helper->call_conv &= 0x20;
if (helper->call_conv == 0) { /* Unmanaged */
idx = helper->unmanaged_call_conv - 1;
} else {
/* Managed */
idx = helper->call_conv & 0x60; /* has_this + explicit_this */
if (helper->call_conv & 0x02) /* varargs */
idx += 0x05;
}
sigbuffer_add_byte (&buf, idx);
sigbuffer_add_value (&buf, nargs);
encode_reflection_type (assembly, helper->return_type, &buf);
for (i = 0; i < nargs; ++i) {
MonoArray *modreqs = NULL;
MonoArray *modopts = NULL;
MonoReflectionType *pt;
if (helper->modreqs && (i < mono_array_length (helper->modreqs)))
modreqs = mono_array_get (helper->modreqs, MonoArray*, i);
if (helper->modopts && (i < mono_array_length (helper->modopts)))
modopts = mono_array_get (helper->modopts, MonoArray*, i);
encode_custom_modifiers (assembly, modreqs, modopts, &buf);
pt = mono_array_get (helper->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
guint32 idx;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] =
mono_reflection_encode_sighelper (assembly, helper);
return idx;
}
static int
reflection_cc_to_file (int call_conv) {
switch (call_conv & 0x3) {
case 0:
case 1: return MONO_CALL_DEFAULT;
case 2: return MONO_CALL_VARARG;
default:
g_assert_not_reached ();
}
return 0;
}
#endif /* !DISABLE_REFLECTION_EMIT */
typedef struct {
MonoType *parent;
MonoMethodSignature *sig;
char *name;
guint32 token;
} ArrayMethod;
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_array_token (MonoDynamicImage *assembly, MonoReflectionArrayMethod *m)
{
guint32 nparams, i;
GList *tmp;
char *name;
MonoMethodSignature *sig;
ArrayMethod *am;
MonoType *mtype;
name = mono_string_to_utf8 (m->name);
nparams = mono_array_length (m->parameters);
sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * nparams);
sig->hasthis = 1;
sig->sentinelpos = -1;
sig->call_convention = reflection_cc_to_file (m->call_conv);
sig->param_count = nparams;
sig->ret = m->ret ? mono_reflection_type_get_handle (m->ret): &mono_defaults.void_class->byval_arg;
mtype = mono_reflection_type_get_handle (m->parent);
for (i = 0; i < nparams; ++i)
sig->params [i] = mono_type_array_get_and_resolve (m->parameters, i);
for (tmp = assembly->array_methods; tmp; tmp = tmp->next) {
am = tmp->data;
if (strcmp (name, am->name) == 0 &&
mono_metadata_type_equal (am->parent, mtype) &&
mono_metadata_signature_equal (am->sig, sig)) {
g_free (name);
g_free (sig);
m->table_idx = am->token & 0xffffff;
return am->token;
}
}
am = g_new0 (ArrayMethod, 1);
am->name = name;
am->sig = sig;
am->parent = mtype;
am->token = mono_image_get_memberref_token (assembly, am->parent, name,
method_encode_signature (assembly, sig));
assembly->array_methods = g_list_prepend (assembly->array_methods, am);
m->table_idx = am->token & 0xffffff;
return am->token;
}
/*
* Insert into the metadata tables all the info about the TypeBuilder tb.
* Data in the tables is inserted in a predefined order, since some tables need to be sorted.
*/
static void
mono_image_get_type_info (MonoDomain *domain, MonoReflectionTypeBuilder *tb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint *values;
int i, is_object = 0, is_system = 0;
char *n;
table = &assembly->tables [MONO_TABLE_TYPEDEF];
values = table->values + tb->table_idx * MONO_TYPEDEF_SIZE;
values [MONO_TYPEDEF_FLAGS] = tb->attrs;
n = mono_string_to_utf8 (tb->name);
if (strcmp (n, "Object") == 0)
is_object++;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, n);
g_free (n);
n = mono_string_to_utf8 (tb->nspace);
if (strcmp (n, "System") == 0)
is_system++;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, n);
g_free (n);
if (tb->parent && !(is_system && is_object) &&
!(tb->attrs & TYPE_ATTRIBUTE_INTERFACE)) { /* interfaces don't have a parent */
values [MONO_TYPEDEF_EXTENDS] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
} else {
values [MONO_TYPEDEF_EXTENDS] = 0;
}
values [MONO_TYPEDEF_FIELD_LIST] = assembly->tables [MONO_TABLE_FIELD].next_idx;
values [MONO_TYPEDEF_METHOD_LIST] = assembly->tables [MONO_TABLE_METHOD].next_idx;
/*
* if we have explicitlayout or sequentiallayouts, output data in the
* ClassLayout table.
*/
if (((tb->attrs & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT) &&
((tb->class_size > 0) || (tb->packing_size > 0))) {
table = &assembly->tables [MONO_TABLE_CLASSLAYOUT];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CLASS_LAYOUT_SIZE;
values [MONO_CLASS_LAYOUT_PARENT] = tb->table_idx;
values [MONO_CLASS_LAYOUT_CLASS_SIZE] = tb->class_size;
values [MONO_CLASS_LAYOUT_PACKING_SIZE] = tb->packing_size;
}
/* handle interfaces */
if (tb->interfaces) {
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
i = table->rows;
table->rows += mono_array_length (tb->interfaces);
alloc_table (table, table->rows);
values = table->values + (i + 1) * MONO_INTERFACEIMPL_SIZE;
for (i = 0; i < mono_array_length (tb->interfaces); ++i) {
MonoReflectionType* iface = (MonoReflectionType*) mono_array_get (tb->interfaces, gpointer, i);
values [MONO_INTERFACEIMPL_CLASS] = tb->table_idx;
values [MONO_INTERFACEIMPL_INTERFACE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (iface));
values += MONO_INTERFACEIMPL_SIZE;
}
}
/* handle fields */
if (tb->fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += tb->num_fields;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_fields; ++i)
mono_image_get_field_info (
mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i), assembly);
}
/* handle constructors */
if (tb->ctors) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (tb->ctors);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->ctors); ++i)
mono_image_get_ctor_info (domain,
mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i), assembly);
}
/* handle methods */
if (tb->methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += tb->num_methods;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_methods; ++i)
mono_image_get_method_info (
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i), assembly);
}
/* Do the same with properties etc.. */
if (tb->events && mono_array_length (tb->events)) {
table = &assembly->tables [MONO_TABLE_EVENT];
table->rows += mono_array_length (tb->events);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_EVENTMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_EVENT_MAP_SIZE;
values [MONO_EVENT_MAP_PARENT] = tb->table_idx;
values [MONO_EVENT_MAP_EVENTLIST] = assembly->tables [MONO_TABLE_EVENT].next_idx;
for (i = 0; i < mono_array_length (tb->events); ++i)
mono_image_get_event_info (
mono_array_get (tb->events, MonoReflectionEventBuilder*, i), assembly);
}
if (tb->properties && mono_array_length (tb->properties)) {
table = &assembly->tables [MONO_TABLE_PROPERTY];
table->rows += mono_array_length (tb->properties);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_PROPERTYMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_PROPERTY_MAP_SIZE;
values [MONO_PROPERTY_MAP_PARENT] = tb->table_idx;
values [MONO_PROPERTY_MAP_PROPERTY_LIST] = assembly->tables [MONO_TABLE_PROPERTY].next_idx;
for (i = 0; i < mono_array_length (tb->properties); ++i)
mono_image_get_property_info (
mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i), assembly);
}
/* handle generic parameters */
if (tb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (tb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_TYPE | (tb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (tb->generic_params, MonoReflectionGenericParam*, i), owner, assembly);
}
}
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx), tb->permissions);
if (tb->subtypes) {
MonoDynamicTable *ntable;
ntable = &assembly->tables [MONO_TABLE_NESTEDCLASS];
ntable->rows += mono_array_length (tb->subtypes);
alloc_table (ntable, ntable->rows);
values = ntable->values + ntable->next_idx * MONO_NESTED_CLASS_SIZE;
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
values [MONO_NESTED_CLASS_NESTED] = subtype->table_idx;
values [MONO_NESTED_CLASS_ENCLOSING] = tb->table_idx;
/*g_print ("nesting %s (%d) in %s (%d) (rows %d/%d)\n",
mono_string_to_utf8 (subtype->name), subtype->table_idx,
mono_string_to_utf8 (tb->name), tb->table_idx,
ntable->next_idx, ntable->rows);*/
values += MONO_NESTED_CLASS_SIZE;
ntable->next_idx++;
}
}
}
#endif
static void
collect_types (MonoPtrArray *types, MonoReflectionTypeBuilder *type)
{
int i;
mono_ptr_array_append (*types, type);
if (!type->subtypes)
return;
for (i = 0; i < mono_array_length (type->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (type->subtypes, MonoReflectionTypeBuilder*, i);
collect_types (types, subtype);
}
}
static gint
compare_types_by_table_idx (MonoReflectionTypeBuilder **type1, MonoReflectionTypeBuilder **type2)
{
if ((*type1)->table_idx < (*type2)->table_idx)
return -1;
else
if ((*type1)->table_idx > (*type2)->table_idx)
return 1;
else
return 0;
}
static void
params_add_cattrs (MonoDynamicImage *assembly, MonoArray *pinfo) {
int i;
if (!pinfo)
return;
for (i = 0; i < mono_array_length (pinfo); ++i) {
MonoReflectionParamBuilder *pb;
pb = mono_array_get (pinfo, MonoReflectionParamBuilder *, i);
if (!pb)
continue;
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PARAMDEF, pb->cattrs);
}
}
static void
type_add_cattrs (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb) {
int i;
mono_image_add_cattrs (assembly, tb->table_idx, MONO_CUSTOM_ATTR_TYPEDEF, tb->cattrs);
if (tb->fields) {
for (i = 0; i < tb->num_fields; ++i) {
MonoReflectionFieldBuilder* fb;
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (tb->events) {
for (i = 0; i < mono_array_length (tb->events); ++i) {
MonoReflectionEventBuilder* eb;
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
mono_image_add_cattrs (assembly, eb->table_idx, MONO_CUSTOM_ATTR_EVENT, eb->cattrs);
}
}
if (tb->properties) {
for (i = 0; i < mono_array_length (tb->properties); ++i) {
MonoReflectionPropertyBuilder* pb;
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PROPERTY, pb->cattrs);
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder* cb;
cb = mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i);
mono_image_add_cattrs (assembly, cb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, cb->cattrs);
params_add_cattrs (assembly, cb->pinfo);
}
}
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder* mb;
mb = mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
type_add_cattrs (assembly, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i));
}
}
static void
module_add_cattrs (MonoDynamicImage *assembly, MonoReflectionModuleBuilder *moduleb)
{
int i;
mono_image_add_cattrs (assembly, moduleb->table_idx, MONO_CUSTOM_ATTR_MODULE, moduleb->cattrs);
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder* mb = mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (moduleb->global_fields) {
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (moduleb->types) {
for (i = 0; i < moduleb->num_types; ++i)
type_add_cattrs (assembly, mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i));
}
}
static void
mono_image_fill_file_table (MonoDomain *domain, MonoReflectionModule *module, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *dir, *path;
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, module->image->module_name);
if (module->image->dynamic) {
/* This depends on the fact that the main module is emitted last */
dir = mono_string_to_utf8 (((MonoReflectionModuleBuilder*)module)->assemblyb->dir);
path = g_strdup_printf ("%s%c%s", dir, G_DIR_SEPARATOR, module->image->module_name);
} else {
dir = NULL;
path = g_strdup (module->image->name);
}
mono_sha1_get_digest_from_file (path, hash);
g_free (dir);
g_free (path);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
table->next_idx ++;
}
static void
mono_image_fill_module_table (MonoDomain *domain, MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
table = &assembly->tables [MONO_TABLE_MODULE];
mb->table_idx = table->next_idx ++;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->module.name);
i = mono_image_add_stream_data (&assembly->guid, mono_array_addr (mb->guid, char, 0), 16);
i /= 16;
++i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_GENERATION] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_MVID] = i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENC] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENCBASE] = 0;
}
static guint32
mono_image_fill_export_table_from_class (MonoDomain *domain, MonoClass *klass,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 visib, res;
visib = klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if (! ((visib & TYPE_ATTRIBUTE_PUBLIC) || (visib & TYPE_ATTRIBUTE_NESTED_PUBLIC)))
return 0;
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = klass->flags;
values [MONO_EXP_TYPE_TYPEDEF] = klass->type_token;
if (klass->nested_in)
values [MONO_EXP_TYPE_IMPLEMENTATION] = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
else
values [MONO_EXP_TYPE_IMPLEMENTATION] = (module_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_FILE;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
res = table->next_idx;
table->next_idx ++;
/* Emit nested types */
if (klass->ext && klass->ext->nested_classes) {
GList *tmp;
for (tmp = klass->ext->nested_classes; tmp; tmp = tmp->next)
mono_image_fill_export_table_from_class (domain, tmp->data, module_index, table->next_idx - 1, assembly);
}
return res;
}
static void
mono_image_fill_export_table (MonoDomain *domain, MonoReflectionTypeBuilder *tb,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoClass *klass;
guint32 idx, i;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
klass->type_token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx);
idx = mono_image_fill_export_table_from_class (domain, klass, module_index,
parent_index, assembly);
/*
* Emit nested types
* We need to do this ourselves since klass->nested_classes is not set up.
*/
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
mono_image_fill_export_table (domain, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i), module_index, idx, assembly);
}
}
static void
mono_image_fill_export_table_from_module (MonoDomain *domain, MonoReflectionModule *module,
guint32 module_index, MonoDynamicImage *assembly)
{
MonoImage *image = module->image;
MonoTableInfo *t;
guint32 i;
t = &image->tables [MONO_TABLE_TYPEDEF];
for (i = 0; i < t->rows; ++i) {
MonoClass *klass = mono_class_get (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, i + 1));
if (klass->flags & TYPE_ATTRIBUTE_PUBLIC)
mono_image_fill_export_table_from_class (domain, klass, module_index, 0, assembly);
}
}
static void
add_exported_type (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly, MonoClass *klass, guint32 parent_index)
{
MonoDynamicTable *table;
guint32 *values;
guint32 scope, scope_idx, impl, current_idx;
gboolean forwarder = TRUE;
gpointer iter = NULL;
MonoClass *nested;
if (klass->nested_in) {
impl = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
forwarder = FALSE;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
g_assert ((scope & MONO_RESOLTION_SCOPE_MASK) == MONO_RESOLTION_SCOPE_ASSEMBLYREF);
scope_idx = scope >> MONO_RESOLTION_SCOPE_BITS;
impl = (scope_idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_ASSEMBLYREF;
}
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
current_idx = table->next_idx;
values = table->values + current_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = forwarder ? TYPE_ATTRIBUTE_FORWARDER : 0;
values [MONO_EXP_TYPE_TYPEDEF] = 0;
values [MONO_EXP_TYPE_IMPLEMENTATION] = impl;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
table->next_idx++;
while ((nested = mono_class_get_nested_types (klass, &iter)))
add_exported_type (assemblyb, assembly, nested, current_idx);
}
static void
mono_image_fill_export_table_from_type_forwarders (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly)
{
MonoClass *klass;
int i;
if (!assemblyb->type_forwarders)
return;
for (i = 0; i < mono_array_length (assemblyb->type_forwarders); ++i) {
MonoReflectionType *t = mono_array_get (assemblyb->type_forwarders, MonoReflectionType *, i);
MonoType *type;
if (!t)
continue;
type = mono_reflection_type_get_handle (t);
g_assert (type);
klass = mono_class_from_mono_type (type);
add_exported_type (assemblyb, assembly, klass, 0);
}
}
#define align_pointer(base,p)\
do {\
guint32 __diff = (unsigned char*)(p)-(unsigned char*)(base);\
if (__diff & 3)\
(p) += 4 - (__diff & 3);\
} while (0)
static int
compare_constants (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CONSTANT_PARENT] - b_values [MONO_CONSTANT_PARENT];
}
static int
compare_semantics (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int assoc = a_values [MONO_METHOD_SEMA_ASSOCIATION] - b_values [MONO_METHOD_SEMA_ASSOCIATION];
if (assoc)
return assoc;
return a_values [MONO_METHOD_SEMA_SEMANTICS] - b_values [MONO_METHOD_SEMA_SEMANTICS];
}
static int
compare_custom_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CUSTOM_ATTR_PARENT] - b_values [MONO_CUSTOM_ATTR_PARENT];
}
static int
compare_field_marshal (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_FIELD_MARSHAL_PARENT] - b_values [MONO_FIELD_MARSHAL_PARENT];
}
static int
compare_nested (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_NESTED_CLASS_NESTED] - b_values [MONO_NESTED_CLASS_NESTED];
}
static int
compare_genericparam (const void *a, const void *b)
{
const GenericParamTableEntry **a_entry = (const GenericParamTableEntry **) a;
const GenericParamTableEntry **b_entry = (const GenericParamTableEntry **) b;
if ((*b_entry)->owner == (*a_entry)->owner)
return
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*a_entry)->gparam)) -
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*b_entry)->gparam));
else
return (*a_entry)->owner - (*b_entry)->owner;
}
static int
compare_declsecurity_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_DECL_SECURITY_PARENT] - b_values [MONO_DECL_SECURITY_PARENT];
}
static int
compare_interface_impl (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int klass = a_values [MONO_INTERFACEIMPL_CLASS] - b_values [MONO_INTERFACEIMPL_CLASS];
if (klass)
return klass;
return a_values [MONO_INTERFACEIMPL_INTERFACE] - b_values [MONO_INTERFACEIMPL_INTERFACE];
}
static void
pad_heap (MonoDynamicStream *sh)
{
if (sh->index & 3) {
int sz = 4 - (sh->index & 3);
memset (sh->data + sh->index, 0, sz);
sh->index += sz;
}
}
struct StreamDesc {
const char *name;
MonoDynamicStream *stream;
};
/*
* build_compressed_metadata() fills in the blob of data that represents the
* raw metadata as it will be saved in the PE file. The five streams are output
* and the metadata tables are comnpressed from the guint32 array representation,
* to the compressed on-disk format.
*/
static void
build_compressed_metadata (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
guint64 valid_mask = 0;
guint64 sorted_mask;
guint32 heapt_size = 0;
guint32 meta_size = 256; /* allow for header and other stuff */
guint32 table_offset;
guint32 ntables = 0;
guint64 *int64val;
guint32 *int32val;
guint16 *int16val;
MonoImage *meta;
unsigned char *p;
struct StreamDesc stream_desc [5];
qsort (assembly->gen_params->pdata, assembly->gen_params->len, sizeof (gpointer), compare_genericparam);
for (i = 0; i < assembly->gen_params->len; i++){
GenericParamTableEntry *entry = g_ptr_array_index (assembly->gen_params, i);
write_generic_param_entry (assembly, entry);
}
stream_desc [0].name = "#~";
stream_desc [0].stream = &assembly->tstream;
stream_desc [1].name = "#Strings";
stream_desc [1].stream = &assembly->sheap;
stream_desc [2].name = "#US";
stream_desc [2].stream = &assembly->us;
stream_desc [3].name = "#Blob";
stream_desc [3].stream = &assembly->blob;
stream_desc [4].name = "#GUID";
stream_desc [4].stream = &assembly->guid;
/* tables that are sorted */
sorted_mask = ((guint64)1 << MONO_TABLE_CONSTANT) | ((guint64)1 << MONO_TABLE_FIELDMARSHAL)
| ((guint64)1 << MONO_TABLE_METHODSEMANTICS) | ((guint64)1 << MONO_TABLE_CLASSLAYOUT)
| ((guint64)1 << MONO_TABLE_FIELDLAYOUT) | ((guint64)1 << MONO_TABLE_FIELDRVA)
| ((guint64)1 << MONO_TABLE_IMPLMAP) | ((guint64)1 << MONO_TABLE_NESTEDCLASS)
| ((guint64)1 << MONO_TABLE_METHODIMPL) | ((guint64)1 << MONO_TABLE_CUSTOMATTRIBUTE)
| ((guint64)1 << MONO_TABLE_DECLSECURITY) | ((guint64)1 << MONO_TABLE_GENERICPARAM)
| ((guint64)1 << MONO_TABLE_INTERFACEIMPL);
/* Compute table sizes */
/* the MonoImage has already been created in mono_image_basic_init() */
meta = &assembly->image;
/* sizes should be multiple of 4 */
pad_heap (&assembly->blob);
pad_heap (&assembly->guid);
pad_heap (&assembly->sheap);
pad_heap (&assembly->us);
/* Setup the info used by compute_sizes () */
meta->idx_blob_wide = assembly->blob.index >= 65536 ? 1 : 0;
meta->idx_guid_wide = assembly->guid.index >= 65536 ? 1 : 0;
meta->idx_string_wide = assembly->sheap.index >= 65536 ? 1 : 0;
meta_size += assembly->blob.index;
meta_size += assembly->guid.index;
meta_size += assembly->sheap.index;
meta_size += assembly->us.index;
for (i=0; i < MONO_TABLE_NUM; ++i)
meta->tables [i].rows = assembly->tables [i].rows;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
valid_mask |= (guint64)1 << i;
ntables ++;
meta->tables [i].row_size = mono_metadata_compute_size (
meta, i, &meta->tables [i].size_bitfield);
heapt_size += meta->tables [i].row_size * meta->tables [i].rows;
}
heapt_size += 24; /* #~ header size */
heapt_size += ntables * 4;
/* make multiple of 4 */
heapt_size += 3;
heapt_size &= ~3;
meta_size += heapt_size;
meta->raw_metadata = g_malloc0 (meta_size);
p = (unsigned char*)meta->raw_metadata;
/* the metadata signature */
*p++ = 'B'; *p++ = 'S'; *p++ = 'J'; *p++ = 'B';
/* version numbers and 4 bytes reserved */
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (meta->md_version_major);
*int16val = GUINT16_TO_LE (meta->md_version_minor);
p += 8;
/* version string */
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE ((strlen (meta->version) + 3) & (~3)); /* needs to be multiple of 4 */
p += 4;
memcpy (p, meta->version, strlen (meta->version));
p += GUINT32_FROM_LE (*int32val);
align_pointer (meta->raw_metadata, p);
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (0); /* flags must be 0 */
*int16val = GUINT16_TO_LE (5); /* number of streams */
p += 4;
/*
* write the stream info.
*/
table_offset = (p - (unsigned char*)meta->raw_metadata) + 5 * 8 + 40; /* room needed for stream headers */
table_offset += 3; table_offset &= ~3;
assembly->tstream.index = heapt_size;
for (i = 0; i < 5; ++i) {
int32val = (guint32*)p;
stream_desc [i].stream->offset = table_offset;
*int32val++ = GUINT32_TO_LE (table_offset);
*int32val = GUINT32_TO_LE (stream_desc [i].stream->index);
table_offset += GUINT32_FROM_LE (*int32val);
table_offset += 3; table_offset &= ~3;
p += 8;
strcpy ((char*)p, stream_desc [i].name);
p += strlen (stream_desc [i].name) + 1;
align_pointer (meta->raw_metadata, p);
}
/*
* now copy the data, the table stream header and contents goes first.
*/
g_assert ((p - (unsigned char*)meta->raw_metadata) < assembly->tstream.offset);
p = (guchar*)meta->raw_metadata + assembly->tstream.offset;
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE (0); /* reserved */
p += 4;
*p++ = 2; /* version */
*p++ = 0;
if (meta->idx_string_wide)
*p |= 0x01;
if (meta->idx_guid_wide)
*p |= 0x02;
if (meta->idx_blob_wide)
*p |= 0x04;
++p;
*p++ = 1; /* reserved */
int64val = (guint64*)p;
*int64val++ = GUINT64_TO_LE (valid_mask);
*int64val++ = GUINT64_TO_LE (valid_mask & sorted_mask); /* bitvector of sorted tables */
p += 16;
int32val = (guint32*)p;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
*int32val++ = GUINT32_TO_LE (meta->tables [i].rows);
}
p = (unsigned char*)int32val;
/* sort the tables that still need sorting */
table = &assembly->tables [MONO_TABLE_CONSTANT];
if (table->rows)
qsort (table->values + MONO_CONSTANT_SIZE, table->rows, sizeof (guint32) * MONO_CONSTANT_SIZE, compare_constants);
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
if (table->rows)
qsort (table->values + MONO_METHOD_SEMA_SIZE, table->rows, sizeof (guint32) * MONO_METHOD_SEMA_SIZE, compare_semantics);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
if (table->rows)
qsort (table->values + MONO_CUSTOM_ATTR_SIZE, table->rows, sizeof (guint32) * MONO_CUSTOM_ATTR_SIZE, compare_custom_attrs);
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
if (table->rows)
qsort (table->values + MONO_FIELD_MARSHAL_SIZE, table->rows, sizeof (guint32) * MONO_FIELD_MARSHAL_SIZE, compare_field_marshal);
table = &assembly->tables [MONO_TABLE_NESTEDCLASS];
if (table->rows)
qsort (table->values + MONO_NESTED_CLASS_SIZE, table->rows, sizeof (guint32) * MONO_NESTED_CLASS_SIZE, compare_nested);
/* Section 21.11 DeclSecurity in Partition II doesn't specify this to be sorted by MS implementation requires it */
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
if (table->rows)
qsort (table->values + MONO_DECL_SECURITY_SIZE, table->rows, sizeof (guint32) * MONO_DECL_SECURITY_SIZE, compare_declsecurity_attrs);
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
if (table->rows)
qsort (table->values + MONO_INTERFACEIMPL_SIZE, table->rows, sizeof (guint32) * MONO_INTERFACEIMPL_SIZE, compare_interface_impl);
/* compress the tables */
for (i = 0; i < MONO_TABLE_NUM; i++){
int row, col;
guint32 *values;
guint32 bitfield = meta->tables [i].size_bitfield;
if (!meta->tables [i].rows)
continue;
if (assembly->tables [i].columns != mono_metadata_table_count (bitfield))
g_error ("col count mismatch in %d: %d %d", i, assembly->tables [i].columns, mono_metadata_table_count (bitfield));
meta->tables [i].base = (char*)p;
for (row = 1; row <= meta->tables [i].rows; ++row) {
values = assembly->tables [i].values + row * assembly->tables [i].columns;
for (col = 0; col < assembly->tables [i].columns; ++col) {
switch (mono_metadata_table_size (bitfield, col)) {
case 1:
*p++ = values [col];
break;
case 2:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
break;
case 4:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
*p++ = (values [col] >> 16) & 0xff;
*p++ = (values [col] >> 24) & 0xff;
break;
default:
g_assert_not_reached ();
}
}
}
g_assert ((p - (const unsigned char*)meta->tables [i].base) == (meta->tables [i].rows * meta->tables [i].row_size));
}
g_assert (assembly->guid.offset + assembly->guid.index < meta_size);
memcpy (meta->raw_metadata + assembly->sheap.offset, assembly->sheap.data, assembly->sheap.index);
memcpy (meta->raw_metadata + assembly->us.offset, assembly->us.data, assembly->us.index);
memcpy (meta->raw_metadata + assembly->blob.offset, assembly->blob.data, assembly->blob.index);
memcpy (meta->raw_metadata + assembly->guid.offset, assembly->guid.data, assembly->guid.index);
assembly->meta_size = assembly->guid.offset + assembly->guid.index;
}
/*
* Some tables in metadata need to be sorted according to some criteria, but
* when methods and fields are first created with reflection, they may be assigned a token
* that doesn't correspond to the final token they will get assigned after the sorting.
* ILGenerator.cs keeps a fixup table that maps the position of tokens in the IL code stream
* with the reflection objects that represent them. Once all the tables are set up, the
* reflection objects will contains the correct table index. fixup_method() will fixup the
* tokens for the method with ILGenerator @ilgen.
*/
static void
fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *assembly)
{
guint32 code_idx = GPOINTER_TO_UINT (value);
MonoReflectionILTokenInfo *iltoken;
MonoReflectionFieldBuilder *field;
MonoReflectionCtorBuilder *ctor;
MonoReflectionMethodBuilder *method;
MonoReflectionTypeBuilder *tb;
MonoReflectionArrayMethod *am;
guint32 i, idx = 0;
unsigned char *target;
for (i = 0; i < ilgen->num_token_fixups; ++i) {
iltoken = (MonoReflectionILTokenInfo *)mono_array_addr_with_size (ilgen->token_fixups, sizeof (MonoReflectionILTokenInfo), i);
target = (guchar*)assembly->code.data + code_idx + iltoken->code_pos;
switch (target [3]) {
case MONO_TABLE_FIELD:
if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
field = (MonoReflectionFieldBuilder *)iltoken->member;
idx = field->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->field_to_table_idx, f));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHOD:
if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
method = (MonoReflectionMethodBuilder *)iltoken->member;
idx = method->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
ctor = (MonoReflectionCtorBuilder *)iltoken->member;
idx = ctor->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_TYPEDEF:
if (strcmp (iltoken->member->vtable->klass->name, "TypeBuilder"))
g_assert_not_reached ();
tb = (MonoReflectionTypeBuilder *)iltoken->member;
idx = tb->table_idx;
break;
case MONO_TABLE_MEMBERREF:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoArrayMethod")) {
am = (MonoReflectionArrayMethod*)iltoken->member;
idx = am->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (m->klass->generic_class || m->klass->generic_container);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
g_assert (is_field_on_inst (f));
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder") ||
!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHODSPEC:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (mono_method_signature (m)->generic_param_count);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
default:
g_error ("got unexpected table 0x%02x in fixup", target [3]);
}
target [0] = idx & 0xff;
target [1] = (idx >> 8) & 0xff;
target [2] = (idx >> 16) & 0xff;
}
}
/*
* fixup_cattrs:
*
* The CUSTOM_ATTRIBUTE table might contain METHODDEF tokens whose final
* value is not known when the table is emitted.
*/
static void
fixup_cattrs (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 type, i, idx, token;
MonoObject *ctor;
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
for (i = 0; i < table->rows; ++i) {
values = table->values + ((i + 1) * MONO_CUSTOM_ATTR_SIZE);
type = values [MONO_CUSTOM_ATTR_TYPE];
if ((type & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_METHODDEF) {
idx = type >> MONO_CUSTOM_ATTR_TYPE_BITS;
token = mono_metadata_make_token (MONO_TABLE_METHOD, idx);
ctor = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
g_assert (ctor);
if (!strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)ctor)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
values [MONO_CUSTOM_ATTR_TYPE] = (idx << MONO_CUSTOM_ATTR_TYPE_BITS) | MONO_CUSTOM_ATTR_TYPE_METHODDEF;
}
}
}
}
static void
assembly_add_resource_manifest (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc, guint32 implementation)
{
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MANIFESTRESOURCE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_MANIFEST_SIZE;
values [MONO_MANIFEST_OFFSET] = rsrc->offset;
values [MONO_MANIFEST_FLAGS] = rsrc->attrs;
values [MONO_MANIFEST_NAME] = string_heap_insert_mstring (&assembly->sheap, rsrc->name);
values [MONO_MANIFEST_IMPLEMENTATION] = implementation;
table->next_idx++;
}
static void
assembly_add_resource (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *name, *sname;
guint32 idx, offset;
if (rsrc->filename) {
name = mono_string_to_utf8 (rsrc->filename);
sname = g_path_get_basename (name);
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_NO_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, sname);
g_free (sname);
mono_sha1_get_digest_from_file (name, hash);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
g_free (name);
idx = table->next_idx++;
rsrc->offset = 0;
idx = MONO_IMPLEMENTATION_FILE | (idx << MONO_IMPLEMENTATION_BITS);
} else {
char sizebuf [4];
char *data;
guint len;
if (rsrc->data) {
data = mono_array_addr (rsrc->data, char, 0);
len = mono_array_length (rsrc->data);
} else {
data = NULL;
len = 0;
}
offset = len;
sizebuf [0] = offset; sizebuf [1] = offset >> 8;
sizebuf [2] = offset >> 16; sizebuf [3] = offset >> 24;
rsrc->offset = mono_image_add_stream_data (&assembly->resources, sizebuf, 4);
mono_image_add_stream_data (&assembly->resources, data, len);
if (!mb->is_main)
/*
* The entry should be emitted into the MANIFESTRESOURCE table of
* the main module, but that needs to reference the FILE table
* which isn't emitted yet.
*/
return;
else
idx = 0;
}
assembly_add_resource_manifest (mb, assembly, rsrc, idx);
}
static void
set_version_from_string (MonoString *version, guint32 *values)
{
gchar *ver, *p, *str;
guint32 i;
values [MONO_ASSEMBLY_MAJOR_VERSION] = 0;
values [MONO_ASSEMBLY_MINOR_VERSION] = 0;
values [MONO_ASSEMBLY_REV_NUMBER] = 0;
values [MONO_ASSEMBLY_BUILD_NUMBER] = 0;
if (!version)
return;
ver = str = mono_string_to_utf8 (version);
for (i = 0; i < 4; ++i) {
values [MONO_ASSEMBLY_MAJOR_VERSION + i] = strtol (ver, &p, 10);
switch (*p) {
case '.':
p++;
break;
case '*':
/* handle Revision and Build */
p++;
break;
}
ver = p;
}
g_free (str);
}
static guint32
load_public_key (MonoArray *pkey, MonoDynamicImage *assembly) {
gsize len;
guint32 token = 0;
char blob_size [6];
char *b = blob_size;
if (!pkey)
return token;
len = mono_array_length (pkey);
mono_metadata_encode_value (len, b, &b);
token = mono_image_add_stream_data (&assembly->blob, blob_size, b - blob_size);
mono_image_add_stream_data (&assembly->blob, mono_array_addr (pkey, char, 0), len);
assembly->public_key = g_malloc (len);
memcpy (assembly->public_key, mono_array_addr (pkey, char, 0), len);
assembly->public_key_len = len;
/* Special case: check for ECMA key (16 bytes) */
if ((len == MONO_ECMA_KEY_LENGTH) && mono_is_ecma_key (mono_array_addr (pkey, char, 0), len)) {
/* In this case we must reserve 128 bytes (1024 bits) for the signature */
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH;
} else if (len >= MONO_PUBLIC_KEY_HEADER_LENGTH + MONO_MINIMUM_PUBLIC_KEY_LENGTH) {
/* minimum key size (in 2.0) is 384 bits */
assembly->strong_name_size = len - MONO_PUBLIC_KEY_HEADER_LENGTH;
} else {
/* FIXME - verifier */
g_warning ("Invalid public key length: %d bits (total: %d)", (int)MONO_PUBLIC_KEY_BIT_SIZE (len), (int)len);
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH; /* to be safe */
}
assembly->strong_name = g_malloc0 (assembly->strong_name_size);
return token;
}
static void
mono_image_emit_manifest (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
guint32 *values;
int i;
guint32 module_index;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
/* Emit ASSEMBLY table */
table = &assembly->tables [MONO_TABLE_ASSEMBLY];
alloc_table (table, 1);
values = table->values + MONO_ASSEMBLY_SIZE;
values [MONO_ASSEMBLY_HASH_ALG] = assemblyb->algid? assemblyb->algid: ASSEMBLY_HASH_SHA1;
values [MONO_ASSEMBLY_NAME] = string_heap_insert_mstring (&assembly->sheap, assemblyb->name);
if (assemblyb->culture) {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert_mstring (&assembly->sheap, assemblyb->culture);
} else {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert (&assembly->sheap, "");
}
values [MONO_ASSEMBLY_PUBLIC_KEY] = load_public_key (assemblyb->public_key, assembly);
values [MONO_ASSEMBLY_FLAGS] = assemblyb->flags;
set_version_from_string (assemblyb->version, values);
/* Emit FILE + EXPORTED_TYPE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
if (file_module != moduleb) {
mono_image_fill_file_table (domain, (MonoReflectionModule*)file_module, assembly);
module_index ++;
if (file_module->types) {
for (j = 0; j < file_module->num_types; ++j) {
MonoReflectionTypeBuilder *tb = mono_array_get (file_module->types, MonoReflectionTypeBuilder*, j);
mono_image_fill_export_table (domain, tb, module_index, 0, assembly);
}
}
}
}
if (assemblyb->loaded_modules) {
for (i = 0; i < mono_array_length (assemblyb->loaded_modules); ++i) {
MonoReflectionModule *file_module =
mono_array_get (assemblyb->loaded_modules, MonoReflectionModule*, i);
mono_image_fill_file_table (domain, file_module, assembly);
module_index ++;
mono_image_fill_export_table_from_module (domain, file_module, module_index, assembly);
}
}
if (assemblyb->type_forwarders)
mono_image_fill_export_table_from_type_forwarders (assemblyb, assembly);
/* Emit MANIFESTRESOURCE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
/* The table for the main module is emitted later */
if (file_module != moduleb) {
module_index ++;
if (file_module->resources) {
int len = mono_array_length (file_module->resources);
for (j = 0; j < len; ++j) {
MonoReflectionResource* res = (MonoReflectionResource*)mono_array_addr (file_module->resources, MonoReflectionResource, j);
assembly_add_resource_manifest (file_module, assembly, res, MONO_IMPLEMENTATION_FILE | (module_index << MONO_IMPLEMENTATION_BITS));
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT_SAVE
/*
* mono_image_build_metadata() will fill the info in all the needed metadata tables
* for the modulebuilder @moduleb.
* At the end of the process, method and field tokens are fixed up and the
* on-disk compressed metadata representation is created.
*/
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
MonoPtrArray types;
guint32 *values;
int i, j;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
if (assembly->text_rva)
return;
assembly->text_rva = START_TEXT_RVA;
if (moduleb->is_main) {
mono_image_emit_manifest (moduleb);
}
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows = 1; /* .<Module> */
table->next_idx++;
alloc_table (table, table->rows);
/*
* Set the first entry.
*/
values = table->values + table->columns;
values [MONO_TYPEDEF_FLAGS] = 0;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, "<Module>") ;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, "") ;
values [MONO_TYPEDEF_EXTENDS] = 0;
values [MONO_TYPEDEF_FIELD_LIST] = 1;
values [MONO_TYPEDEF_METHOD_LIST] = 1;
/*
* handle global methods
* FIXME: test what to do when global methods are defined in multiple modules.
*/
if (moduleb->global_methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (moduleb->global_methods);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i)
mono_image_get_method_info (
mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i), assembly);
}
if (moduleb->global_fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += mono_array_length (moduleb->global_fields);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i)
mono_image_get_field_info (
mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i), assembly);
}
table = &assembly->tables [MONO_TABLE_MODULE];
alloc_table (table, 1);
mono_image_fill_module_table (domain, moduleb, assembly);
/* Collect all types into a list sorted by their table_idx */
mono_ptr_array_init (types, moduleb->num_types);
if (moduleb->types)
for (i = 0; i < moduleb->num_types; ++i) {
MonoReflectionTypeBuilder *type = mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i);
collect_types (&types, type);
}
mono_ptr_array_sort (types, (gpointer)compare_types_by_table_idx);
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows += mono_ptr_array_size (types);
alloc_table (table, table->rows);
/*
* Emit type names + namespaces at one place inside the string heap,
* so load_class_names () needs to touch fewer pages.
*/
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *tb = mono_ptr_array_get (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->nspace);
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *tb = mono_ptr_array_get (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->name);
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *type = mono_ptr_array_get (types, i);
mono_image_get_type_info (domain, type, assembly);
}
/*
* table->rows is already set above and in mono_image_fill_module_table.
*/
/* add all the custom attributes at the end, once all the indexes are stable */
mono_image_add_cattrs (assembly, 1, MONO_CUSTOM_ATTR_ASSEMBLY, assemblyb->cattrs);
/* CAS assembly permissions */
if (assemblyb->permissions_minimum)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_minimum);
if (assemblyb->permissions_optional)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_optional);
if (assemblyb->permissions_refused)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_refused);
module_add_cattrs (assembly, moduleb);
/* fixup tokens */
mono_g_hash_table_foreach (assembly->token_fixups, (GHFunc)fixup_method, assembly);
/* Create the MethodImpl table. We do this after emitting all methods so we already know
* the final tokens and don't need another fixup pass. */
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (
moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_methodimpl (assembly, mb);
}
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *type = mono_ptr_array_get (types, i);
if (type->methods) {
for (j = 0; j < type->num_methods; ++j) {
MonoReflectionMethodBuilder *mb = mono_array_get (
type->methods, MonoReflectionMethodBuilder*, j);
mono_image_add_methodimpl (assembly, mb);
}
}
}
mono_ptr_array_destroy (types);
fixup_cattrs (assembly);
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit_save, so saving of dynamic assemblies is not supported.");
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
typedef struct {
guint32 import_lookup_table;
guint32 timestamp;
guint32 forwarder;
guint32 name_rva;
guint32 import_address_table_rva;
} MonoIDT;
typedef struct {
guint32 name_rva;
guint32 flags;
} MonoILT;
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_insert_string:
* @module: module builder object
* @str: a string
*
* Insert @str into the user string stream of @module.
*/
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
MonoDynamicImage *assembly;
guint32 idx;
char buf [16];
char *b = buf;
MONO_ARCH_SAVE_REGS;
if (!module->dynamic_image)
mono_image_module_basic_init (module);
assembly = module->dynamic_image;
if (assembly->save) {
mono_metadata_encode_value (1 | (str->length * 2), b, &b);
idx = mono_image_add_stream_data (&assembly->us, buf, b-buf);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
mono_image_add_stream_data (&assembly->us, swapped, str->length * 2);
g_free (swapped);
}
#else
mono_image_add_stream_data (&assembly->us, (const char*)mono_string_chars (str), str->length * 2);
#endif
mono_image_add_stream_data (&assembly->us, "", 1);
} else {
idx = assembly->us.index ++;
}
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (MONO_TOKEN_STRING | idx), str);
return MONO_TOKEN_STRING | idx;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
MonoClass *klass;
guint32 token = 0;
MonoMethodSignature *sig;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MonoMethod") == 0) {
MonoMethod *method = ((MonoReflectionMethod *)obj)->method;
MonoMethodSignature *old;
guint32 sig_token, parent;
int nargs, i;
g_assert (opt_param_types && (mono_method_signature (method)->sentinelpos >= 0));
nargs = mono_array_length (opt_param_types);
old = mono_method_signature (method);
sig = mono_metadata_signature_alloc ( &assembly->image, old->param_count + nargs);
sig->hasthis = old->hasthis;
sig->explicit_this = old->explicit_this;
sig->call_convention = old->call_convention;
sig->generic_param_count = old->generic_param_count;
sig->param_count = old->param_count + nargs;
sig->sentinelpos = old->param_count;
sig->ret = old->ret;
for (i = 0; i < old->param_count; i++)
sig->params [i] = old->params [i];
for (i = 0; i < nargs; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [old->param_count + i] = mono_reflection_type_get_handle (rt);
}
parent = mono_image_typedef_or_ref (assembly, &method->klass->byval_arg);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_MEMBERREF_PARENT_TYPEREF);
parent >>= MONO_TYPEDEFORREF_BITS;
parent <<= MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_TYPEREF;
sig_token = method_encode_signature (assembly, sig);
token = mono_image_get_varargs_method_token (assembly, parent, method->name, sig_token);
} else if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
ReflectionMethodBuilder rmb;
guint32 parent, sig_token;
int nopt_args, nparams, ngparams, i;
char *name;
reflection_methodbuilder_from_method_builder (&rmb, mb);
rmb.opt_types = opt_param_types;
nopt_args = mono_array_length (opt_param_types);
nparams = rmb.parameters ? mono_array_length (rmb.parameters): 0;
ngparams = rmb.generic_params ? mono_array_length (rmb.generic_params): 0;
sig = mono_metadata_signature_alloc (&assembly->image, nparams + nopt_args);
sig->hasthis = !(rmb.attrs & METHOD_ATTRIBUTE_STATIC);
sig->explicit_this = (rmb.call_conv & 0x40) == 0x40;
sig->call_convention = rmb.call_conv;
sig->generic_param_count = ngparams;
sig->param_count = nparams + nopt_args;
sig->sentinelpos = nparams;
sig->ret = mono_reflection_type_get_handle (rmb.rtype);
for (i = 0; i < nparams; i++) {
MonoReflectionType *rt = mono_array_get (rmb.parameters, MonoReflectionType *, i);
sig->params [i] = mono_reflection_type_get_handle (rt);
}
for (i = 0; i < nopt_args; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [nparams + i] = mono_reflection_type_get_handle (rt);
}
sig_token = method_builder_encode_signature (assembly, &rmb);
parent = mono_image_create_token (assembly, obj, TRUE, TRUE);
g_assert (mono_metadata_token_table (parent) == MONO_TABLE_METHOD);
parent = mono_metadata_token_index (parent) << MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_METHODDEF;
name = mono_string_to_utf8 (rmb.name);
token = mono_image_get_varargs_method_token (
assembly, parent, name, sig_token);
g_free (name);
} else {
g_error ("requested method token for %s\n", klass->name);
}
g_hash_table_insert (assembly->vararg_aux_hash, GUINT_TO_POINTER (token), sig);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
return token;
}
/*
* mono_image_create_token:
* @assembly: a dynamic assembly
* @obj:
* @register_token: Whenever to register the token in the assembly->tokens hash.
*
* Get a token to insert in the IL code stream for the given MemberInfo.
* The metadata emission routines need to pass FALSE as REGISTER_TOKEN, since by that time,
* the table_idx-es were recomputed, so registering the token would overwrite an existing
* entry.
*/
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_methodspec, gboolean register_token)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
/* Check for user defined reflection objects */
/* TypeDelegator is the only corlib type which doesn't look like a MonoReflectionType */
if (klass->image != mono_defaults.corlib || (strcmp (klass->name, "TypeDelegator") == 0))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported")); \
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params && !mb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_methodbuilder_token (assembly, mb, create_methodspec);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_ctorbuilder_token (assembly, mb);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)fb->typeb;
if (tb->generic_params) {
token = mono_image_get_generic_field_token (assembly, fb);
} else {
if ((tb->module->dynamic_image == assembly)) {
token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
} else {
token = mono_image_get_fieldref_token (assembly, (MonoObject*)fb, fb->handle);
}
}
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref_full (assembly, type, mc->generic_container == NULL));
} else if (strcmp (klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, m->method);
else
token = mono_image_get_inflated_method_token (assembly, m->method);
} else if ((m->method->klass->image == &assembly->image) &&
!m->method->klass->generic_class) {
static guint32 method_table_idx = 0xffffff;
if (m->method->klass->wastypebuilder) {
/* we use the same token as the one that was assigned
* to the Methodbuilder.
* FIXME: do the equivalent for Fields.
*/
token = m->method->token;
} else {
/*
* Each token should have a unique index, but the indexes are
* assigned by managed code, so we don't know about them. An
* easy solution is to count backwards...
*/
method_table_idx --;
token = MONO_TOKEN_METHOD_DEF | method_table_idx;
}
} else {
token = mono_image_get_methodref_token (assembly, m->method, create_methodspec);
}
/*g_print ("got token 0x%08x for %s\n", token, m->method->name);*/
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField *)obj;
if ((f->field->parent->image == &assembly->image) && !is_field_on_inst (f->field)) {
static guint32 field_table_idx = 0xffffff;
field_table_idx --;
token = MONO_TOKEN_FIELD_DEF | field_table_idx;
} else {
token = mono_image_get_fieldref_token (assembly, (MonoObject*)f, f->field);
}
/*g_print ("got token 0x%08x for %s\n", token, f->field->name);*/
} else if (strcmp (klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod *)obj;
token = mono_image_get_array_token (assembly, m);
} else if (strcmp (klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *s = (MonoReflectionSigHelper*)obj;
token = MONO_TOKEN_SIGNATURE | mono_image_get_sighelper_token (assembly, s);
} else if (strcmp (klass->name, "EnumBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
token = mono_image_get_field_on_inst_token (assembly, f);
} else if (strcmp (klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
token = mono_image_get_ctor_on_inst_token (assembly, c, create_methodspec);
} else if (strcmp (klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
token = mono_image_get_method_on_inst_token (assembly, m, create_methodspec);
} else if (is_sre_array (klass) || is_sre_byref (klass) || is_sre_pointer (klass)) {
MonoReflectionType *type = (MonoReflectionType *)obj;
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (type)));
} else {
g_error ("requested token for %s\n", klass->name);
}
if (register_token)
mono_image_register_token (assembly, token, obj);
return token;
}
/*
* mono_image_register_token:
*
* Register the TOKEN->OBJ mapping in the mapping table in ASSEMBLY. This is required for
* the Module.ResolveXXXToken () methods to work.
*/
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
MonoObject *prev = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
if (prev) {
/* There could be multiple MethodInfo objects with the same token */
//g_assert (prev == obj);
} else {
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
}
}
static MonoDynamicImage*
create_dynamic_mono_image (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name)
{
static const guchar entrycode [16] = {0xff, 0x25, 0};
MonoDynamicImage *image;
int i;
const char *version;
if (!strcmp (mono_get_runtime_info ()->framework_version, "2.1"))
version = "v2.0.50727"; /* HACK: SL 2 enforces the .net 2 metadata version */
else
version = mono_get_runtime_info ()->runtime_version;
#if HAVE_BOEHM_GC
/* The MonoGHashTable's need GC tracking */
image = GC_MALLOC (sizeof (MonoDynamicImage));
#else
image = g_new0 (MonoDynamicImage, 1);
#endif
mono_profiler_module_event (&image->image, MONO_PROFILE_START_LOAD);
/*g_print ("created image %p\n", image);*/
/* keep in sync with image.c */
image->image.name = assembly_name;
image->image.assembly_name = image->image.name; /* they may be different */
image->image.module_name = module_name;
image->image.version = g_strdup (version);
image->image.md_version_major = 1;
image->image.md_version_minor = 1;
image->image.dynamic = TRUE;
image->image.references = g_new0 (MonoAssembly*, 1);
image->image.references [0] = NULL;
mono_image_init (&image->image);
image->token_fixups = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->method_to_table_idx = g_hash_table_new (NULL, NULL);
image->field_to_table_idx = g_hash_table_new (NULL, NULL);
image->method_aux_hash = g_hash_table_new (NULL, NULL);
image->vararg_aux_hash = g_hash_table_new (NULL, NULL);
image->handleref = g_hash_table_new (NULL, NULL);
image->handleref_managed = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->generic_def_objects = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->methodspec = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->typespec = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->typeref = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->blob_cache = g_hash_table_new ((GHashFunc)mono_blob_entry_hash, (GCompareFunc)mono_blob_entry_equal);
image->gen_params = g_ptr_array_new ();
/*g_print ("string heap create for image %p (%s)\n", image, module_name);*/
string_heap_init (&image->sheap);
mono_image_add_stream_data (&image->us, "", 1);
add_to_blob_cached (image, (char*) "", 1, NULL, 0);
/* import tables... */
mono_image_add_stream_data (&image->code, (char*)entrycode, sizeof (entrycode));
image->iat_offset = mono_image_add_stream_zero (&image->code, 8); /* two IAT entries */
image->idt_offset = mono_image_add_stream_zero (&image->code, 2 * sizeof (MonoIDT)); /* two IDT entries */
image->imp_names_offset = mono_image_add_stream_zero (&image->code, 2); /* flags for name entry */
mono_image_add_stream_data (&image->code, "_CorExeMain", 12);
mono_image_add_stream_data (&image->code, "mscoree.dll", 12);
image->ilt_offset = mono_image_add_stream_zero (&image->code, 8); /* two ILT entries */
stream_data_align (&image->code);
image->cli_header_offset = mono_image_add_stream_zero (&image->code, sizeof (MonoCLIHeader));
for (i=0; i < MONO_TABLE_NUM; ++i) {
image->tables [i].next_idx = 1;
image->tables [i].columns = table_sizes [i];
}
image->image.assembly = (MonoAssembly*)assembly;
image->run = assembly->run;
image->save = assembly->save;
image->pe_kind = 0x1; /* ILOnly */
image->machine = 0x14c; /* I386 */
mono_profiler_module_loaded (&image->image, MONO_PROFILE_OK);
return image;
}
#endif
static void
free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
{
g_free (key);
}
void
mono_dynamic_image_free (MonoDynamicImage *image)
{
MonoDynamicImage *di = image;
GList *list;
int i;
if (di->methodspec)
mono_g_hash_table_destroy (di->methodspec);
if (di->typespec)
g_hash_table_destroy (di->typespec);
if (di->typeref)
g_hash_table_destroy (di->typeref);
if (di->handleref)
g_hash_table_destroy (di->handleref);
if (di->handleref_managed)
mono_g_hash_table_destroy (di->handleref_managed);
if (di->tokens)
mono_g_hash_table_destroy (di->tokens);
if (di->generic_def_objects)
mono_g_hash_table_destroy (di->generic_def_objects);
if (di->blob_cache) {
g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
g_hash_table_destroy (di->blob_cache);
}
if (di->standalonesig_cache)
g_hash_table_destroy (di->standalonesig_cache);
for (list = di->array_methods; list; list = list->next) {
ArrayMethod *am = (ArrayMethod *)list->data;
g_free (am->sig);
g_free (am->name);
g_free (am);
}
g_list_free (di->array_methods);
if (di->gen_params) {
for (i = 0; i < di->gen_params->len; i++) {
GenericParamTableEntry *entry = g_ptr_array_index (di->gen_params, i);
if (entry->gparam->type.type) {
MonoGenericParam *param = entry->gparam->type.type->data.generic_param;
g_free ((char*)mono_generic_param_info (param)->name);
g_free (param);
}
mono_gc_deregister_root ((char*) &entry->gparam);
g_free (entry);
}
g_ptr_array_free (di->gen_params, TRUE);
}
if (di->token_fixups)
mono_g_hash_table_destroy (di->token_fixups);
if (di->method_to_table_idx)
g_hash_table_destroy (di->method_to_table_idx);
if (di->field_to_table_idx)
g_hash_table_destroy (di->field_to_table_idx);
if (di->method_aux_hash)
g_hash_table_destroy (di->method_aux_hash);
if (di->vararg_aux_hash)
g_hash_table_destroy (di->vararg_aux_hash);
g_free (di->strong_name);
g_free (di->win32_res);
if (di->public_key)
g_free (di->public_key);
/*g_print ("string heap destroy for image %p\n", di);*/
mono_dynamic_stream_reset (&di->sheap);
mono_dynamic_stream_reset (&di->code);
mono_dynamic_stream_reset (&di->resources);
mono_dynamic_stream_reset (&di->us);
mono_dynamic_stream_reset (&di->blob);
mono_dynamic_stream_reset (&di->tstream);
mono_dynamic_stream_reset (&di->guid);
for (i = 0; i < MONO_TABLE_NUM; ++i) {
g_free (di->tables [i].values);
}
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_basic_init:
* @assembly: an assembly builder object
*
* Create the MonoImage that represents the assembly builder and setup some
* of the helper hash table and the basic metadata streams.
*/
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
MonoDynamicAssembly *assembly;
MonoDynamicImage *image;
MonoDomain *domain = mono_object_domain (assemblyb);
MONO_ARCH_SAVE_REGS;
if (assemblyb->dynamic_assembly)
return;
#if HAVE_BOEHM_GC
/* assembly->assembly.image might be GC allocated */
assembly = assemblyb->dynamic_assembly = GC_MALLOC (sizeof (MonoDynamicAssembly));
#else
assembly = assemblyb->dynamic_assembly = g_new0 (MonoDynamicAssembly, 1);
#endif
mono_profiler_assembly_event (&assembly->assembly, MONO_PROFILE_START_LOAD);
assembly->assembly.ref_count = 1;
assembly->assembly.dynamic = TRUE;
assembly->assembly.corlib_internal = assemblyb->corlib_internal;
assemblyb->assembly.assembly = (MonoAssembly*)assembly;
assembly->assembly.basedir = mono_string_to_utf8 (assemblyb->dir);
if (assemblyb->culture)
assembly->assembly.aname.culture = mono_string_to_utf8 (assemblyb->culture);
else
assembly->assembly.aname.culture = g_strdup ("");
if (assemblyb->version) {
char *vstr = mono_string_to_utf8 (assemblyb->version);
char **version = g_strsplit (vstr, ".", 4);
char **parts = version;
assembly->assembly.aname.major = atoi (*parts++);
assembly->assembly.aname.minor = atoi (*parts++);
assembly->assembly.aname.build = *parts != NULL ? atoi (*parts++) : 0;
assembly->assembly.aname.revision = *parts != NULL ? atoi (*parts) : 0;
g_strfreev (version);
g_free (vstr);
} else {
assembly->assembly.aname.major = 0;
assembly->assembly.aname.minor = 0;
assembly->assembly.aname.build = 0;
assembly->assembly.aname.revision = 0;
}
assembly->run = assemblyb->access != 2;
assembly->save = assemblyb->access != 1;
assembly->domain = domain;
image = create_dynamic_mono_image (assembly, mono_string_to_utf8 (assemblyb->name), g_strdup ("RefEmit_YouForgotToDefineAModule"));
image->initial_image = TRUE;
assembly->assembly.aname.name = image->image.name;
assembly->assembly.image = &image->image;
if (assemblyb->pktoken && assemblyb->pktoken->max_length) {
/* -1 to correct for the trailing NULL byte */
if (assemblyb->pktoken->max_length != MONO_PUBLIC_KEY_TOKEN_LENGTH - 1) {
g_error ("Public key token length invalid for assembly %s: %i", assembly->assembly.aname.name, assemblyb->pktoken->max_length);
}
memcpy (&assembly->assembly.aname.public_key_token, mono_array_addr (assemblyb->pktoken, guint8, 0), assemblyb->pktoken->max_length);
}
mono_domain_assemblies_lock (domain);
domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, assembly);
mono_domain_assemblies_unlock (domain);
register_assembly (mono_object_domain (assemblyb), &assemblyb->assembly, &assembly->assembly);
mono_profiler_assembly_loaded (&assembly->assembly, MONO_PROFILE_OK);
mono_assembly_invoke_load_hook ((MonoAssembly*)assembly);
}
#endif /* !DISABLE_REFLECTION_EMIT */
#ifndef DISABLE_REFLECTION_EMIT_SAVE
static int
calc_section_size (MonoDynamicImage *assembly)
{
int nsections = 0;
/* alignment constraints */
mono_image_add_stream_zero (&assembly->code, 4 - (assembly->code.index % 4));
g_assert ((assembly->code.index % 4) == 0);
assembly->meta_size += 3;
assembly->meta_size &= ~3;
mono_image_add_stream_zero (&assembly->resources, 4 - (assembly->resources.index % 4));
g_assert ((assembly->resources.index % 4) == 0);
assembly->sections [MONO_SECTION_TEXT].size = assembly->meta_size + assembly->code.index + assembly->resources.index + assembly->strong_name_size;
assembly->sections [MONO_SECTION_TEXT].attrs = SECT_FLAGS_HAS_CODE | SECT_FLAGS_MEM_EXECUTE | SECT_FLAGS_MEM_READ;
nsections++;
if (assembly->win32_res) {
guint32 res_size = (assembly->win32_res_size + 3) & ~3;
assembly->sections [MONO_SECTION_RSRC].size = res_size;
assembly->sections [MONO_SECTION_RSRC].attrs = SECT_FLAGS_HAS_INITIALIZED_DATA | SECT_FLAGS_MEM_READ;
nsections++;
}
assembly->sections [MONO_SECTION_RELOC].size = 12;
assembly->sections [MONO_SECTION_RELOC].attrs = SECT_FLAGS_MEM_READ | SECT_FLAGS_MEM_DISCARDABLE | SECT_FLAGS_HAS_INITIALIZED_DATA;
nsections++;
return nsections;
}
typedef struct {
guint32 id;
guint32 offset;
GSList *children;
MonoReflectionWin32Resource *win32_res; /* Only for leaf nodes */
} ResTreeNode;
static int
resource_tree_compare_by_id (gconstpointer a, gconstpointer b)
{
ResTreeNode *t1 = (ResTreeNode*)a;
ResTreeNode *t2 = (ResTreeNode*)b;
return t1->id - t2->id;
}
/*
* resource_tree_create:
*
* Organize the resources into a resource tree.
*/
static ResTreeNode *
resource_tree_create (MonoArray *win32_resources)
{
ResTreeNode *tree, *res_node, *type_node, *lang_node;
GSList *l;
int i;
tree = g_new0 (ResTreeNode, 1);
for (i = 0; i < mono_array_length (win32_resources); ++i) {
MonoReflectionWin32Resource *win32_res =
(MonoReflectionWin32Resource*)mono_array_addr (win32_resources, MonoReflectionWin32Resource, i);
/* Create node */
/* FIXME: BUG: this stores managed references in unmanaged memory */
lang_node = g_new0 (ResTreeNode, 1);
lang_node->id = win32_res->lang_id;
lang_node->win32_res = win32_res;
/* Create type node if neccesary */
type_node = NULL;
for (l = tree->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_type) {
type_node = (ResTreeNode*)l->data;
break;
}
if (!type_node) {
type_node = g_new0 (ResTreeNode, 1);
type_node->id = win32_res->res_type;
/*
* The resource types have to be sorted otherwise
* Windows Explorer can't display the version information.
*/
tree->children = g_slist_insert_sorted (tree->children,
type_node, resource_tree_compare_by_id);
}
/* Create res node if neccesary */
res_node = NULL;
for (l = type_node->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_id) {
res_node = (ResTreeNode*)l->data;
break;
}
if (!res_node) {
res_node = g_new0 (ResTreeNode, 1);
res_node->id = win32_res->res_id;
type_node->children = g_slist_append (type_node->children, res_node);
}
res_node->children = g_slist_append (res_node->children, lang_node);
}
return tree;
}
/*
* resource_tree_encode:
*
* Encode the resource tree into the format used in the PE file.
*/
static void
resource_tree_encode (ResTreeNode *node, char *begin, char *p, char **endbuf)
{
char *entries;
MonoPEResourceDir dir;
MonoPEResourceDirEntry dir_entry;
MonoPEResourceDataEntry data_entry;
GSList *l;
guint32 res_id_entries;
/*
* For the format of the resource directory, see the article
* "An In-Depth Look into the Win32 Portable Executable File Format" by
* Matt Pietrek
*/
memset (&dir, 0, sizeof (dir));
memset (&dir_entry, 0, sizeof (dir_entry));
memset (&data_entry, 0, sizeof (data_entry));
g_assert (sizeof (dir) == 16);
g_assert (sizeof (dir_entry) == 8);
g_assert (sizeof (data_entry) == 16);
node->offset = p - begin;
/* IMAGE_RESOURCE_DIRECTORY */
res_id_entries = g_slist_length (node->children);
dir.res_id_entries = GUINT16_TO_LE (res_id_entries);
memcpy (p, &dir, sizeof (dir));
p += sizeof (dir);
/* Reserve space for entries */
entries = p;
p += sizeof (dir_entry) * res_id_entries;
/* Write children */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
if (child->win32_res) {
guint32 size;
child->offset = p - begin;
/* IMAGE_RESOURCE_DATA_ENTRY */
data_entry.rde_data_offset = GUINT32_TO_LE (p - begin + sizeof (data_entry));
size = mono_array_length (child->win32_res->res_data);
data_entry.rde_size = GUINT32_TO_LE (size);
memcpy (p, &data_entry, sizeof (data_entry));
p += sizeof (data_entry);
memcpy (p, mono_array_addr (child->win32_res->res_data, char, 0), size);
p += size;
} else {
resource_tree_encode (child, begin, p, &p);
}
}
/* IMAGE_RESOURCE_ENTRY */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
MONO_PE_RES_DIR_ENTRY_SET_NAME (dir_entry, FALSE, child->id);
MONO_PE_RES_DIR_ENTRY_SET_DIR (dir_entry, !child->win32_res, child->offset);
memcpy (entries, &dir_entry, sizeof (dir_entry));
entries += sizeof (dir_entry);
}
*endbuf = p;
}
static void
resource_tree_free (ResTreeNode * node)
{
GSList * list;
for (list = node->children; list; list = list->next)
resource_tree_free ((ResTreeNode*)list->data);
g_slist_free(node->children);
g_free (node);
}
static void
assembly_add_win32_resources (MonoDynamicImage *assembly, MonoReflectionAssemblyBuilder *assemblyb)
{
char *buf;
char *p;
guint32 size, i;
MonoReflectionWin32Resource *win32_res;
ResTreeNode *tree;
if (!assemblyb->win32_resources)
return;
/*
* Resources are stored in a three level tree inside the PE file.
* - level one contains a node for each type of resource
* - level two contains a node for each resource
* - level three contains a node for each instance of a resource for a
* specific language.
*/
tree = resource_tree_create (assemblyb->win32_resources);
/* Estimate the size of the encoded tree */
size = 0;
for (i = 0; i < mono_array_length (assemblyb->win32_resources); ++i) {
win32_res = (MonoReflectionWin32Resource*)mono_array_addr (assemblyb->win32_resources, MonoReflectionWin32Resource, i);
size += mono_array_length (win32_res->res_data);
}
/* Directory structure */
size += mono_array_length (assemblyb->win32_resources) * 256;
p = buf = g_malloc (size);
resource_tree_encode (tree, p, p, &p);
g_assert (p - buf <= size);
assembly->win32_res = g_malloc (p - buf);
assembly->win32_res_size = p - buf;
memcpy (assembly->win32_res, buf, p - buf);
g_free (buf);
resource_tree_free (tree);
}
static void
fixup_resource_directory (char *res_section, char *p, guint32 rva)
{
MonoPEResourceDir *dir = (MonoPEResourceDir*)p;
int i;
p += sizeof (MonoPEResourceDir);
for (i = 0; i < GUINT16_FROM_LE (dir->res_named_entries) + GUINT16_FROM_LE (dir->res_id_entries); ++i) {
MonoPEResourceDirEntry *dir_entry = (MonoPEResourceDirEntry*)p;
char *child = res_section + MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*dir_entry);
if (MONO_PE_RES_DIR_ENTRY_IS_DIR (*dir_entry)) {
fixup_resource_directory (res_section, child, rva);
} else {
MonoPEResourceDataEntry *data_entry = (MonoPEResourceDataEntry*)child;
data_entry->rde_data_offset = GUINT32_TO_LE (GUINT32_FROM_LE (data_entry->rde_data_offset) + rva);
}
p += sizeof (MonoPEResourceDirEntry);
}
}
static void
checked_write_file (HANDLE f, gconstpointer buffer, guint32 numbytes)
{
guint32 dummy;
if (!WriteFile (f, buffer, numbytes, &dummy, NULL))
g_error ("WriteFile returned %d\n", GetLastError ());
}
/*
* mono_image_create_pefile:
* @mb: a module builder object
*
* This function creates the PE-COFF header, the image sections, the CLI header * etc. all the data is written in
* assembly->pefile where it can be easily retrieved later in chunks.
*/
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
MonoMSDOSHeader *msdos;
MonoDotNetHeader *header;
MonoSectionTable *section;
MonoCLIHeader *cli_header;
guint32 size, image_size, virtual_base, text_offset;
guint32 header_start, section_start, file_offset, virtual_offset;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDynamicStream pefile_stream = {0};
MonoDynamicStream *pefile = &pefile_stream;
int i, nsections;
guint32 *rva, value;
guchar *p;
static const unsigned char msheader[] = {
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
assemblyb = mb->assemblyb;
mono_image_basic_init (assemblyb);
assembly = mb->dynamic_image;
assembly->pe_kind = assemblyb->pe_kind;
assembly->machine = assemblyb->machine;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->pe_kind = assemblyb->pe_kind;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->machine = assemblyb->machine;
mono_image_build_metadata (mb);
if (mb->is_main && assemblyb->resources) {
int len = mono_array_length (assemblyb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (assemblyb->resources, MonoReflectionResource, i));
}
if (mb->resources) {
int len = mono_array_length (mb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (mb->resources, MonoReflectionResource, i));
}
build_compressed_metadata (assembly);
if (mb->is_main)
assembly_add_win32_resources (assembly, assemblyb);
nsections = calc_section_size (assembly);
/* The DOS header and stub */
g_assert (sizeof (MonoMSDOSHeader) == sizeof (msheader));
mono_image_add_stream_data (pefile, (char*)msheader, sizeof (msheader));
/* the dotnet header */
header_start = mono_image_add_stream_zero (pefile, sizeof (MonoDotNetHeader));
/* the section tables */
section_start = mono_image_add_stream_zero (pefile, sizeof (MonoSectionTable) * nsections);
file_offset = section_start + sizeof (MonoSectionTable) * nsections;
virtual_offset = VIRT_ALIGN;
image_size = 0;
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
/* align offsets */
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
virtual_offset += VIRT_ALIGN - 1;
virtual_offset &= ~(VIRT_ALIGN - 1);
assembly->sections [i].offset = file_offset;
assembly->sections [i].rva = virtual_offset;
file_offset += assembly->sections [i].size;
virtual_offset += assembly->sections [i].size;
image_size += (assembly->sections [i].size + VIRT_ALIGN - 1) & ~(VIRT_ALIGN - 1);
}
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
image_size += section_start + sizeof (MonoSectionTable) * nsections;
/* back-patch info */
msdos = (MonoMSDOSHeader*)pefile->data;
msdos->pe_offset = GUINT32_FROM_LE (sizeof (MonoMSDOSHeader));
header = (MonoDotNetHeader*)(pefile->data + header_start);
header->pesig [0] = 'P';
header->pesig [1] = 'E';
header->coff.coff_machine = GUINT16_FROM_LE (assemblyb->machine);
header->coff.coff_sections = GUINT16_FROM_LE (nsections);
header->coff.coff_time = GUINT32_FROM_LE (time (NULL));
header->coff.coff_opt_header_size = GUINT16_FROM_LE (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4);
if (assemblyb->pekind == 1) {
/* it's a dll */
header->coff.coff_attributes = GUINT16_FROM_LE (0x210e);
} else {
/* it's an exe */
header->coff.coff_attributes = GUINT16_FROM_LE (0x010e);
}
virtual_base = 0x400000; /* FIXME: 0x10000000 if a DLL */
header->pe.pe_magic = GUINT16_FROM_LE (0x10B);
header->pe.pe_major = 6;
header->pe.pe_minor = 0;
size = assembly->sections [MONO_SECTION_TEXT].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_code_size = GUINT32_FROM_LE(size);
size = assembly->sections [MONO_SECTION_RSRC].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_data_size = GUINT32_FROM_LE(size);
g_assert (START_TEXT_RVA == assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_code_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_data_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
/* pe_rva_entry_point always at the beginning of the text section */
header->pe.pe_rva_entry_point = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->nt.pe_image_base = GUINT32_FROM_LE (virtual_base);
header->nt.pe_section_align = GUINT32_FROM_LE (VIRT_ALIGN);
header->nt.pe_file_alignment = GUINT32_FROM_LE (FILE_ALIGN);
header->nt.pe_os_major = GUINT16_FROM_LE (4);
header->nt.pe_os_minor = GUINT16_FROM_LE (0);
header->nt.pe_subsys_major = GUINT16_FROM_LE (4);
size = section_start;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->nt.pe_header_size = GUINT32_FROM_LE (size);
size = image_size;
size += VIRT_ALIGN - 1;
size &= ~(VIRT_ALIGN - 1);
header->nt.pe_image_size = GUINT32_FROM_LE (size);
/*
// Translate the PEFileKind value to the value expected by the Windows loader
*/
{
short kind;
/*
// PEFileKinds.Dll == 1
// PEFileKinds.ConsoleApplication == 2
// PEFileKinds.WindowApplication == 3
//
// need to get:
// IMAGE_SUBSYSTEM_WINDOWS_GUI 2 // Image runs in the Windows GUI subsystem.
// IMAGE_SUBSYSTEM_WINDOWS_CUI 3 // Image runs in the Windows character subsystem.
*/
if (assemblyb->pekind == 3)
kind = 2;
else
kind = 3;
header->nt.pe_subsys_required = GUINT16_FROM_LE (kind);
}
header->nt.pe_stack_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_stack_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_heap_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_heap_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_loader_flags = GUINT32_FROM_LE (0);
header->nt.pe_data_dir_count = GUINT32_FROM_LE (16);
/* fill data directory entries */
header->datadir.pe_resource_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].size);
header->datadir.pe_resource_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
header->datadir.pe_reloc_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].size);
header->datadir.pe_reloc_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].rva);
header->datadir.pe_cli_header.size = GUINT32_FROM_LE (72);
header->datadir.pe_cli_header.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->cli_header_offset);
header->datadir.pe_iat.size = GUINT32_FROM_LE (8);
header->datadir.pe_iat.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
/* patch entrypoint name */
if (assemblyb->pekind == 1)
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorDllMain", 12);
else
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorExeMain", 12);
/* patch imported function RVA name */
rva = (guint32*)(assembly->code.data + assembly->iat_offset);
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset);
/* the import table */
header->datadir.pe_import_table.size = GUINT32_FROM_LE (79); /* FIXME: magic number? */
header->datadir.pe_import_table.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->idt_offset);
/* patch imported dll RVA name and other entries in the dir */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, name_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset + 14); /* 14 is hint+strlen+1 of func name */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_address_table_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_lookup_table));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->ilt_offset);
p = (guchar*)(assembly->code.data + assembly->ilt_offset);
value = (assembly->text_rva + assembly->imp_names_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & (0xff);
*p++ = (value >> 16) & (0xff);
*p++ = (value >> 24) & (0xff);
/* the CLI header info */
cli_header = (MonoCLIHeader*)(assembly->code.data + assembly->cli_header_offset);
cli_header->ch_size = GUINT32_FROM_LE (72);
cli_header->ch_runtime_major = GUINT16_FROM_LE (2);
cli_header->ch_runtime_minor = GUINT16_FROM_LE (5);
cli_header->ch_flags = GUINT32_FROM_LE (assemblyb->pe_kind);
if (assemblyb->entry_point) {
guint32 table_idx = 0;
if (!strcmp (assemblyb->entry_point->object.vtable->klass->name, "MethodBuilder")) {
MonoReflectionMethodBuilder *methodb = (MonoReflectionMethodBuilder*)assemblyb->entry_point;
table_idx = methodb->table_idx;
} else {
table_idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, assemblyb->entry_point->method));
}
cli_header->ch_entry_point = GUINT32_FROM_LE (table_idx | MONO_TOKEN_METHOD_DEF);
} else {
cli_header->ch_entry_point = GUINT32_FROM_LE (0);
}
/* The embedded managed resources */
text_offset = assembly->text_rva + assembly->code.index;
cli_header->ch_resources.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_resources.size = GUINT32_FROM_LE (assembly->resources.index);
text_offset += assembly->resources.index;
cli_header->ch_metadata.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_metadata.size = GUINT32_FROM_LE (assembly->meta_size);
text_offset += assembly->meta_size;
if (assembly->strong_name_size) {
cli_header->ch_strong_name.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_strong_name.size = GUINT32_FROM_LE (assembly->strong_name_size);
text_offset += assembly->strong_name_size;
}
/* write the section tables and section content */
section = (MonoSectionTable*)(pefile->data + section_start);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
static const char section_names [][7] = {
".text", ".rsrc", ".reloc"
};
if (!assembly->sections [i].size)
continue;
strcpy (section->st_name, section_names [i]);
/*g_print ("output section %s (%d), size: %d\n", section->st_name, i, assembly->sections [i].size);*/
section->st_virtual_address = GUINT32_FROM_LE (assembly->sections [i].rva);
section->st_virtual_size = GUINT32_FROM_LE (assembly->sections [i].size);
section->st_raw_data_size = GUINT32_FROM_LE (GUINT32_TO_LE (section->st_virtual_size) + (FILE_ALIGN - 1));
section->st_raw_data_size &= GUINT32_FROM_LE (~(FILE_ALIGN - 1));
section->st_raw_data_ptr = GUINT32_FROM_LE (assembly->sections [i].offset);
section->st_flags = GUINT32_FROM_LE (assembly->sections [i].attrs);
section ++;
}
checked_write_file (file, pefile->data, pefile->index);
mono_dynamic_stream_reset (pefile);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
if (SetFilePointer (file, assembly->sections [i].offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
switch (i) {
case MONO_SECTION_TEXT:
/* patch entry point */
p = (guchar*)(assembly->code.data + 2);
value = (virtual_base + assembly->text_rva + assembly->iat_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & 0xff;
*p++ = (value >> 16) & 0xff;
*p++ = (value >> 24) & 0xff;
checked_write_file (file, assembly->code.data, assembly->code.index);
checked_write_file (file, assembly->resources.data, assembly->resources.index);
checked_write_file (file, assembly->image.raw_metadata, assembly->meta_size);
checked_write_file (file, assembly->strong_name, assembly->strong_name_size);
g_free (assembly->image.raw_metadata);
break;
case MONO_SECTION_RELOC: {
struct {
guint32 page_rva;
guint32 block_size;
guint16 type_and_offset;
guint16 term;
} reloc;
g_assert (sizeof (reloc) == 12);
reloc.page_rva = GUINT32_FROM_LE (assembly->text_rva);
reloc.block_size = GUINT32_FROM_LE (12);
/*
* the entrypoint is always at the start of the text section
* 3 is IMAGE_REL_BASED_HIGHLOW
* 2 is patch_size_rva - text_rva
*/
reloc.type_and_offset = GUINT16_FROM_LE ((3 << 12) + (2));
reloc.term = 0;
checked_write_file (file, &reloc, sizeof (reloc));
break;
}
case MONO_SECTION_RSRC:
if (assembly->win32_res) {
/* Fixup the offsets in the IMAGE_RESOURCE_DATA_ENTRY structures */
fixup_resource_directory (assembly->win32_res, assembly->win32_res, assembly->sections [i].rva);
checked_write_file (file, assembly->win32_res, assembly->win32_res_size);
}
break;
default:
g_assert_not_reached ();
}
}
/* check that the file is properly padded */
if (SetFilePointer (file, file_offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
if (! SetEndOfFile (file))
g_error ("SetEndOfFile returned %d\n", GetLastError ());
mono_dynamic_stream_reset (&assembly->code);
mono_dynamic_stream_reset (&assembly->us);
mono_dynamic_stream_reset (&assembly->blob);
mono_dynamic_stream_reset (&assembly->guid);
mono_dynamic_stream_reset (&assembly->sheap);
g_hash_table_foreach (assembly->blob_cache, (GHFunc)g_free, NULL);
g_hash_table_destroy (assembly->blob_cache);
assembly->blob_cache = NULL;
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
g_assert_not_reached ();
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
char *name;
MonoImage *image;
MonoImageOpenStatus status;
MonoDynamicAssembly *assembly;
guint32 module_count;
MonoImage **new_modules;
gboolean *new_modules_loaded;
name = mono_string_to_utf8 (fileName);
image = mono_image_open (name, &status);
if (!image) {
MonoException *exc;
if (status == MONO_IMAGE_ERROR_ERRNO)
exc = mono_get_exception_file_not_found (fileName);
else
exc = mono_get_exception_bad_image_format (name);
g_free (name);
mono_raise_exception (exc);
}
g_free (name);
assembly = ab->dynamic_assembly;
image->assembly = (MonoAssembly*)assembly;
module_count = image->assembly->image->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
new_modules_loaded = g_new0 (gboolean, module_count + 1);
if (image->assembly->image->modules)
memcpy (new_modules, image->assembly->image->modules, module_count * sizeof (MonoImage *));
if (image->assembly->image->modules_loaded)
memcpy (new_modules_loaded, image->assembly->image->modules_loaded, module_count * sizeof (gboolean));
new_modules [module_count] = image;
new_modules_loaded [module_count] = TRUE;
mono_image_addref (image);
g_free (image->assembly->image->modules);
image->assembly->image->modules = new_modules;
image->assembly->image->modules_loaded = new_modules_loaded;
image->assembly->image->module_count ++;
mono_assembly_load_references (image, &status);
if (status) {
mono_image_close (image);
mono_raise_exception (mono_get_exception_file_not_found (fileName));
}
return mono_module_get_object (mono_domain_get (), image);
}
#endif /* DISABLE_REFLECTION_EMIT */
/*
* We need to return always the same object for MethodInfo, FieldInfo etc..
* but we need to consider the reflected type.
* type uses a different hash, since it uses custom hash/equal functions.
*/
typedef struct {
gpointer item;
MonoClass *refclass;
} ReflectedEntry;
static gboolean
reflected_equal (gconstpointer a, gconstpointer b) {
const ReflectedEntry *ea = a;
const ReflectedEntry *eb = b;
return (ea->item == eb->item) && (ea->refclass == eb->refclass);
}
static guint
reflected_hash (gconstpointer a) {
const ReflectedEntry *ea = a;
return mono_aligned_addr_hash (ea->item);
}
#define CHECK_OBJECT(t,p,k) \
do { \
t _obj; \
ReflectedEntry e; \
e.item = (p); \
e.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
if ((_obj = mono_g_hash_table_lookup (domain->refobject_hash, &e))) { \
mono_domain_unlock (domain); \
return _obj; \
} \
mono_domain_unlock (domain); \
} while (0)
#ifdef HAVE_BOEHM_GC
/* ReflectedEntry doesn't need to be GC tracked */
#define ALLOC_REFENTRY g_new0 (ReflectedEntry, 1)
#define FREE_REFENTRY(entry) g_free ((entry))
#define REFENTRY_REQUIRES_CLEANUP
#else
#define ALLOC_REFENTRY mono_mempool_alloc (domain->mp, sizeof (ReflectedEntry))
/* FIXME: */
#define FREE_REFENTRY(entry)
#endif
#define CACHE_OBJECT(t,p,o,k) \
do { \
t _obj; \
ReflectedEntry pe; \
pe.item = (p); \
pe.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
_obj = mono_g_hash_table_lookup (domain->refobject_hash, &pe); \
if (!_obj) { \
ReflectedEntry *e = ALLOC_REFENTRY; \
e->item = (p); \
e->refclass = (k); \
mono_g_hash_table_insert (domain->refobject_hash, e,o); \
_obj = o; \
} \
mono_domain_unlock (domain); \
return _obj; \
} while (0)
static void
clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass)
{
mono_domain_lock (domain);
if (domain->refobject_hash) {
ReflectedEntry pe;
gpointer orig_pe, orig_value;
pe.item = o;
pe.refclass = klass;
if (mono_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) {
mono_g_hash_table_remove (domain->refobject_hash, &pe);
FREE_REFENTRY (orig_pe);
}
}
mono_domain_unlock (domain);
}
#ifdef REFENTRY_REQUIRES_CLEANUP
static void
cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data)
{
FREE_REFENTRY (key);
}
#endif
void
mono_reflection_cleanup_domain (MonoDomain *domain)
{
if (domain->refobject_hash) {
/*let's avoid scanning the whole hashtable if not needed*/
#ifdef REFENTRY_REQUIRES_CLEANUP
mono_g_hash_table_foreach (domain->refobject_hash, cleanup_refobject_hash, NULL);
#endif
mono_g_hash_table_destroy (domain->refobject_hash);
domain->refobject_hash = NULL;
}
}
#ifndef DISABLE_REFLECTION_EMIT
static gpointer
register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly)
{
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
static gpointer
register_module (MonoDomain *domain, MonoReflectionModuleBuilder *res, MonoDynamicImage *module)
{
CACHE_OBJECT (MonoReflectionModuleBuilder *, module, res, NULL);
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicImage *image = moduleb->dynamic_image;
MonoReflectionAssemblyBuilder *ab = moduleb->assemblyb;
if (!image) {
MonoError error;
int module_count;
MonoImage **new_modules;
MonoImage *ass;
char *name, *fqname;
/*
* FIXME: we already created an image in mono_image_basic_init (), but
* we don't know which module it belongs to, since that is only
* determined at assembly save time.
*/
/*image = (MonoDynamicImage*)ab->dynamic_assembly->assembly.image; */
name = mono_string_to_utf8 (ab->name);
fqname = mono_string_to_utf8_checked (moduleb->module.fqname, &error);
if (!mono_error_ok (&error)) {
g_free (name);
mono_error_raise_exception (&error);
}
image = create_dynamic_mono_image (ab->dynamic_assembly, name, fqname);
moduleb->module.image = &image->image;
moduleb->dynamic_image = image;
register_module (mono_object_domain (moduleb), moduleb, image);
/* register the module with the assembly */
ass = ab->dynamic_assembly->assembly.image;
module_count = ass->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
if (ass->modules)
memcpy (new_modules, ass->modules, module_count * sizeof (MonoImage *));
new_modules [module_count] = &image->image;
mono_image_addref (&image->image);
g_free (ass->modules);
ass->modules = new_modules;
ass->module_count ++;
}
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
MonoDynamicImage *image = moduleb->dynamic_image;
g_assert (type->type);
image->wrappers_type = mono_class_from_mono_type (type->type);
}
#endif
/*
* mono_assembly_get_object:
* @domain: an app domain
* @assembly: an assembly
*
* Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
*/
MonoReflectionAssembly*
mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
{
static MonoClass *assembly_type;
MonoReflectionAssembly *res;
CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL);
if (!assembly_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoAssembly");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Assembly");
g_assert (class);
assembly_type = class;
}
res = (MonoReflectionAssembly *)mono_object_new (domain, assembly_type);
res->assembly = assembly;
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
MonoReflectionModule*
mono_module_get_object (MonoDomain *domain, MonoImage *image)
{
static MonoClass *module_type;
MonoReflectionModule *res;
char* basename;
CHECK_OBJECT (MonoReflectionModule *, image, NULL);
if (!module_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
g_assert (class);
module_type = class;
}
res = (MonoReflectionModule *)mono_object_new (domain, module_type);
res->image = image;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, image->name));
basename = g_path_get_basename (image->name);
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, basename));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, image->module_name));
g_free (basename);
if (image->assembly->image == image) {
res->token = mono_metadata_make_token (MONO_TABLE_MODULE, 1);
} else {
int i;
res->token = 0;
if (image->assembly->image->modules) {
for (i = 0; i < image->assembly->image->module_count; i++) {
if (image->assembly->image->modules [i] == image)
res->token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1);
}
g_assert (res->token);
}
}
CACHE_OBJECT (MonoReflectionModule *, image, res, NULL);
}
MonoReflectionModule*
mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
{
static MonoClass *module_type;
MonoReflectionModule *res;
MonoTableInfo *table;
guint32 cols [MONO_FILE_SIZE];
const char *name;
guint32 i, name_idx;
const char *val;
if (!module_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
g_assert (class);
module_type = class;
}
res = (MonoReflectionModule *)mono_object_new (domain, module_type);
table = &image->tables [MONO_TABLE_FILE];
g_assert (table_index < table->rows);
mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE);
res->image = NULL;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
/* Check whenever the row has a corresponding row in the moduleref table */
table = &image->tables [MONO_TABLE_MODULEREF];
for (i = 0; i < table->rows; ++i) {
name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME);
val = mono_metadata_string_heap (image, name_idx);
if (strcmp (val, name) == 0)
res->image = image->modules [i];
}
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, name));
res->is_resource = cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA;
res->token = mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1);
return res;
}
static gboolean
mymono_metadata_type_equal (MonoType *t1, MonoType *t2)
{
if ((t1->type != t2->type) ||
(t1->byref != t2->byref))
return FALSE;
switch (t1->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
return TRUE;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
return t1->data.klass == t2->data.klass;
case MONO_TYPE_PTR:
return mymono_metadata_type_equal (t1->data.type, t2->data.type);
case MONO_TYPE_ARRAY:
if (t1->data.array->rank != t2->data.array->rank)
return FALSE;
return t1->data.array->eklass == t2->data.array->eklass;
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *i1 = t1->data.generic_class->context.class_inst;
MonoGenericInst *i2 = t2->data.generic_class->context.class_inst;
if (i1->type_argc != i2->type_argc)
return FALSE;
if (!mono_metadata_type_equal (&t1->data.generic_class->container_class->byval_arg,
&t2->data.generic_class->container_class->byval_arg))
return FALSE;
/* FIXME: we should probably just compare the instance pointers directly. */
for (i = 0; i < i1->type_argc; ++i) {
if (!mono_metadata_type_equal (i1->type_argv [i], i2->type_argv [i]))
return FALSE;
}
return TRUE;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return t1->data.generic_param == t2->data.generic_param;
default:
g_error ("implement type compare for %0x!", t1->type);
return FALSE;
}
return FALSE;
}
static guint
mymono_metadata_type_hash (MonoType *t1)
{
guint hash;
hash = t1->type;
hash |= t1->byref << 6; /* do not collide with t1->type values */
switch (t1->type) {
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
/* check if the distribution is good enough */
return ((hash << 5) - hash) ^ mono_aligned_addr_hash (t1->data.klass);
case MONO_TYPE_PTR:
return ((hash << 5) - hash) ^ mymono_metadata_type_hash (t1->data.type);
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *inst = t1->data.generic_class->context.class_inst;
hash += g_str_hash (t1->data.generic_class->container_class->name);
hash *= 13;
for (i = 0; i < inst->type_argc; ++i) {
hash += mymono_metadata_type_hash (inst->type_argv [i]);
hash *= 13;
}
return hash;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return ((hash << 5) - hash) ^ GPOINTER_TO_UINT (t1->data.generic_param);
}
return hash;
}
static gboolean
verify_safe_for_managed_space (MonoType *type)
{
switch (type->type) {
#ifdef DEBUG_HARDER
case MONO_TYPE_ARRAY:
return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
case MONO_TYPE_PTR:
return verify_safe_for_managed_space (type->data.type);
case MONO_TYPE_SZARRAY:
return verify_safe_for_managed_space (&type->data.klass->byval_arg);
case MONO_TYPE_GENERICINST: {
MonoGenericInst *inst = type->data.generic_class->inst;
int i;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!verify_safe_for_managed_space (inst->type_argv [i]))
return FALSE;
break;
}
#endif
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return TRUE;
}
return TRUE;
}
static MonoType*
mono_type_normalize (MonoType *type)
{
int i;
MonoGenericClass *gclass;
MonoGenericInst *ginst;
MonoClass *gtd;
MonoGenericContainer *gcontainer;
MonoType **argv = NULL;
gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE;
if (type->type != MONO_TYPE_GENERICINST)
return type;
gclass = type->data.generic_class;
ginst = gclass->context.class_inst;
if (!ginst->is_open)
return type;
gtd = gclass->container_class;
gcontainer = gtd->generic_container;
argv = g_newa (MonoType*, ginst->type_argc);
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *t = ginst->type_argv [i], *norm;
if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer)
is_denorm_gtd = FALSE;
norm = mono_type_normalize (t);
argv [i] = norm;
if (norm != t)
requires_rebind = TRUE;
}
if (is_denorm_gtd)
return type->byref == gtd->byval_arg.byref ? >d->byval_arg : >d->this_arg;
if (requires_rebind) {
MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic);
return type->byref == klass->byval_arg.byref ? &klass->byval_arg : &klass->this_arg;
}
return type;
}
/*
* mono_type_get_object:
* @domain: an app domain
* @type: a type
*
* Return an System.MonoType object representing the type @type.
*/
MonoReflectionType*
mono_type_get_object (MonoDomain *domain, MonoType *type)
{
MonoType *norm_type;
MonoReflectionType *res;
MonoClass *klass = mono_class_from_mono_type (type);
/*we must avoid using @type as it might have come
* from a mono_metadata_type_dup and the caller
* expects that is can be freed.
* Using the right type from
*/
type = klass->byval_arg.byref == type->byref ? &klass->byval_arg : &klass->this_arg;
/* void is very common */
if (type->type == MONO_TYPE_VOID && domain->typeof_void)
return (MonoReflectionType*)domain->typeof_void;
/*
* If the vtable of the given class was already created, we can use
* the MonoType from there and avoid all locking and hash table lookups.
*
* We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
* that the resulting object is different.
*/
if (type == &klass->byval_arg && !klass->image->dynamic) {
MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
if (vtable && vtable->type)
return vtable->type;
}
mono_loader_lock (); /*FIXME mono_class_init and mono_class_vtable acquire it*/
mono_domain_lock (domain);
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
if ((res = mono_g_hash_table_lookup (domain->type_hash, type))) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*Types must be normalized so a generic instance of the GTD get's the same inner type.
* For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>>
* The second Bar will be encoded a generic instance of Bar with <A> as parameter.
* On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation
* artifact of how generics are encoded and should be transparent to managed code so we
* need to weed out this diference when retrieving managed System.Type objects.
*/
norm_type = mono_type_normalize (type);
if (norm_type != type) {
res = mono_type_get_object (domain, norm_type);
mono_g_hash_table_insert (domain->type_hash, type, res);
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/* This MonoGenericClass hack is no longer necessary. Let's leave it here until we finish with the 2-stage type-builder setup.*/
if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
g_assert (0);
if (!verify_safe_for_managed_space (type)) {
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_raise_exception (mono_get_exception_invalid_operation ("This type cannot be propagated to managed space"));
}
if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
gboolean is_type_done = TRUE;
/* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
* We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
* We can't simply close the types as this will interfere with other parts of the generics machinery.
*/
if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
if (gparam->owner && gparam->owner->is_method) {
MonoMethod *method = gparam->owner->owner.method;
if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
is_type_done = FALSE;
} else if (gparam->owner && !gparam->owner->is_method) {
MonoClass *klass = gparam->owner->owner.klass;
if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
is_type_done = FALSE;
}
}
/* g_assert_not_reached (); */
/* should this be considered an error condition? */
if (is_type_done && !type->byref) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_class_get_ref_info (klass);
}
}
#ifdef HAVE_SGEN_GC
res = (MonoReflectionType *)mono_gc_alloc_pinned_obj (mono_class_vtable (domain, mono_defaults.monotype_class), mono_class_instance_size (mono_defaults.monotype_class));
#else
res = (MonoReflectionType *)mono_object_new (domain, mono_defaults.monotype_class);
#endif
res->type = type;
mono_g_hash_table_insert (domain->type_hash, type, res);
if (type->type == MONO_TYPE_VOID)
domain->typeof_void = (MonoObject*)res;
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*
* mono_method_get_object:
* @domain: an app domain
* @method: a method
* @refclass: the reflected type (can be NULL)
*
* Return an System.Reflection.MonoMethod object representing the method @method.
*/
MonoReflectionMethod*
mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
/*
* We use the same C representation for methods and constructors, but the type
* name in C# is different.
*/
static MonoClass *System_Reflection_MonoMethod = NULL;
static MonoClass *System_Reflection_MonoCMethod = NULL;
static MonoClass *System_Reflection_MonoGenericMethod = NULL;
static MonoClass *System_Reflection_MonoGenericCMethod = NULL;
MonoClass *klass;
MonoReflectionMethod *ret;
if (method->is_inflated) {
MonoReflectionGenericMethod *gret;
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if ((*method->name == '.') && (!strcmp (method->name, ".ctor") || !strcmp (method->name, ".cctor"))) {
if (!System_Reflection_MonoGenericCMethod)
System_Reflection_MonoGenericCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericCMethod");
klass = System_Reflection_MonoGenericCMethod;
} else {
if (!System_Reflection_MonoGenericMethod)
System_Reflection_MonoGenericMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericMethod");
klass = System_Reflection_MonoGenericMethod;
}
gret = (MonoReflectionGenericMethod*)mono_object_new (domain, klass);
gret->method.method = method;
MONO_OBJECT_SETREF (gret, method.name, mono_string_new (domain, method->name));
MONO_OBJECT_SETREF (gret, method.reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, (MonoReflectionMethod*)gret, refclass);
}
if (!refclass)
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) {
if (!System_Reflection_MonoCMethod)
System_Reflection_MonoCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoCMethod");
klass = System_Reflection_MonoCMethod;
}
else {
if (!System_Reflection_MonoMethod)
System_Reflection_MonoMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoMethod");
klass = System_Reflection_MonoMethod;
}
ret = (MonoReflectionMethod*)mono_object_new (domain, klass);
ret->method = method;
MONO_OBJECT_SETREF (ret, reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, ret, refclass);
}
/*
* mono_method_clear_object:
*
* Clear the cached reflection objects for the dynamic method METHOD.
*/
void
mono_method_clear_object (MonoDomain *domain, MonoMethod *method)
{
MonoClass *klass;
g_assert (method->dynamic);
klass = method->klass;
while (klass) {
clear_cached_object (domain, method, klass);
klass = klass->parent;
}
/* Added by mono_param_get_objects () */
clear_cached_object (domain, &(method->signature), NULL);
klass = method->klass;
while (klass) {
clear_cached_object (domain, &(method->signature), klass);
klass = klass->parent;
}
}
/*
* mono_field_get_object:
* @domain: an app domain
* @klass: a type
* @field: a field
*
* Return an System.Reflection.MonoField object representing the field @field
* in class @klass.
*/
MonoReflectionField*
mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field)
{
MonoReflectionField *res;
static MonoClass *monofield_klass;
CHECK_OBJECT (MonoReflectionField *, field, klass);
if (!monofield_klass)
monofield_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoField");
res = (MonoReflectionField *)mono_object_new (domain, monofield_klass);
res->klass = klass;
res->field = field;
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, mono_field_get_name (field)));
if (is_field_on_inst (field)) {
res->attrs = get_field_on_inst_generic_type (field)->attrs;
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
} else {
if (field->type)
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
res->attrs = mono_field_get_flags (field);
}
CACHE_OBJECT (MonoReflectionField *, field, res, klass);
}
/*
* mono_property_get_object:
* @domain: an app domain
* @klass: a type
* @property: a property
*
* Return an System.Reflection.MonoProperty object representing the property @property
* in class @klass.
*/
MonoReflectionProperty*
mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property)
{
MonoReflectionProperty *res;
static MonoClass *monoproperty_klass;
CHECK_OBJECT (MonoReflectionProperty *, property, klass);
if (!monoproperty_klass)
monoproperty_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoProperty");
res = (MonoReflectionProperty *)mono_object_new (domain, monoproperty_klass);
res->klass = klass;
res->property = property;
CACHE_OBJECT (MonoReflectionProperty *, property, res, klass);
}
/*
* mono_event_get_object:
* @domain: an app domain
* @klass: a type
* @event: a event
*
* Return an System.Reflection.MonoEvent object representing the event @event
* in class @klass.
*/
MonoReflectionEvent*
mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event)
{
MonoReflectionEvent *res;
MonoReflectionMonoEvent *mono_event;
static MonoClass *monoevent_klass;
CHECK_OBJECT (MonoReflectionEvent *, event, klass);
if (!monoevent_klass)
monoevent_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoEvent");
mono_event = (MonoReflectionMonoEvent *)mono_object_new (domain, monoevent_klass);
mono_event->klass = klass;
mono_event->event = event;
res = (MonoReflectionEvent*)mono_event;
CACHE_OBJECT (MonoReflectionEvent *, event, res, klass);
}
/**
* mono_get_reflection_missing_object:
* @domain: Domain where the object lives
*
* Returns the System.Reflection.Missing.Value singleton object
* (of type System.Reflection.Missing).
*
* Used as the value for ParameterInfo.DefaultValue when Optional
* is present
*/
static MonoObject *
mono_get_reflection_missing_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *missing_value_field = NULL;
if (!missing_value_field) {
MonoClass *missing_klass;
missing_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Missing");
mono_class_init (missing_klass);
missing_value_field = mono_class_get_field_from_name (missing_klass, "Value");
g_assert (missing_value_field);
}
obj = mono_field_get_value_object (domain, missing_value_field, NULL);
g_assert (obj);
return obj;
}
static MonoObject*
get_dbnull (MonoDomain *domain, MonoObject **dbnull)
{
if (!*dbnull)
*dbnull = mono_get_dbnull_object (domain);
return *dbnull;
}
static MonoObject*
get_reflection_missing (MonoDomain *domain, MonoObject **reflection_missing)
{
if (!*reflection_missing)
*reflection_missing = mono_get_reflection_missing_object (domain);
return *reflection_missing;
}
/*
* mono_param_get_objects:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.ParameterInfo array object representing the parameters
* in the method @method.
*/
MonoArray*
mono_param_get_objects_internal (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
static MonoClass *System_Reflection_ParameterInfo;
static MonoClass *System_Reflection_ParameterInfo_array;
MonoArray *res = NULL;
MonoReflectionMethod *member = NULL;
MonoReflectionParameter *param = NULL;
char **names, **blobs = NULL;
guint32 *types = NULL;
MonoType *type = NULL;
MonoObject *dbnull = NULL;
MonoObject *missing = NULL;
MonoMarshalSpec **mspecs;
MonoMethodSignature *sig;
MonoVTable *pinfo_vtable;
int i;
if (!System_Reflection_ParameterInfo_array) {
MonoClass *klass;
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ParameterInfo");
mono_memory_barrier ();
System_Reflection_ParameterInfo = klass;
klass = mono_array_class_get (klass, 1);
mono_memory_barrier ();
System_Reflection_ParameterInfo_array = klass;
}
if (!mono_method_signature (method)->param_count)
return mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), 0);
/* Note: the cache is based on the address of the signature into the method
* since we already cache MethodInfos with the method as keys.
*/
CHECK_OBJECT (MonoArray*, &(method->signature), refclass);
sig = mono_method_signature (method);
member = mono_method_get_object (domain, method, refclass);
names = g_new (char *, sig->param_count);
mono_method_get_param_names (method, (const char **) names);
mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
mono_method_get_marshal_info (method, mspecs);
res = mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), sig->param_count);
pinfo_vtable = mono_class_vtable (domain, System_Reflection_ParameterInfo);
for (i = 0; i < sig->param_count; ++i) {
param = (MonoReflectionParameter *)mono_object_new_specific (pinfo_vtable);
MONO_OBJECT_SETREF (param, ClassImpl, mono_type_get_object (domain, sig->params [i]));
MONO_OBJECT_SETREF (param, MemberImpl, (MonoObject*)member);
MONO_OBJECT_SETREF (param, NameImpl, mono_string_new (domain, names [i]));
param->PositionImpl = i;
param->AttrsImpl = sig->params [i]->attrs;
if (!(param->AttrsImpl & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
} else {
if (!blobs) {
blobs = g_new0 (char *, sig->param_count);
types = g_new0 (guint32, sig->param_count);
get_default_param_value_blobs (method, blobs, types);
}
/* Build MonoType for the type from the Constant Table */
if (!type)
type = g_new0 (MonoType, 1);
type->type = types [i];
type->data.klass = NULL;
if (types [i] == MONO_TYPE_CLASS)
type->data.klass = mono_defaults.object_class;
else if ((sig->params [i]->type == MONO_TYPE_VALUETYPE) && sig->params [i]->data.klass->enumtype) {
/* For enums, types [i] contains the base type */
type->type = MONO_TYPE_VALUETYPE;
type->data.klass = mono_class_from_mono_type (sig->params [i]);
} else
type->data.klass = mono_class_from_mono_type (type);
MONO_OBJECT_SETREF (param, DefaultValueImpl, mono_get_object_from_blob (domain, type, blobs [i]));
/* Type in the Constant table is MONO_TYPE_CLASS for nulls */
if (types [i] != MONO_TYPE_CLASS && !param->DefaultValueImpl) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
}
}
if (mspecs [i + 1])
MONO_OBJECT_SETREF (param, MarshalAsImpl, (MonoObject*)mono_reflection_marshal_from_marshal_spec (domain, method->klass, mspecs [i + 1]));
mono_array_setref (res, i, param);
}
g_free (names);
g_free (blobs);
g_free (types);
g_free (type);
for (i = mono_method_signature (method)->param_count; i >= 0; i--)
if (mspecs [i])
mono_metadata_free_marshal_spec (mspecs [i]);
g_free (mspecs);
CACHE_OBJECT (MonoArray *, &(method->signature), res, refclass);
}
MonoArray*
mono_param_get_objects (MonoDomain *domain, MonoMethod *method)
{
return mono_param_get_objects_internal (domain, method, NULL);
}
/*
* mono_method_body_get_object:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.MethodBody object representing the method @method.
*/
MonoReflectionMethodBody*
mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
{
static MonoClass *System_Reflection_MethodBody = NULL;
static MonoClass *System_Reflection_LocalVariableInfo = NULL;
static MonoClass *System_Reflection_ExceptionHandlingClause = NULL;
MonoReflectionMethodBody *ret;
MonoMethodHeader *header;
MonoImage *image;
guint32 method_rva, local_var_sig_token;
char *ptr;
unsigned char format, flags;
int i;
if (!System_Reflection_MethodBody)
System_Reflection_MethodBody = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MethodBody");
if (!System_Reflection_LocalVariableInfo)
System_Reflection_LocalVariableInfo = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "LocalVariableInfo");
if (!System_Reflection_ExceptionHandlingClause)
System_Reflection_ExceptionHandlingClause = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ExceptionHandlingClause");
CHECK_OBJECT (MonoReflectionMethodBody *, method, NULL);
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
return NULL;
image = method->klass->image;
header = mono_method_get_header (method);
if (!image->dynamic) {
/* Obtain local vars signature token */
method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA);
ptr = mono_image_rva_map (image, method_rva);
flags = *(const unsigned char *) ptr;
format = flags & METHOD_HEADER_FORMAT_MASK;
switch (format){
case METHOD_HEADER_TINY_FORMAT:
local_var_sig_token = 0;
break;
case METHOD_HEADER_FAT_FORMAT:
ptr += 2;
ptr += 2;
ptr += 4;
local_var_sig_token = read32 (ptr);
break;
default:
g_assert_not_reached ();
}
} else
local_var_sig_token = 0; //FIXME
ret = (MonoReflectionMethodBody*)mono_object_new (domain, System_Reflection_MethodBody);
ret->init_locals = header->init_locals;
ret->max_stack = header->max_stack;
ret->local_var_sig_token = local_var_sig_token;
MONO_OBJECT_SETREF (ret, il, mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size));
memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
/* Locals */
MONO_OBJECT_SETREF (ret, locals, mono_array_new_cached (domain, System_Reflection_LocalVariableInfo, header->num_locals));
for (i = 0; i < header->num_locals; ++i) {
MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new (domain, System_Reflection_LocalVariableInfo);
MONO_OBJECT_SETREF (info, local_type, mono_type_get_object (domain, header->locals [i]));
info->is_pinned = header->locals [i]->pinned;
info->local_index = i;
mono_array_setref (ret->locals, i, info);
}
/* Exceptions */
MONO_OBJECT_SETREF (ret, clauses, mono_array_new_cached (domain, System_Reflection_ExceptionHandlingClause, header->num_clauses));
for (i = 0; i < header->num_clauses; ++i) {
MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new (domain, System_Reflection_ExceptionHandlingClause);
MonoExceptionClause *clause = &header->clauses [i];
info->flags = clause->flags;
info->try_offset = clause->try_offset;
info->try_length = clause->try_len;
info->handler_offset = clause->handler_offset;
info->handler_length = clause->handler_len;
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
info->filter_offset = clause->data.filter_offset;
else if (clause->data.catch_class)
MONO_OBJECT_SETREF (info, catch_type, mono_type_get_object (mono_domain_get (), &clause->data.catch_class->byval_arg));
mono_array_setref (ret->clauses, i, info);
}
mono_metadata_free_mh (header);
CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
return ret;
}
/**
* mono_get_dbnull_object:
* @domain: Domain where the object lives
*
* Returns the System.DBNull.Value singleton object
*
* Used as the value for ParameterInfo.DefaultValue
*/
MonoObject *
mono_get_dbnull_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *dbnull_value_field = NULL;
if (!dbnull_value_field) {
MonoClass *dbnull_klass;
dbnull_klass = mono_class_from_name (mono_defaults.corlib, "System", "DBNull");
mono_class_init (dbnull_klass);
dbnull_value_field = mono_class_get_field_from_name (dbnull_klass, "Value");
g_assert (dbnull_value_field);
}
obj = mono_field_get_value_object (domain, dbnull_value_field, NULL);
g_assert (obj);
return obj;
}
static void
get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
{
guint32 param_index, i, lastp, crow = 0;
guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE];
gint32 idx;
MonoClass *klass = method->klass;
MonoImage *image = klass->image;
MonoMethodSignature *methodsig = mono_method_signature (method);
MonoTableInfo *constt;
MonoTableInfo *methodt;
MonoTableInfo *paramt;
if (!methodsig->param_count)
return;
mono_class_init (klass);
if (klass->image->dynamic) {
MonoReflectionMethodAux *aux;
if (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (aux && aux->param_defaults) {
memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*));
memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32));
}
return;
}
methodt = &klass->image->tables [MONO_TABLE_METHOD];
paramt = &klass->image->tables [MONO_TABLE_PARAM];
constt = &image->tables [MONO_TABLE_CONSTANT];
idx = mono_method_get_index (method) - 1;
g_assert (idx != -1);
param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
if (idx + 1 < methodt->rows)
lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
else
lastp = paramt->rows + 1;
for (i = param_index; i < lastp; ++i) {
guint32 paramseq;
mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
paramseq = param_cols [MONO_PARAM_SEQUENCE];
if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
continue;
crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
if (!crow) {
continue;
}
mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE);
blobs [paramseq - 1] = (gpointer) mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]);
types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE];
}
return;
}
MonoObject *
mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob)
{
void *retval;
MonoClass *klass;
MonoObject *object;
MonoType *basetype = type;
if (!blob)
return NULL;
klass = mono_class_from_mono_type (type);
if (klass->valuetype) {
object = mono_object_new (domain, klass);
retval = ((gchar *) object + sizeof (MonoObject));
if (klass->enumtype)
basetype = mono_class_enum_basetype (klass);
} else {
retval = &object;
}
if (!mono_get_constant_value_from_blob (domain, basetype->type, blob, retval))
return object;
else
return NULL;
}
static int
assembly_name_to_aname (MonoAssemblyName *assembly, char *p) {
int found_sep;
char *s;
memset (assembly, 0, sizeof (MonoAssemblyName));
assembly->name = p;
assembly->culture = "";
memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@'))
p++;
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
while (*p) {
if (*p == 'V' && g_ascii_strncasecmp (p, "Version=", 8) == 0) {
p += 8;
assembly->major = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->minor = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->build = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->revision = strtoul (p, &s, 10);
if (s == p)
return 1;
p = s;
} else if (*p == 'C' && g_ascii_strncasecmp (p, "Culture=", 8) == 0) {
p += 8;
if (g_ascii_strncasecmp (p, "neutral", 7) == 0) {
assembly->culture = "";
p += 7;
} else {
assembly->culture = p;
while (*p && *p != ',') {
p++;
}
}
} else if (*p == 'P' && g_ascii_strncasecmp (p, "PublicKeyToken=", 15) == 0) {
p += 15;
if (strncmp (p, "null", 4) == 0) {
p += 4;
} else {
int len;
gchar *start = p;
while (*p && *p != ',') {
p++;
}
len = (p - start + 1);
if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH)
len = MONO_PUBLIC_KEY_TOKEN_LENGTH;
g_strlcpy ((char*)assembly->public_key_token, start, len);
}
} else {
while (*p && *p != ',')
p++;
}
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
}
return 0;
}
/*
* mono_reflection_parse_type:
* @name: type name
*
* Parse a type name as accepted by the GetType () method and output the info
* extracted in the info structure.
* the name param will be mangled, so, make a copy before passing it to this function.
* The fields in info will be valid until the memory pointed to by name is valid.
*
* See also mono_type_get_name () below.
*
* Returns: 0 on parse error.
*/
static int
_mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
MonoTypeNameParse *info)
{
char *start, *p, *w, *temp, *last_point, *startn;
int in_modifiers = 0;
int isbyref = 0, rank, arity = 0, i;
start = p = w = name;
//FIXME could we just zero the whole struct? memset (&info, 0, sizeof (MonoTypeNameParse))
memset (&info->assembly, 0, sizeof (MonoAssemblyName));
info->name = info->name_space = NULL;
info->nested = NULL;
info->modifiers = NULL;
info->type_arguments = NULL;
/* last_point separates the namespace from the name */
last_point = NULL;
/* Skips spaces */
while (*p == ' ') p++, start++, w++, name++;
while (*p) {
switch (*p) {
case '+':
*p = 0; /* NULL terminate the name */
startn = p + 1;
info->nested = g_list_append (info->nested, startn);
/* we have parsed the nesting namespace + name */
if (info->name)
break;
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
break;
case '.':
last_point = p;
break;
case '\\':
++p;
break;
case '&':
case '*':
case '[':
case ',':
case ']':
in_modifiers = 1;
break;
case '`':
++p;
i = strtol (p, &temp, 10);
arity += i;
if (p == temp)
return 0;
p = temp-1;
break;
default:
break;
}
if (in_modifiers)
break;
// *w++ = *p++;
p++;
}
if (!info->name) {
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
}
while (*p) {
switch (*p) {
case '&':
if (isbyref) /* only one level allowed by the spec */
return 0;
isbyref = 1;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0));
*p++ = 0;
break;
case '*':
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1));
*p++ = 0;
break;
case '[':
if (arity != 0) {
*p++ = 0;
info->type_arguments = g_ptr_array_new ();
for (i = 0; i < arity; i++) {
MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1);
gboolean fqname = FALSE;
g_ptr_array_add (info->type_arguments, subinfo);
if (*p == '[') {
p++;
fqname = TRUE;
}
if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
return 0;
/*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
if (fqname && (*p != ']')) {
char *aname;
if (*p != ',')
return 0;
*p++ = 0;
aname = p;
while (*p && (*p != ']'))
p++;
if (*p != ']')
return 0;
*p++ = 0;
while (*aname) {
if (g_ascii_isspace (*aname)) {
++aname;
continue;
}
break;
}
if (!*aname ||
!assembly_name_to_aname (&subinfo->assembly, aname))
return 0;
} else if (fqname && (*p == ']')) {
*p++ = 0;
}
if (i + 1 < arity) {
if (*p != ',')
return 0;
} else {
if (*p != ']')
return 0;
}
*p++ = 0;
}
arity = 0;
break;
}
rank = 1;
*p++ = 0;
while (*p) {
if (*p == ']')
break;
if (*p == ',')
rank++;
else if (*p == '*') /* '*' means unknown lower bound */
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2));
else
return 0;
++p;
}
if (*p++ != ']')
return 0;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank));
break;
case ']':
if (is_recursed)
goto end;
return 0;
case ',':
if (is_recursed)
goto end;
*p++ = 0;
while (*p) {
if (g_ascii_isspace (*p)) {
++p;
continue;
}
break;
}
if (!*p)
return 0; /* missing assembly name */
if (!assembly_name_to_aname (&info->assembly, p))
return 0;
break;
default:
return 0;
}
if (info->assembly.name)
break;
}
// *w = 0; /* terminate class name */
end:
if (!info->name || !*info->name)
return 0;
if (endptr)
*endptr = p;
/* add other consistency checks */
return 1;
}
int
mono_reflection_parse_type (char *name, MonoTypeNameParse *info)
{
return _mono_reflection_parse_type (name, NULL, FALSE, info);
}
static MonoType*
_mono_reflection_get_type_from_info (MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase)
{
gboolean type_resolve = FALSE;
MonoType *type;
MonoImage *rootimage = image;
if (info->assembly.name) {
MonoAssembly *assembly = mono_assembly_loaded (&info->assembly);
if (!assembly && image && image->assembly && mono_assembly_names_equal (&info->assembly, &image->assembly->aname))
/*
* This could happen in the AOT compiler case when the search hook is not
* installed.
*/
assembly = image->assembly;
if (!assembly) {
/* then we must load the assembly ourselve - see #60439 */
assembly = mono_assembly_load (&info->assembly, NULL, NULL);
if (!assembly)
return NULL;
}
image = assembly->image;
} else if (!image) {
image = mono_defaults.corlib;
}
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
if (type == NULL && !info->assembly.name && image != mono_defaults.corlib) {
image = mono_defaults.corlib;
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
}
return type;
}
static MonoType*
mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoClass *klass;
GList *mod;
int modval;
gboolean bounded = FALSE;
if (!image)
image = mono_defaults.corlib;
if (ignorecase)
klass = mono_class_from_name_case (image, info->name_space, info->name);
else
klass = mono_class_from_name (image, info->name_space, info->name);
if (!klass)
return NULL;
for (mod = info->nested; mod; mod = mod->next) {
gpointer iter = NULL;
MonoClass *parent;
parent = klass;
mono_class_init (parent);
while ((klass = mono_class_get_nested_types (parent, &iter))) {
if (ignorecase) {
if (mono_utf8_strcasecmp (klass->name, mod->data) == 0)
break;
} else {
if (strcmp (klass->name, mod->data) == 0)
break;
}
}
if (!klass)
break;
}
if (!klass)
return NULL;
if (info->type_arguments) {
MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len);
MonoReflectionType *the_type;
MonoType *instance;
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
type_args [i] = _mono_reflection_get_type_from_info (subinfo, rootimage, ignorecase);
if (!type_args [i]) {
g_free (type_args);
return NULL;
}
}
the_type = mono_type_get_object (mono_domain_get (), &klass->byval_arg);
instance = mono_reflection_bind_generic_parameters (
the_type, info->type_arguments->len, type_args);
g_free (type_args);
if (!instance)
return NULL;
klass = mono_class_from_mono_type (instance);
}
for (mod = info->modifiers; mod; mod = mod->next) {
modval = GPOINTER_TO_UINT (mod->data);
if (!modval) { /* byref: must be last modifier */
return &klass->this_arg;
} else if (modval == -1) {
klass = mono_ptr_class_get (&klass->byval_arg);
} else if (modval == -2) {
bounded = TRUE;
} else { /* array rank */
klass = mono_bounded_array_class_get (klass, modval, bounded);
}
}
return &klass->byval_arg;
}
/*
* mono_reflection_get_type:
* @image: a metadata context
* @info: type description structure
* @ignorecase: flag for case-insensitive string compares
* @type_resolve: whenever type resolve was already tried
*
* Build a MonoType from the type description in @info.
*
*/
MonoType*
mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
return mono_reflection_get_type_with_rootimage(image, image, info, ignorecase, type_resolve);
}
static MonoType*
mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoReflectionAssemblyBuilder *abuilder;
MonoType *type;
int i;
g_assert (assembly->dynamic);
abuilder = (MonoReflectionAssemblyBuilder*)mono_assembly_get_object (((MonoDynamicAssembly*)assembly)->domain, assembly);
/* Enumerate all modules */
type = NULL;
if (abuilder->modules) {
for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase);
if (type)
break;
}
}
if (!type && abuilder->loaded_modules) {
for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase);
if (type)
break;
}
}
return type;
}
MonoType*
mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve)
{
MonoType *type;
MonoReflectionAssembly *assembly;
GString *fullName;
GList *mod;
if (image && image->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase);
if (type)
return type;
if (!mono_domain_has_type_resolve (mono_domain_get ()))
return NULL;
if (type_resolve) {
if (*type_resolve)
return NULL;
else
*type_resolve = TRUE;
}
/* Reconstruct the type name */
fullName = g_string_new ("");
if (info->name_space && (info->name_space [0] != '\0'))
g_string_printf (fullName, "%s.%s", info->name_space, info->name);
else
g_string_printf (fullName, "%s", info->name);
for (mod = info->nested; mod; mod = mod->next)
g_string_append_printf (fullName, "+%s", (char*)mod->data);
assembly = mono_domain_try_type_resolve ( mono_domain_get (), fullName->str, NULL);
if (assembly) {
if (assembly->assembly->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image,
info, ignorecase);
}
g_string_free (fullName, TRUE);
return type;
}
void
mono_reflection_free_type_info (MonoTypeNameParse *info)
{
g_list_free (info->modifiers);
g_list_free (info->nested);
if (info->type_arguments) {
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
mono_reflection_free_type_info (subinfo);
/*We free the subinfo since it is allocated by _mono_reflection_parse_type*/
g_free (subinfo);
}
g_ptr_array_free (info->type_arguments, TRUE);
}
}
/*
* mono_reflection_type_from_name:
* @name: type name.
* @image: a metadata context (can be NULL).
*
* Retrieves a MonoType from its @name. If the name is not fully qualified,
* it defaults to get the type from @image or, if @image is NULL or loading
* from it fails, uses corlib.
*
*/
MonoType*
mono_reflection_type_from_name (char *name, MonoImage *image)
{
MonoType *type = NULL;
MonoTypeNameParse info;
char *tmp;
/* Make a copy since parse_type modifies its argument */
tmp = g_strdup (name);
/*g_print ("requested type %s\n", str);*/
if (mono_reflection_parse_type (tmp, &info)) {
type = _mono_reflection_get_type_from_info (&info, image, FALSE);
}
g_free (tmp);
mono_reflection_free_type_info (&info);
return type;
}
/*
* mono_reflection_get_token:
*
* Return the metadata token of OBJ which should be an object
* representing a metadata element.
*/
guint32
mono_reflection_get_token (MonoObject *obj)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
/* Call mono_image_create_token so the object gets added to the tokens hash table */
token = mono_image_create_token (((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image, obj, FALSE, TRUE);
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
token = mc->type_token;
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
return inflated->declaring->token;
} else {
token = m->method->token;
}
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField*)obj;
if (is_field_on_inst (f->field)) {
MonoDynamicGenericClass *dgclass = (MonoDynamicGenericClass*)f->field->parent->generic_class;
int field_index = f->field - dgclass->fields;
MonoObject *obj;
g_assert (field_index >= 0 && field_index < dgclass->count_fields);
obj = dgclass->field_objects [field_index];
return mono_reflection_get_token (obj);
}
token = mono_class_get_field_token (f->field);
} else if (strcmp (klass->name, "MonoProperty") == 0) {
MonoReflectionProperty *p = (MonoReflectionProperty*)obj;
token = mono_class_get_property_token (p->property);
} else if (strcmp (klass->name, "MonoEvent") == 0) {
MonoReflectionMonoEvent *p = (MonoReflectionMonoEvent*)obj;
token = mono_class_get_event_token (p->event);
} else if (strcmp (klass->name, "ParameterInfo") == 0) {
MonoReflectionParameter *p = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (p->MemberImpl);
g_assert (mono_class_is_reflection_method_or_constructor (member_class));
token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
} else if (strcmp (klass->name, "Module") == 0 || strcmp (klass->name, "MonoModule") == 0) {
MonoReflectionModule *m = (MonoReflectionModule*)obj;
token = m->token;
} else if (strcmp (klass->name, "Assembly") == 0 || strcmp (klass->name, "MonoAssembly") == 0) {
token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
} else {
gchar *msg = g_strdup_printf ("MetadataToken is not supported for type '%s.%s'", klass->name_space, klass->name);
MonoException *ex = mono_get_exception_not_implemented (msg);
g_free (msg);
mono_raise_exception (ex);
}
return token;
}
static void*
load_cattr_value (MonoImage *image, MonoType *t, const char *p, const char **end)
{
int slen, type = t->type;
MonoClass *tklass = t->data.klass;
handle_enum:
switch (type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN: {
MonoBoolean *bval = g_malloc (sizeof (MonoBoolean));
*bval = *p;
*end = p + 1;
return bval;
}
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2: {
guint16 *val = g_malloc (sizeof (guint16));
*val = read16 (p);
*end = p + 2;
return val;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_U:
case MONO_TYPE_I:
#endif
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4: {
guint32 *val = g_malloc (sizeof (guint32));
*val = read32 (p);
*end = p + 4;
return val;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_U: /* error out instead? this should probably not happen */
case MONO_TYPE_I:
#endif
case MONO_TYPE_U8:
case MONO_TYPE_I8: {
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
case MONO_TYPE_R8: {
double *val = g_malloc (sizeof (double));
readr8 (p, val);
*end = p + 8;
return val;
}
case MONO_TYPE_VALUETYPE:
if (t->data.klass->enumtype) {
type = mono_class_enum_basetype (t->data.klass)->type;
goto handle_enum;
} else {
MonoClass *k = t->data.klass;
if (mono_is_corlib_image (k->image) && strcmp (k->name_space, "System") == 0 && strcmp (k->name, "DateTime") == 0){
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
}
g_error ("generic valutype %s not handled in custom attr value decoding", t->data.klass->name);
break;
case MONO_TYPE_STRING:
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
slen = mono_metadata_decode_value (p, &p);
*end = p + slen;
return mono_string_new_len (mono_domain_get (), p, slen);
case MONO_TYPE_CLASS: {
char *n;
MonoType *t;
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
handle_type:
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_warning ("Cannot load type '%s'", n);
g_free (n);
*end = p + slen;
if (t)
return mono_type_get_object (mono_domain_get (), t);
else
return NULL;
}
case MONO_TYPE_OBJECT: {
char subt = *p++;
MonoObject *obj;
MonoClass *subc = NULL;
void *val;
if (subt == 0x50) {
goto handle_type;
} else if (subt == 0x0E) {
type = MONO_TYPE_STRING;
goto handle_enum;
} else if (subt == 0x1D) {
MonoType simple_type = {{0}};
int etype = *p;
p ++;
if (etype == 0x51)
/* See Partition II, Appendix B3 */
etype = MONO_TYPE_OBJECT;
type = MONO_TYPE_SZARRAY;
simple_type.type = etype;
tklass = mono_class_from_mono_type (&simple_type);
goto handle_enum;
} else if (subt == 0x55) {
char *n;
MonoType *t;
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_error ("Cannot load type '%s'", n);
g_free (n);
p += slen;
subc = mono_class_from_mono_type (t);
} else if (subt >= MONO_TYPE_BOOLEAN && subt <= MONO_TYPE_R8) {
MonoType simple_type = {{0}};
simple_type.type = subt;
subc = mono_class_from_mono_type (&simple_type);
} else {
g_error ("Unknown type 0x%02x for object type encoding in custom attr", subt);
}
val = load_cattr_value (image, &subc->byval_arg, p, end);
obj = mono_object_new (mono_domain_get (), subc);
g_assert (!subc->has_references);
memcpy ((char*)obj + sizeof (MonoObject), val, mono_class_value_size (subc, NULL));
g_free (val);
return obj;
}
case MONO_TYPE_SZARRAY: {
MonoArray *arr;
guint32 i, alen, basetype;
alen = read32 (p);
p += 4;
if (alen == 0xffffffff) {
*end = p;
return NULL;
}
arr = mono_array_new (mono_domain_get(), tklass, alen);
basetype = tklass->byval_arg.type;
if (basetype == MONO_TYPE_VALUETYPE && tklass->enumtype)
basetype = mono_class_enum_basetype (tklass)->type;
switch (basetype)
{
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
for (i = 0; i < alen; i++) {
MonoBoolean val = *p++;
mono_array_set (arr, MonoBoolean, i, val);
}
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
for (i = 0; i < alen; i++) {
guint16 val = read16 (p);
mono_array_set (arr, guint16, i, val);
p += 2;
}
break;
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
for (i = 0; i < alen; i++) {
guint32 val = read32 (p);
mono_array_set (arr, guint32, i, val);
p += 4;
}
break;
case MONO_TYPE_R8:
for (i = 0; i < alen; i++) {
double val;
readr8 (p, &val);
mono_array_set (arr, double, i, val);
p += 8;
}
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
for (i = 0; i < alen; i++) {
guint64 val = read64 (p);
mono_array_set (arr, guint64, i, val);
p += 8;
}
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_STRING:
for (i = 0; i < alen; i++) {
MonoObject *item = load_cattr_value (image, &tklass->byval_arg, p, &p);
mono_array_setref (arr, i, item);
}
break;
default:
g_error ("Type 0x%02x not handled in custom attr array decoding", basetype);
}
*end=p;
return arr;
}
default:
g_error ("Type 0x%02x not handled in custom attr value decoding", type);
}
return NULL;
}
static MonoObject*
create_cattr_typed_arg (MonoType *t, MonoObject *val)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *params [2], *unboxed;
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeTypedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = mono_type_get_object (mono_domain_get (), t);
params [1] = val;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static MonoObject*
create_cattr_named_arg (void *minfo, MonoObject *typedarg)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *unboxed, *params [2];
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeNamedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = minfo;
params [1] = typedarg;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static gboolean
type_is_reference (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_R4:
case MONO_TYPE_VALUETYPE:
return FALSE;
default:
return TRUE;
}
}
static void
free_param_data (MonoMethodSignature *sig, void **params) {
int i;
for (i = 0; i < sig->param_count; ++i) {
if (!type_is_reference (sig->params [i]))
g_free (params [i]);
}
}
/*
* Find the field index in the metadata FieldDef table.
*/
static guint32
find_field_index (MonoClass *klass, MonoClassField *field) {
int i;
for (i = 0; i < klass->field.count; ++i) {
if (field == &klass->fields [i])
return klass->field.first + 1 + i;
}
return 0;
}
/*
* Find the property index in the metadata Property table.
*/
static guint32
find_property_index (MonoClass *klass, MonoProperty *property) {
int i;
for (i = 0; i < klass->ext->property.count; ++i) {
if (property == &klass->ext->properties [i])
return klass->ext->property.first + 1 + i;
}
return 0;
}
/*
* Find the event index in the metadata Event table.
*/
static guint32
find_event_index (MonoClass *klass, MonoEvent *event) {
int i;
for (i = 0; i < klass->ext->event.count; ++i) {
if (event == &klass->ext->events [i])
return klass->ext->event.first + 1 + i;
}
return 0;
}
static MonoObject*
create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
{
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
MonoObject *attr;
void *params_buf [32];
void **params;
MonoMethodSignature *sig;
mono_class_init (method->klass);
if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
return NULL;
if (len == 0) {
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, NULL, NULL);
return attr;
}
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return NULL;
/*g_print ("got attr %s\n", method->klass->name);*/
sig = mono_method_signature (method);
if (sig->param_count < 32)
params = params_buf;
else
/* Allocate using GC so it gets GC tracking */
params = mono_gc_alloc_fixed (sig->param_count * sizeof (void*), NULL);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
params [i] = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
}
named = p;
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, params, NULL);
free_param_data (method->signature, params);
num_named = read16 (named);
named += 2;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoClassField *field = mono_class_get_field_from_name (mono_object_class (attr), name);
void *val = load_cattr_value (image, field->type, named, &named);
mono_field_set_value (attr, field, val);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoProperty *prop;
void *pparams [1];
MonoType *prop_type;
prop = mono_class_get_property_from_name (mono_object_class (attr), name);
/* can we have more that 1 arg in a custom attr named property? */
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
pparams [0] = load_cattr_value (image, prop_type, named, &named);
mono_property_set_value (prop, attr, pparams, NULL);
if (!type_is_reference (prop_type))
g_free (pparams [0]);
}
g_free (name);
}
if (params != params_buf)
mono_gc_free_fixed (params);
return attr;
}
/*
* mono_reflection_create_custom_attr_data_args:
*
* Create an array of typed and named arguments from the cattr blob given by DATA.
* TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
* NAMED_ARG_INFO will contain information about the named arguments.
*/
void
mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArray **typed_args, MonoArray **named_args, CattrNamedArg **named_arg_info)
{
MonoArray *typedargs, *namedargs;
MonoClass *attrklass;
MonoDomain *domain;
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
return;
mono_class_init (method->klass);
*typed_args = NULL;
*named_args = NULL;
*named_arg_info = NULL;
domain = mono_domain_get ();
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return;
typedargs = mono_array_new (domain, mono_get_object_class (), mono_method_signature (method)->param_count);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj;
void *val;
val = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
obj = type_is_reference (mono_method_signature (method)->params [i]) ?
val : mono_value_box (domain, mono_class_from_mono_type (mono_method_signature (method)->params [i]), val);
mono_array_setref (typedargs, i, obj);
if (!type_is_reference (mono_method_signature (method)->params [i]))
g_free (val);
}
named = p;
num_named = read16 (named);
namedargs = mono_array_new (domain, mono_get_object_class (), num_named);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoObject *obj;
MonoClassField *field = mono_class_get_field_from_name (attrklass, name);
void *val;
arginfo [j].type = field->type;
arginfo [j].field = field;
val = load_cattr_value (image, field->type, named, &named);
obj = type_is_reference (field->type) ? val : mono_value_box (domain, mono_class_from_mono_type (field->type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoObject *obj;
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name (attrklass, name);
void *val;
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
val = load_cattr_value (image, prop_type, named, &named);
obj = type_is_reference (prop_type) ? val : mono_value_box (domain, mono_class_from_mono_type (prop_type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (prop_type))
g_free (val);
}
g_free (name);
}
*typed_args = typedargs;
*named_args = namedargs;
}
void
mono_reflection_resolve_custom_attribute_data (MonoReflectionMethod *ref_method, MonoReflectionAssembly *assembly, gpointer data, guint32 len, MonoArray **ctor_args, MonoArray **named_args)
{
MonoDomain *domain;
MonoArray *typedargs, *namedargs;
MonoImage *image;
MonoMethod *method;
CattrNamedArg *arginfo;
int i;
*ctor_args = NULL;
*named_args = NULL;
if (len == 0)
return;
image = assembly->assembly->image;
method = ref_method->method;
domain = mono_object_domain (ref_method);
if (!mono_class_init (method->klass))
mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
mono_reflection_create_custom_attr_data_args (image, method, data, len, &typedargs, &namedargs, &arginfo);
if (mono_loader_get_last_error ())
mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
if (!typedargs || !namedargs)
return;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj = mono_array_get (typedargs, MonoObject*, i);
MonoObject *typedarg;
typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj);
mono_array_setref (typedargs, i, typedarg);
}
for (i = 0; i < mono_array_length (namedargs); ++i) {
MonoObject *obj = mono_array_get (namedargs, MonoObject*, i);
MonoObject *typedarg, *namedarg, *minfo;
if (arginfo [i].prop)
minfo = (MonoObject*)mono_property_get_object (domain, NULL, arginfo [i].prop);
else
minfo = (MonoObject*)mono_field_get_object (domain, NULL, arginfo [i].field);
typedarg = create_cattr_typed_arg (arginfo [i].type, obj);
namedarg = create_cattr_named_arg (minfo, typedarg);
mono_array_setref (namedargs, i, namedarg);
}
*ctor_args = typedargs;
*named_args = namedargs;
}
static MonoObject*
create_custom_attr_data (MonoImage *image, MonoCustomAttrEntry *cattr)
{
static MonoMethod *ctor;
MonoDomain *domain;
MonoObject *attr;
void *params [4];
g_assert (image->assembly);
if (!ctor)
ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 4);
domain = mono_domain_get ();
attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
params [0] = mono_method_get_object (domain, cattr->ctor, NULL);
params [1] = mono_assembly_get_object (domain, image->assembly);
params [2] = (gpointer)&cattr->data;
params [3] = &cattr->data_size;
mono_runtime_invoke (ctor, attr, params, NULL);
return attr;
}
MonoArray*
mono_custom_attrs_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
if (!cinfo->attrs [i].ctor)
/* The cattr type is not finished yet */
/* We should include the type name but cinfo doesn't contain it */
mono_raise_exception (mono_get_exception_type_load (NULL, NULL));
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, i, attr);
}
return result;
}
static MonoArray*
mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_klass)
{
MonoArray *result;
MonoObject *attr;
int i, n;
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass))
n ++;
}
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, n);
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass)) {
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, n, attr);
n ++;
}
}
return result;
}
static MonoArray*
mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
attr = create_custom_attr_data (cinfo->image, &cinfo->attrs [i]);
mono_array_setref (result, i, attr);
}
return result;
}
/**
* mono_custom_attrs_from_index:
*
* Returns: NULL if no attributes are found or if a loading error occurs.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
{
guint32 mtoken, i, len;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
MonoCustomAttrInfo *ainfo;
GList *tmp, *list = NULL;
const char *data;
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return NULL;
i --;
while (i < ca->rows) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx)
break;
list = g_list_prepend (list, GUINT_TO_POINTER (i));
++i;
}
len = g_list_length (list);
if (!len)
return NULL;
ainfo = g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
ainfo->num_attrs = len;
ainfo->image = image;
for (i = 0, tmp = list; i < len; ++i, tmp = tmp->next) {
mono_metadata_decode_row (ca, GPOINTER_TO_UINT (tmp->data), cols, MONO_CUSTOM_ATTR_SIZE);
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_error ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
break;
}
ainfo->attrs [i].ctor = mono_get_method (image, mtoken, NULL);
if (!ainfo->attrs [i].ctor) {
g_warning ("Can't find custom attr constructor image: %s mtoken: 0x%08x", image->name, mtoken);
g_list_free (list);
g_free (ainfo);
return NULL;
}
if (!mono_verifier_verify_cattr_blob (image, cols [MONO_CUSTOM_ATTR_VALUE], NULL)) {
/*FIXME raising an exception here doesn't make any sense*/
g_warning ("Invalid custom attribute blob on image %s for index %x", image->name, idx);
g_list_free (list);
g_free (ainfo);
return NULL;
}
data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
ainfo->attrs [i].data_size = mono_metadata_decode_value (data, &data);
ainfo->attrs [i].data = (guchar*)data;
}
g_list_free (list);
return ainfo;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_method (MonoMethod *method)
{
guint32 idx;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->dynamic || method->klass->image->dynamic)
return lookup_custom_attr (method->klass->image, method);
if (!method->token)
/* Synthetic methods */
return NULL;
idx = mono_method_get_index (method);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_METHODDEF;
return mono_custom_attrs_from_index (method->klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_class (MonoClass *klass)
{
guint32 idx;
if (klass->generic_class)
klass = klass->generic_class->container_class;
if (klass->image->dynamic)
return lookup_custom_attr (klass->image, klass);
if (klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR) {
idx = mono_metadata_token_index (klass->sizes.generic_param_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_GENERICPAR;
} else {
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_TYPEDEF;
}
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly (MonoAssembly *assembly)
{
guint32 idx;
if (assembly->image->dynamic)
return lookup_custom_attr (assembly->image, assembly);
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
return mono_custom_attrs_from_index (assembly->image, idx);
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_module (MonoImage *image)
{
guint32 idx;
if (image->dynamic)
return lookup_custom_attr (image, image);
idx = 1; /* there is only one module */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_MODULE;
return mono_custom_attrs_from_index (image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_property (MonoClass *klass, MonoProperty *property)
{
guint32 idx;
if (klass->image->dynamic) {
property = mono_metadata_get_corresponding_property_from_generic_type_definition (property);
return lookup_custom_attr (klass->image, property);
}
idx = find_property_index (klass, property);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PROPERTY;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_event (MonoClass *klass, MonoEvent *event)
{
guint32 idx;
if (klass->image->dynamic) {
event = mono_metadata_get_corresponding_event_from_generic_type_definition (event);
return lookup_custom_attr (klass->image, event);
}
idx = find_event_index (klass, event);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_EVENT;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_field (MonoClass *klass, MonoClassField *field)
{
guint32 idx;
if (klass->image->dynamic) {
field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
return lookup_custom_attr (klass->image, field);
}
idx = find_field_index (klass, field);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_FIELDDEF;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
{
MonoTableInfo *ca;
guint32 i, idx, method_index;
guint32 param_list, param_last, param_pos, found;
MonoImage *image;
MonoReflectionMethodAux *aux;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->klass->image->dynamic) {
MonoCustomAttrInfo *res, *ainfo;
int size;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (!aux || !aux->param_cattr)
return NULL;
/* Need to copy since it will be freed later */
ainfo = aux->param_cattr [param];
if (!ainfo)
return NULL;
size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
res = g_malloc0 (size);
memcpy (res, ainfo, size);
return res;
}
image = method->klass->image;
method_index = mono_method_get_index (method);
if (!method_index)
return NULL;
ca = &image->tables [MONO_TABLE_METHOD];
param_list = mono_metadata_decode_row_col (ca, method_index - 1, MONO_METHOD_PARAMLIST);
if (method_index == ca->rows) {
ca = &image->tables [MONO_TABLE_PARAM];
param_last = ca->rows + 1;
} else {
param_last = mono_metadata_decode_row_col (ca, method_index, MONO_METHOD_PARAMLIST);
ca = &image->tables [MONO_TABLE_PARAM];
}
found = FALSE;
for (i = param_list; i < param_last; ++i) {
param_pos = mono_metadata_decode_row_col (ca, i - 1, MONO_PARAM_SEQUENCE);
if (param_pos == param) {
found = TRUE;
break;
}
}
if (!found)
return NULL;
idx = i;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PARAMDEF;
return mono_custom_attrs_from_index (image, idx);
}
gboolean
mono_custom_attrs_has_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i;
MonoClass *klass;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass) || (MONO_CLASS_IS_INTERFACE (attr_klass) && mono_class_is_assignable_from (attr_klass, klass)))
return TRUE;
}
return FALSE;
}
MonoObject*
mono_custom_attrs_get_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i, attr_index;
MonoClass *klass;
MonoArray *attrs;
attr_index = -1;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass)) {
attr_index = i;
break;
}
}
if (attr_index == -1)
return NULL;
attrs = mono_custom_attrs_construct (ainfo);
if (attrs)
return mono_array_get (attrs, MonoObject*, attr_index);
else
return NULL;
}
/*
* mono_reflection_get_custom_attrs_info:
* @obj: a reflection object handle
*
* Return the custom attribute info for attributes defined for the
* reflection handle @obj. The objects.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info (MonoObject *obj)
{
MonoClass *klass;
MonoCustomAttrInfo *cinfo = NULL;
klass = obj->vtable->klass;
if (klass == mono_defaults.monotype_class) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
klass = mono_class_from_mono_type (type);
/*We cannot mono_class_init the class from which we'll load the custom attributes since this must work with broken types.*/
cinfo = mono_custom_attrs_from_class (klass);
} else if (strcmp ("Assembly", klass->name) == 0 || strcmp ("MonoAssembly", klass->name) == 0) {
MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj;
cinfo = mono_custom_attrs_from_assembly (rassembly->assembly);
} else if (strcmp ("Module", klass->name) == 0 || strcmp ("MonoModule", klass->name) == 0) {
MonoReflectionModule *module = (MonoReflectionModule*)obj;
cinfo = mono_custom_attrs_from_module (module->image);
} else if (strcmp ("MonoProperty", klass->name) == 0) {
MonoReflectionProperty *rprop = (MonoReflectionProperty*)obj;
cinfo = mono_custom_attrs_from_property (rprop->property->parent, rprop->property);
} else if (strcmp ("MonoEvent", klass->name) == 0) {
MonoReflectionMonoEvent *revent = (MonoReflectionMonoEvent*)obj;
cinfo = mono_custom_attrs_from_event (revent->event->parent, revent->event);
} else if (strcmp ("MonoField", klass->name) == 0) {
MonoReflectionField *rfield = (MonoReflectionField*)obj;
cinfo = mono_custom_attrs_from_field (rfield->field->parent, rfield->field);
} else if ((strcmp ("MonoMethod", klass->name) == 0) || (strcmp ("MonoCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if ((strcmp ("MonoGenericMethod", klass->name) == 0) || (strcmp ("MonoGenericCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if (strcmp ("ParameterInfo", klass->name) == 0) {
MonoReflectionParameter *param = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (param->MemberImpl);
if (mono_class_is_reflection_method_or_constructor (member_class)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
cinfo = mono_custom_attrs_from_param (rmethod->method, param->PositionImpl + 1);
} else if (is_sr_mono_property (member_class)) {
MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
MonoMethod *method;
if (!(method = prop->property->get))
method = prop->property->set;
g_assert (method);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
}
#ifndef DISABLE_REFLECTION_EMIT
else if (is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
MonoMethod *method = mono_reflection_method_on_tb_inst_get_handle ((MonoReflectionMethodOnTypeBuilderInst*)param->MemberImpl);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
} else if (is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
MonoMethod *method = NULL;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("mono_reflection_get_custom_attrs_info:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (member_class));
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
}
#endif
else {
char *type_name = mono_type_get_full_name (member_class);
char *msg = g_strdup_printf ("Custom attributes on a ParamInfo with member %s are not supported", type_name);
MonoException *ex = mono_get_exception_not_supported (msg);
g_free (type_name);
g_free (msg);
mono_raise_exception (ex);
}
} else if (strcmp ("AssemblyBuilder", klass->name) == 0) {
MonoReflectionAssemblyBuilder *assemblyb = (MonoReflectionAssemblyBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, assemblyb->assembly.assembly->image, assemblyb->cattrs);
} else if (strcmp ("TypeBuilder", klass->name) == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &tb->module->dynamic_image->image, tb->cattrs);
} else if (strcmp ("ModuleBuilder", klass->name) == 0) {
MonoReflectionModuleBuilder *mb = (MonoReflectionModuleBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &mb->dynamic_image->image, mb->cattrs);
} else if (strcmp ("ConstructorBuilder", klass->name) == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, cb->mhandle->klass->image, cb->cattrs);
} else if (strcmp ("MethodBuilder", klass->name) == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, mb->mhandle->klass->image, mb->cattrs);
} else if (strcmp ("FieldBuilder", klass->name) == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image->image, fb->cattrs);
} else if (strcmp ("MonoGenericClass", klass->name) == 0) {
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)obj;
cinfo = mono_reflection_get_custom_attrs_info ((MonoObject*)gclass->generic_type);
} else { /* handle other types here... */
g_error ("get custom attrs not yet supported for %s", klass->name);
}
return cinfo;
}
/*
* mono_reflection_get_custom_attrs_by_type:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. If @attr_klass is non-NULL, only custom attributes
* of that type are returned. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs_by_type (MonoObject *obj, MonoClass *attr_klass)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
if (attr_klass)
result = mono_custom_attrs_construct_by_type (cinfo, attr_klass);
else
result = mono_custom_attrs_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
if (mono_loader_get_last_error ())
return NULL;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, 0);
}
return result;
}
/*
* mono_reflection_get_custom_attrs:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs (MonoObject *obj)
{
return mono_reflection_get_custom_attrs_by_type (obj, NULL);
}
/*
* mono_reflection_get_custom_attrs_data:
* @obj: a reflection obj handle
*
* Returns an array of System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArray*
mono_reflection_get_custom_attrs_data (MonoObject *obj)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
result = mono_custom_attrs_data_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, 0);
return result;
}
static MonoReflectionType*
mono_reflection_type_get_underlying_system_type (MonoReflectionType* t)
{
static MonoMethod *method_get_underlying_system_type = NULL;
MonoMethod *usertype_method;
if (!method_get_underlying_system_type)
method_get_underlying_system_type = mono_class_get_method_from_name (mono_defaults.systemtype_class, "get_UnderlyingSystemType", 0);
usertype_method = mono_object_get_virtual_method ((MonoObject *) t, method_get_underlying_system_type);
return (MonoReflectionType *) mono_runtime_invoke (usertype_method, t, NULL, NULL);
}
static gboolean
is_corlib_type (MonoClass *class)
{
return class->image == mono_defaults.corlib;
}
#define check_corlib_type_cached(_class, _namespace, _name) do { \
static MonoClass *cached_class; \
if (cached_class) \
return cached_class == _class; \
if (is_corlib_type (_class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
cached_class = _class; \
return TRUE; \
} \
return FALSE; \
} while (0) \
#ifndef DISABLE_REFLECTION_EMIT
static gboolean
is_sre_array (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ArrayType");
}
static gboolean
is_sre_byref (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ByRefType");
}
static gboolean
is_sre_pointer (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "PointerType");
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericClass");
}
static gboolean
is_sre_type_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "TypeBuilder");
}
static gboolean
is_sre_method_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodBuilder");
}
static gboolean
is_sre_ctor_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorBuilder");
}
static gboolean
is_sre_field_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "FieldBuilder");
}
static gboolean
is_sre_method_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodOnTypeBuilderInst");
}
static gboolean
is_sre_ctor_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorOnTypeBuilderInst");
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
MonoClass *class;
if (!ref)
return NULL;
if (ref->type)
return ref->type;
if (is_usertype (ref)) {
ref = mono_reflection_type_get_underlying_system_type (ref);
if (ref == NULL || is_usertype (ref))
return NULL;
if (ref->type)
return ref->type;
}
class = mono_object_class (ref);
if (is_sre_array (class)) {
MonoType *res;
MonoReflectionArrayType *sre_array = (MonoReflectionArrayType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_array->element_type);
g_assert (base);
if (sre_array->rank == 0) //single dimentional array
res = &mono_array_class_get (mono_class_from_mono_type (base), 1)->byval_arg;
else
res = &mono_bounded_array_class_get (mono_class_from_mono_type (base), sre_array->rank, TRUE)->byval_arg;
sre_array->type.type = res;
return res;
} else if (is_sre_byref (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_byref = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_byref->element_type);
g_assert (base);
res = &mono_class_from_mono_type (base)->this_arg;
sre_byref->type.type = res;
return res;
} else if (is_sre_pointer (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_pointer = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_pointer->element_type);
g_assert (base);
res = &mono_ptr_class_get (base)->byval_arg;
sre_pointer->type.type = res;
return res;
} else if (is_sre_generic_instance (class)) {
MonoType *res, **types;
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)ref;
int i, count;
count = mono_array_length (gclass->type_arguments);
types = g_new0 (MonoType*, count);
for (i = 0; i < count; ++i) {
MonoReflectionType *t = mono_array_get (gclass->type_arguments, gpointer, i);
types [i] = mono_reflection_type_get_handle (t);
if (!types[i]) {
g_free (types);
return NULL;
}
}
res = mono_reflection_bind_generic_parameters (gclass->generic_type, count, types);
g_free (types);
g_assert (res);
gclass->type.type = res;
return res;
}
g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
return NULL;
}
void
mono_reflection_create_unmanaged_type (MonoReflectionType *type)
{
mono_reflection_type_get_handle (type);
}
void
mono_reflection_register_with_runtime (MonoReflectionType *type)
{
MonoType *res = mono_reflection_type_get_handle (type);
MonoDomain *domain = mono_object_domain ((MonoObject*)type);
MonoClass *class;
if (!res)
mono_raise_exception (mono_get_exception_argument (NULL, "Invalid generic instantiation, one or more arguments are not proper user types"));
class = mono_class_from_mono_type (res);
mono_loader_lock (); /*same locking as mono_type_get_object*/
mono_domain_lock (domain);
if (!class->image->dynamic) {
mono_class_setup_supertypes (class);
} else {
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
mono_g_hash_table_insert (domain->type_hash, res, type);
}
mono_domain_unlock (domain);
mono_loader_unlock ();
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
parameters_to_signature (MonoImage *image, MonoArray *parameters) {
MonoMethodSignature *sig;
int count, i;
count = parameters? mono_array_length (parameters): 0;
sig = image_g_malloc0 (image, MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * count);
sig->param_count = count;
sig->sentinelpos = -1; /* FIXME */
for (i = 0; i < count; ++i)
sig->params [i] = mono_type_array_get_and_resolve (parameters, i);
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
ctor_builder_to_signature (MonoImage *image, MonoReflectionCtorBuilder *ctor) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, ctor->parameters);
sig->hasthis = ctor->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = &mono_defaults.void_class->byval_arg;
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
method_builder_to_signature (MonoImage *image, MonoReflectionMethodBuilder *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle ((MonoReflectionType*)method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = method->generic_params ? mono_array_length (method->generic_params) : 0;
return sig;
}
static MonoMethodSignature*
dynamic_method_to_signature (MonoReflectionDynamicMethod *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (NULL, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle (method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = 0;
return sig;
}
static void
get_prop_name_and_type (MonoObject *prop, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (prop);
if (strcmp (klass->name, "PropertyBuilder") == 0) {
MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *)prop;
*name = mono_string_to_utf8 (pb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)pb->type);
} else {
MonoReflectionProperty *p = (MonoReflectionProperty *)prop;
*name = g_strdup (p->property->name);
if (p->property->get)
*type = mono_method_signature (p->property->get)->ret;
else
*type = mono_method_signature (p->property->set)->params [mono_method_signature (p->property->set)->param_count - 1];
}
}
static void
get_field_name_and_type (MonoObject *field, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (field);
if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)field;
*name = mono_string_to_utf8 (fb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
} else {
MonoReflectionField *f = (MonoReflectionField *)field;
*name = g_strdup (mono_field_get_name (f->field));
*type = f->field->type;
}
}
#else /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_register_with_runtime (MonoReflectionType *type)
{
/* This is empty */
}
static gboolean
is_sre_type_builder (MonoClass *class)
{
return FALSE;
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
return FALSE;
}
#endif /* !DISABLE_REFLECTION_EMIT */
static gboolean
is_sr_mono_field (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoField");
}
static gboolean
is_sr_mono_property (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoProperty");
}
static gboolean
is_sr_mono_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoMethod");
}
static gboolean
is_sr_mono_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoCMethod");
}
static gboolean
is_sr_mono_generic_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericMethod");
}
static gboolean
is_sr_mono_generic_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericCMethod");
}
gboolean
mono_class_is_reflection_method_or_constructor (MonoClass *class)
{
return is_sr_mono_method (class) || is_sr_mono_cmethod (class) || is_sr_mono_generic_method (class) || is_sr_mono_generic_cmethod (class);
}
static gboolean
is_usertype (MonoReflectionType *ref)
{
MonoClass *class = mono_object_class (ref);
return class->image != mono_defaults.corlib || strcmp ("TypeDelegator", class->name) == 0;
}
static MonoReflectionType*
mono_reflection_type_resolve_user_types (MonoReflectionType *type)
{
if (!type || type->type)
return type;
if (is_usertype (type)) {
type = mono_reflection_type_get_underlying_system_type (type);
if (is_usertype (type))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported22"));
}
return type;
}
/*
* Encode a value in a custom attribute stream of bytes.
* The value to encode is either supplied as an object in argument val
* (valuetypes are boxed), or as a pointer to the data in the
* argument argval.
* @type represents the type of the value
* @buffer is the start of the buffer
* @p the current position in the buffer
* @buflen contains the size of the buffer and is used to return the new buffer size
* if this needs to be realloced.
* @retbuffer and @retp return the start and the position of the buffer
*/
static void
encode_cattr_value (MonoAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, MonoObject *arg, char *argval)
{
MonoTypeEnum simple_type;
if ((p-buffer) + 10 >= *buflen) {
char *newbuf;
*buflen *= 2;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
if (!argval)
argval = ((char*)arg + sizeof (MonoObject));
simple_type = type->type;
handle_enum:
switch (simple_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
*p++ = *argval;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
swap_with_size (p, argval, 2, 1);
p += 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
swap_with_size (p, argval, 4, 1);
p += 4;
break;
case MONO_TYPE_R8:
#if defined(ARM_FPU_FPA) && G_BYTE_ORDER == G_LITTLE_ENDIAN
p [0] = argval [4];
p [1] = argval [5];
p [2] = argval [6];
p [3] = argval [7];
p [4] = argval [0];
p [5] = argval [1];
p [6] = argval [2];
p [7] = argval [3];
#else
swap_with_size (p, argval, 8, 1);
#endif
p += 8;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
swap_with_size (p, argval, 8, 1);
p += 8;
break;
case MONO_TYPE_VALUETYPE:
if (type->data.klass->enumtype) {
simple_type = mono_class_enum_basetype (type->data.klass)->type;
goto handle_enum;
} else {
g_warning ("generic valutype %s not handled in custom attr value decoding", type->data.klass->name);
}
break;
case MONO_TYPE_STRING: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
str = mono_string_to_utf8 ((MonoString*)arg);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_CLASS: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
handle_type:
str = type_get_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)arg), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_SZARRAY: {
int len, i;
MonoClass *eclass, *arg_eclass;
if (!arg) {
*p++ = 0xff; *p++ = 0xff; *p++ = 0xff; *p++ = 0xff;
break;
}
len = mono_array_length ((MonoArray*)arg);
*p++ = len & 0xff;
*p++ = (len >> 8) & 0xff;
*p++ = (len >> 16) & 0xff;
*p++ = (len >> 24) & 0xff;
*retp = p;
*retbuffer = buffer;
eclass = type->data.klass;
arg_eclass = mono_object_class (arg)->element_class;
if (!eclass) {
/* Happens when we are called from the MONO_TYPE_OBJECT case below */
eclass = mono_defaults.object_class;
}
if (eclass == mono_defaults.object_class && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (arg_eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &arg_eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else if (eclass->valuetype && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else {
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, mono_array_get ((MonoArray*)arg, MonoObject*, i), NULL);
}
}
break;
}
case MONO_TYPE_OBJECT: {
MonoClass *klass;
char *str;
guint32 slen;
/*
* The parameter type is 'object' but the type of the actual
* argument is not. So we have to add type information to the blob
* too. This is completely undocumented in the spec.
*/
if (arg == NULL) {
*p++ = MONO_TYPE_STRING; // It's same hack as MS uses
*p++ = 0xFF;
break;
}
klass = mono_object_class (arg);
if (mono_object_isinst (arg, mono_defaults.systemtype_class)) {
*p++ = 0x50;
goto handle_type;
} else if (klass->enumtype) {
*p++ = 0x55;
} else if (klass == mono_defaults.string_class) {
simple_type = MONO_TYPE_STRING;
*p++ = 0x0E;
goto handle_enum;
} else if (klass->rank == 1) {
*p++ = 0x1D;
if (klass->element_class->byval_arg.type == MONO_TYPE_OBJECT)
/* See Partition II, Appendix B3 */
*p++ = 0x51;
else
*p++ = klass->element_class->byval_arg.type;
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &klass->byval_arg, arg, NULL);
break;
} else if (klass->byval_arg.type >= MONO_TYPE_BOOLEAN && klass->byval_arg.type <= MONO_TYPE_R8) {
*p++ = simple_type = klass->byval_arg.type;
goto handle_enum;
} else {
g_error ("unhandled type in custom attr");
}
str = type_get_qualified_name (mono_class_get_type(klass), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
simple_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
}
default:
g_error ("type 0x%02x not yet supported in custom attr encoder", simple_type);
}
*retp = p;
*retbuffer = buffer;
}
static void
encode_field_or_prop_type (MonoType *type, char *p, char **retp)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
int slen = strlen (str);
*p++ = 0x55;
/*
* This seems to be optional...
* *p++ = 0x80;
*/
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
} else if (type->type == MONO_TYPE_OBJECT) {
*p++ = 0x51;
} else if (type->type == MONO_TYPE_CLASS) {
/* it should be a type: encode_cattr_value () has the check */
*p++ = 0x50;
} else {
mono_metadata_encode_value (type->type, p, &p);
if (type->type == MONO_TYPE_SZARRAY)
/* See the examples in Partition VI, Annex B */
encode_field_or_prop_type (&type->data.klass->byval_arg, p, &p);
}
*retp = p;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
encode_named_val (MonoReflectionAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, char *name, MonoObject *value)
{
int len;
/* Preallocate a large enough buffer */
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
len = strlen (str);
g_free (str);
} else if (type->type == MONO_TYPE_SZARRAY && type->data.klass->enumtype) {
char *str = type_get_qualified_name (&type->data.klass->byval_arg, NULL);
len = strlen (str);
g_free (str);
} else {
len = 0;
}
len += strlen (name);
if ((p-buffer) + 20 + len >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += len;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
encode_field_or_prop_type (type, p, &p);
len = strlen (name);
mono_metadata_encode_value (len, p, &p);
memcpy (p, name, len);
p += len;
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, buflen, type, value, NULL);
*retp = p;
*retbuffer = buffer;
}
/*
* mono_reflection_get_custom_attrs_blob:
* @ctor: custom attribute constructor
* @ctorArgs: arguments o the constructor
* @properties:
* @propValues:
* @fields:
* @fieldValues:
*
* Creates the blob of data that needs to be saved in the metadata and that represents
* the custom attributed described by @ctor, @ctorArgs etc.
* Returns: a Byte array representing the blob of data.
*/
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
MonoArray *result;
MonoMethodSignature *sig;
MonoObject *arg;
char *buffer, *p;
guint32 buflen, i;
MONO_ARCH_SAVE_REGS;
if (strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
/* sig is freed later so allocate it in the heap */
sig = ctor_builder_to_signature (NULL, (MonoReflectionCtorBuilder*)ctor);
} else {
sig = mono_method_signature (((MonoReflectionMethod*)ctor)->method);
}
g_assert (mono_array_length (ctorArgs) == sig->param_count);
buflen = 256;
p = buffer = g_malloc (buflen);
/* write the prolog */
*p++ = 1;
*p++ = 0;
for (i = 0; i < sig->param_count; ++i) {
arg = mono_array_get (ctorArgs, MonoObject*, i);
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, &buflen, sig->params [i], arg, NULL);
}
i = 0;
if (properties)
i += mono_array_length (properties);
if (fields)
i += mono_array_length (fields);
*p++ = i & 0xff;
*p++ = (i >> 8) & 0xff;
if (properties) {
MonoObject *prop;
for (i = 0; i < mono_array_length (properties); ++i) {
MonoType *ptype;
char *pname;
prop = mono_array_get (properties, gpointer, i);
get_prop_name_and_type (prop, &pname, &ptype);
*p++ = 0x54; /* PROPERTY signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ptype, pname, (MonoObject*)mono_array_get (propValues, gpointer, i));
g_free (pname);
}
}
if (fields) {
MonoObject *field;
for (i = 0; i < mono_array_length (fields); ++i) {
MonoType *ftype;
char *fname;
field = mono_array_get (fields, gpointer, i);
get_field_name_and_type (field, &fname, &ftype);
*p++ = 0x53; /* FIELD signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ftype, fname, (MonoObject*)mono_array_get (fieldValues, gpointer, i));
g_free (fname);
}
}
g_assert (p - buffer <= buflen);
buflen = p - buffer;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
p = mono_array_addr (result, char, 0);
memcpy (p, buffer, buflen);
g_free (buffer);
if (strcmp (ctor->vtable->klass->name, "MonoCMethod"))
g_free (sig);
return result;
}
/*
* mono_reflection_setup_internal_class:
* @tb: a TypeBuilder object
*
* Creates a MonoClass that represents the TypeBuilder.
* This is a trick that lets us simplify a lot of reflection code
* (and will allow us to support Build and Run assemblies easier).
*/
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass, *parent;
MONO_ARCH_SAVE_REGS;
RESOLVE_TYPE (tb->parent);
mono_loader_lock ();
if (tb->parent) {
/* check so we can compile corlib correctly */
if (strcmp (mono_object_class (tb->parent)->name, "TypeBuilder") == 0) {
/* mono_class_setup_mono_type () guaranteess type->data.klass is valid */
parent = mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent)->data.klass;
} else {
parent = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
}
} else {
parent = NULL;
}
/* the type has already being created: it means we just have to change the parent */
if (tb->type.type) {
klass = mono_class_from_mono_type (tb->type.type);
klass->parent = NULL;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
mono_class_setup_mono_type (klass);
mono_loader_unlock ();
return;
}
klass = mono_image_alloc0 (&tb->module->dynamic_image->image, sizeof (MonoClass));
klass->image = &tb->module->dynamic_image->image;
klass->inited = 1; /* we lie to the runtime */
klass->name = mono_string_to_utf8_image (klass->image, tb->name, &error);
if (!mono_error_ok (&error))
goto failure;
klass->name_space = mono_string_to_utf8_image (klass->image, tb->nspace, &error);
if (!mono_error_ok (&error))
goto failure;
klass->type_token = MONO_TOKEN_TYPE_DEF | tb->table_idx;
klass->flags = tb->attrs;
mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
klass->element_class = klass;
if (mono_class_get_ref_info (klass) == NULL) {
mono_class_set_ref_info (klass, tb);
/* Put into cache so mono_class_get () will find it.
Skip nested types as those should not be available on the global scope. */
if (!tb->nesting_type) {
mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx);
} else {
klass->image->reflection_info_unregister_classes =
g_slist_prepend (klass->image->reflection_info_unregister_classes, klass);
}
} else {
g_assert (mono_class_get_ref_info (klass) == tb);
}
mono_g_hash_table_insert (tb->module->dynamic_image->tokens,
GUINT_TO_POINTER (MONO_TOKEN_TYPE_DEF | tb->table_idx), tb);
if (parent != NULL) {
mono_class_setup_parent (klass, parent);
} else if (strcmp (klass->name, "Object") == 0 && strcmp (klass->name_space, "System") == 0) {
const char *old_n = klass->name;
/* trick to get relative numbering right when compiling corlib */
klass->name = "BuildingObject";
mono_class_setup_parent (klass, mono_defaults.object_class);
klass->name = old_n;
}
if ((!strcmp (klass->name, "ValueType") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Object") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Enum") && !strcmp (klass->name_space, "System"))) {
klass->instance_size = sizeof (MonoObject);
klass->size_inited = 1;
mono_class_setup_vtable_general (klass, NULL, 0);
}
mono_class_setup_mono_type (klass);
mono_class_setup_supertypes (klass);
/*
* FIXME: handle interfaces.
*/
tb->type.type = &klass->byval_arg;
if (tb->nesting_type) {
g_assert (tb->nesting_type->type);
klass->nested_in = mono_class_from_mono_type (mono_reflection_type_get_handle (tb->nesting_type));
}
/*g_print ("setup %s as %s (%p)\n", klass->name, ((MonoObject*)tb)->vtable->klass->name, tb);*/
mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
mono_loader_unlock ();
return;
failure:
mono_loader_unlock ();
mono_error_raise_exception (&error);
}
/*
* mono_reflection_setup_generic_class:
* @tb: a TypeBuilder object
*
* Setup the generic class before adding the first generic parameter.
*/
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
}
/*
* mono_reflection_create_generic_class:
* @tb: a TypeBuilder object
*
* Creates the generic class after all generic parameters have been added.
*/
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
int count, i;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
count = tb->generic_params ? mono_array_length (tb->generic_params) : 0;
if (klass->generic_container || (count == 0))
return;
g_assert (tb->generic_container && (tb->generic_container->owner.klass == klass));
klass->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
klass->generic_container->owner.klass = klass;
klass->generic_container->type_argc = count;
klass->generic_container->type_params = mono_image_alloc0 (klass->image, sizeof (MonoGenericParamFull) * count);
klass->is_generic = 1;
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam = mono_array_get (tb->generic_params, gpointer, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gparam)->data.generic_param;
klass->generic_container->type_params [i] = *param;
/*Make sure we are a diferent type instance */
klass->generic_container->type_params [i].param.owner = klass->generic_container;
klass->generic_container->type_params [i].info.pklass = NULL;
klass->generic_container->type_params [i].info.flags = gparam->attrs;
g_assert (klass->generic_container->type_params [i].param.owner);
}
klass->generic_container->context.class_inst = mono_get_shared_generic_inst (klass->generic_container);
}
/*
* mono_reflection_create_internal_class:
* @tb: a TypeBuilder object
*
* Actually create the MonoClass that is associated with the TypeBuilder.
*/
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
mono_loader_lock ();
if (klass->enumtype && mono_class_enum_basetype (klass) == NULL) {
MonoReflectionFieldBuilder *fb;
MonoClass *ec;
MonoType *enum_basetype;
g_assert (tb->fields != NULL);
g_assert (mono_array_length (tb->fields) >= 1);
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, 0);
if (!mono_type_is_valid_enum_basetype (mono_reflection_type_get_handle ((MonoReflectionType*)fb->type))) {
mono_loader_unlock ();
return;
}
enum_basetype = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
klass->element_class = mono_class_from_mono_type (enum_basetype);
if (!klass->element_class)
klass->element_class = mono_class_from_mono_type (enum_basetype);
/*
* get the element_class from the current corlib.
*/
ec = default_class_from_mono_type (enum_basetype);
klass->instance_size = ec->instance_size;
klass->size_inited = 1;
/*
* this is almost safe to do with enums and it's needed to be able
* to create objects of the enum type (for use in SetConstant).
*/
/* FIXME: Does this mean enums can't have method overrides ? */
mono_class_setup_vtable_general (klass, NULL, 0);
}
mono_loader_unlock ();
}
static MonoMarshalSpec*
mono_marshal_spec_from_builder (MonoImage *image, MonoAssembly *assembly,
MonoReflectionMarshal *minfo)
{
MonoMarshalSpec *res;
res = image_g_new0 (image, MonoMarshalSpec, 1);
res->native = minfo->type;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
res->data.array_data.elem_type = minfo->eltype;
if (minfo->has_size) {
res->data.array_data.param_num = minfo->param_num;
res->data.array_data.num_elem = minfo->count;
res->data.array_data.elem_mult = minfo->param_num == -1 ? 0 : 1;
}
else {
res->data.array_data.param_num = -1;
res->data.array_data.num_elem = -1;
res->data.array_data.elem_mult = -1;
}
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
res->data.array_data.num_elem = minfo->count;
break;
case MONO_NATIVE_CUSTOM:
if (minfo->marshaltyperef)
res->data.custom_data.custom_name =
type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
if (minfo->mcookie)
res->data.custom_data.cookie = mono_string_to_utf8 (minfo->mcookie);
break;
default:
break;
}
return res;
}
#endif /* !DISABLE_REFLECTION_EMIT */
MonoReflectionMarshal*
mono_reflection_marshal_from_marshal_spec (MonoDomain *domain, MonoClass *klass,
MonoMarshalSpec *spec)
{
static MonoClass *System_Reflection_Emit_UnmanagedMarshalClass;
MonoReflectionMarshal *minfo;
MonoType *mtype;
if (!System_Reflection_Emit_UnmanagedMarshalClass) {
System_Reflection_Emit_UnmanagedMarshalClass = mono_class_from_name (
mono_defaults.corlib, "System.Reflection.Emit", "UnmanagedMarshal");
g_assert (System_Reflection_Emit_UnmanagedMarshalClass);
}
minfo = (MonoReflectionMarshal*)mono_object_new (domain, System_Reflection_Emit_UnmanagedMarshalClass);
minfo->type = spec->native;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
minfo->eltype = spec->data.array_data.elem_type;
minfo->count = spec->data.array_data.num_elem;
minfo->param_num = spec->data.array_data.param_num;
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
minfo->count = spec->data.array_data.num_elem;
break;
case MONO_NATIVE_CUSTOM:
if (spec->data.custom_data.custom_name) {
mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, klass->image);
if (mtype)
MONO_OBJECT_SETREF (minfo, marshaltyperef, mono_type_get_object (domain, mtype));
MONO_OBJECT_SETREF (minfo, marshaltype, mono_string_new (domain, spec->data.custom_data.custom_name));
}
if (spec->data.custom_data.cookie)
MONO_OBJECT_SETREF (minfo, mcookie, mono_string_new (domain, spec->data.custom_data.cookie));
break;
default:
break;
}
return minfo;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod*
reflection_methodbuilder_to_mono_method (MonoClass *klass,
ReflectionMethodBuilder *rmb,
MonoMethodSignature *sig)
{
MonoError error;
MonoMethod *m;
MonoMethodWrapper *wrapperm;
MonoMarshalSpec **specs;
MonoReflectionMethodAux *method_aux;
MonoImage *image;
gboolean dynamic;
int i;
mono_error_init (&error);
/*
* Methods created using a MethodBuilder should have their memory allocated
* inside the image mempool, while dynamic methods should have their memory
* malloc'd.
*/
dynamic = rmb->refs != NULL;
image = dynamic ? NULL : klass->image;
if (!dynamic)
g_assert (!klass->generic_class);
mono_loader_lock ();
if ((rmb->attrs & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(rmb->iattrs & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
m = (MonoMethod *)image_g_new0 (image, MonoMethodPInvoke, 1);
else
m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1);
wrapperm = (MonoMethodWrapper*)m;
m->dynamic = dynamic;
m->slot = -1;
m->flags = rmb->attrs;
m->iflags = rmb->iattrs;
m->name = mono_string_to_utf8_image (image, rmb->name, &error);
g_assert (mono_error_ok (&error));
m->klass = klass;
m->signature = sig;
m->sre_method = TRUE;
m->skip_visibility = rmb->skip_visibility;
if (rmb->table_idx)
m->token = MONO_TOKEN_METHOD_DEF | (*rmb->table_idx);
if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (klass == mono_defaults.string_class && !strcmp (m->name, ".ctor"))
m->string_ctor = 1;
m->signature->pinvoke = 1;
} else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
m->signature->pinvoke = 1;
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->dllentry = rmb->dllentry ? mono_string_to_utf8_image (image, rmb->dllentry, &error) : image_strdup (image, m->name);
g_assert (mono_error_ok (&error));
method_aux->dll = mono_string_to_utf8_image (image, rmb->dll, &error);
g_assert (mono_error_ok (&error));
((MonoMethodPInvoke*)m)->piflags = (rmb->native_cc << 8) | (rmb->charset ? (rmb->charset - 1) * 2 : 0) | rmb->extra_flags;
if (klass->image->dynamic)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
} else if (!(m->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
!(m->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
MonoMethodHeader *header;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_clauses = 0;
guint8 *code;
if (rmb->ilgen) {
code = mono_array_addr (rmb->ilgen->code, guint8, 0);
code_size = rmb->ilgen->code_len;
max_stack = rmb->ilgen->max_stack;
num_locals = rmb->ilgen->locals ? mono_array_length (rmb->ilgen->locals) : 0;
if (rmb->ilgen->ex_handlers)
num_clauses = method_count_clauses (rmb->ilgen);
} else {
if (rmb->code) {
code = mono_array_addr (rmb->code, guint8, 0);
code_size = mono_array_length (rmb->code);
/* we probably need to run a verifier on the code... */
max_stack = 8;
}
else {
code = NULL;
code_size = 0;
max_stack = 8;
}
}
header = image_g_malloc0 (image, MONO_SIZEOF_METHOD_HEADER + num_locals * sizeof (MonoType*));
header->code_size = code_size;
header->code = image_g_malloc (image, code_size);
memcpy ((char*)header->code, code, code_size);
header->max_stack = max_stack;
header->init_locals = rmb->init_locals;
header->num_locals = num_locals;
for (i = 0; i < num_locals; ++i) {
MonoReflectionLocalBuilder *lb =
mono_array_get (rmb->ilgen->locals, MonoReflectionLocalBuilder*, i);
header->locals [i] = image_g_new0 (image, MonoType, 1);
memcpy (header->locals [i], mono_reflection_type_get_handle ((MonoReflectionType*)lb->type), MONO_SIZEOF_TYPE);
}
header->num_clauses = num_clauses;
if (num_clauses) {
header->clauses = method_encode_clauses (image, (MonoDynamicImage*)klass->image,
rmb->ilgen, num_clauses);
}
wrapperm->header = header;
}
if (rmb->generic_params) {
int count = mono_array_length (rmb->generic_params);
MonoGenericContainer *container = rmb->generic_container;
g_assert (container);
container->type_argc = count;
container->type_params = image_g_new0 (image, MonoGenericParamFull, count);
container->owner.method = m;
m->is_generic = TRUE;
mono_method_set_generic_container (m, container);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gp =
mono_array_get (rmb->generic_params, MonoReflectionGenericParam*, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gp)->data.generic_param;
container->type_params [i] = *param;
}
/*
* The method signature might have pointers to generic parameters that belong to other methods.
* This is a valid SRE case, but the resulting method signature must be encoded using the proper
* generic parameters.
*/
for (i = 0; i < m->signature->param_count; ++i) {
MonoType *t = m->signature->params [i];
if (t->type == MONO_TYPE_MVAR) {
MonoGenericParam *gparam = t->data.generic_param;
if (gparam->num < count) {
m->signature->params [i] = mono_metadata_type_dup (image, m->signature->params [i]);
m->signature->params [i]->data.generic_param = mono_generic_container_get_param (container, gparam->num);
}
}
}
if (klass->generic_container) {
container->parent = klass->generic_container;
container->context.class_inst = klass->generic_container->context.class_inst;
}
container->context.method_inst = mono_get_shared_generic_inst (container);
}
if (rmb->refs) {
MonoMethodWrapper *mw = (MonoMethodWrapper*)m;
int i;
void **data;
m->wrapper_type = MONO_WRAPPER_DYNAMIC_METHOD;
mw->method_data = data = image_g_new (image, gpointer, rmb->nrefs + 1);
data [0] = GUINT_TO_POINTER (rmb->nrefs);
for (i = 0; i < rmb->nrefs; ++i)
data [i + 1] = rmb->refs [i];
}
method_aux = NULL;
/* Parameter info */
if (rmb->pinfo) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_names = image_g_new0 (image, char *, mono_method_signature (m)->param_count + 1);
for (i = 0; i <= m->signature->param_count; ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if ((i > 0) && (pb->attrs)) {
/* Make a copy since it might point to a shared type structure */
m->signature->params [i - 1] = mono_metadata_type_dup (klass->image, m->signature->params [i - 1]);
m->signature->params [i - 1]->attrs = pb->attrs;
}
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
MonoDynamicImage *assembly;
guint32 idx, def_type, len;
char *p;
const char *p2;
if (!method_aux->param_defaults) {
method_aux->param_defaults = image_g_new0 (image, guint8*, m->signature->param_count + 1);
method_aux->param_default_types = image_g_new0 (image, guint32, m->signature->param_count + 1);
}
assembly = (MonoDynamicImage*)klass->image;
idx = encode_constant (assembly, pb->def_value, &def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
method_aux->param_defaults [i] = image_g_malloc (image, len);
method_aux->param_default_types [i] = def_type;
memcpy ((gpointer)method_aux->param_defaults [i], p, len);
}
if (pb->name) {
method_aux->param_names [i] = mono_string_to_utf8_image (image, pb->name, &error);
g_assert (mono_error_ok (&error));
}
if (pb->cattrs) {
if (!method_aux->param_cattr)
method_aux->param_cattr = image_g_new0 (image, MonoCustomAttrInfo*, m->signature->param_count + 1);
method_aux->param_cattr [i] = mono_custom_attrs_from_builders (image, klass->image, pb->cattrs);
}
}
}
}
/* Parameter marshalling */
specs = NULL;
if (rmb->pinfo)
for (i = 0; i < mono_array_length (rmb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if (pb->marshal_info) {
if (specs == NULL)
specs = image_g_new0 (image, MonoMarshalSpec*, sig->param_count + 1);
specs [pb->position] =
mono_marshal_spec_from_builder (image, klass->image->assembly, pb->marshal_info);
}
}
}
if (specs != NULL) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_marshall = specs;
}
if (klass->image->dynamic && method_aux)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
}
static MonoMethod*
ctorbuilder_to_mono_method (MonoClass *klass, MonoReflectionCtorBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = ctor_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoMethod*
methodbuilder_to_mono_method (MonoClass *klass, MonoReflectionMethodBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = method_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_method_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoClassField*
fieldbuilder_to_mono_class_field (MonoClass *klass, MonoReflectionFieldBuilder* fb)
{
MonoClassField *field;
MonoType *custom;
field = g_new0 (MonoClassField, 1);
field->name = mono_string_to_utf8 (fb->name);
if (fb->attrs || fb->modreq || fb->modopt) {
field->type = mono_metadata_type_dup (NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
g_assert (klass->image->dynamic);
custom = add_custom_modifiers ((MonoDynamicImage*)klass->image, field->type, fb->modreq, fb->modopt);
g_free (field->type);
field->type = custom;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
// FIXME: Can't store fb->def_value/RVA, is it needed for field_on_insts ?
return field;
}
#endif
MonoType*
mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types)
{
MonoClass *klass;
MonoReflectionTypeBuilder *tb = NULL;
gboolean is_dynamic = FALSE;
MonoDomain *domain;
MonoClass *geninst;
mono_loader_lock ();
domain = mono_object_domain (type);
if (is_sre_type_builder (mono_object_class (type))) {
tb = (MonoReflectionTypeBuilder *) type;
is_dynamic = TRUE;
} else if (is_sre_generic_instance (mono_object_class (type))) {
MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
MonoReflectionType *gtd = rgi->generic_type;
if (is_sre_type_builder (mono_object_class (gtd))) {
tb = (MonoReflectionTypeBuilder *)gtd;
is_dynamic = TRUE;
}
}
/* FIXME: fix the CreateGenericParameters protocol to avoid the two stage setup of TypeBuilders */
if (tb && tb->generic_container)
mono_reflection_create_generic_class (tb);
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
if (!klass->generic_container) {
mono_loader_unlock ();
return NULL;
}
if (klass->wastypebuilder) {
tb = (MonoReflectionTypeBuilder *) mono_class_get_ref_info (klass);
is_dynamic = TRUE;
}
mono_loader_unlock ();
geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic);
return &geninst->byval_arg;
}
MonoClass*
mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic)
{
MonoGenericClass *gclass;
MonoGenericInst *inst;
g_assert (klass->generic_container);
inst = mono_metadata_get_generic_inst (type_argc, types);
gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic);
return mono_generic_class_get_class (gclass);
}
MonoReflectionMethod*
mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types)
{
MonoClass *klass;
MonoMethod *method, *inflated;
MonoMethodInflated *imethod;
MonoGenericContext tmp_context;
MonoGenericInst *ginst;
MonoType **type_argv;
int count, i;
MONO_ARCH_SAVE_REGS;
/*FIXME but this no longer should happen*/
if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionMethodBuilder *mb = NULL;
MonoReflectionTypeBuilder *tb;
MonoClass *klass;
mb = (MonoReflectionMethodBuilder *) rmethod;
tb = (MonoReflectionTypeBuilder *) mb->type;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
method = methodbuilder_to_mono_method (klass, mb);
#else
g_assert_not_reached ();
method = NULL;
#endif
} else {
method = rmethod->method;
}
klass = method->klass;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_method_signature (method)->generic_param_count;
if (count != mono_array_length (types))
return NULL;
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (types, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
imethod = (MonoMethodInflated *) inflated;
/*FIXME but I think this is no longer necessary*/
if (method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
/*
* This table maps metadata structures representing inflated methods/fields
* to the reflection objects representing their generic definitions.
*/
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
mono_loader_unlock ();
}
return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL);
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod *
inflate_mono_method (MonoClass *klass, MonoMethod *method, MonoObject *obj)
{
MonoMethodInflated *imethod;
MonoGenericContext *context;
int i;
/*
* With generic code sharing the klass might not be inflated.
* This can happen because classes inflated with their own
* type arguments are "normalized" to the uninflated class.
*/
if (!klass->generic_class)
return method;
context = mono_class_get_context (klass);
if (klass->method.count && klass->methods) {
/* Find the already created inflated method */
for (i = 0; i < klass->method.count; ++i) {
g_assert (klass->methods [i]->is_inflated);
if (((MonoMethodInflated*)klass->methods [i])->declaring == method)
break;
}
g_assert (i < klass->method.count);
imethod = (MonoMethodInflated*)klass->methods [i];
} else {
imethod = (MonoMethodInflated *) mono_class_inflate_generic_method_full (method, klass, context);
}
if (method->is_generic && method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, obj);
mono_loader_unlock ();
}
return (MonoMethod *) imethod;
}
static MonoMethod *
inflate_method (MonoReflectionType *type, MonoObject *obj)
{
MonoMethod *method;
MonoClass *gklass;
MonoClass *type_class = mono_object_class (type);
if (is_sre_generic_instance (type_class)) {
MonoReflectionGenericClass *mgc = (MonoReflectionGenericClass*)type;
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mgc->generic_type));
} else if (is_sre_type_builder (type_class)) {
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
} else if (type->type) {
gklass = mono_class_from_mono_type (type->type);
gklass = mono_class_get_generic_type_definition (gklass);
} else {
g_error ("Can't handle type %s", mono_type_get_full_name (mono_object_class (type)));
}
if (!strcmp (obj->vtable->klass->name, "MethodBuilder"))
if (((MonoReflectionMethodBuilder*)obj)->mhandle)
method = ((MonoReflectionMethodBuilder*)obj)->mhandle;
else
method = methodbuilder_to_mono_method (gklass, (MonoReflectionMethodBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "ConstructorBuilder"))
method = ctorbuilder_to_mono_method (gklass, (MonoReflectionCtorBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoMethod") || !strcmp (obj->vtable->klass->name, "MonoCMethod"))
method = ((MonoReflectionMethod *) obj)->method;
else {
method = NULL; /* prevent compiler warning */
g_error ("can't handle type %s", obj->vtable->klass->name);
}
return inflate_mono_method (mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type)), method, obj);
}
/*TODO avoid saving custom attrs for generic classes as it's enough to have them on the generic type definition.*/
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoClass *klass, *gklass;
MonoType *gtype;
int i;
MONO_ARCH_SAVE_REGS;
gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type);
klass = mono_class_from_mono_type (gtype);
g_assert (gtype->type == MONO_TYPE_GENERICINST);
gclass = gtype->data.generic_class;
if (!gclass->is_dynamic)
return;
dgclass = (MonoDynamicGenericClass *) gclass;
if (dgclass->initialized)
return;
gklass = gclass->container_class;
mono_class_init (gklass);
dgclass->count_methods = methods ? mono_array_length (methods) : 0;
dgclass->count_ctors = ctors ? mono_array_length (ctors) : 0;
dgclass->count_fields = fields ? mono_array_length (fields) : 0;
dgclass->methods = g_new0 (MonoMethod *, dgclass->count_methods);
dgclass->ctors = g_new0 (MonoMethod *, dgclass->count_ctors);
dgclass->fields = g_new0 (MonoClassField, dgclass->count_fields);
dgclass->field_objects = g_new0 (MonoObject*, dgclass->count_fields);
dgclass->field_generic_types = g_new0 (MonoType*, dgclass->count_fields);
for (i = 0; i < dgclass->count_methods; i++) {
MonoObject *obj = mono_array_get (methods, gpointer, i);
dgclass->methods [i] = inflate_method ((MonoReflectionType*)type, obj);
}
for (i = 0; i < dgclass->count_ctors; i++) {
MonoObject *obj = mono_array_get (ctors, gpointer, i);
dgclass->ctors [i] = inflate_method ((MonoReflectionType*)type, obj);
}
for (i = 0; i < dgclass->count_fields; i++) {
MonoObject *obj = mono_array_get (fields, gpointer, i);
MonoClassField *field, *inflated_field = NULL;
if (!strcmp (obj->vtable->klass->name, "FieldBuilder"))
inflated_field = field = fieldbuilder_to_mono_class_field (klass, (MonoReflectionFieldBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoField"))
field = ((MonoReflectionField *) obj)->field;
else {
field = NULL; /* prevent compiler warning */
g_assert_not_reached ();
}
dgclass->fields [i] = *field;
dgclass->fields [i].parent = klass;
dgclass->fields [i].type = mono_class_inflate_generic_type (
field->type, mono_generic_class_get_context ((MonoGenericClass *) dgclass));
dgclass->field_generic_types [i] = field->type;
MOVING_GC_REGISTER (&dgclass->field_objects [i]);
dgclass->field_objects [i] = obj;
if (inflated_field) {
g_free (inflated_field);
} else {
dgclass->fields [i].name = g_strdup (dgclass->fields [i].name);
}
}
dgclass->initialized = TRUE;
}
static void
fix_partial_generic_class (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
MonoDynamicGenericClass *dgclass;
int i;
if (klass->wastypebuilder)
return;
dgclass = (MonoDynamicGenericClass *) klass->generic_class;
if (klass->parent != gklass->parent) {
MonoError error;
MonoType *parent_type = mono_class_inflate_generic_type_checked (&gklass->parent->byval_arg, &klass->generic_class->context, &error);
if (mono_error_ok (&error)) {
MonoClass *parent = mono_class_from_mono_type (parent_type);
mono_metadata_free_type (parent_type);
if (parent != klass->parent) {
/*fool mono_class_setup_parent*/
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
}
} else {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_error_cleanup (&error);
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
}
if (!dgclass->initialized)
return;
if (klass->method.count != gklass->method.count) {
klass->method.count = gklass->method.count;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * (klass->method.count + 1));
for (i = 0; i < klass->method.count; i++) {
klass->methods [i] = mono_class_inflate_generic_method_full (
gklass->methods [i], klass, mono_class_get_context (klass));
}
}
if (klass->interface_count && klass->interface_count != gklass->interface_count) {
klass->interface_count = gklass->interface_count;
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * gklass->interface_count);
klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
for (i = 0; i < gklass->interface_count; ++i) {
MonoType *iface_type = mono_class_inflate_generic_type (&gklass->interfaces [i]->byval_arg, mono_class_get_context (klass));
klass->interfaces [i] = mono_class_from_mono_type (iface_type);
mono_metadata_free_type (iface_type);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
if (klass->field.count != gklass->field.count) {
klass->field.count = gklass->field.count;
klass->fields = image_g_new0 (klass->image, MonoClassField, klass->field.count);
for (i = 0; i < klass->field.count; i++) {
klass->fields [i] = gklass->fields [i];
klass->fields [i].parent = klass;
klass->fields [i].type = mono_class_inflate_generic_type (gklass->fields [i].type, mono_class_get_context (klass));
}
}
/*We can only finish with this klass once it's parent has as well*/
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
static void
ensure_generic_class_runtime_vtable (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
ensure_runtime_vtable (gklass);
fix_partial_generic_class (klass);
}
static void
ensure_runtime_vtable (MonoClass *klass)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
int i, num, j;
if (!klass->image->dynamic || (!tb && !klass->generic_class) || klass->wastypebuilder)
return;
if (klass->parent)
ensure_runtime_vtable (klass->parent);
if (tb) {
num = tb->ctors? mono_array_length (tb->ctors): 0;
num += tb->num_methods;
klass->method.count = num;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * num);
num = tb->ctors? mono_array_length (tb->ctors): 0;
for (i = 0; i < num; ++i)
klass->methods [i] = ctorbuilder_to_mono_method (klass, mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i));
num = tb->num_methods;
j = i;
for (i = 0; i < num; ++i)
klass->methods [j++] = methodbuilder_to_mono_method (klass, mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i));
if (tb->interfaces) {
klass->interface_count = mono_array_length (tb->interfaces);
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count);
for (i = 0; i < klass->interface_count; ++i) {
MonoType *iface = mono_type_array_get_and_resolve (tb->interfaces, i);
klass->interfaces [i] = mono_class_from_mono_type (iface);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
} else if (klass->generic_class){
ensure_generic_class_runtime_vtable (klass);
}
if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
for (i = 0; i < klass->method.count; ++i)
klass->methods [i]->slot = i;
klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
mono_class_setup_interface_offsets (klass);
mono_class_setup_interface_id (klass);
}
/*
* The generic vtable is needed even if image->run is not set since some
* runtime code like ves_icall_Type_GetMethodsByName depends on
* method->slot being defined.
*/
/*
* tb->methods could not be freed since it is used for determining
* overrides during dynamic vtable construction.
*/
}
static MonoMethod*
mono_reflection_method_get_handle (MonoObject *method)
{
MonoClass *class = mono_object_class (method);
if (is_sr_mono_method (class) || is_sr_mono_generic_method (class)) {
MonoReflectionMethod *sr_method = (MonoReflectionMethod*)method;
return sr_method->method;
}
if (is_sre_method_builder (class)) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)method;
return mb->mhandle;
}
if (is_sre_method_on_tb_inst (class)) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)method;
MonoMethod *result;
/*FIXME move this to a proper method and unify with resolve_object*/
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
} else {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *mono_method;
if (is_sre_method_builder (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, mono_method, (MonoObject*)m->mb);
}
return result;
}
g_error ("Can't handle methods of type %s:%s", class->name_space, class->name);
return NULL;
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
MonoReflectionTypeBuilder *tb;
int i, onum;
*overrides = NULL;
*num_overrides = 0;
g_assert (klass->image->dynamic);
if (!mono_class_get_ref_info (klass))
return;
g_assert (strcmp (((MonoObject*)mono_class_get_ref_info (klass))->vtable->klass->name, "TypeBuilder") == 0);
tb = (MonoReflectionTypeBuilder*)mono_class_get_ref_info (klass);
onum = 0;
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method)
onum ++;
}
}
if (onum) {
*overrides = g_new0 (MonoMethod*, onum * 2);
onum = 0;
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method) {
(*overrides) [onum * 2] = mono_reflection_method_get_handle ((MonoObject *)mb->override_method);
(*overrides) [onum * 2 + 1] = mb->mhandle;
g_assert (mb->mhandle);
onum ++;
}
}
}
*num_overrides = onum;
}
static void
typebuilder_setup_fields (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionFieldBuilder *fb;
MonoClassField *field;
MonoImage *image = klass->image;
const char *p, *p2;
int i;
guint32 len, idx, real_size = 0;
klass->field.count = tb->num_fields;
klass->field.first = 0;
mono_error_init (error);
if (tb->class_size) {
g_assert ((tb->packing_size & 0xfffffff0) == 0);
klass->packing_size = tb->packing_size;
real_size = klass->instance_size + tb->class_size;
}
if (!klass->field.count) {
klass->instance_size = MAX (klass->instance_size, real_size);
return;
}
klass->fields = image_g_new0 (image, MonoClassField, klass->field.count);
mono_class_alloc_ext (klass);
klass->ext->field_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->field.count);
/*
This is, guess what, a hack.
The issue is that the runtime doesn't know how to setup the fields of a typebuider and crash.
On the static path no field class is resolved, only types are built. This is the right thing to do
but we suck.
Setting size_inited is harmless because we're doing the same job as mono_class_setup_fields anyway.
*/
klass->size_inited = 1;
for (i = 0; i < klass->field.count; ++i) {
fb = mono_array_get (tb->fields, gpointer, i);
field = &klass->fields [i];
field->name = mono_string_to_utf8_image (image, fb->name, error);
if (!mono_error_ok (error))
return;
if (fb->attrs) {
field->type = mono_metadata_type_dup (klass->image, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if ((fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) && fb->rva_data)
klass->ext->field_def_values [i].data = mono_array_addr (fb->rva_data, char, 0);
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
fb->handle = field;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
if (klass->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
klass->cast_class = klass->element_class = mono_class_from_mono_type (field->type);
}
if (fb->def_value) {
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
field->type->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, fb->def_value, &klass->ext->field_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->field_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->field_def_values [i].data, p, len);
}
}
klass->instance_size = MAX (klass->instance_size, real_size);
mono_class_layout_fields (klass);
}
static void
typebuilder_setup_properties (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionPropertyBuilder *pb;
MonoImage *image = klass->image;
MonoProperty *properties;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->property.count = tb->properties ? mono_array_length (tb->properties) : 0;
klass->ext->property.first = 0;
properties = image_g_new0 (image, MonoProperty, klass->ext->property.count);
klass->ext->properties = properties;
for (i = 0; i < klass->ext->property.count; ++i) {
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
properties [i].parent = klass;
properties [i].attrs = pb->attrs;
properties [i].name = mono_string_to_utf8_image (image, pb->name, error);
if (!mono_error_ok (error))
return;
if (pb->get_method)
properties [i].get = pb->get_method->mhandle;
if (pb->set_method)
properties [i].set = pb->set_method->mhandle;
mono_save_custom_attrs (klass->image, &properties [i], pb->cattrs);
if (pb->def_value) {
guint32 len, idx;
const char *p, *p2;
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
if (!klass->ext->prop_def_values)
klass->ext->prop_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->ext->property.count);
properties [i].attrs |= PROPERTY_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, pb->def_value, &klass->ext->prop_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->prop_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->prop_def_values [i].data, p, len);
}
}
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
MonoEvent *event = g_new0 (MonoEvent, 1);
MonoClass *klass;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
event->parent = klass;
event->attrs = eb->attrs;
event->name = mono_string_to_utf8 (eb->name);
if (eb->add_method)
event->add = eb->add_method->mhandle;
if (eb->remove_method)
event->remove = eb->remove_method->mhandle;
if (eb->raise_method)
event->raise = eb->raise_method->mhandle;
#ifndef MONO_SMALL_CONFIG
if (eb->other_methods) {
int j;
event->other = g_new0 (MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
event->other [j] = mb->mhandle;
}
}
#endif
return mono_event_get_object (mono_object_domain (tb), klass, event);
}
static void
typebuilder_setup_events (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionEventBuilder *eb;
MonoImage *image = klass->image;
MonoEvent *events;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->event.count = tb->events ? mono_array_length (tb->events) : 0;
klass->ext->event.first = 0;
events = image_g_new0 (image, MonoEvent, klass->ext->event.count);
klass->ext->events = events;
for (i = 0; i < klass->ext->event.count; ++i) {
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
events [i].parent = klass;
events [i].attrs = eb->attrs;
events [i].name = mono_string_to_utf8_image (image, eb->name, error);
if (!mono_error_ok (error))
return;
if (eb->add_method)
events [i].add = eb->add_method->mhandle;
if (eb->remove_method)
events [i].remove = eb->remove_method->mhandle;
if (eb->raise_method)
events [i].raise = eb->raise_method->mhandle;
#ifndef MONO_SMALL_CONFIG
if (eb->other_methods) {
int j;
events [i].other = image_g_new0 (image, MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
events [i].other [j] = mb->mhandle;
}
}
#endif
mono_save_custom_attrs (klass->image, &events [i], eb->cattrs);
}
}
static gboolean
remove_instantiations_of_and_ensure_contents (gpointer key,
gpointer value,
gpointer user_data)
{
MonoType *type = (MonoType*)key;
MonoClass *klass = (MonoClass*)user_data;
if ((type->type == MONO_TYPE_GENERICINST) && (type->data.generic_class->container_class == klass)) {
fix_partial_generic_class (mono_class_from_mono_type (type)); //Ensure it's safe to use it.
return TRUE;
} else
return FALSE;
}
static void
check_array_for_usertypes (MonoArray *arr)
{
int i;
if (!arr)
return;
for (i = 0; i < mono_array_length (arr); ++i)
RESOLVE_ARRAY_TYPE_ELEMENT (arr, i);
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass;
MonoDomain* domain;
MonoReflectionType* res;
int i, j;
MONO_ARCH_SAVE_REGS;
domain = mono_object_domain (tb);
klass = mono_class_from_mono_type (tb->type.type);
/*
* Check for user defined Type subclasses.
*/
RESOLVE_TYPE (tb->parent);
check_array_for_usertypes (tb->interfaces);
if (tb->fields) {
for (i = 0; i < mono_array_length (tb->fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (tb->fields, gpointer, i);
if (fb) {
RESOLVE_TYPE (fb->type);
check_array_for_usertypes (fb->modreq);
check_array_for_usertypes (fb->modopt);
if (fb->marshal_info && fb->marshal_info->marshaltyperef)
RESOLVE_TYPE (fb->marshal_info->marshaltyperef);
}
}
}
if (tb->methods) {
for (i = 0; i < mono_array_length (tb->methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (tb->methods, gpointer, i);
if (mb) {
RESOLVE_TYPE (mb->rtype);
check_array_for_usertypes (mb->return_modreq);
check_array_for_usertypes (mb->return_modopt);
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder *mb = mono_array_get (tb->ctors, gpointer, i);
if (mb) {
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
mono_save_custom_attrs (klass->image, klass, tb->cattrs);
/*
* we need to lock the domain because the lock will be taken inside
* So, we need to keep the locking order correct.
*/
mono_loader_lock ();
mono_domain_lock (domain);
if (klass->wastypebuilder) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
/*
* Fields to set in klass:
* the various flags: delegate/unicode/contextbound etc.
*/
klass->flags = tb->attrs;
klass->has_cctor = 1;
klass->has_finalize = 1;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, klass->parent);
mono_class_setup_mono_type (klass);
#if 0
if (!((MonoDynamicImage*)klass->image)->run) {
if (klass->generic_container) {
/* FIXME: The code below can't handle generic classes */
klass->wastypebuilder = TRUE;
mono_loader_unlock ();
mono_domain_unlock (domain);
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
}
#endif
/* enums are done right away */
if (!klass->enumtype)
ensure_runtime_vtable (klass);
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtb = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
mono_class_alloc_ext (klass);
klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)subtb)));
}
}
klass->nested_classes_inited = TRUE;
/* fields and object layout */
if (klass->parent) {
if (!klass->parent->size_inited)
mono_class_init (klass->parent);
klass->instance_size = klass->parent->instance_size;
klass->sizes.class_size = 0;
klass->min_align = klass->parent->min_align;
/* if the type has no fields we won't call the field_setup
* routine which sets up klass->has_references.
*/
klass->has_references |= klass->parent->has_references;
} else {
klass->instance_size = sizeof (MonoObject);
klass->min_align = 1;
}
/* FIXME: handle packing_size and instance_size */
typebuilder_setup_fields (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_properties (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_events (klass, &error);
if (!mono_error_ok (&error))
goto failure;
klass->wastypebuilder = TRUE;
/*
* If we are a generic TypeBuilder, there might be instantiations in the type cache
* which have type System.Reflection.MonoGenericClass, but after the type is created,
* we want to return normal System.MonoType objects, so clear these out from the cache.
*
* Together with this we must ensure the contents of all instances to match the created type.
*/
if (domain->type_hash && klass->generic_container)
mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of_and_ensure_contents, klass);
mono_domain_unlock (domain);
mono_loader_unlock ();
if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_raise_exception (mono_get_exception_type_load (tb->name, NULL));
}
res = mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
g_assert (res != (MonoReflectionType*)tb);
return res;
failure:
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
klass->wastypebuilder = TRUE;
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_error_raise_exception (&error);
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
MonoGenericParamFull *param;
MonoImage *image;
MonoClass *pklass;
MONO_ARCH_SAVE_REGS;
param = g_new0 (MonoGenericParamFull, 1);
if (gparam->mbuilder) {
if (!gparam->mbuilder->generic_container) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)gparam->mbuilder->type;
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
gparam->mbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->mbuilder->generic_container->is_method = TRUE;
/*
* Cannot set owner.method, since the MonoMethod is not created yet.
* Set the image field instead, so type_in_image () works.
*/
gparam->mbuilder->generic_container->image = klass->image;
}
param->param.owner = gparam->mbuilder->generic_container;
} else if (gparam->tbuilder) {
if (!gparam->tbuilder->generic_container) {
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)gparam->tbuilder));
gparam->tbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->tbuilder->generic_container->owner.klass = klass;
}
param->param.owner = gparam->tbuilder->generic_container;
}
param->info.name = mono_string_to_utf8 (gparam->name);
param->param.num = gparam->index;
image = &gparam->tbuilder->module->dynamic_image->image;
pklass = mono_class_from_generic_parameter ((MonoGenericParam *) param, image, gparam->mbuilder != NULL);
gparam->type.type = &pklass->byval_arg;
mono_class_set_ref_info (pklass, gparam);
mono_image_lock (image);
image->reflection_info_unregister_classes = g_slist_prepend (image->reflection_info_unregister_classes, pklass);
mono_image_unlock (image);
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
MonoReflectionModuleBuilder *module = sig->module;
MonoDynamicImage *assembly = module != NULL ? module->dynamic_image : NULL;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, na);
if (assembly != NULL){
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
MonoDynamicImage *assembly = sig->module->dynamic_image;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
MonoClass *klass;
GSList *l;
int i;
sig = dynamic_method_to_signature (mb);
reflection_methodbuilder_from_dynamic_method (&rmb, mb);
/*
* Resolve references.
*/
/*
* Every second entry in the refs array is reserved for storing handle_class,
* which is needed by the ldtoken implementation in the JIT.
*/
rmb.nrefs = mb->nrefs;
rmb.refs = g_new0 (gpointer, mb->nrefs + 1);
for (i = 0; i < mb->nrefs; i += 2) {
MonoClass *handle_class;
gpointer ref;
MonoObject *obj = mono_array_get (mb->refs, MonoObject*, i);
if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/*
* The referenced DynamicMethod should already be created by the managed
* code, except in the case of circular references. In that case, we store
* method in the refs array, and fix it up later when the referenced
* DynamicMethod is created.
*/
if (method->mhandle) {
ref = method->mhandle;
} else {
/* FIXME: GC object stored in unmanaged memory */
ref = method;
/* FIXME: GC object stored in unmanaged memory */
method->referenced_by = g_slist_append (method->referenced_by, mb);
}
handle_class = mono_defaults.methodhandle_class;
} else {
MonoException *ex = NULL;
ref = resolve_object (mb->module->image, obj, &handle_class, NULL);
if (!ref)
ex = mono_get_exception_type_load (NULL, NULL);
else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
ex = mono_security_core_clr_ensure_dynamic_method_resolved_object (ref, handle_class);
if (ex) {
g_free (rmb.refs);
mono_raise_exception (ex);
return;
}
}
rmb.refs [i] = ref; /* FIXME: GC object stored in unmanaged memory (change also resolve_object() signature) */
rmb.refs [i + 1] = handle_class;
}
klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
/* Fix up refs entries pointing at us */
for (l = mb->referenced_by; l; l = l->next) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)l->data;
MonoMethodWrapper *wrapper = (MonoMethodWrapper*)method->mhandle;
gpointer *data;
g_assert (method->mhandle);
data = (gpointer*)wrapper->method_data;
for (i = 0; i < GPOINTER_TO_UINT (data [0]); i += 2) {
if ((data [i + 1] == mb) && (data [i + 1 + 1] == mono_defaults.methodhandle_class))
data [i + 1] = mb->mhandle;
}
}
g_slist_free (mb->referenced_by);
g_free (rmb.refs);
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
#endif /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb)
{
g_assert (mb);
if (mb->mhandle)
mono_runtime_free_method (
mono_object_get_domain ((MonoObject*)mb), mb->mhandle);
}
/**
*
* mono_reflection_is_valid_dynamic_token:
*
* Returns TRUE if token is valid.
*
*/
gboolean
mono_reflection_is_valid_dynamic_token (MonoDynamicImage *image, guint32 token)
{
return mono_g_hash_table_lookup (image->tokens, GUINT_TO_POINTER (token)) != NULL;
}
MonoMethodSignature *
mono_reflection_lookup_signature (MonoImage *image, MonoMethod *method, guint32 token)
{
MonoMethodSignature *sig;
g_assert (image->dynamic);
sig = g_hash_table_lookup (((MonoDynamicImage*)image)->vararg_aux_hash, GUINT_TO_POINTER (token));
if (sig)
return sig;
return mono_method_signature (method);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mono_reflection_lookup_dynamic_token:
*
* Finish the Builder object pointed to by TOKEN and return the corresponding
* runtime structure. If HANDLE_CLASS is not NULL, it is set to the class required by
* mono_ldtoken. If valid_token is TRUE, assert if it is not found in the token->object
* mapping table.
*
* LOCKING: Take the loader lock
*/
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
MonoDynamicImage *assembly = (MonoDynamicImage*)image;
MonoObject *obj;
MonoClass *klass;
mono_loader_lock ();
obj = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
mono_loader_unlock ();
if (!obj) {
if (valid_token)
g_error ("Could not find required dynamic token 0x%08x", token);
else
return NULL;
}
if (!handle_class)
handle_class = &klass;
return resolve_object (image, obj, handle_class, context);
}
/*
* ensure_complete_type:
*
* Ensure that KLASS is completed if it is a dynamic type, or references
* dynamic types.
*/
static void
ensure_complete_type (MonoClass *klass)
{
if (klass->image->dynamic && !klass->wastypebuilder && mono_class_get_ref_info (klass)) {
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
// Asserting here could break a lot of code
//g_assert (klass->wastypebuilder);
}
if (klass->generic_class) {
MonoGenericInst *inst = klass->generic_class->context.class_inst;
int i;
for (i = 0; i < inst->type_argc; ++i) {
ensure_complete_type (mono_class_from_mono_type (inst->type_argv [i]));
}
}
}
static gpointer
resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context)
{
gpointer result = NULL;
if (strcmp (obj->vtable->klass->name, "String") == 0) {
result = mono_string_intern ((MonoString*)obj);
*handle_class = mono_defaults.string_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
} else {
result = mono_class_from_mono_type (type);
}
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericMethod") == 0) {
result = ((MonoReflectionMethod*)obj)->method;
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
result = mb->mhandle;
if (!result) {
/* Type is not yet created */
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
/*
* Hopefully this has been filled in by calling CreateType() on the
* TypeBuilder.
*/
/*
* TODO: This won't work if the application finishes another
* TypeBuilder instance instead of this one.
*/
result = mb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
result = cb->mhandle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)cb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = cb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoField") == 0) {
MonoClassField *field = ((MonoReflectionField*)obj)->field;
ensure_complete_type (field->parent);
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (&field->parent->byval_arg, context);
MonoClass *class = mono_class_from_mono_type (inflated);
MonoClassField *inflated_field;
gpointer iter = NULL;
mono_metadata_free_type (inflated);
while ((inflated_field = mono_class_get_fields (class, &iter))) {
if (!strcmp (field->name, inflated_field->name))
break;
}
g_assert (inflated_field && !strcmp (field->name, inflated_field->name));
result = inflated_field;
} else {
result = field;
}
*handle_class = mono_defaults.fieldhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
result = fb->handle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)fb->typeb;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = fb->handle;
}
if (fb->handle && fb->handle->parent->generic_container) {
MonoClass *klass = fb->handle->parent;
MonoType *type = mono_class_inflate_generic_type (&klass->byval_arg, context);
MonoClass *inflated = mono_class_from_mono_type (type);
result = mono_class_get_field_from_name (inflated, mono_field_get_name (fb->handle));
g_assert (result);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
MonoClass *klass;
klass = type->data.klass;
if (klass->wastypebuilder) {
/* Already created */
result = klass;
}
else {
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = type->data.klass;
g_assert (result);
}
*handle_class = mono_defaults.typehandle_class;
} else if (strcmp (obj->vtable->klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *helper = (MonoReflectionSigHelper*)obj;
MonoMethodSignature *sig;
int nargs, i;
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
sig = mono_metadata_signature_alloc (image, nargs);
sig->explicit_this = helper->call_conv & 64 ? 1 : 0;
sig->hasthis = helper->call_conv & 32 ? 1 : 0;
if (helper->unmanaged_call_conv) { /* unmanaged */
sig->call_convention = helper->unmanaged_call_conv - 1;
sig->pinvoke = TRUE;
} else if (helper->call_conv & 0x02) {
sig->call_convention = MONO_CALL_VARARG;
} else {
sig->call_convention = MONO_CALL_DEFAULT;
}
sig->param_count = nargs;
/* TODO: Copy type ? */
sig->ret = helper->return_type->type;
for (i = 0; i < nargs; ++i)
sig->params [i] = mono_type_array_get_and_resolve (helper->arguments, i);
result = sig;
*handle_class = NULL;
} else if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/* Already created by the managed code */
g_assert (method->mhandle);
result = method->mhandle;
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
MonoClass *inflated;
MonoType *type;
MonoClassField *field;
if (is_sre_field_builder (mono_object_class (f->fb)))
field = ((MonoReflectionFieldBuilder*)f->fb)->handle;
else if (is_sr_mono_field (mono_object_class (f->fb)))
field = ((MonoReflectionField*)f->fb)->field;
else
g_error ("resolve_object:: can't handle a FTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (f->fb)));
type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)f->inst), context);
inflated = mono_class_from_mono_type (type);
result = field = mono_class_get_field_from_name (inflated, mono_field_get_name (field));
ensure_complete_type (field->parent);
g_assert (result);
mono_metadata_free_type (type);
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)c->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *method;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("resolve_object:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (c->cb)));
result = inflate_mono_method (inflated_klass, method, (MonoObject*)c->cb);
*handle_class = mono_defaults.methodhandle_class;
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
if (context)
result = mono_class_inflate_generic_method (result, context);
} else {
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)m->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *method;
if (is_sre_method_builder (mono_object_class (m->mb)))
method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, method, (MonoObject*)m->mb);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod*)obj;
MonoType *mtype;
MonoClass *klass;
MonoMethod *method;
gpointer iter;
char *name;
mtype = mono_reflection_type_get_handle (m->parent);
klass = mono_class_from_mono_type (mtype);
/* Find the method */
name = mono_string_to_utf8 (m->name);
iter = NULL;
while ((method = mono_class_get_methods (klass, &iter))) {
if (!strcmp (method->name, name))
break;
}
g_free (name);
// FIXME:
g_assert (method);
// FIXME: Check parameters/return value etc. match
result = method;
*handle_class = mono_defaults.methodhandle_class;
} else if (is_sre_array (mono_object_get_class(obj)) ||
is_sre_byref (mono_object_get_class(obj)) ||
is_sre_pointer (mono_object_get_class(obj))) {
MonoReflectionType *ref_type = (MonoReflectionType *)obj;
MonoType *type = mono_reflection_type_get_handle (ref_type);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
} else {
g_print ("%s\n", obj->vtable->klass->name);
g_assert_not_reached ();
}
return result;
}
#else /* DISABLE_REFLECTION_EMIT */
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit, so System.Reflection.Emit is not supported.");
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
g_assert_not_reached ();
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
g_assert_not_reached ();
}
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
g_assert_not_reached ();
return NULL;
}
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_methodspec, gboolean register_token)
{
g_assert_not_reached ();
return 0;
}
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
}
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
g_assert_not_reached ();
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
*overrides = NULL;
*num_overrides = 0;
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
g_assert_not_reached ();
return NULL;
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
g_assert_not_reached ();
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
}
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
return NULL;
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
if (!ref)
return NULL;
return ref->type;
}
#endif /* DISABLE_REFLECTION_EMIT */
/* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */
const static guint32 declsec_flags_map[] = {
0x00000000, /* empty */
MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */
MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */
MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */
MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */
MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */
MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */
MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */
MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */
MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */
MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */
MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */
MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */
MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */
MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */
MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */
MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */
};
/*
* Returns flags that includes all available security action associated to the handle.
* @token: metadata token (either for a class or a method)
* @image: image where resides the metadata.
*/
static guint32
mono_declsec_get_flags (MonoImage *image, guint32 token)
{
int index = mono_metadata_declsec_from_index (image, token);
MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY];
guint32 result = 0;
guint32 action;
int i;
/* HasSecurity can be present for other, not specially encoded, attributes,
e.g. SuppressUnmanagedCodeSecurityAttribute */
if (index < 0)
return 0;
for (i = index; i < t->rows; i++) {
guint32 cols [MONO_DECL_SECURITY_SIZE];
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
break;
action = cols [MONO_DECL_SECURITY_ACTION];
if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) {
result |= declsec_flags_map [action];
} else {
g_assert_not_reached ();
}
}
return result;
}
/*
* Get the security actions (in the form of flags) associated with the specified method.
*
* @method: The method for which we want the declarative security flags.
* Return the declarative security flags for the method (only).
*
* Note: To keep MonoMethod size down we do not cache the declarative security flags
* (except for the stack modifiers which are kept in the MonoJitInfo structure)
*/
guint32
mono_declsec_flags_from_method (MonoMethod *method)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
/* FIXME: No cache (for the moment) */
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return mono_declsec_get_flags (method->klass->image, idx);
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified class.
*
* @klass: The class for which we want the declarative security flags.
* Return the declarative security flags for the class.
*
* Note: We cache the flags inside the MonoClass structure as this will get
* called very often (at least for each method).
*/
guint32
mono_declsec_flags_from_class (MonoClass *klass)
{
if (klass->flags & TYPE_ATTRIBUTE_HAS_SECURITY) {
if (!klass->ext || !klass->ext->declsec_flags) {
guint32 idx;
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
mono_loader_lock ();
mono_class_alloc_ext (klass);
mono_loader_unlock ();
/* we cache the flags on classes */
klass->ext->declsec_flags = mono_declsec_get_flags (klass->image, idx);
}
return klass->ext->declsec_flags;
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified assembly.
*
* @assembly: The assembly for which we want the declarative security flags.
* Return the declarative security flags for the assembly.
*/
guint32
mono_declsec_flags_from_assembly (MonoAssembly *assembly)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return mono_declsec_get_flags (assembly->image, idx);
}
/*
* Fill actions for the specific index (which may either be an encoded class token or
* an encoded method token) from the metadata image.
* Returns TRUE if some actions requiring code generation are present, FALSE otherwise.
*/
static MonoBoolean
fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
MonoBoolean result = FALSE;
MonoTableInfo *t;
guint32 cols [MONO_DECL_SECURITY_SIZE];
int index = mono_metadata_declsec_from_index (image, token);
int i;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
return result;
/* if present only replace (class) permissions with method permissions */
/* if empty accept either class or method permissions */
if (cols [MONO_DECL_SECURITY_ACTION] == id_std) {
if (!actions->demand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demand.blob = (char*) (blob + 2);
actions->demand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) {
if (!actions->noncasdemand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->noncasdemand.blob = (char*) (blob + 2);
actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) {
if (!actions->demandchoice.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demandchoice.blob = (char*) (blob + 2);
actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
}
}
return result;
}
static MonoBoolean
mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return fill_actions_from_index (klass->image, idx, demands, id_std, id_noncas, id_choice);
}
static MonoBoolean
mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return fill_actions_from_index (method->klass->image, idx, demands, id_std, id_noncas, id_choice);
}
/*
* Collect all actions (that requires to generate code in mini) assigned for
* the specified method.
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands)
{
guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND |
MONO_DECLSEC_FLAG_DEMAND_CHOICE;
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result = mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & mask) {
if (!result) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
}
result |= mono_declsec_get_class_demands_params (method->klass, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* The boolean return value is used as a shortcut in case nothing needs to
be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */
return result;
}
/*
* Collect all Link actions: LinkDemand, NonCasLinkDemand and LinkDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* results are independant - zeroize both */
memset (cmethod, 0, sizeof (MonoDeclSecurityActions));
memset (klass, 0, sizeof (MonoDeclSecurityActions));
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
result = mono_declsec_get_method_demands_params (method, cmethod,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) {
mono_class_init (method->klass);
result |= mono_declsec_get_class_demands_params (method->klass, klass,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* @klass The inherited class - this is the class that provides the security check (attributes)
* @demans
* return TRUE if inheritance demands (any kind) are present, FALSE otherwise.
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (klass);
if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) {
mono_class_init (klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result |= mono_declsec_get_class_demands_params (klass, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands)
{
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
return mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return FALSE;
}
static MonoBoolean
get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 cols [MONO_DECL_SECURITY_SIZE];
MonoTableInfo *t;
int i;
int index = mono_metadata_declsec_from_index (image, token);
if (index == -1)
return FALSE;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
/* shortcut - index are ordered */
if (token != cols [MONO_DECL_SECURITY_PARENT])
return FALSE;
if (cols [MONO_DECL_SECURITY_ACTION] == action) {
const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
entry->blob = (char*) (metadata + 2);
entry->size = mono_metadata_decode_blob_size (metadata, &metadata);
return TRUE;
}
}
return FALSE;
}
MonoBoolean
mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return get_declsec_action (method->klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry)
{
/* use cache */
guint32 flags = mono_declsec_flags_from_class (klass);
if (declsec_flags_map [action] & flags) {
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return get_declsec_action (klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return get_declsec_action (assembly->image, idx, action, entry);
}
gboolean
mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass)
{
MonoObject *res, *exc;
void *params [1];
static MonoClass *System_Reflection_Emit_TypeBuilder = NULL;
static MonoMethod *method = NULL;
if (!System_Reflection_Emit_TypeBuilder) {
System_Reflection_Emit_TypeBuilder = mono_class_from_name (mono_defaults.corlib, "System.Reflection.Emit", "TypeBuilder");
g_assert (System_Reflection_Emit_TypeBuilder);
}
if (method == NULL) {
method = mono_class_get_method_from_name (System_Reflection_Emit_TypeBuilder, "IsAssignableTo", 1);
g_assert (method);
}
/*
* The result of mono_type_get_object () might be a System.MonoType but we
* need a TypeBuilder so use mono_class_get_ref_info (klass).
*/
g_assert (mono_class_get_ref_info (klass));
g_assert (!strcmp (((MonoObject*)(mono_class_get_ref_info (klass)))->vtable->klass->name, "TypeBuilder"));
params [0] = mono_type_get_object (mono_domain_get (), &oklass->byval_arg);
res = mono_runtime_invoke (method, (MonoObject*)(mono_class_get_ref_info (klass)), params, &exc);
if (exc)
return FALSE;
else
return *(MonoBoolean*)mono_object_unbox (res);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4717_0 |
crossvul-cpp_data_good_3365_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/pixel.h"
#include "magick/property.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(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 IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% 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 ReadRLEImage method is:
%
% Image *ReadRLEImage(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 Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
#define ThrowRLEException(exception,message) \
{ \
if (colormap != (unsigned char *) NULL) \
colormap=(unsigned char *) RelinquishMagickMemory(colormap); \
if (pixel_info != (MemoryInfo *) NULL) \
pixel_info=RelinquishVirtualMemory(pixel_info); \
ThrowReaderException((exception),(message)); \
}
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
colormap=(unsigned char *) NULL;
pixel_info=(MemoryInfo *) NULL;
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=(ssize_t) ReadBlobLSBShort(image);
image->page.y=(ssize_t) ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 22)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (EOFBlob(image) != MagickFalse)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
{
*p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum(
ReadBlobLSBShort(image)));
if (EOFBlob(image) != MagickFalse)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
}
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if (EOFBlob(image) != MagickFalse)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
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);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,pixel_info_length);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
if (opcode & 0x40)
{
operand=ReadBlobLSBSignedShort(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
}
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
if (opcode & 0x40)
{
operand=ReadBlobLSBSignedShort(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
}
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
if (opcode & 0x40)
{
operand=ReadBlobLSBSignedShort(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
}
offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane);
operand++;
if ((offset < 0) ||
((offset+operand*number_planes) > (ssize_t) pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
if (opcode & 0x40)
{
operand=ReadBlobLSBSignedShort(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
}
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane);
if ((offset < 0) ||
((offset+operand*number_planes) > (ssize_t) pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
if (opcode == EOF)
ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,(ssize_t) (*p & mask),&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(ssize_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
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;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
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;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE 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 RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RLE");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Utah Run length encoded image");
entry->module=ConstantString("RLE");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3365_1 |
crossvul-cpp_data_bad_5845_8 | /*
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 <linux/debugfs.h>
#include <asm/ioctls.h>
#include <net/bluetooth/bluetooth.h>
#include <linux/proc_fs.h>
#define VERSION "2.17"
/* 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);
void bt_sock_unregister(int proto)
{
if (proto < 0 || proto >= BT_MAX_PROTO)
return;
write_lock(&bt_proto_lock);
bt_proto[proto] = NULL;
write_unlock(&bt_proto_lock);
}
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) {
msg->msg_namelen = 0;
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);
if (bt_sk(sk)->skb_msg_name)
bt_sk(sk)->skb_msg_name(skb, msg->msg_name,
&msg->msg_namelen);
else
msg->msg_namelen = 0;
}
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 |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
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);
/* This function expects the sk lock to be held when called */
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);
/* This function expects the sk lock to be held when called */
int bt_sock_wait_ready(struct sock *sk, unsigned long flags)
{
DECLARE_WAITQUEUE(wait, current);
unsigned long timeo;
int err = 0;
BT_DBG("sk %p", sk);
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
add_wait_queue(sk_sleep(sk), &wait);
set_current_state(TASK_INTERRUPTIBLE);
while (test_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags)) {
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_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_ready);
#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 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 %-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->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_DATA(inode);
s = __seq_open_private(file, &bt_seq_ops,
sizeof(struct bt_seq_state));
if (!s)
return -ENOMEM;
s->l = sk_list;
return 0;
}
static const struct file_operations bt_fops = {
.open = bt_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private
};
int bt_procfs_init(struct net *net, const char *name,
struct bt_sock_list* sk_list,
int (* seq_show)(struct seq_file *, void *))
{
sk_list->custom_seq_show = seq_show;
if (!proc_create_data(name, 0, net->proc_net, &bt_fops, sk_list))
return -ENOMEM;
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 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,
};
struct dentry *bt_debugfs;
EXPORT_SYMBOL_GPL(bt_debugfs);
static int __init bt_init(void)
{
int err;
BT_INFO("Core ver %s", VERSION);
bt_debugfs = debugfs_create_dir("bluetooth", NULL);
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();
debugfs_remove_recursive(bt_debugfs);
}
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-20/c/bad_5845_8 |
crossvul-cpp_data_bad_2434_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD DDDD SSSSS %
% D D D D SS %
% D D D D SSS %
% D D D D SS %
% DDDD DDDD SSSSS %
% %
% %
% Read/Write Microsoft Direct Draw Surface Image Format %
% %
% Software Design %
% Bianca van Schaik %
% March 2008 %
% Dirk Lemstra %
% September 2013 %
% %
% %
% Copyright 1999-2015 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 %
% %
% http://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 "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if (max - min < steps) \
max = Min(min + steps, 255); \
if (max - min < steps) \
min = Max(min - steps, 0)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t, const DDSVector4 *, const DDSVector3,
DDSVector4 *, DDSVector4 *, unsigned char *, size_t);
static MagickBooleanType
ReadDDSInfo(Image *, DDSInfo *);
static MagickBooleanType
ReadDXT1(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadDXT3(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadDXT5(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadUncompressedRGB(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadUncompressedRGBA(Image *, DDSInfo *, ExceptionInfo *);
static void
RemapIndices(const ssize_t *, const unsigned char *, unsigned char *);
static void
SkipDXTMipmaps(Image *, DDSInfo *, int);
static void
SkipRGBMipmaps(Image *, DDSInfo *, int);
static
MagickBooleanType WriteDDSImage(const ImageInfo *, Image *);
static void
WriteDDSInfo(Image *, const size_t, const size_t, const size_t);
static void
WriteFourCC(Image *, const size_t, const MagickBooleanType,
const MagickBooleanType, ExceptionInfo *);
static void
WriteImageData(Image *, const size_t, const size_t, const MagickBooleanType,
const MagickBooleanType, ExceptionInfo *);
static void
WriteIndices(Image *, const DDSVector3, const DDSVector3, unsigned char *);
static MagickBooleanType
WriteMipmaps(Image *, const size_t, const size_t, const size_t,
const MagickBooleanType, const MagickBooleanType, ExceptionInfo *);
static void
WriteSingleColorFit(Image *, const DDSVector4 *, const ssize_t *);
static void
WriteUncompressed(Image *, ExceptionInfo *);
static inline size_t Max(size_t one, size_t two)
{
if (one > two)
return one;
return two;
}
static inline float MaxF(float one, float two)
{
if (one > two)
return one;
return two;
}
static inline size_t Min(size_t one, size_t two)
{
if (one < two)
return one;
return two;
}
static inline float MinF(float one, float two)
{
if (one < two)
return one;
return two;
}
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
value->w = MinF(1.0f,MaxF(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex;
ssize_t
i;
unsigned char
*o,
order[128],
unordered[16];
VectorInit(half,0.5f);
VectorInit(two,2.0f);
VectorInit(onethird_onethird2,1.0f/3.0f);
onethird_onethird2.w = 1.0f/9.0f;
VectorInit(twothirds_twothirds2,2.0f/3.0f);
twothirds_twothirds2.w = 4.0f/9.0f;
VectorInit(twonineths,2.0f/9.0f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
grid.w = 0.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
gridrcp.w = 0.0f;
xSumwSum.x = 0.0f;
xSumwSum.y = 0.0f;
xSumwSum.z = 0.0f;
xSumwSum.w = 0.0f;
ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
for (iterationIndex = 0;;)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,1) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
part0,
part1,
part2;
size_t
ii,
j,
k,
kmin;
VectorInit(part0,0.0f);
for(ii=0; ii < (size_t) i; ii++)
VectorAdd(pointsWeights[ii],part0,&part0);
VectorInit(part1,0.0f);
for (j=(size_t) i;;)
{
if (j == 0)
{
VectorCopy44(pointsWeights[0],&part2);
kmin = 1;
}
else
{
VectorInit(part2,0.0f);
kmin = j;
}
for (k=kmin;;)
{
DDSVector4
a,
alpha2_sum,
alphax_sum,
alphabeta_sum,
b,
beta2_sum,
betax_sum,
e1,
e2,
factor,
part3;
float
error;
VectorSubtract(xSumwSum,part2,&part3);
VectorSubtract(part3,part1,&part3);
VectorSubtract(part3,part0,&part3);
VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
VectorInit(alpha2_sum,alphax_sum.w);
VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
VectorInit(beta2_sum,betax_sum.w);
VectorAdd(part1,part2,&alphabeta_sum);
VectorInit(alphabeta_sum,alphabeta_sum.w);
VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
VectorMultiply(alpha2_sum,beta2_sum,&factor);
VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
&factor);
VectorReciprocal(factor,&factor);
VectorMultiply(alphax_sum,beta2_sum,&a);
VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
VectorMultiply(a,factor,&a);
VectorMultiply(betax_sum,alpha2_sum,&b);
VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
VectorMultiply(b,factor,&b);
VectorClamp(&a);
VectorMultiplyAdd(grid,a,half,&a);
VectorTruncate(&a);
VectorMultiply(a,gridrcp,&a);
VectorClamp(&b);
VectorMultiplyAdd(grid,b,half,&b);
VectorTruncate(&b);
VectorMultiply(b,gridrcp,&b);
VectorMultiply(b,b,&e1);
VectorMultiply(e1,beta2_sum,&e1);
VectorMultiply(a,a,&e2);
VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
VectorMultiply(a,b,&e2);
VectorMultiply(e2,alphabeta_sum,&e2);
VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
VectorMultiplyAdd(two,e2,e1,&e2);
VectorMultiply(e2,metric,&e2);
error = e2.x + e2.y + e2.z;
if (error < bestError)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (DDS_CompressClusterFit)
#endif
{
if (error < bestError)
{
VectorCopy43(a,start);
VectorCopy43(b,end);
bestError = error;
besti = i;
bestj = j;
bestk = k;
bestIteration = iterationIndex;
}
}
}
if (k == count)
break;
VectorAdd(pointsWeights[k],part2,&part2);
k++;
}
if (j == count)
break;
VectorAdd(pointsWeights[j],part1,&part1);
j++;
}
}
if (bestIteration != iterationIndex)
break;
iterationIndex++;
if (iterationIndex == 8)
break;
VectorSubtract3(*end,*start,&axis);
if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
iterationIndex) == MagickFalse)
break;
}
o = order + (16*bestIteration);
for (i=0; i < (ssize_t) besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < (ssize_t) bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < (ssize_t) bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < (ssize_t) count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MaxF(w.x,MaxF(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(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 IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface 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 ReadDDSImage method is:
%
% Image *ReadDDSImage(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 Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 8);
return MagickTrue;
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
MagickSizeType
alpha_bits;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 3);
return MagickTrue;
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 4);
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS 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 RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = SetMagickInfo("DDS");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT1");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT5");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if (clusterFit == MagickFalse || count == 0)
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (!image->matte)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
weightByAlpha=MagickTrue;
}
}
}
maxMipmaps=SIZE_MAX;
mipmaps=0;
if ((image->columns & (image->columns - 1)) == 0 &&
(image->rows & (image->rows - 1)) == 0)
{
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while (columns != 1 && rows != 1 && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
&image->exception);
if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
clusterFit,weightByAlpha,&image->exception) == MagickFalse)
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const PixelPacket *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(p));
else
alpha = 255;
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p++;
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression, const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value,
const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char* indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
Image*
resize_image;
register ssize_t
i;
size_t
columns,
rows;
columns = image->columns;
rows = image->rows;
for (i=0; i< (ssize_t) mipmaps; i++)
{
resize_image = ResizeImage(image,columns/2,rows/2,TriangleFilter,1.0,
exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
DestroyBlob(resize_image);
resize_image->blob=ReferenceBlob(image->blob);
WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
resize_image=DestroyImage(resize_image);
columns = DIV2(columns);
rows = DIV2(rows);
}
return(MagickTrue);
}
static void WriteSingleColorFit(Image *image, const DDSVector4* points,
const ssize_t* map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
p++;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2434_0 |
crossvul-cpp_data_bad_1837_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H H DDDD RRRR %
% H H D D R R %
% HHHHH D D RRRR %
% H H D D R R %
% H H DDDD R R %
% %
% %
% Read/Write Radiance RGBE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 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 %
% %
% http://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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.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/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteHDRImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H D R %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHDR() returns MagickTrue if the image format type, identified by the
% magick string, is Radiance RGBE image format.
%
% The format of the IsHDR method is:
%
% MagickBooleanType IsHDR(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 IsHDR(const unsigned char *magick,
const size_t length)
{
if (length < 10)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadHDRImage() reads the Radiance RGBE image format 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 ReadHDRImage method is:
%
% Image *ReadHDRImage(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 Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format[MaxTextExtent],
keyword[MaxTextExtent],
tag[MaxTextExtent],
value[MaxTextExtent];
double
gamma;
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
ssize_t
count,
y;
unsigned char
*end,
pixel[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
image->columns=0;
image->rows=0;
*format='\0';
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
while (isgraph(c) && (image->columns == 0) && (image->rows == 0))
{
if (c == (int) '#')
{
char
*comment;
register char
*p;
size_t
length;
/*
Read comment-- any text between # and end-of-line.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if ((c == EOF) || (c == (int) '\n'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) == MagickFalse)
c=ReadBlobByte(image);
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
}
if (LocaleCompare(keyword,"Y") == 0)
value_expected=MagickTrue;
if (value_expected == MagickFalse)
continue;
p=value;
while ((c != '\n') && (c != '\0'))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"format") == 0)
{
(void) CopyMagickString(format,value,MaxTextExtent);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"primaries") == 0)
{
float
chromaticity[6],
white_point[2];
(void) sscanf(value,"%g %g %g %g %g %g %g %g",
&chromaticity[0],&chromaticity[1],&chromaticity[2],
&chromaticity[3],&chromaticity[4],&chromaticity[5],
&white_point[0],&white_point[1]);
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
image->chromaticity.white_point.x=white_point[0],
image->chromaticity.white_point.y=white_point[1];
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'Y':
case 'y':
{
char
target[] = "Y";
if (strcmp(keyword,target) == 0)
{
int
height,
width;
(void) sscanf(value,"%d +X %d",&height,&width);
image->columns=(size_t) width;
image->rows=(size_t) height;
break;
}
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
default:
{
(void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
}
}
if ((image->columns == 0) && (image->rows == 0))
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) &&
(LocaleCompare(format,"32-bit_rle_xyze") != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) SetImageColorspace(image,RGBColorspace,exception);
if (LocaleCompare(format,"32-bit_rle_xyze") == 0)
(void) SetImageColorspace(image,XYZColorspace,exception);
image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
NoCompression : RLECompression;
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));
/*
Read RGBE (red+green+blue+exponent) pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
if (image->compression != RLECompression)
{
count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
else
{
count=ReadBlob(image,4*sizeof(*pixel),pixel);
if (count != 4)
break;
if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
{
(void) memcpy(pixels,pixel,4*sizeof(*pixel));
count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
image->compression=NoCompression;
}
else
{
p=pixels;
for (i=0; i < 4; i++)
{
end=&pixels[(i+1)*image->columns];
while (p < end)
{
count=ReadBlob(image,2*sizeof(*pixel),pixel);
if (count < 1)
break;
if (pixel[0] > 128)
{
count=(ssize_t) pixel[0]-128;
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
while (count-- > 0)
*p++=pixel[1];
}
else
{
count=(ssize_t) pixel[0];
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
*p++=pixel[1];
if (--count > 0)
{
count=ReadBlob(image,(size_t) count*sizeof(*p),p);
if (count < 1)
break;
p+=count;
}
}
}
}
}
}
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->compression == RLECompression)
{
pixel[0]=pixels[x];
pixel[1]=pixels[x+image->columns];
pixel[2]=pixels[x+2*image->columns];
pixel[3]=pixels[x+3*image->columns];
}
else
{
pixel[0]=pixels[i++];
pixel[1]=pixels[i++];
pixel[2]=pixels[i++];
pixel[3]=pixels[i++];
}
SetPixelRed(image,0,q);
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
if (pixel[3] != 0)
{
gamma=pow(2.0,pixel[3]-(128.0+8.0));
SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q);
SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q);
SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterHDRImage() adds attributes for the Radiance RGBE 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 RegisterHDRImage method is:
%
% size_t RegisterHDRImage(void)
%
*/
ModuleExport size_t RegisterHDRImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("HDR");
entry->decoder=(DecodeImageHandler *) ReadHDRImage;
entry->encoder=(EncodeImageHandler *) WriteHDRImage;
entry->description=ConstantString("Radiance RGBE image format");
entry->module=ConstantString("HDR");
entry->magick=(IsImageFormatHandler *) IsHDR;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterHDRImage() removes format registrations made by the
% HDR module from the list of supported formats.
%
% The format of the UnregisterHDRImage method is:
%
% UnregisterHDRImage(void)
%
*/
ModuleExport void UnregisterHDRImage(void)
{
(void) UnregisterMagickInfo("HDR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteHDRImage() writes an image in the Radience RGBE image format.
%
% The format of the WriteHDRImage method is:
%
% MagickBooleanType WriteHDRImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
{
#define MinimumRunlength 4
register size_t
p,
q;
size_t
runlength;
ssize_t
count,
previous_count;
unsigned char
pixel[2];
for (p=0; p < image->columns; )
{
q=p;
runlength=0;
previous_count=0;
while ((runlength < MinimumRunlength) && (q < image->columns))
{
q+=runlength;
previous_count=(ssize_t) runlength;
runlength=1;
while ((pixels[q] == pixels[q+runlength]) &&
((q+runlength) < image->columns) && (runlength < 127))
runlength++;
}
if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
{
pixel[0]=(unsigned char) (128+previous_count);
pixel[1]=pixels[p];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p=q;
}
while (p < q)
{
count=(ssize_t) (q-p);
if (count > 128)
count=128;
pixel[0]=(unsigned char) count;
if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
break;
if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
break;
p+=count;
}
if (runlength >= MinimumRunlength)
{
pixel[0]=(unsigned char) (128+runlength);
pixel[1]=pixels[q];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p+=runlength;
}
}
return(p);
}
static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
header[MaxTextExtent];
const char
*property;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,RGBColorspace,exception);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MaxTextExtent);
length=CopyMagickString(header,"#?RGBE\n",MaxTextExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment",exception);
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MaxTextExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure",exception);
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MaxTextExtent,"EXPOSURE=%g\n",
strtod(property,(char **) NULL));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MaxTextExtent,"GAMMA=%g\n",image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MaxTextExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MaxTextExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MaxTextExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(image,p);
if ((QuantumScale*GetPixelGreen(image,p)) > gamma)
gamma=QuantumScale*GetPixelGreen(image,p);
if ((QuantumScale*GetPixelBlue(image,p)) > gamma)
gamma=QuantumScale*GetPixelBlue(image,p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p+=GetPixelChannels(image);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1837_0 |
crossvul-cpp_data_bad_4899_0 | /*
* Code to handle user-settable options. This is all pretty much table-
* driven. Checklist for adding a new option:
* - Put it in the options array below (copy an existing entry).
* - For a global option: Add a variable for it in option_defs.h.
* - For a buffer or window local option:
* - Add a PV_XX entry to the enum below.
* - Add a variable to the window or buffer struct in buffer_defs.h.
* - For a window option, add some code to copy_winopt().
* - For a buffer option, add some code to buf_copy_options().
* - For a buffer string option, add code to check_buf_options().
* - If it's a numeric option, add any necessary bounds checks to do_set().
* - If it's a list of flags, add some code in do_set(), search for WW_ALL.
* - When adding an option with expansion (P_EXPAND), but with a different
* default for Vi and Vim (no P_VI_DEF), add some code at VIMEXP.
* - Add documentation! One line in doc/help.txt, full description in
* options.txt, and any other related places.
* - Add an entry in runtime/optwin.vim.
* When making changes:
* - Adjust the help for the option in doc/option.txt.
*/
#define IN_OPTION_C
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
#include "nvim/vim.h"
#include "nvim/ascii.h"
#include "nvim/edit.h"
#include "nvim/option.h"
#include "nvim/buffer.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/diff.h"
#include "nvim/digraph.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds2.h"
#include "nvim/ex_docmd.h"
#include "nvim/ex_getln.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
#include "nvim/getchar.h"
#include "nvim/hardcopy.h"
#include "nvim/indent_c.h"
#include "nvim/mbyte.h"
#include "nvim/memfile.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/misc1.h"
#include "nvim/keymap.h"
#include "nvim/garray.h"
#include "nvim/cursor_shape.h"
#include "nvim/move.h"
#include "nvim/mouse.h"
#include "nvim/normal.h"
#include "nvim/os_unix.h"
#include "nvim/path.h"
#include "nvim/regexp.h"
#include "nvim/screen.h"
#include "nvim/spell.h"
#include "nvim/strings.h"
#include "nvim/syntax.h"
#include "nvim/ui.h"
#include "nvim/undo.h"
#include "nvim/window.h"
#include "nvim/os/os.h"
#include "nvim/os/input.h"
/*
* The options that are local to a window or buffer have "indir" set to one of
* these values. Special values:
* PV_NONE: global option.
* PV_WIN is added: window-local option
* PV_BUF is added: buffer-local option
* PV_BOTH is added: global option which also has a local value.
*/
#define PV_BOTH 0x1000
#define PV_WIN 0x2000
#define PV_BUF 0x4000
#define PV_MASK 0x0fff
#define OPT_WIN(x) (idopt_T)(PV_WIN + (int)(x))
#define OPT_BUF(x) (idopt_T)(PV_BUF + (int)(x))
#define OPT_BOTH(x) (idopt_T)(PV_BOTH + (int)(x))
/* WV_ and BV_ values get typecasted to this for the "indir" field */
typedef enum {
PV_NONE = 0,
PV_MAXVAL = 0xffff /* to avoid warnings for value out of range */
} idopt_T;
/*
* Options local to a window have a value local to a buffer and global to all
* buffers. Indicate this by setting "var" to VAR_WIN.
*/
#define VAR_WIN ((char_u *)-1)
/*
* These are the global values for options which are also local to a buffer.
* Only to be used in option.c!
*/
static int p_ai;
static int p_bin;
static int p_bomb;
static char_u *p_bh;
static char_u *p_bt;
static int p_bl;
static int p_ci;
static int p_cin;
static char_u *p_cink;
static char_u *p_cino;
static char_u *p_cinw;
static char_u *p_com;
static char_u *p_cms;
static char_u *p_cpt;
static char_u *p_cfu;
static char_u *p_ofu;
static int p_eol;
static int p_fixeol;
static int p_et;
static char_u *p_fenc;
static char_u *p_ff;
static char_u *p_fo;
static char_u *p_flp;
static char_u *p_ft;
static long p_iminsert;
static long p_imsearch;
static char_u *p_inex;
static char_u *p_inde;
static char_u *p_indk;
static char_u *p_fex;
static int p_inf;
static char_u *p_isk;
static int p_lisp;
static int p_ml;
static int p_ma;
static int p_mod;
static char_u *p_mps;
static char_u *p_nf;
static int p_pi;
static char_u *p_qe;
static int p_ro;
static int p_si;
static long p_sts;
static char_u *p_sua;
static long p_sw;
static int p_swf;
static long p_smc;
static char_u *p_syn;
static char_u *p_spc;
static char_u *p_spf;
static char_u *p_spl;
static long p_ts;
static long p_tw;
static int p_udf;
static long p_wm;
static char_u *p_keymap;
/* Saved values for when 'bin' is set. */
static int p_et_nobin;
static int p_ml_nobin;
static long p_tw_nobin;
static long p_wm_nobin;
// Saved values for when 'paste' is set.
static int p_ai_nopaste;
static int p_et_nopaste;
static long p_sts_nopaste;
static long p_tw_nopaste;
static long p_wm_nopaste;
typedef struct vimoption {
char *fullname; /* full option name */
char *shortname; /* permissible abbreviation */
uint32_t flags; /* see below */
char_u *var; /* global option: pointer to variable;
* window-local option: VAR_WIN;
* buffer-local option: global value */
idopt_T indir; /* global option: PV_NONE;
* local option: indirect option index */
char_u *def_val[2]; /* default values for variable (vi and vim) */
scid_T scriptID; /* script in which the option was last set */
# define SCRIPTID_INIT , 0
} vimoption_T;
#define VI_DEFAULT 0 /* def_val[VI_DEFAULT] is Vi default value */
#define VIM_DEFAULT 1 /* def_val[VIM_DEFAULT] is Vim default value */
/*
* Flags
*/
#define P_BOOL 0x01U /* the option is boolean */
#define P_NUM 0x02U /* the option is numeric */
#define P_STRING 0x04U /* the option is a string */
#define P_ALLOCED 0x08U /* the string option is in allocated memory,
must use free_string_option() when
assigning new value. Not set if default is
the same. */
#define P_EXPAND 0x10U /* environment expansion. NOTE: P_EXPAND can
never be used for local or hidden options */
#define P_NODEFAULT 0x40U /* don't set to default value */
#define P_DEF_ALLOCED 0x80U /* default value is in allocated memory, must
use free() when assigning new value */
#define P_WAS_SET 0x100U /* option has been set/reset */
#define P_NO_MKRC 0x200U /* don't include in :mkvimrc output */
#define P_VI_DEF 0x400U /* Use Vi default for Vim */
#define P_VIM 0x800U /* Vim option */
/* when option changed, what to display: */
#define P_RSTAT 0x1000U /* redraw status lines */
#define P_RWIN 0x2000U /* redraw current window */
#define P_RBUF 0x4000U /* redraw current buffer */
#define P_RALL 0x6000U /* redraw all windows */
#define P_RCLR 0x7000U /* clear and redraw all */
#define P_COMMA 0x8000U ///< comma separated list
#define P_ONECOMMA 0x18000U ///< P_COMMA and cannot have two consecutive
///< commas
#define P_NODUP 0x20000U ///< don't allow duplicate strings
#define P_FLAGLIST 0x40000U ///< list of single-char flags
#define P_SECURE 0x80000U ///< cannot change in modeline or secure mode
#define P_GETTEXT 0x100000U ///< expand default value with _()
#define P_NOGLOB 0x200000U ///< do not use local value for global vimrc
#define P_NFNAME 0x400000U ///< only normal file name chars allowed
#define P_INSECURE 0x800000U ///< option was set from a modeline
#define P_PRI_MKRC 0x1000000U ///< priority for :mkvimrc (setting option
///< has side effects)
#define P_NO_ML 0x2000000U ///< not allowed in modeline
#define P_CURSWANT 0x4000000U ///< update curswant required; not needed
///< when there is a redraw flag
#define P_NO_DEF_EXP 0x8000000U ///< Do not expand default value.
#define HIGHLIGHT_INIT \
"8:SpecialKey,~:EndOfBuffer,z:TermCursor,Z:TermCursorNC,@:NonText," \
"d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr," \
"N:CursorLineNr,r:Question,s:StatusLine,S:StatusLineNC,c:VertSplit,t:Title," \
"v:Visual,w:WarningMsg,W:WildMenu,f:Folded,F:FoldColumn," \
"A:DiffAdd,C:DiffChange,D:DiffDelete,T:DiffText,>:SignColumn,-:Conceal," \
"B:SpellBad,P:SpellCap,R:SpellRare,L:SpellLocal,+:Pmenu,=:PmenuSel," \
"x:PmenuSbar,X:PmenuThumb,*:TabLine,#:TabLineSel,_:TabLineFill," \
"!:CursorColumn,.:CursorLine,o:ColorColumn,q:QuickFixLine"
/*
* options[] is initialized here.
* The order of the options MUST be alphabetic for ":set all" and findoption().
* All option names MUST start with a lowercase letter (for findoption()).
* Exception: "t_" options are at the end.
* The options with a NULL variable are 'hidden': a set command for them is
* ignored and they are not printed.
*/
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "options.generated.h"
#endif
#define PARAM_COUNT ARRAY_SIZE(options)
static char *(p_ambw_values[]) = { "single", "double", NULL };
static char *(p_bg_values[]) = { "light", "dark", NULL };
static char *(p_nf_values[]) = { "bin", "octal", "hex", "alpha", NULL };
static char *(p_ff_values[]) = { FF_UNIX, FF_DOS, FF_MAC, NULL };
static char *(p_wop_values[]) = { "tagfile", NULL };
static char *(p_wak_values[]) = { "yes", "menu", "no", NULL };
static char *(p_mousem_values[]) = { "extend", "popup", "popup_setpos",
"mac", NULL };
static char *(p_sel_values[]) = { "inclusive", "exclusive", "old", NULL };
static char *(p_slm_values[]) = { "mouse", "key", "cmd", NULL };
static char *(p_km_values[]) = { "startsel", "stopsel", NULL };
static char *(p_scbopt_values[]) = { "ver", "hor", "jump", NULL };
static char *(p_debug_values[]) = { "msg", "throw", "beep", NULL };
static char *(p_ead_values[]) = { "both", "ver", "hor", NULL };
static char *(p_buftype_values[]) = { "nofile", "nowrite", "quickfix",
"help", "acwrite", "terminal", NULL };
static char *(p_bufhidden_values[]) = { "hide", "unload", "delete",
"wipe", NULL };
static char *(p_bs_values[]) = { "indent", "eol", "start", NULL };
static char *(p_fdm_values[]) = { "manual", "expr", "marker", "indent",
"syntax", "diff", NULL };
static char *(p_fcl_values[]) = { "all", NULL };
static char *(p_cot_values[]) = { "menu", "menuone", "longest", "preview",
"noinsert", "noselect", NULL };
static char *(p_icm_values[]) = { "nosplit", "split", NULL };
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "option.c.generated.h"
#endif
/// Append string with escaped commas
static char *strcpy_comma_escaped(char *dest, const char *src, const size_t len)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
size_t shift = 0;
for (size_t i = 0; i < len; i++) {
if (src[i] == ',') {
dest[i + shift++] = '\\';
}
dest[i + shift] = src[i];
}
return &dest[len + shift];
}
/// Compute length of a colon-separated value, doubled and with some suffixes
///
/// @param[in] val Colon-separated array value.
/// @param[in] common_suf_len Length of the common suffix which is appended to
/// each item in the array, twice.
/// @param[in] single_suf_len Length of the suffix which is appended to each
/// item in the array once.
///
/// @return Length of the comma-separated string array that contains each item
/// in the original array twice with suffixes with given length
/// (common_suf is present after each new item, single_suf is present
/// after half of the new items) and with commas after each item, commas
/// inside the values are escaped.
static inline size_t compute_double_colon_len(const char *const val,
const size_t common_suf_len,
const size_t single_suf_len)
FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
{
if (val == NULL || *val == NUL) {
return 0;
}
size_t ret = 0;
const void *iter = NULL;
do {
size_t dir_len;
const char *dir;
iter = vim_colon_env_iter(val, iter, &dir, &dir_len);
if (dir != NULL && dir_len > 0) {
ret += ((dir_len + memcnt(dir, ',', dir_len) + common_suf_len
+ !after_pathsep(dir, dir + dir_len)) * 2
+ single_suf_len);
}
} while (iter != NULL);
return ret;
}
#define NVIM_SIZE (sizeof("nvim") - 1)
/// Add directories to a comma-separated array from a colon-separated one
///
/// Commas are escaped in process. To each item PATHSEP "nvim" is appended in
/// addition to suf1 and suf2.
///
/// @param[in,out] dest Destination comma-separated array.
/// @param[in] val Source colon-separated array.
/// @param[in] suf1 If not NULL, suffix appended to destination. Prior to it
/// directory separator is appended. Suffix must not contain
/// commas.
/// @param[in] len1 Length of the suf1.
/// @param[in] suf2 If not NULL, another suffix appended to destination. Again
/// with directory separator behind. Suffix must not contain
/// commas.
/// @param[in] len2 Length of the suf2.
/// @param[in] forward If true, iterate over val in forward direction.
/// Otherwise in reverse.
///
/// @return (dest + appended_characters_length)
static inline char *add_colon_dirs(char *dest, const char *const val,
const char *const suf1, const size_t len1,
const char *const suf2, const size_t len2,
const bool forward)
FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1)
{
if (val == NULL || *val == NUL) {
return dest;
}
const void *iter = NULL;
do {
size_t dir_len;
const char *dir;
iter = (forward ? vim_colon_env_iter : vim_colon_env_iter_rev)(
val, iter, &dir, &dir_len);
if (dir != NULL && dir_len > 0) {
dest = strcpy_comma_escaped(dest, dir, dir_len);
if (!after_pathsep(dest - 1, dest)) {
*dest++ = PATHSEP;
}
memmove(dest, "nvim", NVIM_SIZE);
dest += NVIM_SIZE;
if (suf1 != NULL) {
*dest++ = PATHSEP;
memmove(dest, suf1, len1);
dest += len1;
if (suf2 != NULL) {
*dest++ = PATHSEP;
memmove(dest, suf2, len2);
dest += len2;
}
}
*dest++ = ',';
}
} while (iter != NULL);
return dest;
}
/// Add directory to a comma-separated list of directories
///
/// In the added directory comma is escaped.
///
/// @param[in,out] dest Destination comma-separated array.
/// @param[in] dir Directory to append.
/// @param[in] append_nvim If true, append "nvim" as the very first suffix.
/// @param[in] suf1 If not NULL, suffix appended to destination. Prior to it
/// directory separator is appended. Suffix must not contain
/// commas.
/// @param[in] len1 Length of the suf1.
/// @param[in] suf2 If not NULL, another suffix appended to destination. Again
/// with directory separator behind. Suffix must not contain
/// commas.
/// @param[in] len2 Length of the suf2.
/// @param[in] forward If true, iterate over val in forward direction.
/// Otherwise in reverse.
///
/// @return (dest + appended_characters_length)
static inline char *add_dir(char *dest, const char *const dir,
const size_t dir_len, const bool append_nvim,
const char *const suf1, const size_t len1,
const char *const suf2, const size_t len2)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT
{
if (dir == NULL || dir_len == 0) {
return dest;
}
dest = strcpy_comma_escaped(dest, dir, dir_len);
if (append_nvim) {
if (!after_pathsep(dest - 1, dest)) {
*dest++ = PATHSEP;
}
memmove(dest, "nvim", NVIM_SIZE);
dest += NVIM_SIZE;
if (suf1 != NULL) {
*dest++ = PATHSEP;
memmove(dest, suf1, len1);
dest += len1;
if (suf2 != NULL) {
*dest++ = PATHSEP;
memmove(dest, suf2, len2);
dest += len2;
}
}
}
*dest++ = ',';
return dest;
}
/// Set &runtimepath to default value
static void set_runtimepath_default(void)
{
size_t rtp_size = 0;
char *const data_home = stdpaths_get_xdg_var(kXDGDataHome);
char *const config_home = stdpaths_get_xdg_var(kXDGConfigHome);
char *const vimruntime = vim_getenv("VIMRUNTIME");
char *const data_dirs = stdpaths_get_xdg_var(kXDGDataDirs);
char *const config_dirs = stdpaths_get_xdg_var(kXDGConfigDirs);
#define SITE_SIZE (sizeof("site") - 1)
#define AFTER_SIZE (sizeof("after") - 1)
size_t data_len = 0;
size_t config_len = 0;
size_t vimruntime_len = 0;
if (data_home != NULL) {
data_len = strlen(data_home);
if (data_len != 0) {
rtp_size += ((data_len + memcnt(data_home, ',', data_len)
+ NVIM_SIZE + 1 + SITE_SIZE + 1
+ !after_pathsep(data_home, data_home + data_len)) * 2
+ AFTER_SIZE + 1);
}
}
if (config_home != NULL) {
config_len = strlen(config_home);
if (config_len != 0) {
rtp_size += ((config_len + memcnt(config_home, ',', config_len)
+ NVIM_SIZE + 1
+ !after_pathsep(config_home, config_home + config_len)) * 2
+ AFTER_SIZE + 1);
}
}
if (vimruntime != NULL) {
vimruntime_len = strlen(vimruntime);
if (vimruntime_len != 0) {
rtp_size += vimruntime_len + memcnt(vimruntime, ',', vimruntime_len) + 1;
}
}
rtp_size += compute_double_colon_len(data_dirs, NVIM_SIZE + 1 + SITE_SIZE + 1,
AFTER_SIZE + 1);
rtp_size += compute_double_colon_len(config_dirs, NVIM_SIZE + 1,
AFTER_SIZE + 1);
if (rtp_size == 0) {
return;
}
char *const rtp = xmalloc(rtp_size);
char *rtp_cur = rtp;
rtp_cur = add_dir(rtp_cur, config_home, config_len, true, NULL, 0, NULL, 0);
rtp_cur = add_colon_dirs(rtp_cur, config_dirs, NULL, 0, NULL, 0, true);
rtp_cur = add_dir(rtp_cur, data_home, data_len, true, "site", SITE_SIZE,
NULL, 0);
rtp_cur = add_colon_dirs(rtp_cur, data_dirs, "site", SITE_SIZE, NULL, 0,
true);
rtp_cur = add_dir(rtp_cur, vimruntime, vimruntime_len, false, NULL, 0,
NULL, 0);
rtp_cur = add_colon_dirs(rtp_cur, data_dirs, "site", SITE_SIZE,
"after", AFTER_SIZE, false);
rtp_cur = add_dir(rtp_cur, data_home, data_len, true, "site", SITE_SIZE,
"after", AFTER_SIZE);
rtp_cur = add_colon_dirs(rtp_cur, config_dirs, "after", AFTER_SIZE, NULL, 0,
false);
rtp_cur = add_dir(rtp_cur, config_home, config_len, true,
"after", AFTER_SIZE, NULL, 0);
// Strip trailing comma.
rtp_cur[-1] = NUL;
assert((size_t) (rtp_cur - rtp) == rtp_size);
#undef SITE_SIZE
#undef AFTER_SIZE
set_string_default("runtimepath", rtp, true);
// Make a copy of 'rtp' for 'packpath'
set_string_default("packpath", rtp, false);
xfree(data_dirs);
xfree(config_dirs);
xfree(data_home);
xfree(config_home);
xfree(vimruntime);
}
#undef NVIM_SIZE
/*
* Initialize the options, first part.
*
* Called only once from main(), just after creating the first buffer.
*/
void set_init_1(void)
{
int opt_idx;
langmap_init();
/* Be nocompatible */
p_cp = FALSE;
/*
* Find default value for 'shell' option.
* Don't use it if it is empty.
*/
{
const char *shell = os_getenv("SHELL");
if (shell != NULL) {
set_string_default("sh", (char *) shell, false);
}
}
/*
* Set the default for 'backupskip' to include environment variables for
* temp files.
*/
{
# ifdef UNIX
static char *(names[4]) = {"", "TMPDIR", "TEMP", "TMP"};
# else
static char *(names[3]) = {"TMPDIR", "TEMP", "TMP"};
# endif
int len;
garray_T ga;
ga_init(&ga, 1, 100);
for (size_t n = 0; n < ARRAY_SIZE(names); ++n) {
bool mustfree = true;
char *p;
# ifdef UNIX
if (*names[n] == NUL) {
p = "/tmp";
mustfree = false;
}
else
# endif
p = vim_getenv(names[n]);
if (p != NULL && *p != NUL) {
// First time count the NUL, otherwise count the ','.
len = (int)strlen(p) + 3;
ga_grow(&ga, len);
if (!GA_EMPTY(&ga))
STRCAT(ga.ga_data, ",");
STRCAT(ga.ga_data, p);
add_pathsep(ga.ga_data);
STRCAT(ga.ga_data, "*");
ga.ga_len += len;
}
if(mustfree) {
xfree(p);
}
}
if (ga.ga_data != NULL) {
set_string_default("bsk", ga.ga_data, true);
}
}
/*
* 'maxmemtot' and 'maxmem' may have to be adjusted for available memory
*/
opt_idx = findoption((char_u *)"maxmemtot");
if (opt_idx >= 0) {
{
/* Use half of amount of memory available to Vim. */
/* If too much to fit in uintptr_t, get uintptr_t max */
uint64_t available_kib = os_get_total_mem_kib();
uintptr_t n = available_kib / 2 > UINTPTR_MAX
? UINTPTR_MAX
: (uintptr_t)(available_kib /2);
options[opt_idx].def_val[VI_DEFAULT] = (char_u *)n;
opt_idx = findoption((char_u *)"maxmem");
if (opt_idx >= 0) {
options[opt_idx].def_val[VI_DEFAULT] = (char_u *)n;
}
}
}
{
char_u *cdpath;
char_u *buf;
int i;
int j;
/* Initialize the 'cdpath' option's default value. */
cdpath = (char_u *)vim_getenv("CDPATH");
if (cdpath != NULL) {
buf = xmalloc(2 * STRLEN(cdpath) + 2);
{
buf[0] = ','; /* start with ",", current dir first */
j = 1;
for (i = 0; cdpath[i] != NUL; ++i) {
if (vim_ispathlistsep(cdpath[i]))
buf[j++] = ',';
else {
if (cdpath[i] == ' ' || cdpath[i] == ',')
buf[j++] = '\\';
buf[j++] = cdpath[i];
}
}
buf[j] = NUL;
opt_idx = findoption((char_u *)"cdpath");
if (opt_idx >= 0) {
options[opt_idx].def_val[VI_DEFAULT] = buf;
options[opt_idx].flags |= P_DEF_ALLOCED;
} else
xfree(buf); /* cannot happen */
}
xfree(cdpath);
}
}
#if defined(MSWIN) || defined(MAC)
/* Set print encoding on platforms that don't default to latin1 */
set_string_default("printencoding", "hp-roman8", false);
#endif
// 'printexpr' must be allocated to be able to evaluate it.
set_string_default("printexpr",
#ifdef UNIX
"system(['lpr'] "
"+ (empty(&printdevice)?[]:['-P', &printdevice]) "
"+ [v:fname_in])"
". delete(v:fname_in)"
"+ v:shell_error",
#elif defined(MSWIN)
"system(['copy', v:fname_in, "
"empty(&printdevice)?'LPT1':&printdevice])"
". delete(v:fname_in)",
#else
"",
#endif
false);
char *backupdir = stdpaths_user_data_subpath("backup", 0, true);
const size_t backupdir_len = strlen(backupdir);
backupdir = xrealloc(backupdir, backupdir_len + 3);
memmove(backupdir + 2, backupdir, backupdir_len + 1);
memmove(backupdir, ".,", 2);
set_string_default("viewdir", stdpaths_user_data_subpath("view", 0, true),
true);
set_string_default("backupdir", backupdir, true);
set_string_default("directory", stdpaths_user_data_subpath("swap", 2, true),
true);
set_string_default("undodir", stdpaths_user_data_subpath("undo", 0, true),
true);
// Set default for &runtimepath. All necessary expansions are performed in
// this function.
set_runtimepath_default();
/*
* Set all the options (except the terminal options) to their default
* value. Also set the global value for local options.
*/
set_options_default(0);
curbuf->b_p_initialized = true;
curbuf->b_p_ar = -1; /* no local 'autoread' value */
curbuf->b_p_ul = NO_LOCAL_UNDOLEVEL;
check_buf_options(curbuf);
check_win_options(curwin);
check_options();
/* Set all options to their Vim default */
set_options_default(OPT_FREE);
// set 'laststatus'
last_status(false);
/* Must be before option_expand(), because that one needs vim_isIDc() */
didset_options();
// Use the current chartab for the generic chartab. This is not in
// didset_options() because it only depends on 'encoding'.
init_spell_chartab();
/*
* Expand environment variables and things like "~" for the defaults.
* If option_expand() returns non-NULL the variable is expanded. This can
* only happen for non-indirect options.
* Also set the default to the expanded value, so ":set" does not list
* them.
* Don't set the P_ALLOCED flag, because we don't want to free the
* default.
*/
for (opt_idx = 0; options[opt_idx].fullname; opt_idx++) {
if (options[opt_idx].flags & P_NO_DEF_EXP) {
continue;
}
char *p;
if ((options[opt_idx].flags & P_GETTEXT)
&& options[opt_idx].var != NULL) {
p = _(*(char **)options[opt_idx].var);
} else {
p = (char *) option_expand(opt_idx, NULL);
}
if (p != NULL) {
p = xstrdup(p);
*(char **)options[opt_idx].var = p;
/* VIMEXP
* Defaults for all expanded options are currently the same for Vi
* and Vim. When this changes, add some code here! Also need to
* split P_DEF_ALLOCED in two.
*/
if (options[opt_idx].flags & P_DEF_ALLOCED)
xfree(options[opt_idx].def_val[VI_DEFAULT]);
options[opt_idx].def_val[VI_DEFAULT] = (char_u *) p;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
}
save_file_ff(curbuf); /* Buffer is unchanged */
/* Detect use of mlterm.
* Mlterm is a terminal emulator akin to xterm that has some special
* abilities (bidi namely).
* NOTE: mlterm's author is being asked to 'set' a variable
* instead of an environment variable due to inheritance.
*/
if (os_env_exists("MLTERM"))
set_option_value((char_u *)"tbidi", 1L, NULL, 0);
didset_options2();
// enc_locale() will try to find the encoding of the current locale.
// This will be used when 'default' is used as encoding specifier
// in 'fileencodings'
char_u *p = enc_locale();
if (p == NULL) {
// use utf-8 as 'default' if locale encoding can't be detected.
p = vim_strsave((char_u *)"utf-8");
}
fenc_default = p;
#ifdef HAVE_WORKING_LIBINTL
// GNU gettext 0.10.37 supports this feature: set the codeset used for
// translated messages independently from the current locale.
(void)bind_textdomain_codeset(PROJECT_NAME, (char *)p_enc);
#endif
/* Set the default for 'helplang'. */
set_helplang_default(get_mess_lang());
}
/*
* Set an option to its default value.
* This does not take care of side effects!
*/
static void
set_option_default (
int opt_idx,
int opt_flags, /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */
int compatible /* use Vi default value */
)
{
char_u *varp; /* pointer to variable for current option */
int dvi; /* index in def_val[] */
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
varp = get_varp_scope(&(options[opt_idx]), both ? OPT_LOCAL : opt_flags);
uint32_t flags = options[opt_idx].flags;
if (varp != NULL) { /* skip hidden option, nothing to do for it */
dvi = ((flags & P_VI_DEF) || compatible) ? VI_DEFAULT : VIM_DEFAULT;
if (flags & P_STRING) {
/* Use set_string_option_direct() for local options to handle
* freeing and allocating the value. */
if (options[opt_idx].indir != PV_NONE)
set_string_option_direct(NULL, opt_idx,
options[opt_idx].def_val[dvi], opt_flags, 0);
else {
if ((opt_flags & OPT_FREE) && (flags & P_ALLOCED))
free_string_option(*(char_u **)(varp));
*(char_u **)varp = options[opt_idx].def_val[dvi];
options[opt_idx].flags &= ~P_ALLOCED;
}
} else if (flags & P_NUM) {
if (options[opt_idx].indir == PV_SCROLL)
win_comp_scroll(curwin);
else {
*(long *)varp = (long)options[opt_idx].def_val[dvi];
/* May also set global value for local option. */
if (both)
*(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) =
*(long *)varp;
}
} else { /* P_BOOL */
*(int *)varp = (int)(intptr_t)options[opt_idx].def_val[dvi];
#ifdef UNIX
/* 'modeline' defaults to off for root */
if (options[opt_idx].indir == PV_ML && getuid() == ROOT_UID)
*(int *)varp = FALSE;
#endif
/* May also set global value for local option. */
if (both)
*(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) =
*(int *)varp;
}
/* The default value is not insecure. */
uint32_t *flagsp = insecure_flag(opt_idx, opt_flags);
*flagsp = *flagsp & ~P_INSECURE;
}
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
}
/*
* Set all options (except terminal options) to their default value.
*/
static void
set_options_default (
int opt_flags /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */
)
{
for (int i = 0; options[i].fullname; i++) {
if (!(options[i].flags & P_NODEFAULT)) {
set_option_default(i, opt_flags, p_cp);
}
}
/* The 'scroll' option must be computed for all windows. */
FOR_ALL_TAB_WINDOWS(tp, wp) {
win_comp_scroll(wp);
}
parse_cino(curbuf);
}
/// Set the Vi-default value of a string option.
/// Used for 'sh', 'backupskip' and 'term'.
///
/// @param name The name of the option
/// @param val The value of the option
/// @param allocated If true, do not copy default as it was already allocated.
static void set_string_default(const char *name, char *val, bool allocated)
FUNC_ATTR_NONNULL_ALL
{
int opt_idx = findoption((char_u *)name);
if (opt_idx >= 0) {
if (options[opt_idx].flags & P_DEF_ALLOCED) {
xfree(options[opt_idx].def_val[VI_DEFAULT]);
}
options[opt_idx].def_val[VI_DEFAULT] = (char_u *) (
allocated
? (char_u *) val
: (char_u *) xstrdup(val));
options[opt_idx].flags |= P_DEF_ALLOCED;
}
}
/*
* Set the Vi-default value of a number option.
* Used for 'lines' and 'columns'.
*/
void set_number_default(char *name, long val)
{
int opt_idx;
opt_idx = findoption((char_u *)name);
if (opt_idx >= 0)
options[opt_idx].def_val[VI_DEFAULT] = (char_u *)val;
}
#if defined(EXITFREE)
/*
* Free all options.
*/
void free_all_options(void)
{
int i;
for (i = 0; options[i].fullname; i++) {
if (options[i].indir == PV_NONE) {
/* global option: free value and default value. */
if (options[i].flags & P_ALLOCED && options[i].var != NULL)
free_string_option(*(char_u **)options[i].var);
if (options[i].flags & P_DEF_ALLOCED)
free_string_option(options[i].def_val[VI_DEFAULT]);
} else if (options[i].var != VAR_WIN
&& (options[i].flags & P_STRING))
/* buffer-local option: free global value */
free_string_option(*(char_u **)options[i].var);
}
}
#endif
/*
* Initialize the options, part two: After getting Rows and Columns and
* setting 'term'.
*/
void set_init_2(void)
{
int idx;
/*
* 'scroll' defaults to half the window height. Note that this default is
* wrong when the window height changes.
*/
set_number_default("scroll", Rows / 2);
idx = findoption((char_u *)"scroll");
if (idx >= 0 && !(options[idx].flags & P_WAS_SET))
set_option_default(idx, OPT_LOCAL, p_cp);
comp_col();
/*
* 'window' is only for backwards compatibility with Vi.
* Default is Rows - 1.
*/
if (!option_was_set((char_u *)"window"))
p_window = Rows - 1;
set_number_default("window", Rows - 1);
parse_shape_opt(SHAPE_CURSOR); /* set cursor shapes from 'guicursor' */
(void)parse_printoptions(); /* parse 'printoptions' default value */
}
/*
* Initialize the options, part three: After reading the .vimrc
*/
void set_init_3(void)
{
// Set 'shellpipe' and 'shellredir', depending on the 'shell' option.
// This is done after other initializations, where 'shell' might have been
// set, but only if they have not been set before.
int idx_srr;
int do_srr;
int idx_sp;
int do_sp;
idx_srr = findoption((char_u *)"srr");
if (idx_srr < 0)
do_srr = FALSE;
else
do_srr = !(options[idx_srr].flags & P_WAS_SET);
idx_sp = findoption((char_u *)"sp");
if (idx_sp < 0)
do_sp = FALSE;
else
do_sp = !(options[idx_sp].flags & P_WAS_SET);
size_t len = 0;
char_u *p = (char_u *)invocation_path_tail(p_sh, &len);
p = vim_strnsave(p, len);
{
/*
* Default for p_sp is "| tee", for p_srr is ">".
* For known shells it is changed here to include stderr.
*/
if ( fnamecmp(p, "csh") == 0
|| fnamecmp(p, "tcsh") == 0
) {
if (do_sp) {
p_sp = (char_u *)"|& tee";
options[idx_sp].def_val[VI_DEFAULT] = p_sp;
}
if (do_srr) {
p_srr = (char_u *)">&";
options[idx_srr].def_val[VI_DEFAULT] = p_srr;
}
} else if ( fnamecmp(p, "sh") == 0
|| fnamecmp(p, "ksh") == 0
|| fnamecmp(p, "mksh") == 0
|| fnamecmp(p, "pdksh") == 0
|| fnamecmp(p, "zsh") == 0
|| fnamecmp(p, "zsh-beta") == 0
|| fnamecmp(p, "bash") == 0
|| fnamecmp(p, "fish") == 0
) {
if (do_sp) {
p_sp = (char_u *)"2>&1| tee";
options[idx_sp].def_val[VI_DEFAULT] = p_sp;
}
if (do_srr) {
p_srr = (char_u *)">%s 2>&1";
options[idx_srr].def_val[VI_DEFAULT] = p_srr;
}
}
xfree(p);
}
if (bufempty()) {
int idx_ffs = findoption((char_u *)"ffs");
// Apply the first entry of 'fileformats' to the initial buffer.
if (idx_ffs >= 0 && (options[idx_ffs].flags & P_WAS_SET)) {
set_fileformat(default_fileformat(), OPT_LOCAL);
}
}
set_title_defaults();
}
/*
* When 'helplang' is still at its default value, set it to "lang".
* Only the first two characters of "lang" are used.
*/
void set_helplang_default(const char *lang)
{
int idx;
if (lang == NULL || STRLEN(lang) < 2) /* safety check */
return;
idx = findoption((char_u *)"hlg");
if (idx >= 0 && !(options[idx].flags & P_WAS_SET)) {
if (options[idx].flags & P_ALLOCED)
free_string_option(p_hlg);
p_hlg = (char_u *)xstrdup(lang);
/* zh_CN becomes "cn", zh_TW becomes "tw". */
if (STRNICMP(p_hlg, "zh_", 3) == 0 && STRLEN(p_hlg) >= 5) {
p_hlg[0] = (char_u)TOLOWER_ASC(p_hlg[3]);
p_hlg[1] = (char_u)TOLOWER_ASC(p_hlg[4]);
}
p_hlg[2] = NUL;
options[idx].flags |= P_ALLOCED;
}
}
/*
* 'title' and 'icon' only default to true if they have not been set or reset
* in .vimrc and we can read the old value.
* When 'title' and 'icon' have been reset in .vimrc, we won't even check if
* they can be reset. This reduces startup time when using X on a remote
* machine.
*/
void set_title_defaults(void)
{
int idx1;
/*
* If GUI is (going to be) used, we can always set the window title and
* icon name. Saves a bit of time, because the X11 display server does
* not need to be contacted.
*/
idx1 = findoption((char_u *)"title");
if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) {
options[idx1].def_val[VI_DEFAULT] = (char_u *)(intptr_t)0;
p_title = 0;
}
idx1 = findoption((char_u *)"icon");
if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) {
options[idx1].def_val[VI_DEFAULT] = (char_u *)(intptr_t)0;
p_icon = 0;
}
}
/*
* Parse 'arg' for option settings.
*
* 'arg' may be IObuff, but only when no errors can be present and option
* does not need to be expanded with option_expand().
* "opt_flags":
* 0 for ":set"
* OPT_GLOBAL for ":setglobal"
* OPT_LOCAL for ":setlocal" and a modeline
* OPT_MODELINE for a modeline
* OPT_WINONLY to only set window-local options
* OPT_NOWIN to skip setting window-local options
*
* returns FAIL if an error is detected, OK otherwise
*/
int
do_set (
char_u *arg, /* option string (may be written to!) */
int opt_flags
)
{
int opt_idx;
char_u *errmsg;
char_u errbuf[80];
char_u *startarg;
int prefix; /* 1: nothing, 0: "no", 2: "inv" in front of name */
char_u nextchar; /* next non-white char after option name */
int afterchar; /* character just after option name */
int len;
int i;
long value;
int key;
uint32_t flags; /* flags for current option */
char_u *varp = NULL; /* pointer to variable for current option */
int did_show = FALSE; /* already showed one value */
int adding; /* "opt+=arg" */
int prepending; /* "opt^=arg" */
int removing; /* "opt-=arg" */
int cp_val = 0;
if (*arg == NUL) {
showoptions(0, opt_flags);
did_show = TRUE;
goto theend;
}
while (*arg != NUL) { /* loop to process all options */
errmsg = NULL;
startarg = arg; /* remember for error message */
if (STRNCMP(arg, "all", 3) == 0 && !isalpha(arg[3])
&& !(opt_flags & OPT_MODELINE)) {
/*
* ":set all" show all options.
* ":set all&" set all options to their default value.
*/
arg += 3;
if (*arg == '&') {
arg++;
// Only for :set command set global value of local options.
set_options_default(OPT_FREE | opt_flags);
didset_options();
didset_options2();
redraw_all_later(CLEAR);
} else {
showoptions(1, opt_flags);
did_show = TRUE;
}
} else if (STRNCMP(arg, "termcap",
7) == 0 && !(opt_flags & OPT_MODELINE)) {
did_show = TRUE;
arg += 7;
} else {
prefix = 1;
if (STRNCMP(arg, "no", 2) == 0) {
prefix = 0;
arg += 2;
} else if (STRNCMP(arg, "inv", 3) == 0) {
prefix = 2;
arg += 3;
}
/* find end of name */
key = 0;
if (*arg == '<') {
opt_idx = -1;
/* look out for <t_>;> */
if (arg[1] == 't' && arg[2] == '_' && arg[3] && arg[4])
len = 5;
else {
len = 1;
while (arg[len] != NUL && arg[len] != '>')
++len;
}
if (arg[len] != '>') {
errmsg = e_invarg;
goto skip;
}
if (arg[1] == 't' && arg[2] == '_') { // could be term code
opt_idx = findoption_len(arg + 1, (size_t) (len - 1));
}
len++;
if (opt_idx == -1) {
key = find_key_option(arg + 1);
}
} else {
len = 0;
// The two characters after "t_" may not be alphanumeric.
if (arg[0] == 't' && arg[1] == '_' && arg[2] && arg[3]) {
len = 4;
} else {
while (ASCII_ISALNUM(arg[len]) || arg[len] == '_') {
len++;
}
}
opt_idx = findoption_len(arg, (size_t) len);
if (opt_idx == -1) {
key = find_key_option(arg);
}
}
/* remember character after option name */
afterchar = arg[len];
/* skip white space, allow ":set ai ?" */
while (ascii_iswhite(arg[len]))
++len;
adding = FALSE;
prepending = FALSE;
removing = FALSE;
if (arg[len] != NUL && arg[len + 1] == '=') {
if (arg[len] == '+') {
adding = TRUE; /* "+=" */
++len;
} else if (arg[len] == '^') {
prepending = TRUE; /* "^=" */
++len;
} else if (arg[len] == '-') {
removing = TRUE; /* "-=" */
++len;
}
}
nextchar = arg[len];
if (opt_idx == -1 && key == 0) { /* found a mismatch: skip */
errmsg = (char_u *)N_("E518: Unknown option");
goto skip;
}
if (opt_idx >= 0) {
if (options[opt_idx].var == NULL) { /* hidden option: skip */
/* Only give an error message when requesting the value of
* a hidden option, ignore setting it. */
if (vim_strchr((char_u *)"=:!&<", nextchar) == NULL
&& (!(options[opt_idx].flags & P_BOOL)
|| nextchar == '?'))
errmsg = (char_u *)_(e_unsupportedoption);
goto skip;
}
flags = options[opt_idx].flags;
varp = get_varp_scope(&(options[opt_idx]), opt_flags);
} else {
flags = P_STRING;
}
/* Skip all options that are not window-local (used when showing
* an already loaded buffer in a window). */
if ((opt_flags & OPT_WINONLY)
&& (opt_idx < 0 || options[opt_idx].var != VAR_WIN))
goto skip;
/* Skip all options that are window-local (used for :vimgrep). */
if ((opt_flags & OPT_NOWIN) && opt_idx >= 0
&& options[opt_idx].var == VAR_WIN)
goto skip;
/* Disallow changing some options from modelines. */
if (opt_flags & OPT_MODELINE) {
if (flags & (P_SECURE | P_NO_ML)) {
errmsg = (char_u *)_("E520: Not allowed in a modeline");
goto skip;
}
/* In diff mode some options are overruled. This avoids that
* 'foldmethod' becomes "marker" instead of "diff" and that
* "wrap" gets set. */
if (curwin->w_p_diff
&& opt_idx >= 0 /* shut up coverity warning */
&& (options[opt_idx].indir == PV_FDM
|| options[opt_idx].indir == PV_WRAP))
goto skip;
}
/* Disallow changing some options in the sandbox */
if (sandbox != 0 && (flags & P_SECURE)) {
errmsg = (char_u *)_(e_sandbox);
goto skip;
}
if (vim_strchr((char_u *)"?=:!&<", nextchar) != NULL) {
arg += len;
cp_val = p_cp;
if (nextchar == '&' && arg[1] == 'v' && arg[2] == 'i') {
if (arg[3] == 'm') { /* "opt&vim": set to Vim default */
cp_val = FALSE;
arg += 3;
} else { /* "opt&vi": set to Vi default */
cp_val = TRUE;
arg += 2;
}
}
if (vim_strchr((char_u *)"?!&<", nextchar) != NULL
&& arg[1] != NUL && !ascii_iswhite(arg[1])) {
errmsg = e_trailing;
goto skip;
}
}
/*
* allow '=' and ':' as MSDOS command.com allows only one
* '=' character per "set" command line. grrr. (jw)
*/
if (nextchar == '?'
|| (prefix == 1
&& vim_strchr((char_u *)"=:&<", nextchar) == NULL
&& !(flags & P_BOOL))) {
/*
* print value
*/
if (did_show)
msg_putchar('\n'); /* cursor below last one */
else {
gotocmdline(TRUE); /* cursor at status line */
did_show = TRUE; /* remember that we did a line */
}
if (opt_idx >= 0) {
showoneopt(&options[opt_idx], opt_flags);
if (p_verbose > 0) {
/* Mention where the option was last set. */
if (varp == options[opt_idx].var)
last_set_msg(options[opt_idx].scriptID);
else if ((int)options[opt_idx].indir & PV_WIN)
last_set_msg(curwin->w_p_scriptID[
(int)options[opt_idx].indir & PV_MASK]);
else if ((int)options[opt_idx].indir & PV_BUF)
last_set_msg(curbuf->b_p_scriptID[
(int)options[opt_idx].indir & PV_MASK]);
}
} else {
errmsg = (char_u *)N_("E846: Key code not set");
goto skip;
}
if (nextchar != '?'
&& nextchar != NUL && !ascii_iswhite(afterchar))
errmsg = e_trailing;
} else {
if (flags & P_BOOL) { /* boolean */
if (nextchar == '=' || nextchar == ':') {
errmsg = e_invarg;
goto skip;
}
/*
* ":set opt!": invert
* ":set opt&": reset to default value
* ":set opt<": reset to global value
*/
if (nextchar == '!')
value = *(int *)(varp) ^ 1;
else if (nextchar == '&')
value = (int)(intptr_t)options[opt_idx].def_val[
((flags & P_VI_DEF) || cp_val)
? VI_DEFAULT : VIM_DEFAULT];
else if (nextchar == '<') {
/* For 'autoread' -1 means to use global value. */
if ((int *)varp == &curbuf->b_p_ar
&& opt_flags == OPT_LOCAL)
value = -1;
else
value = *(int *)get_varp_scope(&(options[opt_idx]),
OPT_GLOBAL);
} else {
/*
* ":set invopt": invert
* ":set opt" or ":set noopt": set or reset
*/
if (nextchar != NUL && !ascii_iswhite(afterchar)) {
errmsg = e_trailing;
goto skip;
}
if (prefix == 2) /* inv */
value = *(int *)(varp) ^ 1;
else
value = prefix;
}
errmsg = set_bool_option(opt_idx, varp, (int)value,
opt_flags);
} else { /* numeric or string */
if (vim_strchr((char_u *)"=:&<", nextchar) == NULL
|| prefix != 1) {
errmsg = e_invarg;
goto skip;
}
if (flags & P_NUM) { /* numeric */
/*
* Different ways to set a number option:
* & set to default value
* < set to global value
* <xx> accept special key codes for 'wildchar'
* c accept any non-digit for 'wildchar'
* [-]0-9 set number
* other error
*/
++arg;
if (nextchar == '&')
value = (long)options[opt_idx].def_val[
((flags & P_VI_DEF) || cp_val)
? VI_DEFAULT : VIM_DEFAULT];
else if (nextchar == '<') {
/* For 'undolevels' NO_LOCAL_UNDOLEVEL means to
* use the global value. */
if ((long *)varp == &curbuf->b_p_ul
&& opt_flags == OPT_LOCAL)
value = NO_LOCAL_UNDOLEVEL;
else
value = *(long *)get_varp_scope(
&(options[opt_idx]), OPT_GLOBAL);
} else if (((long *)varp == &p_wc
|| (long *)varp == &p_wcm)
&& (*arg == '<'
|| *arg == '^'
|| ((!arg[1] || ascii_iswhite(arg[1]))
&& !ascii_isdigit(*arg)))) {
value = string_to_key(arg);
if (value == 0 && (long *)varp != &p_wcm) {
errmsg = e_invarg;
goto skip;
}
} else if (*arg == '-' || ascii_isdigit(*arg)) {
// Allow negative (for 'undolevels'), octal and
// hex numbers.
vim_str2nr(arg, NULL, &i, STR2NR_ALL, &value, NULL, 0);
if (arg[i] != NUL && !ascii_iswhite(arg[i])) {
errmsg = e_invarg;
goto skip;
}
} else {
errmsg = (char_u *)N_("E521: Number required after =");
goto skip;
}
if (adding)
value = *(long *)varp + value;
if (prepending)
value = *(long *)varp * value;
if (removing)
value = *(long *)varp - value;
errmsg = set_num_option(opt_idx, varp, value,
errbuf, sizeof(errbuf), opt_flags);
} else if (opt_idx >= 0) { /* string */
char_u *save_arg = NULL;
char_u *s = NULL;
char_u *oldval = NULL; // previous value if *varp
char_u *newval;
char_u *origval = NULL;
char *saved_origval = NULL;
unsigned newlen;
int comma;
int bs;
int new_value_alloced; /* new string option
was allocated */
/* When using ":set opt=val" for a global option
* with a local value the local value will be
* reset, use the global value here. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
&& ((int)options[opt_idx].indir & PV_BOTH))
varp = options[opt_idx].var;
/* The old value is kept until we are sure that the
* new value is valid. */
oldval = *(char_u **)varp;
if (nextchar == '&') { /* set to default val */
newval = options[opt_idx].def_val[
((flags & P_VI_DEF) || cp_val)
? VI_DEFAULT : VIM_DEFAULT];
/* expand environment variables and ~ (since the
* default value was already expanded, only
* required when an environment variable was set
* later */
new_value_alloced = true;
if (newval == NULL) {
newval = empty_option;
} else if (!(options[opt_idx].flags | P_NO_DEF_EXP)) {
s = option_expand(opt_idx, newval);
if (s == NULL) {
s = newval;
}
newval = vim_strsave(s);
} else {
newval = (char_u *)xstrdup((char *)newval);
}
} else if (nextchar == '<') { // set to global val
newval = vim_strsave(*(char_u **)get_varp_scope(
&(options[opt_idx]), OPT_GLOBAL));
new_value_alloced = TRUE;
} else {
++arg; /* jump to after the '=' or ':' */
/*
* Set 'keywordprg' to ":help" if an empty
* value was passed to :set by the user.
* Misuse errbuf[] for the resulting string.
*/
if (varp == (char_u *)&p_kp
&& (*arg == NUL || *arg == ' ')) {
STRCPY(errbuf, ":help");
save_arg = arg;
arg = errbuf;
}
/*
* Convert 'backspace' number to string, for
* adding, prepending and removing string.
*/
else if (varp == (char_u *)&p_bs
&& ascii_isdigit(**(char_u **)varp)) {
i = getdigits_int((char_u **)varp);
switch (i) {
case 0:
*(char_u **)varp = empty_option;
break;
case 1:
*(char_u **)varp = vim_strsave(
(char_u *)"indent,eol");
break;
case 2:
*(char_u **)varp = vim_strsave(
(char_u *)"indent,eol,start");
break;
}
xfree(oldval);
oldval = *(char_u **)varp;
}
/*
* Convert 'whichwrap' number to string, for
* backwards compatibility with Vim 3.0.
* Misuse errbuf[] for the resulting string.
*/
else if (varp == (char_u *)&p_ww
&& ascii_isdigit(*arg)) {
*errbuf = NUL;
i = getdigits_int(&arg);
if (i & 1)
STRCAT(errbuf, "b,");
if (i & 2)
STRCAT(errbuf, "s,");
if (i & 4)
STRCAT(errbuf, "h,l,");
if (i & 8)
STRCAT(errbuf, "<,>,");
if (i & 16)
STRCAT(errbuf, "[,],");
if (*errbuf != NUL) /* remove trailing , */
errbuf[STRLEN(errbuf) - 1] = NUL;
save_arg = arg;
arg = errbuf;
}
/*
* Remove '>' before 'dir' and 'bdir', for
* backwards compatibility with version 3.0
*/
else if ( *arg == '>'
&& (varp == (char_u *)&p_dir
|| varp == (char_u *)&p_bdir)) {
++arg;
}
/* When setting the local value of a global
* option, the old value may be the global value. */
if (((int)options[opt_idx].indir & PV_BOTH)
&& (opt_flags & OPT_LOCAL))
origval = *(char_u **)get_varp(
&options[opt_idx]);
else
origval = oldval;
/*
* Copy the new string into allocated memory.
* Can't use set_string_option_direct(), because
* we need to remove the backslashes.
*/
/* get a bit too much */
newlen = (unsigned)STRLEN(arg) + 1;
if (adding || prepending || removing)
newlen += (unsigned)STRLEN(origval) + 1;
newval = xmalloc(newlen);
s = newval;
/*
* Copy the string, skip over escaped chars.
* For WIN32 backslashes before normal
* file name characters are not removed, and keep
* backslash at start, for "\\machine\path", but
* do remove it for "\\\\machine\\path".
* The reverse is found in ExpandOldSetting().
*/
while (*arg && !ascii_iswhite(*arg)) {
if (*arg == '\\' && arg[1] != NUL
#ifdef BACKSLASH_IN_FILENAME
&& !((flags & P_EXPAND)
&& vim_isfilec(arg[1])
&& (arg[1] != '\\'
|| (s == newval
&& arg[2] != '\\')))
#endif
)
++arg; /* remove backslash */
if (has_mbyte
&& (i = (*mb_ptr2len)(arg)) > 1) {
/* copy multibyte char */
memmove(s, arg, (size_t)i);
arg += i;
s += i;
} else
*s++ = *arg++;
}
*s = NUL;
/*
* Expand environment variables and ~.
* Don't do it when adding without inserting a
* comma.
*/
if (!(adding || prepending || removing)
|| (flags & P_COMMA)) {
s = option_expand(opt_idx, newval);
if (s != NULL) {
xfree(newval);
newlen = (unsigned)STRLEN(s) + 1;
if (adding || prepending || removing)
newlen += (unsigned)STRLEN(origval) + 1;
newval = xmalloc(newlen);
STRCPY(newval, s);
}
}
/* locate newval[] in origval[] when removing it
* and when adding to avoid duplicates */
i = 0; /* init for GCC */
if (removing || (flags & P_NODUP)) {
i = (int)STRLEN(newval);
bs = 0;
for (s = origval; *s; ++s) {
if ((!(flags & P_COMMA)
|| s == origval
|| (s[-1] == ',' && !(bs & 1)))
&& STRNCMP(s, newval, i) == 0
&& (!(flags & P_COMMA)
|| s[i] == ','
|| s[i] == NUL)) {
break;
}
// Count backslashes. Only a comma with an even number of
// backslashes or a single backslash preceded by a comma
// before it is recognized as a separator
if ((s > origval + 1 && s[-1] == '\\' && s[-2] != ',')
|| (s == origval + 1 && s[-1] == '\\')) {
bs++;
} else {
bs = 0;
}
}
// do not add if already there
if ((adding || prepending) && *s) {
prepending = FALSE;
adding = FALSE;
STRCPY(newval, origval);
}
}
/* concatenate the two strings; add a ',' if
* needed */
if (adding || prepending) {
comma = ((flags & P_COMMA) && *origval != NUL
&& *newval != NUL);
if (adding) {
i = (int)STRLEN(origval);
// Strip a trailing comma, would get 2.
if (comma && i > 1
&& (flags & P_ONECOMMA) == P_ONECOMMA
&& origval[i - 1] == ','
&& origval[i - 2] != '\\') {
i--;
}
memmove(newval + i + comma, newval,
STRLEN(newval) + 1);
memmove(newval, origval, (size_t)i);
} else {
i = (int)STRLEN(newval);
STRMOVE(newval + i + comma, origval);
}
if (comma)
newval[i] = ',';
}
/* Remove newval[] from origval[]. (Note: "i" has
* been set above and is used here). */
if (removing) {
STRCPY(newval, origval);
if (*s) {
/* may need to remove a comma */
if (flags & P_COMMA) {
if (s == origval) {
/* include comma after string */
if (s[i] == ',')
++i;
} else {
/* include comma before string */
--s;
++i;
}
}
STRMOVE(newval + (s - origval), s + i);
}
}
if (flags & P_FLAGLIST) {
// Remove flags that appear twice.
for (s = newval; *s; s++) {
// if options have P_FLAGLIST and P_ONECOMMA such as
// 'whichwrap'
if (flags & P_ONECOMMA) {
if (*s != ',' && *(s + 1) == ','
&& vim_strchr(s + 2, *s) != NULL) {
// Remove the duplicated value and the next comma.
STRMOVE(s, s + 2);
s -= 2;
}
} else {
if ((!(flags & P_COMMA) || *s != ',')
&& vim_strchr(s + 1, *s) != NULL) {
STRMOVE(s, s + 1);
s--;
}
}
}
}
if (save_arg != NULL) /* number for 'whichwrap' */
arg = save_arg;
new_value_alloced = TRUE;
}
/* Set the new value. */
*(char_u **)(varp) = newval;
if (!starting && origval != NULL) {
// origval may be freed by
// did_set_string_option(), make a copy.
saved_origval = xstrdup((char *) origval);
}
/* Handle side effects, and set the global value for
* ":set" on local options. */
errmsg = did_set_string_option(opt_idx, (char_u **)varp,
new_value_alloced, oldval, errbuf, opt_flags);
// If error detected, print the error message.
if (errmsg != NULL) {
xfree(saved_origval);
goto skip;
}
if (saved_origval != NULL) {
char buf_type[7];
vim_snprintf(buf_type, ARRAY_SIZE(buf_type), "%s",
(opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, *(char **) varp, -1);
set_vim_var_string(VV_OPTION_OLD, saved_origval, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET,
(char_u *)options[opt_idx].fullname,
NULL, false, NULL);
reset_v_option_vars();
xfree(saved_origval);
}
} else {
// key code option(FIXME(tarruda): Show a warning or something
// similar)
}
}
if (opt_idx >= 0)
did_set_option(opt_idx, opt_flags,
!prepending && !adding && !removing);
}
skip:
/*
* Advance to next argument.
* - skip until a blank found, taking care of backslashes
* - skip blanks
* - skip one "=val" argument (for hidden options ":set gfn =xx")
*/
for (i = 0; i < 2; ++i) {
while (*arg != NUL && !ascii_iswhite(*arg))
if (*arg++ == '\\' && *arg != NUL)
++arg;
arg = skipwhite(arg);
if (*arg != '=')
break;
}
}
if (errmsg != NULL) {
STRLCPY(IObuff, _(errmsg), IOSIZE);
i = (int)STRLEN(IObuff) + 2;
if (i + (arg - startarg) < IOSIZE) {
/* append the argument with the error */
STRCAT(IObuff, ": ");
assert(arg >= startarg);
memmove(IObuff + i, startarg, (size_t)(arg - startarg));
IObuff[i + (arg - startarg)] = NUL;
}
/* make sure all characters are printable */
trans_characters(IObuff, IOSIZE);
++no_wait_return; /* wait_return done later */
emsg(IObuff); /* show error highlighted */
--no_wait_return;
return FAIL;
}
arg = skipwhite(arg);
}
theend:
if (silent_mode && did_show) {
/* After displaying option values in silent mode. */
silent_mode = FALSE;
info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
msg_putchar('\n');
ui_flush();
silent_mode = TRUE;
info_message = FALSE; /* use mch_msg(), not mch_errmsg() */
}
return OK;
}
/*
* Call this when an option has been given a new value through a user command.
* Sets the P_WAS_SET flag and takes care of the P_INSECURE flag.
*/
static void
did_set_option (
int opt_idx,
int opt_flags, /* possibly with OPT_MODELINE */
int new_value /* value was replaced completely */
)
{
options[opt_idx].flags |= P_WAS_SET;
/* When an option is set in the sandbox, from a modeline or in secure mode
* set the P_INSECURE flag. Otherwise, if a new value is stored reset the
* flag. */
uint32_t *p = insecure_flag(opt_idx, opt_flags);
if (secure
|| sandbox != 0
|| (opt_flags & OPT_MODELINE))
*p = *p | P_INSECURE;
else if (new_value)
*p = *p & ~P_INSECURE;
}
static char_u *illegal_char(char_u *errbuf, int c)
{
if (errbuf == NULL)
return (char_u *)"";
sprintf((char *)errbuf, _("E539: Illegal character <%s>"),
(char *)transchar(c));
return errbuf;
}
/*
* Convert a key name or string into a key value.
* Used for 'wildchar' and 'cedit' options.
*/
static int string_to_key(char_u *arg)
{
if (*arg == '<')
return find_key_option(arg + 1);
if (*arg == '^')
return Ctrl_chr(arg[1]);
return *arg;
}
/*
* Check value of 'cedit' and set cedit_key.
* Returns NULL if value is OK, error message otherwise.
*/
static char_u *check_cedit(void)
{
int n;
if (*p_cedit == NUL)
cedit_key = -1;
else {
n = string_to_key(p_cedit);
if (vim_isprintc(n))
return e_invarg;
cedit_key = n;
}
return NULL;
}
/*
* When changing 'title', 'titlestring', 'icon' or 'iconstring', call
* maketitle() to create and display it.
* When switching the title or icon off, call ui_set_{icon,title}(NULL) to get
* the old value back.
*/
static void
did_set_title (
int icon /* Did set icon instead of title */
)
{
if (starting != NO_SCREEN) {
maketitle();
if (icon) {
if (!p_icon) {
ui_set_icon(NULL);
}
} else {
if (!p_title) {
ui_set_title(NULL);
}
}
}
}
/*
* set_options_bin - called when 'bin' changes value.
*/
void
set_options_bin (
int oldval,
int newval,
int opt_flags /* OPT_LOCAL and/or OPT_GLOBAL */
)
{
/*
* The option values that are changed when 'bin' changes are
* copied when 'bin is set and restored when 'bin' is reset.
*/
if (newval) {
if (!oldval) { /* switched on */
if (!(opt_flags & OPT_GLOBAL)) {
curbuf->b_p_tw_nobin = curbuf->b_p_tw;
curbuf->b_p_wm_nobin = curbuf->b_p_wm;
curbuf->b_p_ml_nobin = curbuf->b_p_ml;
curbuf->b_p_et_nobin = curbuf->b_p_et;
}
if (!(opt_flags & OPT_LOCAL)) {
p_tw_nobin = p_tw;
p_wm_nobin = p_wm;
p_ml_nobin = p_ml;
p_et_nobin = p_et;
}
}
if (!(opt_flags & OPT_GLOBAL)) {
curbuf->b_p_tw = 0; /* no automatic line wrap */
curbuf->b_p_wm = 0; /* no automatic line wrap */
curbuf->b_p_ml = 0; /* no modelines */
curbuf->b_p_et = 0; /* no expandtab */
}
if (!(opt_flags & OPT_LOCAL)) {
p_tw = 0;
p_wm = 0;
p_ml = FALSE;
p_et = FALSE;
p_bin = TRUE; /* needed when called for the "-b" argument */
}
} else if (oldval) { /* switched off */
if (!(opt_flags & OPT_GLOBAL)) {
curbuf->b_p_tw = curbuf->b_p_tw_nobin;
curbuf->b_p_wm = curbuf->b_p_wm_nobin;
curbuf->b_p_ml = curbuf->b_p_ml_nobin;
curbuf->b_p_et = curbuf->b_p_et_nobin;
}
if (!(opt_flags & OPT_LOCAL)) {
p_tw = p_tw_nobin;
p_wm = p_wm_nobin;
p_ml = p_ml_nobin;
p_et = p_et_nobin;
}
}
}
/*
* Find the parameter represented by the given character (eg ', :, ", or /),
* and return its associated value in the 'shada' string.
* Only works for number parameters, not for 'r' or 'n'.
* If the parameter is not specified in the string or there is no following
* number, return -1.
*/
int get_shada_parameter(int type)
{
char_u *p;
p = find_shada_parameter(type);
if (p != NULL && ascii_isdigit(*p))
return atoi((char *)p);
return -1;
}
/*
* Find the parameter represented by the given character (eg ''', ':', '"', or
* '/') in the 'shada' option and return a pointer to the string after it.
* Return NULL if the parameter is not specified in the string.
*/
char_u *find_shada_parameter(int type)
{
char_u *p;
for (p = p_shada; *p; ++p) {
if (*p == type)
return p + 1;
if (*p == 'n') /* 'n' is always the last one */
break;
p = vim_strchr(p, ','); /* skip until next ',' */
if (p == NULL) /* hit the end without finding parameter */
break;
}
return NULL;
}
/*
* Expand environment variables for some string options.
* These string options cannot be indirect!
* If "val" is NULL expand the current value of the option.
* Return pointer to NameBuff, or NULL when not expanded.
*/
static char_u *option_expand(int opt_idx, char_u *val)
{
/* if option doesn't need expansion nothing to do */
if (!(options[opt_idx].flags & P_EXPAND) || options[opt_idx].var == NULL)
return NULL;
if (val == NULL) {
val = *(char_u **)options[opt_idx].var;
}
// If val is longer than MAXPATHL no meaningful expansion can be done,
// expand_env() would truncate the string.
if (val == NULL || STRLEN(val) > MAXPATHL) {
return NULL;
}
/*
* Expanding this with NameBuff, expand_env() must not be passed IObuff.
* Escape spaces when expanding 'tags', they are used to separate file
* names.
* For 'spellsuggest' expand after "file:".
*/
expand_env_esc(val, NameBuff, MAXPATHL,
(char_u **)options[opt_idx].var == &p_tags, FALSE,
(char_u **)options[opt_idx].var == &p_sps ? (char_u *)"file:" :
NULL);
if (STRCMP(NameBuff, val) == 0) /* they are the same */
return NULL;
return NameBuff;
}
/*
* After setting various option values: recompute variables that depend on
* option values.
*/
static void didset_options(void)
{
/* initialize the table for 'iskeyword' et.al. */
(void)init_chartab();
(void)opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, true);
(void)opt_strings_flags(p_bkc, p_bkc_values, &bkc_flags, true);
(void)opt_strings_flags(p_bo, p_bo_values, &bo_flags, true);
(void)opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, true);
(void)opt_strings_flags(p_vop, p_ssop_values, &vop_flags, true);
(void)opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true);
(void)opt_strings_flags(p_dy, p_dy_values, &dy_flags, true);
(void)opt_strings_flags(p_tc, p_tc_values, &tc_flags, false);
(void)opt_strings_flags(p_ve, p_ve_values, &ve_flags, true);
(void)spell_check_msm();
(void)spell_check_sps();
(void)compile_cap_prog(curwin->w_s);
(void)did_set_spell_option(true);
// set cedit_key
(void)check_cedit();
briopt_check(curwin);
// initialize the table for 'breakat'.
fill_breakat_flags();
}
// More side effects of setting options.
static void didset_options2(void)
{
// Initialize the highlight_attr[] table.
(void)highlight_changed();
// Parse default for 'clipboard'.
(void)opt_strings_flags(p_cb, p_cb_values, &cb_flags, true);
// Parse default for 'fillchars'.
(void)set_chars_option(&p_fcs);
// Parse default for 'listchars'.
(void)set_chars_option(&p_lcs);
// Parse default for 'wildmode'.
check_opt_wim();
}
/*
* Check for string options that are NULL (normally only termcap options).
*/
void check_options(void)
{
int opt_idx;
for (opt_idx = 0; options[opt_idx].fullname != NULL; opt_idx++)
if ((options[opt_idx].flags & P_STRING) && options[opt_idx].var != NULL)
check_string_option((char_u **)get_varp(&(options[opt_idx])));
}
/*
* Check string options in a buffer for NULL value.
*/
void check_buf_options(buf_T *buf)
{
check_string_option(&buf->b_p_bh);
check_string_option(&buf->b_p_bt);
check_string_option(&buf->b_p_fenc);
check_string_option(&buf->b_p_ff);
check_string_option(&buf->b_p_def);
check_string_option(&buf->b_p_inc);
check_string_option(&buf->b_p_inex);
check_string_option(&buf->b_p_inde);
check_string_option(&buf->b_p_indk);
check_string_option(&buf->b_p_fex);
check_string_option(&buf->b_p_kp);
check_string_option(&buf->b_p_mps);
check_string_option(&buf->b_p_fo);
check_string_option(&buf->b_p_flp);
check_string_option(&buf->b_p_isk);
check_string_option(&buf->b_p_com);
check_string_option(&buf->b_p_cms);
check_string_option(&buf->b_p_nf);
check_string_option(&buf->b_p_qe);
check_string_option(&buf->b_p_syn);
check_string_option(&buf->b_s.b_syn_isk);
check_string_option(&buf->b_s.b_p_spc);
check_string_option(&buf->b_s.b_p_spf);
check_string_option(&buf->b_s.b_p_spl);
check_string_option(&buf->b_p_sua);
check_string_option(&buf->b_p_cink);
check_string_option(&buf->b_p_cino);
parse_cino(buf);
check_string_option(&buf->b_p_ft);
check_string_option(&buf->b_p_cinw);
check_string_option(&buf->b_p_cpt);
check_string_option(&buf->b_p_cfu);
check_string_option(&buf->b_p_ofu);
check_string_option(&buf->b_p_keymap);
check_string_option(&buf->b_p_gp);
check_string_option(&buf->b_p_mp);
check_string_option(&buf->b_p_efm);
check_string_option(&buf->b_p_ep);
check_string_option(&buf->b_p_path);
check_string_option(&buf->b_p_tags);
check_string_option(&buf->b_p_tc);
check_string_option(&buf->b_p_dict);
check_string_option(&buf->b_p_tsr);
check_string_option(&buf->b_p_lw);
check_string_option(&buf->b_p_bkc);
}
/*
* Free the string allocated for an option.
* Checks for the string being empty_option. This may happen if we're out of
* memory, vim_strsave() returned NULL, which was replaced by empty_option by
* check_options().
* Does NOT check for P_ALLOCED flag!
*/
void free_string_option(char_u *p)
{
if (p != empty_option)
xfree(p);
}
void clear_string_option(char_u **pp)
{
if (*pp != empty_option)
xfree(*pp);
*pp = empty_option;
}
static void check_string_option(char_u **pp)
{
if (*pp == NULL)
*pp = empty_option;
}
/*
* Return TRUE when option "opt" was set from a modeline or in secure mode.
* Return FALSE when it wasn't.
* Return -1 for an unknown option.
*/
int was_set_insecurely(char_u *opt, int opt_flags)
{
int idx = findoption(opt);
if (idx >= 0) {
uint32_t *flagp = insecure_flag(idx, opt_flags);
return (*flagp & P_INSECURE) != 0;
}
EMSG2(_(e_intern2), "was_set_insecurely()");
return -1;
}
/*
* Get a pointer to the flags used for the P_INSECURE flag of option
* "opt_idx". For some local options a local flags field is used.
*/
static uint32_t *insecure_flag(int opt_idx, int opt_flags)
{
if (opt_flags & OPT_LOCAL)
switch ((int)options[opt_idx].indir) {
case PV_STL: return &curwin->w_p_stl_flags;
case PV_FDE: return &curwin->w_p_fde_flags;
case PV_FDT: return &curwin->w_p_fdt_flags;
case PV_INDE: return &curbuf->b_p_inde_flags;
case PV_FEX: return &curbuf->b_p_fex_flags;
case PV_INEX: return &curbuf->b_p_inex_flags;
}
/* Nothing special, return global flags field. */
return &options[opt_idx].flags;
}
/*
* Redraw the window title and/or tab page text later.
*/
static void redraw_titles(void) {
need_maketitle = TRUE;
redraw_tabline = TRUE;
}
static int shada_idx = -1;
/*
* Set a string option to a new value (without checking the effect).
* The string is copied into allocated memory.
* if ("opt_idx" == -1) "name" is used, otherwise "opt_idx" is used.
* When "set_sid" is zero set the scriptID to current_SID. When "set_sid" is
* SID_NONE don't set the scriptID. Otherwise set the scriptID to "set_sid".
*/
void
set_string_option_direct (
char_u *name,
int opt_idx,
char_u *val,
int opt_flags, /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */
int set_sid
)
{
char_u *s;
char_u **varp;
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
int idx = opt_idx;
if (idx == -1) { /* use name */
idx = findoption(name);
if (idx < 0) { /* not found (should not happen) */
EMSG2(_(e_intern2), "set_string_option_direct()");
EMSG2(_("For option %s"), name);
return;
}
}
if (options[idx].var == NULL) /* can't set hidden option */
return;
assert((void *) options[idx].var != (void *) &p_shada);
s = vim_strsave(val);
{
varp = (char_u **)get_varp_scope(&(options[idx]),
both ? OPT_LOCAL : opt_flags);
if ((opt_flags & OPT_FREE) && (options[idx].flags & P_ALLOCED))
free_string_option(*varp);
*varp = s;
/* For buffer/window local option may also set the global value. */
if (both)
set_string_option_global(idx, varp);
options[idx].flags |= P_ALLOCED;
/* When setting both values of a global option with a local value,
* make the local value empty, so that the global value is used. */
if (((int)options[idx].indir & PV_BOTH) && both) {
free_string_option(*varp);
*varp = empty_option;
}
if (set_sid != SID_NONE)
set_option_scriptID_idx(idx, opt_flags,
set_sid == 0 ? current_SID : set_sid);
}
}
/*
* Set global value for string option when it's a local option.
*/
static void
set_string_option_global (
int opt_idx, /* option index */
char_u **varp /* pointer to option variable */
)
{
char_u **p, *s;
/* the global value is always allocated */
if (options[opt_idx].var == VAR_WIN)
p = (char_u **)GLOBAL_WO(varp);
else
p = (char_u **)options[opt_idx].var;
if (options[opt_idx].indir != PV_NONE && p != varp) {
s = vim_strsave(*varp);
free_string_option(*p);
*p = s;
}
}
/// Set a string option to a new value, handling the effects
///
/// @param[in] opt_idx Option to set.
/// @param[in] value New value.
/// @param[in] opt_flags Option flags: expected to contain #OPT_LOCAL and/or
/// #OPT_GLOBAL.
///
/// @return NULL on success, error message on error.
static char *set_string_option(const int opt_idx, const char *const value,
const int opt_flags)
FUNC_ATTR_NONNULL_ARG(2) FUNC_ATTR_WARN_UNUSED_RESULT
{
if (options[opt_idx].var == NULL) { // don't set hidden option
return NULL;
}
char *const s = xstrdup(value);
char **const varp = (char **)get_varp_scope(
&(options[opt_idx]),
((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
? (((int)options[opt_idx].indir & PV_BOTH)
? OPT_GLOBAL : OPT_LOCAL)
: opt_flags));
char *const oldval = *varp;
*varp = s;
char *const saved_oldval = (starting ? NULL : xstrdup(oldval));
char *const r = (char *)did_set_string_option(
opt_idx, (char_u **)varp, (int)true, (char_u *)oldval, NULL, opt_flags);
if (r == NULL) {
did_set_option(opt_idx, opt_flags, true);
}
// call autocommand after handling side effects
if (saved_oldval != NULL) {
char buf_type[7];
vim_snprintf(buf_type, ARRAY_SIZE(buf_type), "%s",
(opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, (char *)(*varp), -1);
set_vim_var_string(VV_OPTION_OLD, saved_oldval, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET,
(char_u *)options[opt_idx].fullname,
NULL, false, NULL);
reset_v_option_vars();
xfree(saved_oldval);
}
return r;
}
/*
* Handle string options that need some action to perform when changed.
* Returns NULL for success, or an error message for an error.
*/
static char_u *
did_set_string_option (
int opt_idx, /* index in options[] table */
char_u **varp, /* pointer to the option variable */
int new_value_alloced, /* new value was allocated */
char_u *oldval, /* previous value of the option */
char_u *errbuf, /* buffer for errors, or NULL */
int opt_flags /* OPT_LOCAL and/or OPT_GLOBAL */
)
{
char_u *errmsg = NULL;
char_u *s, *p;
int did_chartab = FALSE;
char_u **gvarp;
bool free_oldval = (options[opt_idx].flags & P_ALLOCED);
/* Get the global option to compare with, otherwise we would have to check
* two values for all local options. */
gvarp = (char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL);
/* Disallow changing some options from secure mode */
if ((secure || sandbox != 0)
&& (options[opt_idx].flags & P_SECURE)) {
errmsg = e_secure;
}
/* Check for a "normal" file name in some options. Disallow a path
* separator (slash and/or backslash), wildcards and characters that are
* often illegal in a file name. */
else if ((options[opt_idx].flags & P_NFNAME)
&& vim_strpbrk(*varp, (char_u *)"/\\*?[|<>") != NULL) {
errmsg = e_invarg;
}
/* 'backupcopy' */
else if (gvarp == &p_bkc) {
char_u *bkc = p_bkc;
unsigned int *flags = &bkc_flags;
if (opt_flags & OPT_LOCAL) {
bkc = curbuf->b_p_bkc;
flags = &curbuf->b_bkc_flags;
}
if ((opt_flags & OPT_LOCAL) && *bkc == NUL) {
// make the local value empty: use the global value
*flags = 0;
} else {
if (opt_strings_flags(bkc, p_bkc_values, flags, true) != OK) {
errmsg = e_invarg;
}
if (((*flags & BKC_AUTO) != 0)
+ ((*flags & BKC_YES) != 0)
+ ((*flags & BKC_NO) != 0) != 1) {
// Must have exactly one of "auto", "yes" and "no".
(void)opt_strings_flags(oldval, p_bkc_values, flags, true);
errmsg = e_invarg;
}
}
}
/* 'backupext' and 'patchmode' */
else if (varp == &p_bex || varp == &p_pm) {
if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex,
*p_pm == '.' ? p_pm + 1 : p_pm) == 0)
errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal");
}
/* 'breakindentopt' */
else if (varp == &curwin->w_p_briopt) {
if (briopt_check(curwin) == FAIL)
errmsg = e_invarg;
} else if (varp == &p_isi
|| varp == &(curbuf->b_p_isk)
|| varp == &p_isp
|| varp == &p_isf) {
// 'isident', 'iskeyword', 'isprint or 'isfname' option: refill g_chartab[]
// If the new option is invalid, use old value. 'lisp' option: refill
// g_chartab[] for '-' char
if (init_chartab() == FAIL) {
did_chartab = TRUE; /* need to restore it below */
errmsg = e_invarg; /* error in value */
}
}
/* 'helpfile' */
else if (varp == &p_hf) {
/* May compute new values for $VIM and $VIMRUNTIME */
if (didset_vim) {
vim_setenv("VIM", "");
didset_vim = FALSE;
}
if (didset_vimruntime) {
vim_setenv("VIMRUNTIME", "");
didset_vimruntime = FALSE;
}
}
/* 'colorcolumn' */
else if (varp == &curwin->w_p_cc)
errmsg = check_colorcolumn(curwin);
/* 'helplang' */
else if (varp == &p_hlg) {
/* Check for "", "ab", "ab,cd", etc. */
for (s = p_hlg; *s != NUL; s += 3) {
if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL)) {
errmsg = e_invarg;
break;
}
if (s[2] == NUL)
break;
}
}
/* 'highlight' */
else if (varp == &p_hl) {
if (highlight_changed() == FAIL)
errmsg = e_invarg; /* invalid flags */
}
/* 'nrformats' */
else if (gvarp == &p_nf) {
if (check_opt_strings(*varp, p_nf_values, TRUE) != OK)
errmsg = e_invarg;
} else if (varp == &p_ssop) { // 'sessionoptions'
if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, true) != OK)
errmsg = e_invarg;
if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR)) {
/* Don't allow both "sesdir" and "curdir". */
(void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, true);
errmsg = e_invarg;
}
} else if (varp == &p_vop) { // 'viewoptions'
if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, true) != OK)
errmsg = e_invarg;
}
/* 'scrollopt' */
else if (varp == &p_sbo) {
if (check_opt_strings(p_sbo, p_scbopt_values, TRUE) != OK)
errmsg = e_invarg;
} else if (varp == &p_ambw || (int *)varp == &p_emoji) {
// 'ambiwidth'
if (check_opt_strings(p_ambw, p_ambw_values, false) != OK) {
errmsg = e_invarg;
} else if (set_chars_option(&p_lcs) != NULL) {
errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'");
} else if (set_chars_option(&p_fcs) != NULL) {
errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'");
}
}
/* 'background' */
else if (varp == &p_bg) {
if (check_opt_strings(p_bg, p_bg_values, FALSE) == OK) {
int dark = (*p_bg == 'd');
init_highlight(FALSE, FALSE);
if (dark != (*p_bg == 'd')
&& get_var_value((char_u *)"g:colors_name") != NULL) {
/* The color scheme must have set 'background' back to another
* value, that's not what we want here. Disable the color
* scheme and set the colors again. */
do_unlet((char_u *)"g:colors_name", TRUE);
free_string_option(p_bg);
p_bg = vim_strsave((char_u *)(dark ? "dark" : "light"));
check_string_option(&p_bg);
init_highlight(FALSE, FALSE);
}
} else
errmsg = e_invarg;
}
/* 'wildmode' */
else if (varp == &p_wim) {
if (check_opt_wim() == FAIL)
errmsg = e_invarg;
}
/* 'wildoptions' */
else if (varp == &p_wop) {
if (check_opt_strings(p_wop, p_wop_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'winaltkeys' */
else if (varp == &p_wak) {
if (*p_wak == NUL
|| check_opt_strings(p_wak, p_wak_values, FALSE) != OK)
errmsg = e_invarg;
}
/* 'eventignore' */
else if (varp == &p_ei) {
if (check_ei() == FAIL)
errmsg = e_invarg;
/* 'encoding' and 'fileencoding' */
} else if (varp == &p_enc || gvarp == &p_fenc) {
if (gvarp == &p_fenc) {
if (!MODIFIABLE(curbuf) && opt_flags != OPT_GLOBAL) {
errmsg = e_modifiable;
} else if (vim_strchr(*varp, ',') != NULL) {
// No comma allowed in 'fileencoding'; catches confusing it
// with 'fileencodings'.
errmsg = e_invarg;
} else {
// May show a "+" in the title now.
redraw_titles();
// Add 'fileencoding' to the swap file.
ml_setflags(curbuf);
}
}
if (errmsg == NULL) {
/* canonize the value, so that STRCMP() can be used on it */
p = enc_canonize(*varp);
xfree(*varp);
*varp = p;
if (varp == &p_enc) {
// only encoding=utf-8 allowed
if (STRCMP(p_enc, "utf-8") != 0) {
errmsg = e_invarg;
}
}
}
} else if (varp == &p_penc) {
/* Canonize printencoding if VIM standard one */
p = enc_canonize(p_penc);
xfree(p_penc);
p_penc = p;
} else if (varp == &curbuf->b_p_keymap) {
/* load or unload key mapping tables */
errmsg = keymap_init();
if (errmsg == NULL) {
if (*curbuf->b_p_keymap != NUL) {
/* Installed a new keymap, switch on using it. */
curbuf->b_p_iminsert = B_IMODE_LMAP;
if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT)
curbuf->b_p_imsearch = B_IMODE_LMAP;
} else {
/* Cleared the keymap, may reset 'iminsert' and 'imsearch'. */
if (curbuf->b_p_iminsert == B_IMODE_LMAP)
curbuf->b_p_iminsert = B_IMODE_NONE;
if (curbuf->b_p_imsearch == B_IMODE_LMAP)
curbuf->b_p_imsearch = B_IMODE_USE_INSERT;
}
if ((opt_flags & OPT_LOCAL) == 0) {
set_iminsert_global();
set_imsearch_global();
}
status_redraw_curbuf();
}
}
/* 'fileformat' */
else if (gvarp == &p_ff) {
if (!MODIFIABLE(curbuf) && !(opt_flags & OPT_GLOBAL))
errmsg = e_modifiable;
else if (check_opt_strings(*varp, p_ff_values, FALSE) != OK)
errmsg = e_invarg;
else {
redraw_titles();
/* update flag in swap file */
ml_setflags(curbuf);
/* Redraw needed when switching to/from "mac": a CR in the text
* will be displayed differently. */
if (get_fileformat(curbuf) == EOL_MAC || *oldval == 'm')
redraw_curbuf_later(NOT_VALID);
}
}
/* 'fileformats' */
else if (varp == &p_ffs) {
if (check_opt_strings(p_ffs, p_ff_values, TRUE) != OK) {
errmsg = e_invarg;
}
}
/* 'matchpairs' */
else if (gvarp == &p_mps) {
if (has_mbyte) {
for (p = *varp; *p != NUL; ++p) {
int x2 = -1;
int x3 = -1;
if (*p != NUL)
p += mb_ptr2len(p);
if (*p != NUL)
x2 = *p++;
if (*p != NUL) {
x3 = mb_ptr2char(p);
p += mb_ptr2len(p);
}
if (x2 != ':' || x3 == -1 || (*p != NUL && *p != ',')) {
errmsg = e_invarg;
break;
}
if (*p == NUL)
break;
}
} else {
/* Check for "x:y,x:y" */
for (p = *varp; *p != NUL; p += 4) {
if (p[1] != ':' || p[2] == NUL || (p[3] != NUL && p[3] != ',')) {
errmsg = e_invarg;
break;
}
if (p[3] == NUL)
break;
}
}
}
/* 'comments' */
else if (gvarp == &p_com) {
for (s = *varp; *s; ) {
while (*s && *s != ':') {
if (vim_strchr((char_u *)COM_ALL, *s) == NULL
&& !ascii_isdigit(*s) && *s != '-') {
errmsg = illegal_char(errbuf, *s);
break;
}
++s;
}
if (*s++ == NUL)
errmsg = (char_u *)N_("E524: Missing colon");
else if (*s == ',' || *s == NUL)
errmsg = (char_u *)N_("E525: Zero length string");
if (errmsg != NULL)
break;
while (*s && *s != ',') {
if (*s == '\\' && s[1] != NUL)
++s;
++s;
}
s = skip_to_option_part(s);
}
}
/* 'listchars' */
else if (varp == &p_lcs) {
errmsg = set_chars_option(varp);
}
/* 'fillchars' */
else if (varp == &p_fcs) {
errmsg = set_chars_option(varp);
}
/* 'cedit' */
else if (varp == &p_cedit) {
errmsg = check_cedit();
}
/* 'verbosefile' */
else if (varp == &p_vfile) {
verbose_stop();
if (*p_vfile != NUL && verbose_open() == FAIL)
errmsg = e_invarg;
/* 'shada' */
} else if (varp == &p_shada) {
// TODO(ZyX-I): Remove this code in the future, alongside with &viminfo
// option.
opt_idx = ((options[opt_idx].fullname[0] == 'v')
? (shada_idx == -1
? ((shada_idx = findoption((char_u *) "shada")))
: shada_idx)
: opt_idx);
for (s = p_shada; *s; ) {
/* Check it's a valid character */
if (vim_strchr((char_u *)"!\"%'/:<@cfhnrs", *s) == NULL) {
errmsg = illegal_char(errbuf, *s);
break;
}
if (*s == 'n') { /* name is always last one */
break;
} else if (*s == 'r') { /* skip until next ',' */
while (*++s && *s != ',')
;
} else if (*s == '%') {
/* optional number */
while (ascii_isdigit(*++s))
;
} else if (*s == '!' || *s == 'h' || *s == 'c')
++s; /* no extra chars */
else { /* must have a number */
while (ascii_isdigit(*++s))
;
if (!ascii_isdigit(*(s - 1))) {
if (errbuf != NULL) {
sprintf((char *)errbuf,
_("E526: Missing number after <%s>"),
transchar_byte(*(s - 1)));
errmsg = errbuf;
} else
errmsg = (char_u *)"";
break;
}
}
if (*s == ',')
++s;
else if (*s) {
if (errbuf != NULL)
errmsg = (char_u *)N_("E527: Missing comma");
else
errmsg = (char_u *)"";
break;
}
}
if (*p_shada && errmsg == NULL && get_shada_parameter('\'') < 0)
errmsg = (char_u *)N_("E528: Must specify a ' value");
}
/* 'showbreak' */
else if (varp == &p_sbr) {
for (s = p_sbr; *s; ) {
if (ptr2cells(s) != 1)
errmsg = (char_u *)N_("E595: contains unprintable or wide character");
mb_ptr_adv(s);
}
}
/* 'guicursor' */
else if (varp == &p_guicursor)
errmsg = parse_shape_opt(SHAPE_CURSOR);
else if (varp == &p_popt)
errmsg = parse_printoptions();
else if (varp == &p_pmfn)
errmsg = parse_printmbfont();
/* 'langmap' */
else if (varp == &p_langmap)
langmap_set();
/* 'breakat' */
else if (varp == &p_breakat)
fill_breakat_flags();
/* 'titlestring' and 'iconstring' */
else if (varp == &p_titlestring || varp == &p_iconstring) {
int flagval = (varp == &p_titlestring) ? STL_IN_TITLE : STL_IN_ICON;
/* NULL => statusline syntax */
if (vim_strchr(*varp, '%') && check_stl_option(*varp) == NULL)
stl_syntax |= flagval;
else
stl_syntax &= ~flagval;
did_set_title(varp == &p_iconstring);
}
/* 'selection' */
else if (varp == &p_sel) {
if (*p_sel == NUL
|| check_opt_strings(p_sel, p_sel_values, FALSE) != OK)
errmsg = e_invarg;
}
/* 'selectmode' */
else if (varp == &p_slm) {
if (check_opt_strings(p_slm, p_slm_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'keymodel' */
else if (varp == &p_km) {
if (check_opt_strings(p_km, p_km_values, TRUE) != OK)
errmsg = e_invarg;
else {
km_stopsel = (vim_strchr(p_km, 'o') != NULL);
km_startsel = (vim_strchr(p_km, 'a') != NULL);
}
}
/* 'mousemodel' */
else if (varp == &p_mousem) {
if (check_opt_strings(p_mousem, p_mousem_values, FALSE) != OK)
errmsg = e_invarg;
} else if (varp == &p_swb) { // 'switchbuf'
if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, true) != OK)
errmsg = e_invarg;
}
/* 'debug' */
else if (varp == &p_debug) {
if (check_opt_strings(p_debug, p_debug_values, TRUE) != OK)
errmsg = e_invarg;
} else if (varp == &p_dy) { // 'display'
if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, true) != OK)
errmsg = e_invarg;
else
(void)init_chartab();
}
/* 'eadirection' */
else if (varp == &p_ead) {
if (check_opt_strings(p_ead, p_ead_values, FALSE) != OK)
errmsg = e_invarg;
} else if (varp == &p_cb) { // 'clipboard'
if (opt_strings_flags(p_cb, p_cb_values, &cb_flags, true) != OK) {
errmsg = e_invarg;
}
} else if (varp == &(curwin->w_s->b_p_spl) // 'spell'
|| varp == &(curwin->w_s->b_p_spf)) {
// When 'spelllang' or 'spellfile' is set and there is a window for this
// buffer in which 'spell' is set load the wordlists.
errmsg = did_set_spell_option(varp == &(curwin->w_s->b_p_spf));
}
/* When 'spellcapcheck' is set compile the regexp program. */
else if (varp == &(curwin->w_s->b_p_spc)) {
errmsg = compile_cap_prog(curwin->w_s);
}
/* 'spellsuggest' */
else if (varp == &p_sps) {
if (spell_check_sps() != OK)
errmsg = e_invarg;
}
/* 'mkspellmem' */
else if (varp == &p_msm) {
if (spell_check_msm() != OK)
errmsg = e_invarg;
}
/* When 'bufhidden' is set, check for valid value. */
else if (gvarp == &p_bh) {
if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, FALSE) != OK)
errmsg = e_invarg;
}
/* When 'buftype' is set, check for valid value. */
else if (gvarp == &p_bt) {
if ((curbuf->terminal && curbuf->b_p_bt[0] != 't')
|| (!curbuf->terminal && curbuf->b_p_bt[0] == 't')
|| check_opt_strings(curbuf->b_p_bt, p_buftype_values, FALSE) != OK) {
errmsg = e_invarg;
} else {
if (curwin->w_status_height) {
curwin->w_redr_status = TRUE;
redraw_later(VALID);
}
curbuf->b_help = (curbuf->b_p_bt[0] == 'h');
redraw_titles();
}
}
/* 'statusline' or 'rulerformat' */
else if (gvarp == &p_stl || varp == &p_ruf) {
int wid;
if (varp == &p_ruf) /* reset ru_wid first */
ru_wid = 0;
s = *varp;
if (varp == &p_ruf && *s == '%') {
/* set ru_wid if 'ruf' starts with "%99(" */
if (*++s == '-') /* ignore a '-' */
s++;
wid = getdigits_int(&s);
if (wid && *s == '(' && (errmsg = check_stl_option(p_ruf)) == NULL)
ru_wid = wid;
else
errmsg = check_stl_option(p_ruf);
}
/* check 'statusline' only if it doesn't start with "%!" */
else if (varp == &p_ruf || s[0] != '%' || s[1] != '!')
errmsg = check_stl_option(s);
if (varp == &p_ruf && errmsg == NULL)
comp_col();
}
/* check if it is a valid value for 'complete' -- Acevedo */
else if (gvarp == &p_cpt) {
for (s = *varp; *s; ) {
while (*s == ',' || *s == ' ')
s++;
if (!*s)
break;
if (vim_strchr((char_u *)".wbuksid]tU", *s) == NULL) {
errmsg = illegal_char(errbuf, *s);
break;
}
if (*++s != NUL && *s != ',' && *s != ' ') {
if (s[-1] == 'k' || s[-1] == 's') {
/* skip optional filename after 'k' and 's' */
while (*s && *s != ',' && *s != ' ') {
if (*s == '\\')
++s;
++s;
}
} else {
if (errbuf != NULL) {
sprintf((char *)errbuf,
_("E535: Illegal character after <%c>"),
*--s);
errmsg = errbuf;
} else
errmsg = (char_u *)"";
break;
}
}
}
}
/* 'completeopt' */
else if (varp == &p_cot) {
if (check_opt_strings(p_cot, p_cot_values, true) != OK) {
errmsg = e_invarg;
} else {
completeopt_was_set();
}
}
/* 'pastetoggle': translate key codes like in a mapping */
else if (varp == &p_pt) {
if (*p_pt) {
(void)replace_termcodes(p_pt, STRLEN(p_pt), &p, true, true, false,
CPO_TO_CPO_FLAGS);
if (p != NULL) {
if (new_value_alloced)
free_string_option(p_pt);
p_pt = p;
new_value_alloced = TRUE;
}
}
}
/* 'backspace' */
else if (varp == &p_bs) {
if (ascii_isdigit(*p_bs)) {
if (*p_bs >'2' || p_bs[1] != NUL)
errmsg = e_invarg;
} else if (check_opt_strings(p_bs, p_bs_values, TRUE) != OK)
errmsg = e_invarg;
} else if (varp == &p_bo) {
if (opt_strings_flags(p_bo, p_bo_values, &bo_flags, true) != OK) {
errmsg = e_invarg;
}
} else if (gvarp == &p_tc) { // 'tagcase'
unsigned int *flags;
if (opt_flags & OPT_LOCAL) {
p = curbuf->b_p_tc;
flags = &curbuf->b_tc_flags;
} else {
p = p_tc;
flags = &tc_flags;
}
if ((opt_flags & OPT_LOCAL) && *p == NUL) {
// make the local value empty: use the global value
*flags = 0;
} else if (*p == NUL
|| opt_strings_flags(p, p_tc_values, flags, false) != OK) {
errmsg = e_invarg;
}
} else if (varp == &p_cmp) { // 'casemap'
if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, true) != OK)
errmsg = e_invarg;
}
/* 'diffopt' */
else if (varp == &p_dip) {
if (diffopt_changed() == FAIL)
errmsg = e_invarg;
}
/* 'foldmethod' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fdm) {
if (check_opt_strings(*varp, p_fdm_values, FALSE) != OK
|| *curwin->w_p_fdm == NUL)
errmsg = e_invarg;
else {
foldUpdateAll(curwin);
if (foldmethodIsDiff(curwin))
newFoldLevel();
}
}
/* 'foldexpr' */
else if (varp == &curwin->w_p_fde) {
if (foldmethodIsExpr(curwin))
foldUpdateAll(curwin);
}
/* 'foldmarker' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fmr) {
p = vim_strchr(*varp, ',');
if (p == NULL)
errmsg = (char_u *)N_("E536: comma required");
else if (p == *varp || p[1] == NUL)
errmsg = e_invarg;
else if (foldmethodIsMarker(curwin))
foldUpdateAll(curwin);
}
/* 'commentstring' */
else if (gvarp == &p_cms) {
if (**varp != NUL && strstr((char *)*varp, "%s") == NULL)
errmsg = (char_u *)N_(
"E537: 'commentstring' must be empty or contain %s");
} else if (varp == &p_fdo) { // 'foldopen'
if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true) != OK)
errmsg = e_invarg;
}
/* 'foldclose' */
else if (varp == &p_fcl) {
if (check_opt_strings(p_fcl, p_fcl_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'foldignore' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fdi) {
if (foldmethodIsIndent(curwin))
foldUpdateAll(curwin);
} else if (varp == &p_ve) { // 'virtualedit'
if (opt_strings_flags(p_ve, p_ve_values, &ve_flags, true) != OK)
errmsg = e_invarg;
else if (STRCMP(p_ve, oldval) != 0) {
/* Recompute cursor position in case the new 've' setting
* changes something. */
validate_virtcol();
coladvance(curwin->w_virtcol);
}
} else if (varp == &p_csqf) {
if (p_csqf != NULL) {
p = p_csqf;
while (*p != NUL) {
if (vim_strchr((char_u *)CSQF_CMDS, *p) == NULL
|| p[1] == NUL
|| vim_strchr((char_u *)CSQF_FLAGS, p[1]) == NULL
|| (p[2] != NUL && p[2] != ',')) {
errmsg = e_invarg;
break;
} else if (p[2] == NUL)
break;
else
p += 3;
}
}
}
/* 'cinoptions' */
else if (gvarp == &p_cino) {
/* TODO: recognize errors */
parse_cino(curbuf);
// inccommand
} else if (varp == &p_icm) {
if (check_opt_strings(p_icm, p_icm_values, false) != OK) {
errmsg = e_invarg;
}
// Options that are a list of flags.
} else {
p = NULL;
if (varp == &p_ww)
p = (char_u *)WW_ALL;
if (varp == &p_shm)
p = (char_u *)SHM_ALL;
else if (varp == &(p_cpo))
p = (char_u *)CPO_VI;
else if (varp == &(curbuf->b_p_fo))
p = (char_u *)FO_ALL;
else if (varp == &curwin->w_p_cocu)
p = (char_u *)COCU_ALL;
else if (varp == &p_mouse) {
p = (char_u *)MOUSE_ALL;
}
if (p != NULL) {
for (s = *varp; *s; ++s)
if (vim_strchr(p, *s) == NULL) {
errmsg = illegal_char(errbuf, *s);
break;
}
}
}
/*
* If error detected, restore the previous value.
*/
if (errmsg != NULL) {
if (new_value_alloced)
free_string_option(*varp);
*varp = oldval;
/*
* When resetting some values, need to act on it.
*/
if (did_chartab)
(void)init_chartab();
if (varp == &p_hl)
(void)highlight_changed();
} else {
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
/*
* Free string options that are in allocated memory.
* Use "free_oldval", because recursiveness may change the flags under
* our fingers (esp. init_highlight()).
*/
if (free_oldval)
free_string_option(oldval);
if (new_value_alloced)
options[opt_idx].flags |= P_ALLOCED;
else
options[opt_idx].flags &= ~P_ALLOCED;
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
&& ((int)options[opt_idx].indir & PV_BOTH)) {
/* global option with local value set to use global value; free
* the local value and make it empty */
p = get_varp_scope(&(options[opt_idx]), OPT_LOCAL);
free_string_option(*(char_u **)p);
*(char_u **)p = empty_option;
}
/* May set global value for local option. */
else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL)
set_string_option_global(opt_idx, varp);
/*
* Trigger the autocommand only after setting the flags.
*/
/* When 'syntax' is set, load the syntax of that name */
if (varp == &(curbuf->b_p_syn)) {
apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn,
curbuf->b_fname, TRUE, curbuf);
} else if (varp == &(curbuf->b_p_ft)) {
/* 'filetype' is set, trigger the FileType autocommand */
did_filetype = TRUE;
apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft,
curbuf->b_fname, TRUE, curbuf);
}
if (varp == &(curwin->w_s->b_p_spl)) {
char_u fname[200];
char_u *q = curwin->w_s->b_p_spl;
/* Skip the first name if it is "cjk". */
if (STRNCMP(q, "cjk,", 4) == 0)
q += 4;
/*
* Source the spell/LANG.vim in 'runtimepath'.
* They could set 'spellcapcheck' depending on the language.
* Use the first name in 'spelllang' up to '_region' or
* '.encoding'.
*/
for (p = q; *p != NUL; ++p)
if (vim_strchr((char_u *)"_.,", *p) != NULL)
break;
vim_snprintf((char *)fname, sizeof(fname), "spell/%.*s.vim",
(int)(p - q), q);
source_runtime(fname, DIP_ALL);
}
}
if (varp == &p_mouse) {
if (*p_mouse == NUL) {
ui_mouse_off();
} else {
setmouse(); // in case 'mouse' changed
}
}
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
check_redraw(options[opt_idx].flags);
return errmsg;
}
/*
* Simple int comparison function for use with qsort()
*/
static int int_cmp(const void *a, const void *b)
{
return *(const int *)a - *(const int *)b;
}
/*
* Handle setting 'colorcolumn' or 'textwidth' in window "wp".
* Returns error message, NULL if it's OK.
*/
char_u *check_colorcolumn(win_T *wp)
{
char_u *s;
int col;
unsigned int count = 0;
int color_cols[256];
int j = 0;
if (wp->w_buffer == NULL)
return NULL; /* buffer was closed */
for (s = wp->w_p_cc; *s != NUL && count < 255; ) {
if (*s == '-' || *s == '+') {
/* -N and +N: add to 'textwidth' */
col = (*s == '-') ? -1 : 1;
++s;
if (!ascii_isdigit(*s))
return e_invarg;
col = col * getdigits_int(&s);
if (wp->w_buffer->b_p_tw == 0)
goto skip; /* 'textwidth' not set, skip this item */
assert((col >= 0
&& wp->w_buffer->b_p_tw <= INT_MAX - col
&& wp->w_buffer->b_p_tw + col >= INT_MIN)
|| (col < 0
&& wp->w_buffer->b_p_tw >= INT_MIN - col
&& wp->w_buffer->b_p_tw + col <= INT_MAX));
col += (int)wp->w_buffer->b_p_tw;
if (col < 0)
goto skip;
} else if (ascii_isdigit(*s))
col = getdigits_int(&s);
else
return e_invarg;
color_cols[count++] = col - 1; /* 1-based to 0-based */
skip:
if (*s == NUL)
break;
if (*s != ',')
return e_invarg;
if (*++s == NUL)
return e_invarg; /* illegal trailing comma as in "set cc=80," */
}
xfree(wp->w_p_cc_cols);
if (count == 0)
wp->w_p_cc_cols = NULL;
else {
wp->w_p_cc_cols = xmalloc(sizeof(int) * (count + 1));
/* sort the columns for faster usage on screen redraw inside
* win_line() */
qsort(color_cols, count, sizeof(int), int_cmp);
for (unsigned int i = 0; i < count; ++i)
/* skip duplicates */
if (j == 0 || wp->w_p_cc_cols[j - 1] != color_cols[i])
wp->w_p_cc_cols[j++] = color_cols[i];
wp->w_p_cc_cols[j] = -1; /* end marker */
}
return NULL; /* no error */
}
/*
* Handle setting 'listchars' or 'fillchars'.
* Returns error message, NULL if it's OK.
*/
static char_u *set_chars_option(char_u **varp)
{
int round, i, len, entries;
char_u *p, *s;
int c1, c2 = 0;
struct charstab {
int *cp;
char *name;
};
static struct charstab filltab[] =
{
{&fill_stl, "stl"},
{&fill_stlnc, "stlnc"},
{&fill_vert, "vert"},
{&fill_fold, "fold"},
{&fill_diff, "diff"},
};
static struct charstab lcstab[] =
{
{&lcs_eol, "eol"},
{&lcs_ext, "extends"},
{&lcs_nbsp, "nbsp"},
{&lcs_prec, "precedes"},
{&lcs_space, "space"},
{&lcs_tab2, "tab"},
{&lcs_trail, "trail"},
{&lcs_conceal, "conceal"},
};
struct charstab *tab;
if (varp == &p_lcs) {
tab = lcstab;
entries = ARRAY_SIZE(lcstab);
} else {
tab = filltab;
entries = ARRAY_SIZE(filltab);
}
/* first round: check for valid value, second round: assign values */
for (round = 0; round <= 1; ++round) {
if (round > 0) {
/* After checking that the value is valid: set defaults: space for
* 'fillchars', NUL for 'listchars' */
for (i = 0; i < entries; ++i)
if (tab[i].cp != NULL)
*(tab[i].cp) = (varp == &p_lcs ? NUL : ' ');
if (varp == &p_lcs)
lcs_tab1 = NUL;
else
fill_diff = '-';
}
p = *varp;
while (*p) {
for (i = 0; i < entries; ++i) {
len = (int)STRLEN(tab[i].name);
if (STRNCMP(p, tab[i].name, len) == 0
&& p[len] == ':'
&& p[len + 1] != NUL) {
s = p + len + 1;
c1 = mb_ptr2char_adv(&s);
if (mb_char2cells(c1) > 1)
continue;
if (tab[i].cp == &lcs_tab2) {
if (*s == NUL)
continue;
c2 = mb_ptr2char_adv(&s);
if (mb_char2cells(c2) > 1)
continue;
}
if (*s == ',' || *s == NUL) {
if (round) {
if (tab[i].cp == &lcs_tab2) {
lcs_tab1 = c1;
lcs_tab2 = c2;
} else if (tab[i].cp != NULL)
*(tab[i].cp) = c1;
}
p = s;
break;
}
}
}
if (i == entries)
return e_invarg;
if (*p == ',')
++p;
}
}
return NULL; /* no error */
}
/*
* Check validity of options with the 'statusline' format.
* Return error message or NULL.
*/
char_u *check_stl_option(char_u *s)
{
int itemcnt = 0;
int groupdepth = 0;
static char_u errbuf[80];
while (*s && itemcnt < STL_MAX_ITEM) {
/* Check for valid keys after % sequences */
while (*s && *s != '%')
s++;
if (!*s)
break;
s++;
if (*s != '%' && *s != ')') {
itemcnt++;
}
if (*s == '%' || *s == STL_TRUNCMARK || *s == STL_SEPARATE) {
s++;
continue;
}
if (*s == ')') {
s++;
if (--groupdepth < 0)
break;
continue;
}
if (*s == '-')
s++;
while (ascii_isdigit(*s))
s++;
if (*s == STL_USER_HL)
continue;
if (*s == '.') {
s++;
while (*s && ascii_isdigit(*s))
s++;
}
if (*s == '(') {
groupdepth++;
continue;
}
if (vim_strchr(STL_ALL, *s) == NULL) {
return illegal_char(errbuf, *s);
}
if (*s == '{') {
s++;
while (*s != '}' && *s)
s++;
if (*s != '}')
return (char_u *)N_("E540: Unclosed expression sequence");
}
}
if (itemcnt >= STL_MAX_ITEM)
return (char_u *)N_("E541: too many items");
if (groupdepth != 0)
return (char_u *)N_("E542: unbalanced groups");
return NULL;
}
static char_u *did_set_spell_option(bool is_spellfile)
{
char_u *errmsg = NULL;
if (is_spellfile) {
int l = (int)STRLEN(curwin->w_s->b_p_spf);
if (l > 0
&& (l < 4 || STRCMP(curwin->w_s->b_p_spf + l - 4, ".add") != 0)) {
errmsg = e_invarg;
}
}
if (errmsg == NULL) {
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (wp->w_buffer == curbuf && wp->w_p_spell) {
errmsg = did_set_spelllang(wp);
break;
}
}
}
return errmsg;
}
/*
* Set curbuf->b_cap_prog to the regexp program for 'spellcapcheck'.
* Return error message when failed, NULL when OK.
*/
static char_u *compile_cap_prog(synblock_T *synblock)
{
regprog_T *rp = synblock->b_cap_prog;
char_u *re;
if (*synblock->b_p_spc == NUL)
synblock->b_cap_prog = NULL;
else {
/* Prepend a ^ so that we only match at one column */
re = concat_str((char_u *)"^", synblock->b_p_spc);
synblock->b_cap_prog = vim_regcomp(re, RE_MAGIC);
xfree(re);
if (synblock->b_cap_prog == NULL) {
synblock->b_cap_prog = rp; /* restore the previous program */
return e_invarg;
}
}
vim_regfree(rp);
return NULL;
}
/*
* Set the scriptID for an option, taking care of setting the buffer- or
* window-local value.
*/
static void set_option_scriptID_idx(int opt_idx, int opt_flags, int id)
{
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
int indir = (int)options[opt_idx].indir;
/* Remember where the option was set. For local options need to do that
* in the buffer or window structure. */
if (both || (opt_flags & OPT_GLOBAL) || (indir & (PV_BUF|PV_WIN)) == 0)
options[opt_idx].scriptID = id;
if (both || (opt_flags & OPT_LOCAL)) {
if (indir & PV_BUF)
curbuf->b_p_scriptID[indir & PV_MASK] = id;
else if (indir & PV_WIN)
curwin->w_p_scriptID[indir & PV_MASK] = id;
}
}
/*
* Set the value of a boolean option, and take care of side effects.
* Returns NULL for success, or an error message for an error.
*/
static char_u *
set_bool_option (
int opt_idx, /* index in options[] table */
char_u *varp, /* pointer to the option variable */
int value, /* new value */
int opt_flags /* OPT_LOCAL and/or OPT_GLOBAL */
)
{
int old_value = *(int *)varp;
/* Disallow changing some options from secure mode */
if ((secure || sandbox != 0)
&& (options[opt_idx].flags & P_SECURE)) {
return e_secure;
}
*(int *)varp = value; /* set the new value */
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
/* May set global value for local option. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0)
*(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = value;
// Ensure that options set to p_force_on cannot be disabled.
if ((int *)varp == &p_force_on && p_force_on == FALSE) {
p_force_on = TRUE;
return e_unsupportedoption;
}
// Ensure that options set to p_force_off cannot be enabled.
else if ((int *)varp == &p_force_off && p_force_off == TRUE) {
p_force_off = FALSE;
return e_unsupportedoption;
}
/* 'undofile' */
else if ((int *)varp == &curbuf->b_p_udf || (int *)varp == &p_udf) {
/* Only take action when the option was set. When reset we do not
* delete the undo file, the option may be set again without making
* any changes in between. */
if (curbuf->b_p_udf || p_udf) {
char_u hash[UNDO_HASH_SIZE];
buf_T *save_curbuf = curbuf;
for (curbuf = firstbuf; curbuf != NULL; curbuf = curbuf->b_next) {
/* When 'undofile' is set globally: for every buffer, otherwise
* only for the current buffer: Try to read in the undofile,
* if one exists, the buffer wasn't changed and the buffer was
* loaded */
if ((curbuf == save_curbuf
|| (opt_flags & OPT_GLOBAL) || opt_flags == 0)
&& !curbufIsChanged() && curbuf->b_ml.ml_mfp != NULL) {
u_compute_hash(hash);
u_read_undo(NULL, hash, curbuf->b_fname);
}
}
curbuf = save_curbuf;
}
} else if ((int *)varp == &curbuf->b_p_ro) {
/* when 'readonly' is reset globally, also reset readonlymode */
if (!curbuf->b_p_ro && (opt_flags & OPT_LOCAL) == 0)
readonlymode = FALSE;
/* when 'readonly' is set may give W10 again */
if (curbuf->b_p_ro)
curbuf->b_did_warn = false;
redraw_titles();
}
/* when 'modifiable' is changed, redraw the window title */
else if ((int *)varp == &curbuf->b_p_ma) {
redraw_titles();
}
/* when 'endofline' is changed, redraw the window title */
else if ((int *)varp == &curbuf->b_p_eol) {
redraw_titles();
} else if ((int *)varp == &curbuf->b_p_fixeol) {
// when 'fixeol' is changed, redraw the window title
redraw_titles();
}
/* when 'bomb' is changed, redraw the window title and tab page text */
else if ((int *)varp == &curbuf->b_p_bomb) {
redraw_titles();
}
/* when 'bin' is set also set some other options */
else if ((int *)varp == &curbuf->b_p_bin) {
set_options_bin(old_value, curbuf->b_p_bin, opt_flags);
redraw_titles();
}
/* when 'buflisted' changes, trigger autocommands */
else if ((int *)varp == &curbuf->b_p_bl && old_value != curbuf->b_p_bl) {
apply_autocmds(curbuf->b_p_bl ? EVENT_BUFADD : EVENT_BUFDELETE,
NULL, NULL, TRUE, curbuf);
}
/* when 'swf' is set, create swapfile, when reset remove swapfile */
else if ((int *)varp == (int *)&curbuf->b_p_swf) {
if (curbuf->b_p_swf && p_uc)
ml_open_file(curbuf); /* create the swap file */
else
/* no need to reset curbuf->b_may_swap, ml_open_file() will check
* buf->b_p_swf */
mf_close_file(curbuf, true); /* remove the swap file */
}
/* when 'terse' is set change 'shortmess' */
else if ((int *)varp == &p_terse) {
char_u *p;
p = vim_strchr(p_shm, SHM_SEARCH);
/* insert 's' in p_shm */
if (p_terse && p == NULL) {
STRCPY(IObuff, p_shm);
STRCAT(IObuff, "s");
set_string_option_direct((char_u *)"shm", -1, IObuff, OPT_FREE, 0);
}
/* remove 's' from p_shm */
else if (!p_terse && p != NULL)
STRMOVE(p, p + 1);
}
/* when 'paste' is set or reset also change other options */
else if ((int *)varp == &p_paste) {
paste_option_changed();
}
/* when 'insertmode' is set from an autocommand need to do work here */
else if ((int *)varp == &p_im) {
if (p_im) {
if ((State & INSERT) == 0) {
need_start_insertmode = true;
}
stop_insert_mode = false;
} else if (old_value) { // only reset if it was set previously
need_start_insertmode = false;
stop_insert_mode = true;
if (restart_edit != 0 && mode_displayed) {
clear_cmdline = true; // remove "(insert)"
}
restart_edit = 0;
}
}
/* when 'ignorecase' is set or reset and 'hlsearch' is set, redraw */
else if ((int *)varp == &p_ic && p_hls) {
redraw_all_later(SOME_VALID);
}
/* when 'hlsearch' is set or reset: reset no_hlsearch */
else if ((int *)varp == &p_hls) {
SET_NO_HLSEARCH(FALSE);
}
/* when 'scrollbind' is set: snapshot the current position to avoid a jump
* at the end of normal_cmd() */
else if ((int *)varp == &curwin->w_p_scb) {
if (curwin->w_p_scb) {
do_check_scrollbind(FALSE);
curwin->w_scbind_pos = curwin->w_topline;
}
}
/* There can be only one window with 'previewwindow' set. */
else if ((int *)varp == &curwin->w_p_pvw) {
if (curwin->w_p_pvw) {
FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
if (win->w_p_pvw && win != curwin) {
curwin->w_p_pvw = FALSE;
return (char_u *)N_("E590: A preview window already exists");
}
}
}
} else if (varp == (char_u *)&(curbuf->b_p_lisp)) {
// When 'lisp' option changes include/exclude '-' in
// keyword characters.
(void)buf_init_chartab(curbuf, false); // ignore errors
} else if ((int *)varp == &p_title) {
// when 'title' changed, may need to change the title; same for 'icon'
did_set_title(false);
} else if ((int *)varp == &p_icon) {
did_set_title(true);
} else if ((int *)varp == &curbuf->b_changed) {
if (!value) {
save_file_ff(curbuf); // Buffer is unchanged
}
redraw_titles();
modified_was_set = value;
}
#ifdef BACKSLASH_IN_FILENAME
else if ((int *)varp == &p_ssl) {
if (p_ssl) {
psepc = '/';
psepcN = '\\';
pseps[0] = '/';
} else {
psepc = '\\';
psepcN = '/';
pseps[0] = '\\';
}
/* need to adjust the file name arguments and buffer names. */
buflist_slash_adjust();
alist_slash_adjust();
scriptnames_slash_adjust();
}
#endif
/* If 'wrap' is set, set w_leftcol to zero. */
else if ((int *)varp == &curwin->w_p_wrap) {
if (curwin->w_p_wrap)
curwin->w_leftcol = 0;
} else if ((int *)varp == &p_ea) {
if (p_ea && !old_value) {
win_equal(curwin, false, 0);
}
} else if ((int *)varp == &p_acd) {
// Change directories when the 'acd' option is set now.
do_autochdir();
}
/* 'diff' */
else if ((int *)varp == &curwin->w_p_diff) {
/* May add or remove the buffer from the list of diff buffers. */
diff_buf_adjust(curwin);
if (foldmethodIsDiff(curwin))
foldUpdateAll(curwin);
}
/* 'spell' */
else if ((int *)varp == &curwin->w_p_spell) {
if (curwin->w_p_spell) {
char_u *errmsg = did_set_spelllang(curwin);
if (errmsg != NULL)
EMSG(_(errmsg));
}
} else if ((int *)varp == &p_altkeymap) {
if (old_value != p_altkeymap) {
if (!p_altkeymap) {
p_hkmap = p_fkmap;
p_fkmap = 0;
} else {
p_fkmap = p_hkmap;
p_hkmap = 0;
}
(void)init_chartab();
}
}
/*
* In case some second language keymapping options have changed, check
* and correct the setting in a consistent way.
*/
/*
* If hkmap or fkmap are set, reset Arabic keymapping.
*/
if ((p_hkmap || p_fkmap) && p_altkeymap) {
p_altkeymap = p_fkmap;
curwin->w_p_arab = FALSE;
(void)init_chartab();
}
/*
* If hkmap set, reset Farsi keymapping.
*/
if (p_hkmap && p_altkeymap) {
p_altkeymap = 0;
p_fkmap = 0;
curwin->w_p_arab = FALSE;
(void)init_chartab();
}
/*
* If fkmap set, reset Hebrew keymapping.
*/
if (p_fkmap && !p_altkeymap) {
p_altkeymap = 1;
p_hkmap = 0;
curwin->w_p_arab = FALSE;
(void)init_chartab();
}
if ((int *)varp == &curwin->w_p_arab) {
if (curwin->w_p_arab) {
/*
* 'arabic' is set, handle various sub-settings.
*/
if (!p_tbidi) {
/* set rightleft mode */
if (!curwin->w_p_rl) {
curwin->w_p_rl = TRUE;
changed_window_setting();
}
/* Enable Arabic shaping (major part of what Arabic requires) */
if (!p_arshape) {
p_arshape = TRUE;
redraw_later_clear();
}
}
/* Arabic requires a utf-8 encoding, inform the user if its not
* set. */
if (STRCMP(p_enc, "utf-8") != 0) {
static char *w_arabic = N_(
"W17: Arabic requires UTF-8, do ':set encoding=utf-8'");
msg_source(hl_attr(HLF_W));
MSG_ATTR(_(w_arabic), hl_attr(HLF_W));
set_vim_var_string(VV_WARNINGMSG, _(w_arabic), -1);
}
/* set 'delcombine' */
p_deco = TRUE;
/* Force-set the necessary keymap for arabic */
set_option_value((char_u *)"keymap", 0L, (char_u *)"arabic",
OPT_LOCAL);
p_altkeymap = 0;
p_hkmap = 0;
p_fkmap = 0;
(void)init_chartab();
} else {
/*
* 'arabic' is reset, handle various sub-settings.
*/
if (!p_tbidi) {
/* reset rightleft mode */
if (curwin->w_p_rl) {
curwin->w_p_rl = FALSE;
changed_window_setting();
}
/* 'arabicshape' isn't reset, it is a global option and
* another window may still need it "on". */
}
/* 'delcombine' isn't reset, it is a global option and another
* window may still want it "on". */
/* Revert to the default keymap */
curbuf->b_p_iminsert = B_IMODE_NONE;
curbuf->b_p_imsearch = B_IMODE_USE_INSERT;
}
}
/*
* End of handling side effects for bool options.
*/
// after handling side effects, call autocommand
options[opt_idx].flags |= P_WAS_SET;
if (!starting) {
char buf_old[2];
char buf_new[2];
char buf_type[7];
vim_snprintf(buf_old, ARRAY_SIZE(buf_old), "%d",
old_value ? true: false);
vim_snprintf(buf_new, ARRAY_SIZE(buf_new), "%d",
value ? true: false);
vim_snprintf(buf_type, ARRAY_SIZE(buf_type), "%s",
(opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, buf_new, -1);
set_vim_var_string(VV_OPTION_OLD, buf_old, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET,
(char_u *) options[opt_idx].fullname,
NULL, false, NULL);
reset_v_option_vars();
}
comp_col(); /* in case 'ruler' or 'showcmd' changed */
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
check_redraw(options[opt_idx].flags);
return NULL;
}
/*
* Set the value of a number option, and take care of side effects.
* Returns NULL for success, or an error message for an error.
*/
static char_u *
set_num_option (
int opt_idx, /* index in options[] table */
char_u *varp, /* pointer to the option variable */
long value, /* new value */
char_u *errbuf, /* buffer for error messages */
size_t errbuflen, /* length of "errbuf" */
int opt_flags /* OPT_LOCAL, OPT_GLOBAL and
OPT_MODELINE */
)
{
char_u *errmsg = NULL;
long old_value = *(long *)varp;
long old_Rows = Rows; /* remember old Rows */
long old_Columns = Columns; /* remember old Columns */
long *pp = (long *)varp;
/* Disallow changing some options from secure mode. */
if ((secure || sandbox != 0)
&& (options[opt_idx].flags & P_SECURE)) {
return e_secure;
}
*pp = value;
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
if (curbuf->b_p_sw < 0) {
errmsg = e_positive;
curbuf->b_p_sw = curbuf->b_p_ts;
}
/*
* Number options that need some action when changed
*/
if (pp == &p_wh || pp == &p_hh) {
if (p_wh < 1) {
errmsg = e_positive;
p_wh = 1;
}
if (p_wmh > p_wh) {
errmsg = e_winheight;
p_wh = p_wmh;
}
if (p_hh < 0) {
errmsg = e_positive;
p_hh = 0;
}
/* Change window height NOW */
if (lastwin != firstwin) {
if (pp == &p_wh && curwin->w_height < p_wh)
win_setheight((int)p_wh);
if (pp == &p_hh && curbuf->b_help && curwin->w_height < p_hh)
win_setheight((int)p_hh);
}
}
/* 'winminheight' */
else if (pp == &p_wmh) {
if (p_wmh < 0) {
errmsg = e_positive;
p_wmh = 0;
}
if (p_wmh > p_wh) {
errmsg = e_winheight;
p_wmh = p_wh;
}
win_setminheight();
} else if (pp == &p_wiw) {
if (p_wiw < 1) {
errmsg = e_positive;
p_wiw = 1;
}
if (p_wmw > p_wiw) {
errmsg = e_winwidth;
p_wiw = p_wmw;
}
/* Change window width NOW */
if (lastwin != firstwin && curwin->w_width < p_wiw)
win_setwidth((int)p_wiw);
}
/* 'winminwidth' */
else if (pp == &p_wmw) {
if (p_wmw < 0) {
errmsg = e_positive;
p_wmw = 0;
}
if (p_wmw > p_wiw) {
errmsg = e_winwidth;
p_wmw = p_wiw;
}
win_setminheight();
} else if (pp == &p_ls) {
/* (re)set last window status line */
last_status(false);
}
/* (re)set tab page line */
else if (pp == &p_stal) {
shell_new_rows(); /* recompute window positions and heights */
}
/* 'foldlevel' */
else if (pp == &curwin->w_p_fdl) {
if (curwin->w_p_fdl < 0)
curwin->w_p_fdl = 0;
newFoldLevel();
}
/* 'foldminlines' */
else if (pp == &curwin->w_p_fml) {
foldUpdateAll(curwin);
}
/* 'foldnestmax' */
else if (pp == &curwin->w_p_fdn) {
if (foldmethodIsSyntax(curwin) || foldmethodIsIndent(curwin))
foldUpdateAll(curwin);
}
/* 'foldcolumn' */
else if (pp == &curwin->w_p_fdc) {
if (curwin->w_p_fdc < 0) {
errmsg = e_positive;
curwin->w_p_fdc = 0;
} else if (curwin->w_p_fdc > 12) {
errmsg = e_invarg;
curwin->w_p_fdc = 12;
}
// 'shiftwidth' or 'tabstop'
} else if (pp == &curbuf->b_p_sw || pp == (long *)&curbuf->b_p_ts) {
if (foldmethodIsIndent(curwin)) {
foldUpdateAll(curwin);
}
// When 'shiftwidth' changes, or it's zero and 'tabstop' changes:
// parse 'cinoptions'.
if (pp == &curbuf->b_p_sw || curbuf->b_p_sw == 0) {
parse_cino(curbuf);
}
}
/* 'maxcombine' */
else if (pp == &p_mco) {
if (p_mco > MAX_MCO)
p_mco = MAX_MCO;
else if (p_mco < 0)
p_mco = 0;
screenclear(); /* will re-allocate the screen */
} else if (pp == &curbuf->b_p_iminsert) {
if (curbuf->b_p_iminsert < 0 || curbuf->b_p_iminsert > B_IMODE_LAST) {
errmsg = e_invarg;
curbuf->b_p_iminsert = B_IMODE_NONE;
}
p_iminsert = curbuf->b_p_iminsert;
showmode();
/* Show/unshow value of 'keymap' in status lines. */
status_redraw_curbuf();
} else if (pp == &p_window) {
if (p_window < 1)
p_window = 1;
else if (p_window >= Rows)
p_window = Rows - 1;
} else if (pp == &curbuf->b_p_imsearch) {
if (curbuf->b_p_imsearch < -1 || curbuf->b_p_imsearch > B_IMODE_LAST) {
errmsg = e_invarg;
curbuf->b_p_imsearch = B_IMODE_NONE;
}
p_imsearch = curbuf->b_p_imsearch;
}
/* if 'titlelen' has changed, redraw the title */
else if (pp == &p_titlelen) {
if (p_titlelen < 0) {
errmsg = e_positive;
p_titlelen = 85;
}
if (starting != NO_SCREEN && old_value != p_titlelen)
need_maketitle = TRUE;
}
/* if p_ch changed value, change the command line height */
else if (pp == &p_ch) {
if (p_ch < 1) {
errmsg = e_positive;
p_ch = 1;
}
if (p_ch > Rows - min_rows() + 1)
p_ch = Rows - min_rows() + 1;
/* Only compute the new window layout when startup has been
* completed. Otherwise the frame sizes may be wrong. */
if (p_ch != old_value && full_screen
)
command_height();
}
/* when 'updatecount' changes from zero to non-zero, open swap files */
else if (pp == &p_uc) {
if (p_uc < 0) {
errmsg = e_positive;
p_uc = 100;
}
if (p_uc && !old_value)
ml_open_files();
} else if (pp == &curwin->w_p_cole) {
if (curwin->w_p_cole < 0) {
errmsg = e_positive;
curwin->w_p_cole = 0;
} else if (curwin->w_p_cole > 3) {
errmsg = e_invarg;
curwin->w_p_cole = 3;
}
}
/* sync undo before 'undolevels' changes */
else if (pp == &p_ul) {
/* use the old value, otherwise u_sync() may not work properly */
p_ul = old_value;
u_sync(TRUE);
p_ul = value;
} else if (pp == &curbuf->b_p_ul) {
/* use the old value, otherwise u_sync() may not work properly */
curbuf->b_p_ul = old_value;
u_sync(TRUE);
curbuf->b_p_ul = value;
}
/* 'numberwidth' must be positive */
else if (pp == &curwin->w_p_nuw) {
if (curwin->w_p_nuw < 1) {
errmsg = e_positive;
curwin->w_p_nuw = 1;
}
if (curwin->w_p_nuw > 10) {
errmsg = e_invarg;
curwin->w_p_nuw = 10;
}
curwin->w_nrwidth_line_count = 0;
} else if (pp == &curbuf->b_p_tw) {
if (curbuf->b_p_tw < 0) {
errmsg = e_positive;
curbuf->b_p_tw = 0;
}
FOR_ALL_TAB_WINDOWS(tp, wp) {
check_colorcolumn(wp);
}
}
/*
* Check the bounds for numeric options here
*/
if (Rows < min_rows() && full_screen) {
if (errbuf != NULL) {
vim_snprintf((char *)errbuf, errbuflen,
_("E593: Need at least %d lines"), min_rows());
errmsg = errbuf;
}
Rows = min_rows();
}
if (Columns < MIN_COLUMNS && full_screen) {
if (errbuf != NULL) {
vim_snprintf((char *)errbuf, errbuflen,
_("E594: Need at least %d columns"), MIN_COLUMNS);
errmsg = errbuf;
}
Columns = MIN_COLUMNS;
}
limit_screen_size();
/*
* If the screen (shell) height has been changed, assume it is the
* physical screenheight.
*/
if (old_Rows != Rows || old_Columns != Columns) {
/* Changing the screen size is not allowed while updating the screen. */
if (updating_screen) {
*pp = old_value;
} else if (full_screen) {
screen_resize((int)Columns, (int)Rows);
} else {
/* Postpone the resizing; check the size and cmdline position for
* messages. */
check_shellsize();
if (cmdline_row > Rows - p_ch && Rows > p_ch) {
assert(p_ch >= 0 && Rows - p_ch <= INT_MAX);
cmdline_row = (int)(Rows - p_ch);
}
}
if (p_window >= Rows || !option_was_set((char_u *)"window"))
p_window = Rows - 1;
}
if (curbuf->b_p_ts <= 0) {
errmsg = e_positive;
curbuf->b_p_ts = 8;
}
if (p_tm < 0) {
errmsg = e_positive;
p_tm = 0;
}
if ((curwin->w_p_scr <= 0
|| (curwin->w_p_scr > curwin->w_height
&& curwin->w_height > 0))
&& full_screen) {
if (pp == &(curwin->w_p_scr)) {
if (curwin->w_p_scr != 0)
errmsg = e_scroll;
win_comp_scroll(curwin);
}
/* If 'scroll' became invalid because of a side effect silently adjust
* it. */
else if (curwin->w_p_scr <= 0)
curwin->w_p_scr = 1;
else /* curwin->w_p_scr > curwin->w_height */
curwin->w_p_scr = curwin->w_height;
}
if (p_hi < 0) {
errmsg = e_positive;
p_hi = 0;
} else if (p_hi > 10000) {
errmsg = e_invarg;
p_hi = 10000;
}
if (p_re < 0 || p_re > 2) {
errmsg = e_invarg;
p_re = 0;
}
if (p_report < 0) {
errmsg = e_positive;
p_report = 1;
}
if ((p_sj < -100 || p_sj >= Rows) && full_screen) {
if (Rows != old_Rows) /* Rows changed, just adjust p_sj */
p_sj = Rows / 2;
else {
errmsg = e_scroll;
p_sj = 1;
}
}
if (p_so < 0 && full_screen) {
errmsg = e_scroll;
p_so = 0;
}
if (p_siso < 0 && full_screen) {
errmsg = e_positive;
p_siso = 0;
}
if (p_cwh < 1) {
errmsg = e_positive;
p_cwh = 1;
}
if (p_ut < 0) {
errmsg = e_positive;
p_ut = 2000;
}
if (p_ss < 0) {
errmsg = e_positive;
p_ss = 0;
}
/* May set global value for local option. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0)
*(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = *pp;
options[opt_idx].flags |= P_WAS_SET;
if (!starting && errmsg == NULL) {
char buf_old[NUMBUFLEN];
char buf_new[NUMBUFLEN];
char buf_type[7];
vim_snprintf(buf_old, ARRAY_SIZE(buf_old), "%ld", old_value);
vim_snprintf(buf_new, ARRAY_SIZE(buf_new), "%ld", value);
vim_snprintf(buf_type, ARRAY_SIZE(buf_type), "%s",
(opt_flags & OPT_LOCAL) ? "local" : "global");
set_vim_var_string(VV_OPTION_NEW, buf_new, -1);
set_vim_var_string(VV_OPTION_OLD, buf_old, -1);
set_vim_var_string(VV_OPTION_TYPE, buf_type, -1);
apply_autocmds(EVENT_OPTIONSET,
(char_u *) options[opt_idx].fullname,
NULL, false, NULL);
reset_v_option_vars();
}
comp_col(); /* in case 'columns' or 'ls' changed */
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
check_redraw(options[opt_idx].flags);
return errmsg;
}
/*
* Called after an option changed: check if something needs to be redrawn.
*/
static void check_redraw(uint32_t flags)
{
/* Careful: P_RCLR and P_RALL are a combination of other P_ flags */
bool doclear = (flags & P_RCLR) == P_RCLR;
bool all = ((flags & P_RALL) == P_RALL || doclear);
if ((flags & P_RSTAT) || all) /* mark all status lines dirty */
status_redraw_all();
if ((flags & P_RBUF) || (flags & P_RWIN) || all)
changed_window_setting();
if (flags & P_RBUF)
redraw_curbuf_later(NOT_VALID);
if (doclear)
redraw_all_later(CLEAR);
else if (all)
redraw_all_later(NOT_VALID);
}
/// Find index for named option
///
/// @param[in] arg Option to find index for.
/// @param[in] len Length of the option.
///
/// @return Index of the option or -1 if option was not found.
int findoption_len(const char_u *const arg, const size_t len)
{
char *s, *p;
static int quick_tab[27] = { 0, 0 }; // quick access table
int is_term_opt;
/*
* For first call: Initialize the quick-access table.
* It contains the index for the first option that starts with a certain
* letter. There are 26 letters, plus the first "t_" option.
*/
if (quick_tab[1] == 0) {
p = options[0].fullname;
for (short int i = 1; (s = options[i].fullname) != NULL; i++) {
if (s[0] != p[0]) {
if (s[0] == 't' && s[1] == '_')
quick_tab[26] = i;
else
quick_tab[CharOrdLow(s[0])] = i;
}
p = s;
}
}
/*
* Check for name starting with an illegal character.
*/
if (len == 0 || arg[0] < 'a' || arg[0] > 'z') {
return -1;
}
int opt_idx;
is_term_opt = (len > 2 && arg[0] == 't' && arg[1] == '_');
if (is_term_opt) {
opt_idx = quick_tab[26];
} else {
opt_idx = quick_tab[CharOrdLow(arg[0])];
}
// Match full name
for (; (s = options[opt_idx].fullname) != NULL; opt_idx++) {
if (STRNCMP(arg, s, len) == 0 && s[len] == NUL) {
break;
}
}
if (s == NULL && !is_term_opt) {
opt_idx = quick_tab[CharOrdLow(arg[0])];
// Match short name
for (; options[opt_idx].fullname != NULL; opt_idx++) {
s = options[opt_idx].shortname;
if (s != NULL && STRNCMP(arg, s, len) == 0 && s[len] == NUL) {
break;
}
s = NULL;
}
}
if (s == NULL)
opt_idx = -1;
return opt_idx;
}
bool is_tty_option(char *name)
{
return (name[0] == 't' && name[1] == '_') || !strcmp((char *)name, "term");
}
#define TCO_BUFFER_SIZE 8
bool get_tty_option(char *name, char **value)
{
if (!strcmp(name, "t_Co")) {
if (value) {
if (t_colors <= 1) {
*value = xstrdup("");
} else {
*value = xmalloc(TCO_BUFFER_SIZE);
snprintf(*value, TCO_BUFFER_SIZE, "%d", t_colors);
}
}
return true;
}
if (!strcmp(name, "term") || !strcmp(name, "ttytype")) {
if (value) {
*value = xstrdup("nvim");
}
return true;
}
if (is_tty_option(name)) {
if (value) {
// XXX: All other t_* options were removed in 3baba1e7.
*value = xstrdup("");
}
return true;
}
return false;
}
bool set_tty_option(char *name, char *value)
{
if (!strcmp(name, "t_Co")) {
int colors = atoi(value);
// Only reinitialize colors if t_Co value has really changed to
// avoid expensive reload of colorscheme if t_Co is set to the
// same value multiple times
if (colors != t_colors) {
t_colors = colors;
// We now have a different color setup, initialize it again.
init_highlight(TRUE, FALSE);
}
return true;
}
return is_tty_option(name) || !strcmp(name, "term")
|| !strcmp(name, "ttytype");
}
/*
* Find index for option 'arg'.
* Return -1 if not found.
*/
static int findoption(char_u *arg)
{
return findoption_len(arg, STRLEN(arg));
}
/*
* Get the value for an option.
*
* Returns:
* Number or Toggle option: 1, *numval gets value.
* String option: 0, *stringval gets allocated string.
* Hidden Number or Toggle option: -1.
* hidden String option: -2.
* unknown option: -3.
*/
int
get_option_value (
char_u *name,
long *numval,
char_u **stringval, /* NULL when only checking existence */
int opt_flags
)
{
if (get_tty_option((char *)name, (char **)stringval)) {
return 0;
}
int opt_idx;
char_u *varp;
opt_idx = findoption(name);
if (opt_idx < 0) /* unknown option */
return -3;
varp = get_varp_scope(&(options[opt_idx]), opt_flags);
if (options[opt_idx].flags & P_STRING) {
if (varp == NULL) /* hidden option */
return -2;
if (stringval != NULL) {
*stringval = vim_strsave(*(char_u **)(varp));
}
return 0;
}
if (varp == NULL) /* hidden option */
return -1;
if (options[opt_idx].flags & P_NUM)
*numval = *(long *)varp;
else {
/* Special case: 'modified' is b_changed, but we also want to consider
* it set when 'ff' or 'fenc' changed. */
if ((int *)varp == &curbuf->b_changed) {
*numval = curbufIsChanged();
} else {
*numval = *(int *)varp;
}
}
return 1;
}
// Returns the option attributes and its value. Unlike the above function it
// will return either global value or local value of the option depending on
// what was requested, but it will never return global value if it was
// requested to return local one and vice versa. Neither it will return
// buffer-local value if it was requested to return window-local one.
//
// Pretends that option is absent if it is not present in the requested scope
// (i.e. has no global, window-local or buffer-local value depending on
// opt_type). Uses
//
// Returned flags:
// 0 hidden or unknown option, also option that does not have requested
// type (see SREQ_* in option_defs.h)
// see SOPT_* in option_defs.h for other flags
//
// Possible opt_type values: see SREQ_* in option_defs.h
int get_option_value_strict(char *name,
int64_t *numval,
char **stringval,
int opt_type,
void *from)
{
if (get_tty_option(name, stringval)) {
return SOPT_STRING | SOPT_GLOBAL;
}
char_u *varp = NULL;
vimoption_T *p;
int rv = 0;
int opt_idx = findoption((uint8_t *)name);
if (opt_idx < 0) {
return 0;
}
p = &(options[opt_idx]);
// Hidden option
if (p->var == NULL) {
return 0;
}
if (p->flags & P_BOOL) {
rv |= SOPT_BOOL;
} else if (p->flags & P_NUM) {
rv |= SOPT_NUM;
} else if (p->flags & P_STRING) {
rv |= SOPT_STRING;
}
if (p->indir == PV_NONE) {
if (opt_type == SREQ_GLOBAL)
rv |= SOPT_GLOBAL;
else
return 0; // Did not request global-only option
} else {
if (p->indir & PV_BOTH) {
rv |= SOPT_GLOBAL;
} else if (opt_type == SREQ_GLOBAL) {
return 0; // Requested global option
}
if (p->indir & PV_WIN) {
if (opt_type == SREQ_BUF) {
return 0; // Did not request window-local option
} else {
rv |= SOPT_WIN;
}
} else if (p->indir & PV_BUF) {
if (opt_type == SREQ_WIN) {
return 0; // Did not request buffer-local option
} else {
rv |= SOPT_BUF;
}
}
}
if (stringval == NULL) {
return rv;
}
if (opt_type == SREQ_GLOBAL) {
varp = p->var;
} else {
if (opt_type == SREQ_BUF) {
// Special case: 'modified' is b_changed, but we also want to
// consider it set when 'ff' or 'fenc' changed.
if (p->indir == PV_MOD) {
*numval = bufIsChanged((buf_T *) from);
varp = NULL;
} else {
aco_save_T aco;
aucmd_prepbuf(&aco, (buf_T *) from);
varp = get_varp(p);
aucmd_restbuf(&aco);
}
} else if (opt_type == SREQ_WIN) {
win_T *save_curwin;
save_curwin = curwin;
curwin = (win_T *) from;
curbuf = curwin->w_buffer;
varp = get_varp(p);
curwin = save_curwin;
curbuf = curwin->w_buffer;
}
if (varp == p->var) {
return (rv | SOPT_UNSET);
}
}
if (varp != NULL) {
if (p->flags & P_STRING) {
*stringval = xstrdup(*(char **)(varp));
} else if (p->flags & P_NUM) {
*numval = *(long *) varp;
} else {
*numval = *(int *)varp;
}
}
return rv;
}
/*
* Set the value of option "name".
* Use "string" for string options, use "number" for other options.
*
* Returns NULL on success or error message on error.
*/
char_u *
set_option_value (
char_u *name,
long number,
char_u *string,
int opt_flags /* OPT_LOCAL or 0 (both) */
)
{
if (set_tty_option((char *)name, (char *)string)) {
return NULL;
}
int opt_idx;
char_u *varp;
opt_idx = findoption(name);
if (opt_idx < 0)
EMSG2(_("E355: Unknown option: %s"), name);
else {
uint32_t flags = options[opt_idx].flags;
// Disallow changing some options in the sandbox
if (sandbox > 0 && (flags & P_SECURE)) {
EMSG(_(e_sandbox));
return NULL;
}
if (flags & P_STRING) {
const char *s = (const char *)string;
if (s == NULL) {
s = "";
}
return (char_u *)set_string_option(opt_idx, s, opt_flags);
} else {
varp = get_varp_scope(&(options[opt_idx]), opt_flags);
if (varp != NULL) { /* hidden option is not changed */
if (number == 0 && string != NULL) {
int idx;
// Either we are given a string or we are setting option
// to zero.
for (idx = 0; string[idx] == '0'; idx++) {}
if (string[idx] != NUL || idx == 0) {
// There's another character after zeros or the string
// is empty. In both cases, we are trying to set a
// num option using a string.
EMSG3(_("E521: Number required: &%s = '%s'"),
name, string);
return NULL; // do nothing as we hit an error
}
}
if (flags & P_NUM)
return set_num_option(opt_idx, varp, number,
NULL, 0, opt_flags);
else
return set_bool_option(opt_idx, varp, (int)number,
opt_flags);
}
}
}
return NULL;
}
char_u *get_highlight_default(void)
{
int i;
i = findoption((char_u *)"hl");
if (i >= 0)
return options[i].def_val[VI_DEFAULT];
return (char_u *)NULL;
}
/*
* Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number.
*/
int find_key_option_len(const char_u *arg, size_t len)
{
int key;
int modifiers;
// Don't use get_special_key_code() for t_xx, we don't want it to call
// add_termcap_entry().
if (len >= 4 && arg[0] == 't' && arg[1] == '_') {
key = TERMCAP2KEY(arg[2], arg[3]);
} else {
arg--; // put arg at the '<'
modifiers = 0;
key = find_special_key(&arg, len + 1, &modifiers, true, true);
if (modifiers) { // can't handle modifiers here
key = 0;
}
}
return key;
}
static int find_key_option(const char_u *arg)
{
return find_key_option_len(arg, STRLEN(arg));
}
/*
* if 'all' == 0: show changed options
* if 'all' == 1: show all normal options
*/
static void
showoptions (
int all,
int opt_flags /* OPT_LOCAL and/or OPT_GLOBAL */
)
{
vimoption_T *p;
int col;
char_u *varp;
int item_count;
int run;
int row, rows;
int cols;
int i;
int len;
#define INC 20
#define GAP 3
vimoption_T **items = xmalloc(sizeof(vimoption_T *) * PARAM_COUNT);
/* Highlight title */
if (all == 2)
MSG_PUTS_TITLE(_("\n--- Terminal codes ---"));
else if (opt_flags & OPT_GLOBAL)
MSG_PUTS_TITLE(_("\n--- Global option values ---"));
else if (opt_flags & OPT_LOCAL)
MSG_PUTS_TITLE(_("\n--- Local option values ---"));
else
MSG_PUTS_TITLE(_("\n--- Options ---"));
/*
* do the loop two times:
* 1. display the short items
* 2. display the long items (only strings and numbers)
*/
for (run = 1; run <= 2 && !got_int; ++run) {
/*
* collect the items in items[]
*/
item_count = 0;
for (p = &options[0]; p->fullname != NULL; p++) {
varp = NULL;
if (opt_flags != 0) {
if (p->indir != PV_NONE)
varp = get_varp_scope(p, opt_flags);
} else
varp = get_varp(p);
if (varp != NULL
&& (all == 1 || (all == 0 && !optval_default(p, varp)))) {
if (p->flags & P_BOOL)
len = 1; /* a toggle option fits always */
else {
option_value2string(p, opt_flags);
len = (int)STRLEN(p->fullname) + vim_strsize(NameBuff) + 1;
}
if ((len <= INC - GAP && run == 1)
|| (len > INC - GAP && run == 2)) {
items[item_count++] = p;
}
}
}
/*
* display the items
*/
if (run == 1) {
assert(Columns <= LONG_MAX - GAP
&& Columns + GAP >= LONG_MIN + 3
&& (Columns + GAP - 3) / INC >= INT_MIN
&& (Columns + GAP - 3) / INC <= INT_MAX);
cols = (int)((Columns + GAP - 3) / INC);
if (cols == 0)
cols = 1;
rows = (item_count + cols - 1) / cols;
} else /* run == 2 */
rows = item_count;
for (row = 0; row < rows && !got_int; ++row) {
msg_putchar('\n'); /* go to next line */
if (got_int) /* 'q' typed in more */
break;
col = 0;
for (i = row; i < item_count; i += rows) {
msg_col = col; /* make columns */
showoneopt(items[i], opt_flags);
col += INC;
}
ui_flush();
os_breakcheck();
}
}
xfree(items);
}
/*
* Return TRUE if option "p" has its default value.
*/
static int optval_default(vimoption_T *p, char_u *varp)
{
int dvi;
if (varp == NULL)
return TRUE; /* hidden option is always at default */
dvi = ((p->flags & P_VI_DEF) || p_cp) ? VI_DEFAULT : VIM_DEFAULT;
if (p->flags & P_NUM)
return *(long *)varp == (long)p->def_val[dvi];
if (p->flags & P_BOOL)
return *(int *)varp == (int)(intptr_t)p->def_val[dvi];
/* P_STRING */
return STRCMP(*(char_u **)varp, p->def_val[dvi]) == 0;
}
/*
* showoneopt: show the value of one option
* must not be called with a hidden option!
*/
static void
showoneopt (
vimoption_T *p,
int opt_flags /* OPT_LOCAL or OPT_GLOBAL */
)
{
char_u *varp;
int save_silent = silent_mode;
silent_mode = FALSE;
info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
varp = get_varp_scope(p, opt_flags);
// for 'modified' we also need to check if 'ff' or 'fenc' changed.
if ((p->flags & P_BOOL) && ((int *)varp == &curbuf->b_changed
? !curbufIsChanged() : !*(int *)varp)) {
MSG_PUTS("no");
} else if ((p->flags & P_BOOL) && *(int *)varp < 0) {
MSG_PUTS("--");
} else {
MSG_PUTS(" ");
}
MSG_PUTS(p->fullname);
if (!(p->flags & P_BOOL)) {
msg_putchar('=');
/* put value string in NameBuff */
option_value2string(p, opt_flags);
msg_outtrans(NameBuff);
}
silent_mode = save_silent;
info_message = FALSE;
}
/*
* Write modified options as ":set" commands to a file.
*
* There are three values for "opt_flags":
* OPT_GLOBAL: Write global option values and fresh values of
* buffer-local options (used for start of a session
* file).
* OPT_GLOBAL + OPT_LOCAL: Idem, add fresh values of window-local options for
* curwin (used for a vimrc file).
* OPT_LOCAL: Write buffer-local option values for curbuf, fresh
* and local values for window-local options of
* curwin. Local values are also written when at the
* default value, because a modeline or autocommand
* may have set them when doing ":edit file" and the
* user has set them back at the default or fresh
* value.
* When "local_only" is TRUE, don't write fresh
* values, only local values (for ":mkview").
* (fresh value = value used for a new buffer or window for a local option).
*
* Return FAIL on error, OK otherwise.
*/
int makeset(FILE *fd, int opt_flags, int local_only)
{
vimoption_T *p;
char_u *varp; /* currently used value */
char_u *varp_fresh; /* local value */
char_u *varp_local = NULL; /* fresh value */
char *cmd;
int round;
int pri;
/*
* Some options are never written:
* - Options that don't have a default (terminal name, columns, lines).
* - Terminal options.
* - Hidden options.
*
* Do the loop over "options[]" twice: once for options with the
* P_PRI_MKRC flag and once without.
*/
for (pri = 1; pri >= 0; --pri) {
for (p = &options[0]; p->fullname; p++)
if (!(p->flags & P_NO_MKRC)
&& ((pri == 1) == ((p->flags & P_PRI_MKRC) != 0))) {
/* skip global option when only doing locals */
if (p->indir == PV_NONE && !(opt_flags & OPT_GLOBAL))
continue;
/* Do not store options like 'bufhidden' and 'syntax' in a vimrc
* file, they are always buffer-specific. */
if ((opt_flags & OPT_GLOBAL) && (p->flags & P_NOGLOB))
continue;
varp = get_varp_scope(p, opt_flags);
/* Hidden options are never written. */
if (!varp)
continue;
/* Global values are only written when not at the default value. */
if ((opt_flags & OPT_GLOBAL) && optval_default(p, varp))
continue;
round = 2;
if (p->indir != PV_NONE) {
if (p->var == VAR_WIN) {
/* skip window-local option when only doing globals */
if (!(opt_flags & OPT_LOCAL))
continue;
/* When fresh value of window-local option is not at the
* default, need to write it too. */
if (!(opt_flags & OPT_GLOBAL) && !local_only) {
varp_fresh = get_varp_scope(p, OPT_GLOBAL);
if (!optval_default(p, varp_fresh)) {
round = 1;
varp_local = varp;
varp = varp_fresh;
}
}
}
}
/* Round 1: fresh value for window-local options.
* Round 2: other values */
for (; round <= 2; varp = varp_local, ++round) {
if (round == 1 || (opt_flags & OPT_GLOBAL))
cmd = "set";
else
cmd = "setlocal";
if (p->flags & P_BOOL) {
if (put_setbool(fd, cmd, p->fullname, *(int *)varp) == FAIL)
return FAIL;
} else if (p->flags & P_NUM) {
if (put_setnum(fd, cmd, p->fullname, (long *)varp) == FAIL)
return FAIL;
} else { /* P_STRING */
int do_endif = FALSE;
// Don't set 'syntax' and 'filetype' again if the value is
// already right, avoids reloading the syntax file.
if (p->indir == PV_SYN || p->indir == PV_FT) {
if (fprintf(fd, "if &%s != '%s'", p->fullname,
*(char_u **)(varp)) < 0
|| put_eol(fd) < 0) {
return FAIL;
}
do_endif = true;
}
if (put_setstring(fd, cmd, p->fullname, (char_u **)varp,
(p->flags & P_EXPAND) != 0) == FAIL)
return FAIL;
if (do_endif) {
if (put_line(fd, "endif") == FAIL)
return FAIL;
}
}
}
}
}
return OK;
}
/*
* Generate set commands for the local fold options only. Used when
* 'sessionoptions' or 'viewoptions' contains "folds" but not "options".
*/
int makefoldset(FILE *fd)
{
if (put_setstring(fd, "setlocal", "fdm", &curwin->w_p_fdm, FALSE) == FAIL
|| put_setstring(fd, "setlocal", "fde", &curwin->w_p_fde, FALSE)
== FAIL
|| put_setstring(fd, "setlocal", "fmr", &curwin->w_p_fmr, FALSE)
== FAIL
|| put_setstring(fd, "setlocal", "fdi", &curwin->w_p_fdi, FALSE)
== FAIL
|| put_setnum(fd, "setlocal", "fdl", &curwin->w_p_fdl) == FAIL
|| put_setnum(fd, "setlocal", "fml", &curwin->w_p_fml) == FAIL
|| put_setnum(fd, "setlocal", "fdn", &curwin->w_p_fdn) == FAIL
|| put_setbool(fd, "setlocal", "fen", curwin->w_p_fen) == FAIL
)
return FAIL;
return OK;
}
static int put_setstring(FILE *fd, char *cmd, char *name, char_u **valuep, int expand)
{
char_u *s;
char_u *buf;
if (fprintf(fd, "%s %s=", cmd, name) < 0)
return FAIL;
if (*valuep != NULL) {
/* Output 'pastetoggle' as key names. For other
* options some characters have to be escaped with
* CTRL-V or backslash */
if (valuep == &p_pt) {
s = *valuep;
while (*s != NUL)
if (put_escstr(fd, str2special(&s, FALSE), 2) == FAIL)
return FAIL;
} else if (expand) {
buf = xmalloc(MAXPATHL);
home_replace(NULL, *valuep, buf, MAXPATHL, FALSE);
if (put_escstr(fd, buf, 2) == FAIL) {
xfree(buf);
return FAIL;
}
xfree(buf);
} else if (put_escstr(fd, *valuep, 2) == FAIL)
return FAIL;
}
if (put_eol(fd) < 0)
return FAIL;
return OK;
}
static int put_setnum(FILE *fd, char *cmd, char *name, long *valuep)
{
long wc;
if (fprintf(fd, "%s %s=", cmd, name) < 0)
return FAIL;
if (wc_use_keyname((char_u *)valuep, &wc)) {
/* print 'wildchar' and 'wildcharm' as a key name */
if (fputs((char *)get_special_key_name((int)wc, 0), fd) < 0)
return FAIL;
} else if (fprintf(fd, "%" PRId64, (int64_t)*valuep) < 0)
return FAIL;
if (put_eol(fd) < 0)
return FAIL;
return OK;
}
static int put_setbool(FILE *fd, char *cmd, char *name, int value)
{
if (value < 0) /* global/local option using global value */
return OK;
if (fprintf(fd, "%s %s%s", cmd, value ? "" : "no", name) < 0
|| put_eol(fd) < 0)
return FAIL;
return OK;
}
/*
* Compute columns for ruler and shown command. 'sc_col' is also used to
* decide what the maximum length of a message on the status line can be.
* If there is a status line for the last window, 'sc_col' is independent
* of 'ru_col'.
*/
#define COL_RULER 17 /* columns needed by standard ruler */
void comp_col(void)
{
int last_has_status = (p_ls == 2 || (p_ls == 1 && firstwin != lastwin));
sc_col = 0;
ru_col = 0;
if (p_ru) {
ru_col = (ru_wid ? ru_wid : COL_RULER) + 1;
/* no last status line, adjust sc_col */
if (!last_has_status)
sc_col = ru_col;
}
if (p_sc) {
sc_col += SHOWCMD_COLS;
if (!p_ru || last_has_status) /* no need for separating space */
++sc_col;
}
assert(sc_col >= 0
&& INT_MIN + sc_col <= Columns
&& Columns - sc_col <= INT_MAX);
sc_col = (int)(Columns - sc_col);
assert(ru_col >= 0
&& INT_MIN + ru_col <= Columns
&& Columns - ru_col <= INT_MAX);
ru_col = (int)(Columns - ru_col);
if (sc_col <= 0) /* screen too narrow, will become a mess */
sc_col = 1;
if (ru_col <= 0)
ru_col = 1;
}
// Unset local option value, similar to ":set opt<".
void unset_global_local_option(char *name, void *from)
{
vimoption_T *p;
buf_T *buf = (buf_T *)from;
int opt_idx = findoption((uint8_t *)name);
if (opt_idx < 0) {
EMSG2(_("E355: Unknown option: %s"), name);
return;
}
p = &(options[opt_idx]);
switch ((int)p->indir)
{
// global option with local value: use local value if it's been set
case PV_EP:
clear_string_option(&buf->b_p_ep);
break;
case PV_KP:
clear_string_option(&buf->b_p_kp);
break;
case PV_PATH:
clear_string_option(&buf->b_p_path);
break;
case PV_AR:
buf->b_p_ar = -1;
break;
case PV_BKC:
clear_string_option(&buf->b_p_bkc);
buf->b_bkc_flags = 0;
break;
case PV_TAGS:
clear_string_option(&buf->b_p_tags);
break;
case PV_TC:
clear_string_option(&buf->b_p_tc);
buf->b_tc_flags = 0;
break;
case PV_DEF:
clear_string_option(&buf->b_p_def);
break;
case PV_INC:
clear_string_option(&buf->b_p_inc);
break;
case PV_DICT:
clear_string_option(&buf->b_p_dict);
break;
case PV_TSR:
clear_string_option(&buf->b_p_tsr);
break;
case PV_EFM:
clear_string_option(&buf->b_p_efm);
break;
case PV_GP:
clear_string_option(&buf->b_p_gp);
break;
case PV_MP:
clear_string_option(&buf->b_p_mp);
break;
case PV_STL:
clear_string_option(&((win_T *)from)->w_p_stl);
break;
case PV_UL:
buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
break;
case PV_LW:
clear_string_option(&buf->b_p_lw);
break;
}
}
/*
* Get pointer to option variable, depending on local or global scope.
*/
static char_u *get_varp_scope(vimoption_T *p, int opt_flags)
{
if ((opt_flags & OPT_GLOBAL) && p->indir != PV_NONE) {
if (p->var == VAR_WIN)
return (char_u *)GLOBAL_WO(get_varp(p));
return p->var;
}
if ((opt_flags & OPT_LOCAL) && ((int)p->indir & PV_BOTH)) {
switch ((int)p->indir) {
case PV_EFM: return (char_u *)&(curbuf->b_p_efm);
case PV_GP: return (char_u *)&(curbuf->b_p_gp);
case PV_MP: return (char_u *)&(curbuf->b_p_mp);
case PV_EP: return (char_u *)&(curbuf->b_p_ep);
case PV_KP: return (char_u *)&(curbuf->b_p_kp);
case PV_PATH: return (char_u *)&(curbuf->b_p_path);
case PV_AR: return (char_u *)&(curbuf->b_p_ar);
case PV_TAGS: return (char_u *)&(curbuf->b_p_tags);
case PV_TC: return (char_u *)&(curbuf->b_p_tc);
case PV_DEF: return (char_u *)&(curbuf->b_p_def);
case PV_INC: return (char_u *)&(curbuf->b_p_inc);
case PV_DICT: return (char_u *)&(curbuf->b_p_dict);
case PV_TSR: return (char_u *)&(curbuf->b_p_tsr);
case PV_STL: return (char_u *)&(curwin->w_p_stl);
case PV_UL: return (char_u *)&(curbuf->b_p_ul);
case PV_LW: return (char_u *)&(curbuf->b_p_lw);
case PV_BKC: return (char_u *)&(curbuf->b_p_bkc);
}
return NULL; /* "cannot happen" */
}
return get_varp(p);
}
/*
* Get pointer to option variable.
*/
static char_u *get_varp(vimoption_T *p)
{
/* hidden option, always return NULL */
if (p->var == NULL)
return NULL;
switch ((int)p->indir) {
case PV_NONE: return p->var;
/* global option with local value: use local value if it's been set */
case PV_EP: return *curbuf->b_p_ep != NUL
? (char_u *)&curbuf->b_p_ep : p->var;
case PV_KP: return *curbuf->b_p_kp != NUL
? (char_u *)&curbuf->b_p_kp : p->var;
case PV_PATH: return *curbuf->b_p_path != NUL
? (char_u *)&(curbuf->b_p_path) : p->var;
case PV_AR: return curbuf->b_p_ar >= 0
? (char_u *)&(curbuf->b_p_ar) : p->var;
case PV_TAGS: return *curbuf->b_p_tags != NUL
? (char_u *)&(curbuf->b_p_tags) : p->var;
case PV_TC: return *curbuf->b_p_tc != NUL
? (char_u *)&(curbuf->b_p_tc) : p->var;
case PV_BKC: return *curbuf->b_p_bkc != NUL
? (char_u *)&(curbuf->b_p_bkc) : p->var;
case PV_DEF: return *curbuf->b_p_def != NUL
? (char_u *)&(curbuf->b_p_def) : p->var;
case PV_INC: return *curbuf->b_p_inc != NUL
? (char_u *)&(curbuf->b_p_inc) : p->var;
case PV_DICT: return *curbuf->b_p_dict != NUL
? (char_u *)&(curbuf->b_p_dict) : p->var;
case PV_TSR: return *curbuf->b_p_tsr != NUL
? (char_u *)&(curbuf->b_p_tsr) : p->var;
case PV_EFM: return *curbuf->b_p_efm != NUL
? (char_u *)&(curbuf->b_p_efm) : p->var;
case PV_GP: return *curbuf->b_p_gp != NUL
? (char_u *)&(curbuf->b_p_gp) : p->var;
case PV_MP: return *curbuf->b_p_mp != NUL
? (char_u *)&(curbuf->b_p_mp) : p->var;
case PV_STL: return *curwin->w_p_stl != NUL
? (char_u *)&(curwin->w_p_stl) : p->var;
case PV_UL: return curbuf->b_p_ul != NO_LOCAL_UNDOLEVEL
? (char_u *)&(curbuf->b_p_ul) : p->var;
case PV_LW: return *curbuf->b_p_lw != NUL
? (char_u *)&(curbuf->b_p_lw) : p->var;
case PV_ARAB: return (char_u *)&(curwin->w_p_arab);
case PV_LIST: return (char_u *)&(curwin->w_p_list);
case PV_SPELL: return (char_u *)&(curwin->w_p_spell);
case PV_CUC: return (char_u *)&(curwin->w_p_cuc);
case PV_CUL: return (char_u *)&(curwin->w_p_cul);
case PV_CC: return (char_u *)&(curwin->w_p_cc);
case PV_DIFF: return (char_u *)&(curwin->w_p_diff);
case PV_FDC: return (char_u *)&(curwin->w_p_fdc);
case PV_FEN: return (char_u *)&(curwin->w_p_fen);
case PV_FDI: return (char_u *)&(curwin->w_p_fdi);
case PV_FDL: return (char_u *)&(curwin->w_p_fdl);
case PV_FDM: return (char_u *)&(curwin->w_p_fdm);
case PV_FML: return (char_u *)&(curwin->w_p_fml);
case PV_FDN: return (char_u *)&(curwin->w_p_fdn);
case PV_FDE: return (char_u *)&(curwin->w_p_fde);
case PV_FDT: return (char_u *)&(curwin->w_p_fdt);
case PV_FMR: return (char_u *)&(curwin->w_p_fmr);
case PV_NU: return (char_u *)&(curwin->w_p_nu);
case PV_RNU: return (char_u *)&(curwin->w_p_rnu);
case PV_NUW: return (char_u *)&(curwin->w_p_nuw);
case PV_WFH: return (char_u *)&(curwin->w_p_wfh);
case PV_WFW: return (char_u *)&(curwin->w_p_wfw);
case PV_PVW: return (char_u *)&(curwin->w_p_pvw);
case PV_RL: return (char_u *)&(curwin->w_p_rl);
case PV_RLC: return (char_u *)&(curwin->w_p_rlc);
case PV_SCROLL: return (char_u *)&(curwin->w_p_scr);
case PV_WRAP: return (char_u *)&(curwin->w_p_wrap);
case PV_LBR: return (char_u *)&(curwin->w_p_lbr);
case PV_BRI: return (char_u *)&(curwin->w_p_bri);
case PV_BRIOPT: return (char_u *)&(curwin->w_p_briopt);
case PV_SCBIND: return (char_u *)&(curwin->w_p_scb);
case PV_CRBIND: return (char_u *)&(curwin->w_p_crb);
case PV_COCU: return (char_u *)&(curwin->w_p_cocu);
case PV_COLE: return (char_u *)&(curwin->w_p_cole);
case PV_AI: return (char_u *)&(curbuf->b_p_ai);
case PV_BIN: return (char_u *)&(curbuf->b_p_bin);
case PV_BOMB: return (char_u *)&(curbuf->b_p_bomb);
case PV_BH: return (char_u *)&(curbuf->b_p_bh);
case PV_BT: return (char_u *)&(curbuf->b_p_bt);
case PV_BL: return (char_u *)&(curbuf->b_p_bl);
case PV_CI: return (char_u *)&(curbuf->b_p_ci);
case PV_CIN: return (char_u *)&(curbuf->b_p_cin);
case PV_CINK: return (char_u *)&(curbuf->b_p_cink);
case PV_CINO: return (char_u *)&(curbuf->b_p_cino);
case PV_CINW: return (char_u *)&(curbuf->b_p_cinw);
case PV_COM: return (char_u *)&(curbuf->b_p_com);
case PV_CMS: return (char_u *)&(curbuf->b_p_cms);
case PV_CPT: return (char_u *)&(curbuf->b_p_cpt);
case PV_CFU: return (char_u *)&(curbuf->b_p_cfu);
case PV_OFU: return (char_u *)&(curbuf->b_p_ofu);
case PV_EOL: return (char_u *)&(curbuf->b_p_eol);
case PV_FIXEOL: return (char_u *)&(curbuf->b_p_fixeol);
case PV_ET: return (char_u *)&(curbuf->b_p_et);
case PV_FENC: return (char_u *)&(curbuf->b_p_fenc);
case PV_FF: return (char_u *)&(curbuf->b_p_ff);
case PV_FT: return (char_u *)&(curbuf->b_p_ft);
case PV_FO: return (char_u *)&(curbuf->b_p_fo);
case PV_FLP: return (char_u *)&(curbuf->b_p_flp);
case PV_IMI: return (char_u *)&(curbuf->b_p_iminsert);
case PV_IMS: return (char_u *)&(curbuf->b_p_imsearch);
case PV_INF: return (char_u *)&(curbuf->b_p_inf);
case PV_ISK: return (char_u *)&(curbuf->b_p_isk);
case PV_INEX: return (char_u *)&(curbuf->b_p_inex);
case PV_INDE: return (char_u *)&(curbuf->b_p_inde);
case PV_INDK: return (char_u *)&(curbuf->b_p_indk);
case PV_FEX: return (char_u *)&(curbuf->b_p_fex);
case PV_LISP: return (char_u *)&(curbuf->b_p_lisp);
case PV_ML: return (char_u *)&(curbuf->b_p_ml);
case PV_MPS: return (char_u *)&(curbuf->b_p_mps);
case PV_MA: return (char_u *)&(curbuf->b_p_ma);
case PV_MOD: return (char_u *)&(curbuf->b_changed);
case PV_NF: return (char_u *)&(curbuf->b_p_nf);
case PV_PI: return (char_u *)&(curbuf->b_p_pi);
case PV_QE: return (char_u *)&(curbuf->b_p_qe);
case PV_RO: return (char_u *)&(curbuf->b_p_ro);
case PV_SI: return (char_u *)&(curbuf->b_p_si);
case PV_STS: return (char_u *)&(curbuf->b_p_sts);
case PV_SUA: return (char_u *)&(curbuf->b_p_sua);
case PV_SWF: return (char_u *)&(curbuf->b_p_swf);
case PV_SMC: return (char_u *)&(curbuf->b_p_smc);
case PV_SYN: return (char_u *)&(curbuf->b_p_syn);
case PV_SPC: return (char_u *)&(curwin->w_s->b_p_spc);
case PV_SPF: return (char_u *)&(curwin->w_s->b_p_spf);
case PV_SPL: return (char_u *)&(curwin->w_s->b_p_spl);
case PV_SW: return (char_u *)&(curbuf->b_p_sw);
case PV_TS: return (char_u *)&(curbuf->b_p_ts);
case PV_TW: return (char_u *)&(curbuf->b_p_tw);
case PV_UDF: return (char_u *)&(curbuf->b_p_udf);
case PV_WM: return (char_u *)&(curbuf->b_p_wm);
case PV_KMAP: return (char_u *)&(curbuf->b_p_keymap);
default: EMSG(_("E356: get_varp ERROR"));
}
/* always return a valid pointer to avoid a crash! */
return (char_u *)&(curbuf->b_p_wm);
}
/*
* Get the value of 'equalprg', either the buffer-local one or the global one.
*/
char_u *get_equalprg(void)
{
if (*curbuf->b_p_ep == NUL)
return p_ep;
return curbuf->b_p_ep;
}
/*
* Copy options from one window to another.
* Used when splitting a window.
*/
void win_copy_options(win_T *wp_from, win_T *wp_to)
{
copy_winopt(&wp_from->w_onebuf_opt, &wp_to->w_onebuf_opt);
copy_winopt(&wp_from->w_allbuf_opt, &wp_to->w_allbuf_opt);
/* Is this right? */
wp_to->w_farsi = wp_from->w_farsi;
briopt_check(wp_to);
}
/*
* Copy the options from one winopt_T to another.
* Doesn't free the old option values in "to", use clear_winopt() for that.
* The 'scroll' option is not copied, because it depends on the window height.
* The 'previewwindow' option is reset, there can be only one preview window.
*/
void copy_winopt(winopt_T *from, winopt_T *to)
{
to->wo_arab = from->wo_arab;
to->wo_list = from->wo_list;
to->wo_nu = from->wo_nu;
to->wo_rnu = from->wo_rnu;
to->wo_nuw = from->wo_nuw;
to->wo_rl = from->wo_rl;
to->wo_rlc = vim_strsave(from->wo_rlc);
to->wo_stl = vim_strsave(from->wo_stl);
to->wo_wrap = from->wo_wrap;
to->wo_wrap_save = from->wo_wrap_save;
to->wo_lbr = from->wo_lbr;
to->wo_bri = from->wo_bri;
to->wo_briopt = vim_strsave(from->wo_briopt);
to->wo_scb = from->wo_scb;
to->wo_scb_save = from->wo_scb_save;
to->wo_crb = from->wo_crb;
to->wo_crb_save = from->wo_crb_save;
to->wo_spell = from->wo_spell;
to->wo_cuc = from->wo_cuc;
to->wo_cul = from->wo_cul;
to->wo_cc = vim_strsave(from->wo_cc);
to->wo_diff = from->wo_diff;
to->wo_diff_saved = from->wo_diff_saved;
to->wo_cocu = vim_strsave(from->wo_cocu);
to->wo_cole = from->wo_cole;
to->wo_fdc = from->wo_fdc;
to->wo_fdc_save = from->wo_fdc_save;
to->wo_fen = from->wo_fen;
to->wo_fen_save = from->wo_fen_save;
to->wo_fdi = vim_strsave(from->wo_fdi);
to->wo_fml = from->wo_fml;
to->wo_fdl = from->wo_fdl;
to->wo_fdl_save = from->wo_fdl_save;
to->wo_fdm = vim_strsave(from->wo_fdm);
to->wo_fdm_save = from->wo_diff_saved
? vim_strsave(from->wo_fdm_save) : empty_option;
to->wo_fdn = from->wo_fdn;
to->wo_fde = vim_strsave(from->wo_fde);
to->wo_fdt = vim_strsave(from->wo_fdt);
to->wo_fmr = vim_strsave(from->wo_fmr);
check_winopt(to); /* don't want NULL pointers */
}
/*
* Check string options in a window for a NULL value.
*/
void check_win_options(win_T *win)
{
check_winopt(&win->w_onebuf_opt);
check_winopt(&win->w_allbuf_opt);
}
/*
* Check for NULL pointers in a winopt_T and replace them with empty_option.
*/
static void check_winopt(winopt_T *wop)
{
check_string_option(&wop->wo_fdi);
check_string_option(&wop->wo_fdm);
check_string_option(&wop->wo_fdm_save);
check_string_option(&wop->wo_fde);
check_string_option(&wop->wo_fdt);
check_string_option(&wop->wo_fmr);
check_string_option(&wop->wo_rlc);
check_string_option(&wop->wo_stl);
check_string_option(&wop->wo_cc);
check_string_option(&wop->wo_cocu);
check_string_option(&wop->wo_briopt);
}
/*
* Free the allocated memory inside a winopt_T.
*/
void clear_winopt(winopt_T *wop)
{
clear_string_option(&wop->wo_fdi);
clear_string_option(&wop->wo_fdm);
clear_string_option(&wop->wo_fdm_save);
clear_string_option(&wop->wo_fde);
clear_string_option(&wop->wo_fdt);
clear_string_option(&wop->wo_fmr);
clear_string_option(&wop->wo_rlc);
clear_string_option(&wop->wo_stl);
clear_string_option(&wop->wo_cc);
clear_string_option(&wop->wo_cocu);
clear_string_option(&wop->wo_briopt);
}
/*
* Copy global option values to local options for one buffer.
* Used when creating a new buffer and sometimes when entering a buffer.
* flags:
* BCO_ENTER We will enter the buf buffer.
* BCO_ALWAYS Always copy the options, but only set b_p_initialized when
* appropriate.
* BCO_NOHELP Don't copy the values to a help buffer.
*/
void buf_copy_options(buf_T *buf, int flags)
{
int should_copy = TRUE;
char_u *save_p_isk = NULL; /* init for GCC */
int dont_do_help;
int did_isk = FALSE;
/*
* Don't do anything if the buffer is invalid.
*/
if (buf == NULL || !buf_valid(buf))
return;
/*
* Skip this when the option defaults have not been set yet. Happens when
* main() allocates the first buffer.
*/
if (p_cpo != NULL) {
/*
* Always copy when entering and 'cpo' contains 'S'.
* Don't copy when already initialized.
* Don't copy when 'cpo' contains 's' and not entering.
* 'S' BCO_ENTER initialized 's' should_copy
* yes yes X X TRUE
* yes no yes X FALSE
* no X yes X FALSE
* X no no yes FALSE
* X no no no TRUE
* no yes no X TRUE
*/
if ((vim_strchr(p_cpo, CPO_BUFOPTGLOB) == NULL || !(flags & BCO_ENTER))
&& (buf->b_p_initialized
|| (!(flags & BCO_ENTER)
&& vim_strchr(p_cpo, CPO_BUFOPT) != NULL)))
should_copy = FALSE;
if (should_copy || (flags & BCO_ALWAYS)) {
/* Don't copy the options specific to a help buffer when
* BCO_NOHELP is given or the options were initialized already
* (jumping back to a help file with CTRL-T or CTRL-O) */
dont_do_help = ((flags & BCO_NOHELP) && buf->b_help)
|| buf->b_p_initialized;
if (dont_do_help) { /* don't free b_p_isk */
save_p_isk = buf->b_p_isk;
buf->b_p_isk = NULL;
}
/*
* Always free the allocated strings.
* If not already initialized, set 'readonly' and copy 'fileformat'.
*/
if (!buf->b_p_initialized) {
free_buf_options(buf, TRUE);
buf->b_p_ro = FALSE; /* don't copy readonly */
buf->b_p_fenc = vim_strsave(p_fenc);
buf->b_p_ff = vim_strsave(p_ff);
buf->b_p_bh = empty_option;
buf->b_p_bt = empty_option;
} else
free_buf_options(buf, FALSE);
buf->b_p_ai = p_ai;
buf->b_p_ai_nopaste = p_ai_nopaste;
buf->b_p_sw = p_sw;
buf->b_p_tw = p_tw;
buf->b_p_tw_nopaste = p_tw_nopaste;
buf->b_p_tw_nobin = p_tw_nobin;
buf->b_p_wm = p_wm;
buf->b_p_wm_nopaste = p_wm_nopaste;
buf->b_p_wm_nobin = p_wm_nobin;
buf->b_p_bin = p_bin;
buf->b_p_bomb = p_bomb;
buf->b_p_et = p_et;
buf->b_p_fixeol = p_fixeol;
buf->b_p_et_nobin = p_et_nobin;
buf->b_p_et_nopaste = p_et_nopaste;
buf->b_p_ml = p_ml;
buf->b_p_ml_nobin = p_ml_nobin;
buf->b_p_inf = p_inf;
buf->b_p_swf = p_swf;
buf->b_p_cpt = vim_strsave(p_cpt);
buf->b_p_cfu = vim_strsave(p_cfu);
buf->b_p_ofu = vim_strsave(p_ofu);
buf->b_p_sts = p_sts;
buf->b_p_sts_nopaste = p_sts_nopaste;
buf->b_p_com = vim_strsave(p_com);
buf->b_p_cms = vim_strsave(p_cms);
buf->b_p_fo = vim_strsave(p_fo);
buf->b_p_flp = vim_strsave(p_flp);
buf->b_p_nf = vim_strsave(p_nf);
buf->b_p_mps = vim_strsave(p_mps);
buf->b_p_si = p_si;
buf->b_p_ci = p_ci;
buf->b_p_cin = p_cin;
buf->b_p_cink = vim_strsave(p_cink);
buf->b_p_cino = vim_strsave(p_cino);
/* Don't copy 'filetype', it must be detected */
buf->b_p_ft = empty_option;
buf->b_p_pi = p_pi;
buf->b_p_cinw = vim_strsave(p_cinw);
buf->b_p_lisp = p_lisp;
/* Don't copy 'syntax', it must be set */
buf->b_p_syn = empty_option;
buf->b_p_smc = p_smc;
buf->b_s.b_syn_isk = empty_option;
buf->b_s.b_p_spc = vim_strsave(p_spc);
(void)compile_cap_prog(&buf->b_s);
buf->b_s.b_p_spf = vim_strsave(p_spf);
buf->b_s.b_p_spl = vim_strsave(p_spl);
buf->b_p_inde = vim_strsave(p_inde);
buf->b_p_indk = vim_strsave(p_indk);
buf->b_p_fex = vim_strsave(p_fex);
buf->b_p_sua = vim_strsave(p_sua);
buf->b_p_keymap = vim_strsave(p_keymap);
buf->b_kmap_state |= KEYMAP_INIT;
/* This isn't really an option, but copying the langmap and IME
* state from the current buffer is better than resetting it. */
buf->b_p_iminsert = p_iminsert;
buf->b_p_imsearch = p_imsearch;
/* options that are normally global but also have a local value
* are not copied, start using the global value */
buf->b_p_ar = -1;
buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
buf->b_p_bkc = empty_option;
buf->b_bkc_flags = 0;
buf->b_p_gp = empty_option;
buf->b_p_mp = empty_option;
buf->b_p_efm = empty_option;
buf->b_p_ep = empty_option;
buf->b_p_kp = empty_option;
buf->b_p_path = empty_option;
buf->b_p_tags = empty_option;
buf->b_p_tc = empty_option;
buf->b_tc_flags = 0;
buf->b_p_def = empty_option;
buf->b_p_inc = empty_option;
buf->b_p_inex = vim_strsave(p_inex);
buf->b_p_dict = empty_option;
buf->b_p_tsr = empty_option;
buf->b_p_qe = vim_strsave(p_qe);
buf->b_p_udf = p_udf;
buf->b_p_lw = empty_option;
/*
* Don't copy the options set by ex_help(), use the saved values,
* when going from a help buffer to a non-help buffer.
* Don't touch these at all when BCO_NOHELP is used and going from
* or to a help buffer.
*/
if (dont_do_help)
buf->b_p_isk = save_p_isk;
else {
buf->b_p_isk = vim_strsave(p_isk);
did_isk = true;
buf->b_p_ts = p_ts;
buf->b_help = false;
if (buf->b_p_bt[0] == 'h')
clear_string_option(&buf->b_p_bt);
buf->b_p_ma = p_ma;
}
}
/*
* When the options should be copied (ignoring BCO_ALWAYS), set the
* flag that indicates that the options have been initialized.
*/
if (should_copy)
buf->b_p_initialized = true;
}
check_buf_options(buf); /* make sure we don't have NULLs */
if (did_isk)
(void)buf_init_chartab(buf, FALSE);
}
/*
* Reset the 'modifiable' option and its default value.
*/
void reset_modifiable(void)
{
int opt_idx;
curbuf->b_p_ma = FALSE;
p_ma = FALSE;
opt_idx = findoption((char_u *)"ma");
if (opt_idx >= 0)
options[opt_idx].def_val[VI_DEFAULT] = FALSE;
}
/*
* Set the global value for 'iminsert' to the local value.
*/
void set_iminsert_global(void)
{
p_iminsert = curbuf->b_p_iminsert;
}
/*
* Set the global value for 'imsearch' to the local value.
*/
void set_imsearch_global(void)
{
p_imsearch = curbuf->b_p_imsearch;
}
static int expand_option_idx = -1;
static char_u expand_option_name[5] = {'t', '_', NUL, NUL, NUL};
static int expand_option_flags = 0;
void
set_context_in_set_cmd (
expand_T *xp,
char_u *arg,
int opt_flags /* OPT_GLOBAL and/or OPT_LOCAL */
)
{
char_u nextchar;
uint32_t flags = 0; /* init for GCC */
int opt_idx = 0; /* init for GCC */
char_u *p;
char_u *s;
int is_term_option = FALSE;
int key;
expand_option_flags = opt_flags;
xp->xp_context = EXPAND_SETTINGS;
if (*arg == NUL) {
xp->xp_pattern = arg;
return;
}
p = arg + STRLEN(arg) - 1;
if (*p == ' ' && *(p - 1) != '\\') {
xp->xp_pattern = p + 1;
return;
}
while (p > arg) {
s = p;
/* count number of backslashes before ' ' or ',' */
if (*p == ' ' || *p == ',') {
while (s > arg && *(s - 1) == '\\')
--s;
}
/* break at a space with an even number of backslashes */
if (*p == ' ' && ((p - s) & 1) == 0) {
++p;
break;
}
--p;
}
if (STRNCMP(p, "no", 2) == 0) {
xp->xp_context = EXPAND_BOOL_SETTINGS;
p += 2;
}
if (STRNCMP(p, "inv", 3) == 0) {
xp->xp_context = EXPAND_BOOL_SETTINGS;
p += 3;
}
xp->xp_pattern = arg = p;
if (*arg == '<') {
while (*p != '>')
if (*p++ == NUL) /* expand terminal option name */
return;
key = get_special_key_code(arg + 1);
if (key == 0) { /* unknown name */
xp->xp_context = EXPAND_NOTHING;
return;
}
nextchar = *++p;
is_term_option = TRUE;
expand_option_name[2] = (char_u)KEY2TERMCAP0(key);
expand_option_name[3] = KEY2TERMCAP1(key);
} else {
if (p[0] == 't' && p[1] == '_') {
p += 2;
if (*p != NUL)
++p;
if (*p == NUL)
return; /* expand option name */
nextchar = *++p;
is_term_option = TRUE;
expand_option_name[2] = p[-2];
expand_option_name[3] = p[-1];
} else {
/* Allow * wildcard */
while (ASCII_ISALNUM(*p) || *p == '_' || *p == '*')
p++;
if (*p == NUL)
return;
nextchar = *p;
*p = NUL;
opt_idx = findoption(arg);
*p = nextchar;
if (opt_idx == -1 || options[opt_idx].var == NULL) {
xp->xp_context = EXPAND_NOTHING;
return;
}
flags = options[opt_idx].flags;
if (flags & P_BOOL) {
xp->xp_context = EXPAND_NOTHING;
return;
}
}
}
/* handle "-=" and "+=" */
if ((nextchar == '-' || nextchar == '+' || nextchar == '^') && p[1] == '=') {
++p;
nextchar = '=';
}
if ((nextchar != '=' && nextchar != ':')
|| xp->xp_context == EXPAND_BOOL_SETTINGS) {
xp->xp_context = EXPAND_UNSUCCESSFUL;
return;
}
if (xp->xp_context != EXPAND_BOOL_SETTINGS && p[1] == NUL) {
xp->xp_context = EXPAND_OLD_SETTING;
if (is_term_option)
expand_option_idx = -1;
else
expand_option_idx = opt_idx;
xp->xp_pattern = p + 1;
return;
}
xp->xp_context = EXPAND_NOTHING;
if (is_term_option || (flags & P_NUM))
return;
xp->xp_pattern = p + 1;
if (flags & P_EXPAND) {
p = options[opt_idx].var;
if (p == (char_u *)&p_bdir
|| p == (char_u *)&p_dir
|| p == (char_u *)&p_path
|| p == (char_u *)&p_pp
|| p == (char_u *)&p_rtp
|| p == (char_u *)&p_cdpath
|| p == (char_u *)&p_vdir
) {
xp->xp_context = EXPAND_DIRECTORIES;
if (p == (char_u *)&p_path
|| p == (char_u *)&p_cdpath
)
xp->xp_backslash = XP_BS_THREE;
else
xp->xp_backslash = XP_BS_ONE;
} else {
xp->xp_context = EXPAND_FILES;
/* for 'tags' need three backslashes for a space */
if (p == (char_u *)&p_tags)
xp->xp_backslash = XP_BS_THREE;
else
xp->xp_backslash = XP_BS_ONE;
}
}
/* For an option that is a list of file names, find the start of the
* last file name. */
for (p = arg + STRLEN(arg) - 1; p > xp->xp_pattern; --p) {
/* count number of backslashes before ' ' or ',' */
if (*p == ' ' || *p == ',') {
s = p;
while (s > xp->xp_pattern && *(s - 1) == '\\')
--s;
if ((*p == ' ' && (xp->xp_backslash == XP_BS_THREE && (p - s) < 3))
|| (*p == ',' && (flags & P_COMMA) && ((p - s) & 1) == 0)) {
xp->xp_pattern = p + 1;
break;
}
}
/* for 'spellsuggest' start at "file:" */
if (options[opt_idx].var == (char_u *)&p_sps
&& STRNCMP(p, "file:", 5) == 0) {
xp->xp_pattern = p + 5;
break;
}
}
return;
}
int ExpandSettings(expand_T *xp, regmatch_T *regmatch, int *num_file, char_u ***file)
{
int num_normal = 0; // Nr of matching non-term-code settings
int match;
int count = 0;
char_u *str;
int loop;
static char *(names[]) = {"all", "termcap"};
int ic = regmatch->rm_ic; /* remember the ignore-case flag */
/* do this loop twice:
* loop == 0: count the number of matching options
* loop == 1: copy the matching options into allocated memory
*/
for (loop = 0; loop <= 1; ++loop) {
regmatch->rm_ic = ic;
if (xp->xp_context != EXPAND_BOOL_SETTINGS) {
for (match = 0; match < (int)ARRAY_SIZE(names);
++match)
if (vim_regexec(regmatch, (char_u *)names[match], (colnr_T)0)) {
if (loop == 0)
num_normal++;
else
(*file)[count++] = vim_strsave((char_u *)names[match]);
}
}
for (size_t opt_idx = 0; (str = (char_u *)options[opt_idx].fullname) != NULL;
opt_idx++) {
if (options[opt_idx].var == NULL)
continue;
if (xp->xp_context == EXPAND_BOOL_SETTINGS
&& !(options[opt_idx].flags & P_BOOL))
continue;
match = FALSE;
if (vim_regexec(regmatch, str, (colnr_T)0)
|| (options[opt_idx].shortname != NULL
&& vim_regexec(regmatch,
(char_u *)options[opt_idx].shortname, (colnr_T)0))){
match = TRUE;
}
if (match) {
if (loop == 0) {
num_normal++;
} else
(*file)[count++] = vim_strsave(str);
}
}
if (loop == 0) {
if (num_normal > 0) {
*num_file = num_normal;
} else {
return OK;
}
*file = (char_u **)xmalloc((size_t)(*num_file) * sizeof(char_u *));
}
}
return OK;
}
void ExpandOldSetting(int *num_file, char_u ***file)
{
char_u *var = NULL;
*num_file = 0;
*file = (char_u **)xmalloc(sizeof(char_u *));
/*
* For a terminal key code expand_option_idx is < 0.
*/
if (expand_option_idx < 0) {
expand_option_idx = findoption(expand_option_name);
}
if (expand_option_idx >= 0) {
/* put string of option value in NameBuff */
option_value2string(&options[expand_option_idx], expand_option_flags);
var = NameBuff;
} else if (var == NULL)
var = (char_u *)"";
/* A backslash is required before some characters. This is the reverse of
* what happens in do_set(). */
char_u *buf = vim_strsave_escaped(var, escape_chars);
#ifdef BACKSLASH_IN_FILENAME
/* For MS-Windows et al. we don't double backslashes at the start and
* before a file name character. */
for (var = buf; *var != NUL; mb_ptr_adv(var))
if (var[0] == '\\' && var[1] == '\\'
&& expand_option_idx >= 0
&& (options[expand_option_idx].flags & P_EXPAND)
&& vim_isfilec(var[2])
&& (var[2] != '\\' || (var == buf && var[4] != '\\')))
STRMOVE(var, var + 1);
#endif
*file[0] = buf;
*num_file = 1;
}
/*
* Get the value for the numeric or string option *opp in a nice format into
* NameBuff[]. Must not be called with a hidden option!
*/
static void
option_value2string (
vimoption_T *opp,
int opt_flags /* OPT_GLOBAL and/or OPT_LOCAL */
)
{
char_u *varp;
varp = get_varp_scope(opp, opt_flags);
if (opp->flags & P_NUM) {
long wc = 0;
if (wc_use_keyname(varp, &wc)) {
STRLCPY(NameBuff, get_special_key_name((int)wc, 0), sizeof(NameBuff));
} else if (wc != 0) {
STRLCPY(NameBuff, transchar((int)wc), sizeof(NameBuff));
} else {
snprintf((char *)NameBuff,
sizeof(NameBuff),
"%" PRId64,
(int64_t)*(long *)varp);
}
} else { // P_STRING
varp = *(char_u **)(varp);
if (varp == NULL) /* just in case */
NameBuff[0] = NUL;
else if (opp->flags & P_EXPAND)
home_replace(NULL, varp, NameBuff, MAXPATHL, FALSE);
/* Translate 'pastetoggle' into special key names */
else if ((char_u **)opp->var == &p_pt)
str2specialbuf(p_pt, NameBuff, MAXPATHL);
else
STRLCPY(NameBuff, varp, MAXPATHL);
}
}
/*
* Return TRUE if "varp" points to 'wildchar' or 'wildcharm' and it can be
* printed as a keyname.
* "*wcp" is set to the value of the option if it's 'wildchar' or 'wildcharm'.
*/
static int wc_use_keyname(char_u *varp, long *wcp)
{
if (((long *)varp == &p_wc) || ((long *)varp == &p_wcm)) {
*wcp = *(long *)varp;
if (IS_SPECIAL(*wcp) || find_special_key_in_table((int)*wcp) >= 0)
return TRUE;
}
return FALSE;
}
/*
* Any character has an equivalent 'langmap' character. This is used for
* keyboards that have a special language mode that sends characters above
* 128 (although other characters can be translated too). The "to" field is a
* Vim command character. This avoids having to switch the keyboard back to
* ASCII mode when leaving Insert mode.
*
* langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
* commands.
* langmap_mapga.ga_data is a sorted table of langmap_entry_T.
* This does the same as langmap_mapchar[] for characters >= 256.
*/
/*
* With multi-byte support use growarray for 'langmap' chars >= 256
*/
typedef struct {
int from;
int to;
} langmap_entry_T;
static garray_T langmap_mapga = GA_EMPTY_INIT_VALUE;
/*
* Search for an entry in "langmap_mapga" for "from". If found set the "to"
* field. If not found insert a new entry at the appropriate location.
*/
static void langmap_set_entry(int from, int to)
{
langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
unsigned int a = 0;
assert(langmap_mapga.ga_len >= 0);
unsigned int b = (unsigned int)langmap_mapga.ga_len;
/* Do a binary search for an existing entry. */
while (a != b) {
unsigned int i = (a + b) / 2;
int d = entries[i].from - from;
if (d == 0) {
entries[i].to = to;
return;
}
if (d < 0)
a = i + 1;
else
b = i;
}
ga_grow(&langmap_mapga, 1);
/* insert new entry at position "a" */
entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
memmove(entries + 1, entries,
((unsigned int)langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
++langmap_mapga.ga_len;
entries[0].from = from;
entries[0].to = to;
}
/*
* Apply 'langmap' to multi-byte character "c" and return the result.
*/
int langmap_adjust_mb(int c)
{
langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
int a = 0;
int b = langmap_mapga.ga_len;
while (a != b) {
int i = (a + b) / 2;
int d = entries[i].from - c;
if (d == 0)
return entries[i].to; /* found matching entry */
if (d < 0)
a = i + 1;
else
b = i;
}
return c; /* no entry found, return "c" unmodified */
}
static void langmap_init(void)
{
for (int i = 0; i < 256; i++)
langmap_mapchar[i] = (char_u)i; /* we init with a one-to-one map */
ga_init(&langmap_mapga, sizeof(langmap_entry_T), 8);
}
/*
* Called when langmap option is set; the language map can be
* changed at any time!
*/
static void langmap_set(void)
{
char_u *p;
char_u *p2;
int from, to;
ga_clear(&langmap_mapga); /* clear the previous map first */
langmap_init(); /* back to one-to-one map */
for (p = p_langmap; p[0] != NUL; ) {
for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
mb_ptr_adv(p2)) {
if (p2[0] == '\\' && p2[1] != NUL)
++p2;
}
if (p2[0] == ';')
++p2; /* abcd;ABCD form, p2 points to A */
else
p2 = NULL; /* aAbBcCdD form, p2 is NULL */
while (p[0]) {
if (p[0] == ',') {
++p;
break;
}
if (p[0] == '\\' && p[1] != NUL)
++p;
from = (*mb_ptr2char)(p);
to = NUL;
if (p2 == NULL) {
mb_ptr_adv(p);
if (p[0] != ',') {
if (p[0] == '\\')
++p;
to = (*mb_ptr2char)(p);
}
} else {
if (p2[0] != ',') {
if (p2[0] == '\\')
++p2;
to = (*mb_ptr2char)(p2);
}
}
if (to == NUL) {
EMSG2(_("E357: 'langmap': Matching character missing for %s"),
transchar(from));
return;
}
if (from >= 256)
langmap_set_entry(from, to);
else {
assert(to <= UCHAR_MAX);
langmap_mapchar[from & 255] = (char_u)to;
}
/* Advance to next pair */
mb_ptr_adv(p);
if (p2 != NULL) {
mb_ptr_adv(p2);
if (*p == ';') {
p = p2;
if (p[0] != NUL) {
if (p[0] != ',') {
EMSG2(_(
"E358: 'langmap': Extra characters after semicolon: %s"),
p);
return;
}
++p;
}
break;
}
}
}
}
}
/*
* Return TRUE if format option 'x' is in effect.
* Take care of no formatting when 'paste' is set.
*/
int has_format_option(int x)
{
if (p_paste)
return FALSE;
return vim_strchr(curbuf->b_p_fo, x) != NULL;
}
/// @returns true if "x" is present in 'shortmess' option, or
/// 'shortmess' contains 'a' and "x" is present in SHM_ALL_ABBREVIATIONS.
bool shortmess(int x)
{
return (p_shm != NULL
&& (vim_strchr(p_shm, x) != NULL
|| (vim_strchr(p_shm, 'a') != NULL
&& vim_strchr((char_u *)SHM_ALL_ABBREVIATIONS, x) != NULL)));
}
/*
* paste_option_changed() - Called after p_paste was set or reset.
*/
static void paste_option_changed(void)
{
static int old_p_paste = FALSE;
static int save_sm = 0;
static int save_sta = 0;
static int save_ru = 0;
static int save_ri = 0;
static int save_hkmap = 0;
if (p_paste) {
/*
* Paste switched from off to on.
* Save the current values, so they can be restored later.
*/
if (!old_p_paste) {
/* save options for each buffer */
FOR_ALL_BUFFERS(buf) {
buf->b_p_tw_nopaste = buf->b_p_tw;
buf->b_p_wm_nopaste = buf->b_p_wm;
buf->b_p_sts_nopaste = buf->b_p_sts;
buf->b_p_ai_nopaste = buf->b_p_ai;
buf->b_p_et_nopaste = buf->b_p_et;
}
// save global options
save_sm = p_sm;
save_sta = p_sta;
save_ru = p_ru;
save_ri = p_ri;
save_hkmap = p_hkmap;
// save global values for local buffer options
p_ai_nopaste = p_ai;
p_et_nopaste = p_et;
p_sts_nopaste = p_sts;
p_tw_nopaste = p_tw;
p_wm_nopaste = p_wm;
}
// Always set the option values, also when 'paste' is set when it is
// already on.
// set options for each buffer
FOR_ALL_BUFFERS(buf) {
buf->b_p_tw = 0; // textwidth is 0
buf->b_p_wm = 0; // wrapmargin is 0
buf->b_p_sts = 0; // softtabstop is 0
buf->b_p_ai = 0; // no auto-indent
buf->b_p_et = 0; // no expandtab
}
// set global options
p_sm = 0; // no showmatch
p_sta = 0; // no smarttab
if (p_ru) {
status_redraw_all(); // redraw to remove the ruler
}
p_ru = 0; // no ruler
p_ri = 0; // no reverse insert
p_hkmap = 0; // no Hebrew keyboard
// set global values for local buffer options
p_tw = 0;
p_wm = 0;
p_sts = 0;
p_ai = 0;
}
/*
* Paste switched from on to off: Restore saved values.
*/
else if (old_p_paste) {
/* restore options for each buffer */
FOR_ALL_BUFFERS(buf) {
buf->b_p_tw = buf->b_p_tw_nopaste;
buf->b_p_wm = buf->b_p_wm_nopaste;
buf->b_p_sts = buf->b_p_sts_nopaste;
buf->b_p_ai = buf->b_p_ai_nopaste;
buf->b_p_et = buf->b_p_et_nopaste;
}
/* restore global options */
p_sm = save_sm;
p_sta = save_sta;
if (p_ru != save_ru) {
status_redraw_all(); // redraw to draw the ruler
}
p_ru = save_ru;
p_ri = save_ri;
p_hkmap = save_hkmap;
// set global values for local buffer options
p_ai = p_ai_nopaste;
p_et = p_et_nopaste;
p_sts = p_sts_nopaste;
p_tw = p_tw_nopaste;
p_wm = p_wm_nopaste;
}
old_p_paste = p_paste;
}
/// vimrc_found() - Called when a vimrc or "VIMINIT" has been found.
///
/// Set the values for options that didn't get set yet to the Vim defaults.
/// When "fname" is not NULL, use it to set $"envname" when it wasn't set yet.
void vimrc_found(char_u *fname, char_u *envname)
{
char_u *p;
if (fname != NULL) {
p = (char_u *)vim_getenv((char *)envname);
if (p == NULL) {
/* Set $MYVIMRC to the first vimrc file found. */
p = (char_u *)FullName_save((char *)fname, FALSE);
if (p != NULL) {
vim_setenv((char *)envname, (char *)p);
xfree(p);
}
} else {
xfree(p);
}
}
}
/*
* Return TRUE when option "name" has been set.
* Only works correctly for global options.
*/
int option_was_set(char_u *name)
{
int idx;
idx = findoption(name);
if (idx < 0) /* unknown option */
return FALSE;
if (options[idx].flags & P_WAS_SET)
return TRUE;
return FALSE;
}
/*
* fill_breakat_flags() -- called when 'breakat' changes value.
*/
static void fill_breakat_flags(void)
{
char_u *p;
int i;
for (i = 0; i < 256; i++)
breakat_flags[i] = FALSE;
if (p_breakat != NULL)
for (p = p_breakat; *p; p++)
breakat_flags[*p] = TRUE;
}
/*
* Check an option that can be a range of string values.
*
* Return OK for correct value, FAIL otherwise.
* Empty is always OK.
*/
static int check_opt_strings(
char_u *val,
char **values,
int list /* when TRUE: accept a list of values */
)
{
return opt_strings_flags(val, values, NULL, list);
}
/*
* Handle an option that can be a range of string values.
* Set a flag in "*flagp" for each string present.
*
* Return OK for correct value, FAIL otherwise.
* Empty is always OK.
*/
static int opt_strings_flags(
char_u *val, /* new value */
char **values, /* array of valid string values */
unsigned *flagp,
bool list /* when TRUE: accept a list of values */
)
{
unsigned int new_flags = 0;
while (*val) {
for (unsigned int i = 0;; ++i) {
if (values[i] == NULL) /* val not found in values[] */
return FAIL;
size_t len = STRLEN(values[i]);
if (STRNCMP(values[i], val, len) == 0
&& ((list && val[len] == ',') || val[len] == NUL)) {
val += len + (val[len] == ',');
assert(i < sizeof(1U) * 8);
new_flags |= (1U << i);
break; /* check next item in val list */
}
}
}
if (flagp != NULL)
*flagp = new_flags;
return OK;
}
/*
* Read the 'wildmode' option, fill wim_flags[].
*/
static int check_opt_wim(void)
{
char_u new_wim_flags[4];
char_u *p;
int i;
int idx = 0;
for (i = 0; i < 4; ++i)
new_wim_flags[i] = 0;
for (p = p_wim; *p; ++p) {
for (i = 0; ASCII_ISALPHA(p[i]); ++i)
;
if (p[i] != NUL && p[i] != ',' && p[i] != ':')
return FAIL;
if (i == 7 && STRNCMP(p, "longest", 7) == 0)
new_wim_flags[idx] |= WIM_LONGEST;
else if (i == 4 && STRNCMP(p, "full", 4) == 0)
new_wim_flags[idx] |= WIM_FULL;
else if (i == 4 && STRNCMP(p, "list", 4) == 0)
new_wim_flags[idx] |= WIM_LIST;
else
return FAIL;
p += i;
if (*p == NUL)
break;
if (*p == ',') {
if (idx == 3)
return FAIL;
++idx;
}
}
/* fill remaining entries with last flag */
while (idx < 3) {
new_wim_flags[idx + 1] = new_wim_flags[idx];
++idx;
}
/* only when there are no errors, wim_flags[] is changed */
for (i = 0; i < 4; ++i)
wim_flags[i] = new_wim_flags[i];
return OK;
}
/*
* Check if backspacing over something is allowed.
* The parameter what is one of the following: whatBS_INDENT, BS_EOL
* or BS_START
*/
bool can_bs(int what)
{
switch (*p_bs) {
case '2': return TRUE;
case '1': return what != BS_START;
case '0': return FALSE;
}
return vim_strchr(p_bs, what) != NULL;
}
/*
* Save the current values of 'fileformat' and 'fileencoding', so that we know
* the file must be considered changed when the value is different.
*/
void save_file_ff(buf_T *buf)
{
buf->b_start_ffc = *buf->b_p_ff;
buf->b_start_eol = buf->b_p_eol;
buf->b_start_bomb = buf->b_p_bomb;
/* Only use free/alloc when necessary, they take time. */
if (buf->b_start_fenc == NULL
|| STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0) {
xfree(buf->b_start_fenc);
buf->b_start_fenc = vim_strsave(buf->b_p_fenc);
}
}
/*
* Return TRUE if 'fileformat' and/or 'fileencoding' has a different value
* from when editing started (save_file_ff() called).
* Also when 'endofline' was changed and 'binary' is set, or when 'bomb' was
* changed and 'binary' is not set.
* Also when 'endofline' was changed and 'fixeol' is not set.
* When "ignore_empty" is true don't consider a new, empty buffer to be
* changed.
*/
bool file_ff_differs(buf_T *buf, bool ignore_empty)
{
/* In a buffer that was never loaded the options are not valid. */
if (buf->b_flags & BF_NEVERLOADED)
return FALSE;
if (ignore_empty
&& (buf->b_flags & BF_NEW)
&& buf->b_ml.ml_line_count == 1
&& *ml_get_buf(buf, (linenr_T)1, FALSE) == NUL)
return FALSE;
if (buf->b_start_ffc != *buf->b_p_ff)
return true;
if ((buf->b_p_bin || !buf->b_p_fixeol) && buf->b_start_eol != buf->b_p_eol)
return true;
if (!buf->b_p_bin && buf->b_start_bomb != buf->b_p_bomb)
return TRUE;
if (buf->b_start_fenc == NULL)
return *buf->b_p_fenc != NUL;
return STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0;
}
/*
* return OK if "p" is a valid fileformat name, FAIL otherwise.
*/
int check_ff_value(char_u *p)
{
return check_opt_strings(p, p_ff_values, FALSE);
}
/*
* Return the effective shiftwidth value for current buffer, using the
* 'tabstop' value when 'shiftwidth' is zero.
*/
int get_sw_value(buf_T *buf)
{
long result = buf->b_p_sw ? buf->b_p_sw : buf->b_p_ts;
assert(result >= 0 && result <= INT_MAX);
return (int)result;
}
// Return the effective softtabstop value for the current buffer,
// using the effective shiftwidth value when 'softtabstop' is negative.
int get_sts_value(void)
{
long result = curbuf->b_p_sts < 0 ? get_sw_value(curbuf) : curbuf->b_p_sts;
assert(result >= 0 && result <= INT_MAX);
return (int)result;
}
/*
* Check matchpairs option for "*initc".
* If there is a match set "*initc" to the matching character and "*findc" to
* the opposite character. Set "*backwards" to the direction.
* When "switchit" is TRUE swap the direction.
*/
void find_mps_values(int *initc, int *findc, int *backwards, int switchit)
{
char_u *ptr;
ptr = curbuf->b_p_mps;
while (*ptr != NUL) {
if (has_mbyte) {
char_u *prev;
if (mb_ptr2char(ptr) == *initc) {
if (switchit) {
*findc = *initc;
*initc = mb_ptr2char(ptr + mb_ptr2len(ptr) + 1);
*backwards = TRUE;
} else {
*findc = mb_ptr2char(ptr + mb_ptr2len(ptr) + 1);
*backwards = FALSE;
}
return;
}
prev = ptr;
ptr += mb_ptr2len(ptr) + 1;
if (mb_ptr2char(ptr) == *initc) {
if (switchit) {
*findc = *initc;
*initc = mb_ptr2char(prev);
*backwards = FALSE;
} else {
*findc = mb_ptr2char(prev);
*backwards = TRUE;
}
return;
}
ptr += mb_ptr2len(ptr);
} else {
if (*ptr == *initc) {
if (switchit) {
*backwards = TRUE;
*findc = *initc;
*initc = ptr[2];
} else {
*backwards = FALSE;
*findc = ptr[2];
}
return;
}
ptr += 2;
if (*ptr == *initc) {
if (switchit) {
*backwards = FALSE;
*findc = *initc;
*initc = ptr[-2];
} else {
*backwards = TRUE;
*findc = ptr[-2];
}
return;
}
++ptr;
}
if (*ptr == ',')
++ptr;
}
}
/// This is called when 'breakindentopt' is changed and when a window is
/// initialized
static bool briopt_check(win_T *wp)
{
int bri_shift = 0;
int bri_min = 20;
bool bri_sbr = false;
char_u *p = wp->w_p_briopt;
while (*p != NUL)
{
if (STRNCMP(p, "shift:", 6) == 0
&& ((p[6] == '-' && ascii_isdigit(p[7])) || ascii_isdigit(p[6])))
{
p += 6;
bri_shift = getdigits_int(&p);
}
else if (STRNCMP(p, "min:", 4) == 0 && ascii_isdigit(p[4]))
{
p += 4;
bri_min = getdigits_int(&p);
}
else if (STRNCMP(p, "sbr", 3) == 0)
{
p += 3;
bri_sbr = true;
}
if (*p != ',' && *p != NUL)
return false;
if (*p == ',')
++p;
}
wp->w_p_brishift = bri_shift;
wp->w_p_brimin = bri_min;
wp->w_p_brisbr = bri_sbr;
return true;
}
/// Get the local or global value of 'backupcopy'.
///
/// @param buf The buffer.
unsigned int get_bkc_value(buf_T *buf)
{
return buf->b_bkc_flags ? buf->b_bkc_flags : bkc_flags;
}
/// Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
int get_fileformat(buf_T *buf)
{
int c = *buf->b_p_ff;
if (buf->b_p_bin || c == 'u') {
return EOL_UNIX;
}
if (c == 'm') {
return EOL_MAC;
}
return EOL_DOS;
}
/// Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
/// argument.
///
/// @param eap can be NULL!
int get_fileformat_force(buf_T *buf, exarg_T *eap)
{
int c;
if (eap != NULL && eap->force_ff != 0) {
c = eap->cmd[eap->force_ff];
} else {
if ((eap != NULL && eap->force_bin != 0)
? (eap->force_bin == FORCE_BIN) : buf->b_p_bin) {
return EOL_UNIX;
}
c = *buf->b_p_ff;
}
if (c == 'u') {
return EOL_UNIX;
}
if (c == 'm') {
return EOL_MAC;
}
return EOL_DOS;
}
/// Return the default fileformat from 'fileformats'.
int default_fileformat(void)
{
switch (*p_ffs) {
case 'm': return EOL_MAC;
case 'd': return EOL_DOS;
}
return EOL_UNIX;
}
/// Set the current end-of-line type to EOL_UNIX, EOL_MAC, or EOL_DOS.
///
/// Sets 'fileformat'.
///
/// @param eol_style End-of-line style.
/// @param opt_flags OPT_LOCAL and/or OPT_GLOBAL
void set_fileformat(int eol_style, int opt_flags)
{
char *p = NULL;
switch (eol_style) {
case EOL_UNIX:
p = FF_UNIX;
break;
case EOL_MAC:
p = FF_MAC;
break;
case EOL_DOS:
p = FF_DOS;
break;
}
// p is NULL if "eol_style" is EOL_UNKNOWN.
if (p != NULL) {
set_string_option_direct((char_u *)"ff",
-1,
(char_u *)p,
OPT_FREE | opt_flags,
0);
}
// This may cause the buffer to become (un)modified.
check_status(curbuf);
redraw_tabline = true;
need_maketitle = true; // Set window title later.
}
/// Skip to next part of an option argument: Skip space and comma.
char_u *skip_to_option_part(char_u *p)
{
if (*p == ',') {
p++;
}
while (*p == ' ') {
p++;
}
return p;
}
/// Isolate one part of a string option separated by `sep_chars`.
///
/// @param[in,out] option advanced to the next part
/// @param[in,out] buf copy of the isolated part
/// @param[in] maxlen length of `buf`
/// @param[in] sep_chars chars that separate the option parts
///
/// @return length of `*option`
size_t copy_option_part(char_u **option, char_u *buf, size_t maxlen,
char *sep_chars)
{
size_t len = 0;
char_u *p = *option;
// skip '.' at start of option part, for 'suffixes'
if (*p == '.') {
buf[len++] = *p++;
}
while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL) {
// Skip backslash before a separator character and space.
if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL) {
p++;
}
if (len < maxlen - 1) {
buf[len++] = *p;
}
p++;
}
buf[len] = NUL;
if (*p != NUL && *p != ',') { // skip non-standard separator
p++;
}
p = skip_to_option_part(p); // p points to next file name
*option = p;
return len;
}
/// Return TRUE when 'shell' has "csh" in the tail.
int csh_like_shell(void)
{
return strstr((char *)path_tail(p_sh), "csh") != NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4899_0 |
crossvul-cpp_data_good_1284_2 | /*
** 2008 August 18
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains routines used for walking the parser tree and
** resolve all identifiers by associating them with a particular
** table and column.
*/
#include "sqliteInt.h"
/*
** Walk the expression tree pExpr and increase the aggregate function
** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
** This needs to occur when copying a TK_AGG_FUNCTION node from an
** outer query into an inner subquery.
**
** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
** is a helper function - a callback for the tree walker.
*/
static int incrAggDepth(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
return WRC_Continue;
}
static void incrAggFunctionDepth(Expr *pExpr, int N){
if( N>0 ){
Walker w;
memset(&w, 0, sizeof(w));
w.xExprCallback = incrAggDepth;
w.u.n = N;
sqlite3WalkExpr(&w, pExpr);
}
}
/*
** Turn the pExpr expression into an alias for the iCol-th column of the
** result set in pEList.
**
** If the reference is followed by a COLLATE operator, then make sure
** the COLLATE operator is preserved. For example:
**
** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
**
** Should be transformed into:
**
** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
**
** The nSubquery parameter specifies how many levels of subquery the
** alias is removed from the original expression. The usual value is
** zero but it might be more if the alias is contained within a subquery
** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
** structures must be increased by the nSubquery amount.
*/
static void resolveAlias(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* A result set */
int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
Expr *pExpr, /* Transform this into an alias to the result set */
const char *zType, /* "GROUP" or "ORDER" or "" */
int nSubquery /* Number of subqueries that the label is moving */
){
Expr *pOrig; /* The iCol-th column of the result set */
Expr *pDup; /* Copy of pOrig */
sqlite3 *db; /* The database connection */
assert( iCol>=0 && iCol<pEList->nExpr );
pOrig = pEList->a[iCol].pExpr;
assert( pOrig!=0 );
db = pParse->db;
pDup = sqlite3ExprDup(db, pOrig, 0);
if( pDup!=0 ){
if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
if( pExpr->op==TK_COLLATE ){
pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
}
/* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
** prevents ExprDelete() from deleting the Expr structure itself,
** allowing it to be repopulated by the memcpy() on the following line.
** The pExpr->u.zToken might point into memory that will be freed by the
** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
** make a copy of the token before doing the sqlite3DbFree().
*/
ExprSetProperty(pExpr, EP_Static);
sqlite3ExprDelete(db, pExpr);
memcpy(pExpr, pDup, sizeof(*pExpr));
if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
pExpr->flags |= EP_MemToken;
}
if( ExprHasProperty(pExpr, EP_WinFunc) ){
if( pExpr->y.pWin!=0 ){
pExpr->y.pWin->pOwner = pExpr;
}else{
assert( db->mallocFailed );
}
}
sqlite3DbFree(db, pDup);
}
ExprSetProperty(pExpr, EP_Alias);
}
/*
** Return TRUE if the name zCol occurs anywhere in the USING clause.
**
** Return FALSE if the USING clause is NULL or if it does not contain
** zCol.
*/
static int nameInUsingClause(IdList *pUsing, const char *zCol){
if( pUsing ){
int k;
for(k=0; k<pUsing->nId; k++){
if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
}
}
return 0;
}
/*
** Subqueries stores the original database, table and column names for their
** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
** Check to see if the zSpan given to this routine matches the zDb, zTab,
** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
** match anything.
*/
int sqlite3MatchSpanName(
const char *zSpan,
const char *zCol,
const char *zTab,
const char *zDb
){
int n;
for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
return 0;
}
zSpan += n+1;
for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
return 0;
}
zSpan += n+1;
if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
return 0;
}
return 1;
}
/*
** Return TRUE if the double-quoted string mis-feature should be supported.
*/
static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
if( db->init.busy ) return 1; /* Always support for legacy schemas */
if( pTopNC->ncFlags & NC_IsDDL ){
/* Currently parsing a DDL statement */
if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
return 1;
}
return (db->flags & SQLITE_DqsDDL)!=0;
}else{
/* Currently parsing a DML statement */
return (db->flags & SQLITE_DqsDML)!=0;
}
}
/*
** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
** that name in the set of source tables in pSrcList and make the pExpr
** expression node refer back to that source column. The following changes
** are made to pExpr:
**
** pExpr->iDb Set the index in db->aDb[] of the database X
** (even if X is implied).
** pExpr->iTable Set to the cursor number for the table obtained
** from pSrcList.
** pExpr->y.pTab Points to the Table structure of X.Y (even if
** X and/or Y are implied.)
** pExpr->iColumn Set to the column number within the table.
** pExpr->op Set to TK_COLUMN.
** pExpr->pLeft Any expression this points to is deleted
** pExpr->pRight Any expression this points to is deleted.
**
** The zDb variable is the name of the database (the "X"). This value may be
** NULL meaning that name is of the form Y.Z or Z. Any available database
** can be used. The zTable variable is the name of the table (the "Y"). This
** value can be NULL if zDb is also NULL. If zTable is NULL it
** means that the form of the name is Z and that columns from any table
** can be used.
**
** If the name cannot be resolved unambiguously, leave an error message
** in pParse and return WRC_Abort. Return WRC_Prune on success.
*/
static int lookupName(
Parse *pParse, /* The parsing context */
const char *zDb, /* Name of the database containing table, or NULL */
const char *zTab, /* Name of table containing column, or NULL */
const char *zCol, /* Name of the column. */
NameContext *pNC, /* The name context used to resolve the name */
Expr *pExpr /* Make this EXPR node point to the selected column */
){
int i, j; /* Loop counters */
int cnt = 0; /* Number of matching column names */
int cntTab = 0; /* Number of matching table names */
int nSubquery = 0; /* How many levels of subquery */
sqlite3 *db = pParse->db; /* The database connection */
struct SrcList_item *pItem; /* Use for looping over pSrcList items */
struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
NameContext *pTopNC = pNC; /* First namecontext in the list */
Schema *pSchema = 0; /* Schema of the expression */
int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
Table *pTab = 0; /* Table hold the row */
Column *pCol; /* A column of pTab */
assert( pNC ); /* the name context cannot be NULL. */
assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
/* Initialize the node to no-match */
pExpr->iTable = -1;
ExprSetVVAProperty(pExpr, EP_NoReduce);
/* Translate the schema name in zDb into a pointer to the corresponding
** schema. If not found, pSchema will remain NULL and nothing will match
** resulting in an appropriate error message toward the end of this routine
*/
if( zDb ){
testcase( pNC->ncFlags & NC_PartIdx );
testcase( pNC->ncFlags & NC_IsCheck );
if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
/* Silently ignore database qualifiers inside CHECK constraints and
** partial indices. Do not raise errors because that might break
** legacy and because it does not hurt anything to just ignore the
** database name. */
zDb = 0;
}else{
for(i=0; i<db->nDb; i++){
assert( db->aDb[i].zDbSName );
if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
pSchema = db->aDb[i].pSchema;
break;
}
}
}
}
/* Start at the inner-most context and move outward until a match is found */
assert( pNC && cnt==0 );
do{
ExprList *pEList;
SrcList *pSrcList = pNC->pSrcList;
if( pSrcList ){
for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
pTab = pItem->pTab;
assert( pTab!=0 && pTab->zName!=0 );
assert( pTab->nCol>0 );
if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
int hit = 0;
pEList = pItem->pSelect->pEList;
for(j=0; j<pEList->nExpr; j++){
if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
cnt++;
cntTab = 2;
pMatch = pItem;
pExpr->iColumn = j;
hit = 1;
}
}
if( hit || zTab==0 ) continue;
}
if( zDb && pTab->pSchema!=pSchema ){
continue;
}
if( zTab ){
const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
assert( zTabName!=0 );
if( sqlite3StrICmp(zTabName, zTab)!=0 ){
continue;
}
if( IN_RENAME_OBJECT && pItem->zAlias ){
sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
}
}
if( 0==(cntTab++) ){
pMatch = pItem;
}
for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
/* If there has been exactly one prior match and this match
** is for the right-hand table of a NATURAL JOIN or is in a
** USING clause, then skip this match.
*/
if( cnt==1 ){
if( pItem->fg.jointype & JT_NATURAL ) continue;
if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
}
cnt++;
pMatch = pItem;
/* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
break;
}
}
}
if( pMatch ){
pExpr->iTable = pMatch->iCursor;
pExpr->y.pTab = pMatch->pTab;
/* RIGHT JOIN not (yet) supported */
assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
ExprSetProperty(pExpr, EP_CanBeNull);
}
pSchema = pExpr->y.pTab->pSchema;
}
} /* if( pSrcList ) */
#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
/* If we have not already resolved the name, then maybe
** it is a new.* or old.* trigger argument reference. Or
** maybe it is an excluded.* from an upsert.
*/
if( zDb==0 && zTab!=0 && cntTab==0 ){
pTab = 0;
#ifndef SQLITE_OMIT_TRIGGER
if( pParse->pTriggerTab!=0 ){
int op = pParse->eTriggerOp;
assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
pExpr->iTable = 1;
pTab = pParse->pTriggerTab;
}else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
pExpr->iTable = 0;
pTab = pParse->pTriggerTab;
}
}
#endif /* SQLITE_OMIT_TRIGGER */
#ifndef SQLITE_OMIT_UPSERT
if( (pNC->ncFlags & NC_UUpsert)!=0 ){
Upsert *pUpsert = pNC->uNC.pUpsert;
if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
pTab = pUpsert->pUpsertSrc->a[0].pTab;
pExpr->iTable = 2;
}
}
#endif /* SQLITE_OMIT_UPSERT */
if( pTab ){
int iCol;
pSchema = pTab->pSchema;
cntTab++;
for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
if( iCol==pTab->iPKey ){
iCol = -1;
}
break;
}
}
if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
/* IMP: R-51414-32910 */
iCol = -1;
}
if( iCol<pTab->nCol ){
cnt++;
#ifndef SQLITE_OMIT_UPSERT
if( pExpr->iTable==2 ){
testcase( iCol==(-1) );
if( IN_RENAME_OBJECT ){
pExpr->iColumn = iCol;
pExpr->y.pTab = pTab;
eNewExprOp = TK_COLUMN;
}else{
pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
eNewExprOp = TK_REGISTER;
ExprSetProperty(pExpr, EP_Alias);
}
}else
#endif /* SQLITE_OMIT_UPSERT */
{
#ifndef SQLITE_OMIT_TRIGGER
if( iCol<0 ){
pExpr->affExpr = SQLITE_AFF_INTEGER;
}else if( pExpr->iTable==0 ){
testcase( iCol==31 );
testcase( iCol==32 );
pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
}else{
testcase( iCol==31 );
testcase( iCol==32 );
pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
}
pExpr->y.pTab = pTab;
pExpr->iColumn = (i16)iCol;
eNewExprOp = TK_TRIGGER;
#endif /* SQLITE_OMIT_TRIGGER */
}
}
}
}
#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
/*
** Perhaps the name is a reference to the ROWID
*/
if( cnt==0
&& cntTab==1
&& pMatch
&& (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
&& sqlite3IsRowid(zCol)
&& VisibleRowid(pMatch->pTab)
){
cnt = 1;
pExpr->iColumn = -1;
pExpr->affExpr = SQLITE_AFF_INTEGER;
}
/*
** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
** might refer to an result-set alias. This happens, for example, when
** we are resolving names in the WHERE clause of the following command:
**
** SELECT a+b AS x FROM table WHERE x<10;
**
** In cases like this, replace pExpr with a copy of the expression that
** forms the result set entry ("a+b" in the example) and return immediately.
** Note that the expression in the result set should have already been
** resolved by the time the WHERE clause is resolved.
**
** The ability to use an output result-set column in the WHERE, GROUP BY,
** or HAVING clauses, or as part of a larger expression in the ORDER BY
** clause is not standard SQL. This is a (goofy) SQLite extension, that
** is supported for backwards compatibility only. Hence, we issue a warning
** on sqlite3_log() whenever the capability is used.
*/
if( (pNC->ncFlags & NC_UEList)!=0
&& cnt==0
&& zTab==0
){
pEList = pNC->uNC.pEList;
assert( pEList!=0 );
for(j=0; j<pEList->nExpr; j++){
char *zAs = pEList->a[j].zName;
if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
Expr *pOrig;
assert( pExpr->pLeft==0 && pExpr->pRight==0 );
assert( pExpr->x.pList==0 );
assert( pExpr->x.pSelect==0 );
pOrig = pEList->a[j].pExpr;
if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
return WRC_Abort;
}
if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){
sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
return WRC_Abort;
}
if( sqlite3ExprVectorSize(pOrig)!=1 ){
sqlite3ErrorMsg(pParse, "row value misused");
return WRC_Abort;
}
resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
cnt = 1;
pMatch = 0;
assert( zTab==0 && zDb==0 );
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
}
goto lookupname_end;
}
}
}
/* Advance to the next name context. The loop will exit when either
** we have a match (cnt>0) or when we run out of name contexts.
*/
if( cnt ) break;
pNC = pNC->pNext;
nSubquery++;
}while( pNC );
/*
** If X and Y are NULL (in other words if only the column name Z is
** supplied) and the value of Z is enclosed in double-quotes, then
** Z is a string literal if it doesn't match any column names. In that
** case, we need to return right away and not make any changes to
** pExpr.
**
** Because no reference was made to outer contexts, the pNC->nRef
** fields are not changed in any context.
*/
if( cnt==0 && zTab==0 ){
assert( pExpr->op==TK_ID );
if( ExprHasProperty(pExpr,EP_DblQuoted)
&& areDoubleQuotedStringsEnabled(db, pTopNC)
){
/* If a double-quoted identifier does not match any known column name,
** then treat it as a string.
**
** This hack was added in the early days of SQLite in a misguided attempt
** to be compatible with MySQL 3.x, which used double-quotes for strings.
** I now sorely regret putting in this hack. The effect of this hack is
** that misspelled identifier names are silently converted into strings
** rather than causing an error, to the frustration of countless
** programmers. To all those frustrated programmers, my apologies.
**
** Someday, I hope to get rid of this hack. Unfortunately there is
** a huge amount of legacy SQL that uses it. So for now, we just
** issue a warning.
*/
sqlite3_log(SQLITE_WARNING,
"double-quoted string literal: \"%w\"", zCol);
#ifdef SQLITE_ENABLE_NORMALIZE
sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
#endif
pExpr->op = TK_STRING;
pExpr->y.pTab = 0;
return WRC_Prune;
}
if( sqlite3ExprIdToTrueFalse(pExpr) ){
return WRC_Prune;
}
}
/*
** cnt==0 means there was not match. cnt>1 means there were two or
** more matches. Either way, we have an error.
*/
if( cnt!=1 ){
const char *zErr;
zErr = cnt==0 ? "no such column" : "ambiguous column name";
if( zDb ){
sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
}else if( zTab ){
sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
}else{
sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
}
pParse->checkSchema = 1;
pTopNC->nErr++;
}
/* If a column from a table in pSrcList is referenced, then record
** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
** bit 0 to be set. Column 1 sets bit 1. And so forth.
**
** The colUsed mask is an optimization used to help determine if an
** index is a covering index. The correct answer is still obtained
** if the mask contains extra bits. But omitting bits from the mask
** might result in an incorrect answer.
**
** The high-order bit of the mask is a "we-use-them-all" bit.
** If the column number is greater than the number of bits in the bitmask
** then set the high-order bit of the bitmask. Also set the high-order
** bit if the column is a generated column, as that adds dependencies
** that are difficult to track, so we assume that all columns are used.
*/
if( pExpr->iColumn>=0 && pMatch!=0 ){
int n = pExpr->iColumn;
testcase( n==BMS-1 );
if( n>=BMS ){
n = BMS-1;
}
assert( pExpr->y.pTab!=0 );
assert( pMatch->iCursor==pExpr->iTable );
if( pExpr->y.pTab->tabFlags & TF_HasGenerated ){
Column *pCol = pExpr->y.pTab->aCol + pExpr->iColumn;
if( pCol->colFlags & COLFLAG_GENERATED ) n = BMS-1;
}
pMatch->colUsed |= ((Bitmask)1)<<n;
}
/* Clean up and return
*/
sqlite3ExprDelete(db, pExpr->pLeft);
pExpr->pLeft = 0;
sqlite3ExprDelete(db, pExpr->pRight);
pExpr->pRight = 0;
pExpr->op = eNewExprOp;
ExprSetProperty(pExpr, EP_Leaf);
lookupname_end:
if( cnt==1 ){
assert( pNC!=0 );
if( !ExprHasProperty(pExpr, EP_Alias) ){
sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
}
/* Increment the nRef value on all name contexts from TopNC up to
** the point where the name matched. */
for(;;){
assert( pTopNC!=0 );
pTopNC->nRef++;
if( pTopNC==pNC ) break;
pTopNC = pTopNC->pNext;
}
return WRC_Prune;
} else {
return WRC_Abort;
}
}
/*
** Allocate and return a pointer to an expression to load the column iCol
** from datasource iSrc in SrcList pSrc.
*/
Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
if( p ){
struct SrcList_item *pItem = &pSrc->a[iSrc];
p->y.pTab = pItem->pTab;
p->iTable = pItem->iCursor;
if( p->y.pTab->iPKey==iCol ){
p->iColumn = -1;
}else{
p->iColumn = (ynVar)iCol;
testcase( iCol==BMS );
testcase( iCol==BMS-1 );
pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
}
}
return p;
}
/*
** Report an error that an expression is not valid for some set of
** pNC->ncFlags values determined by validMask.
*/
static void notValid(
Parse *pParse, /* Leave error message here */
NameContext *pNC, /* The name context */
const char *zMsg, /* Type of error */
int validMask /* Set of contexts for which prohibited */
){
assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 );
if( (pNC->ncFlags & validMask)!=0 ){
const char *zIn = "partial index WHERE clauses";
if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
#ifndef SQLITE_OMIT_CHECK
else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
#endif
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
#endif
sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
}
}
/*
** Expression p should encode a floating point value between 1.0 and 0.0.
** Return 1024 times this value. Or return -1 if p is not a floating point
** value between 1.0 and 0.0.
*/
static int exprProbability(Expr *p){
double r = -1.0;
if( p->op!=TK_FLOAT ) return -1;
sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
assert( r>=0.0 );
if( r>1.0 ) return -1;
return (int)(r*134217728.0);
}
/*
** This routine is callback for sqlite3WalkExpr().
**
** Resolve symbolic names into TK_COLUMN operators for the current
** node in the expression tree. Return 0 to continue the search down
** the tree or 2 to abort the tree walk.
**
** This routine also does error checking and name resolution for
** function names. The operator for aggregate functions is changed
** to TK_AGG_FUNCTION.
*/
static int resolveExprStep(Walker *pWalker, Expr *pExpr){
NameContext *pNC;
Parse *pParse;
pNC = pWalker->u.pNC;
assert( pNC!=0 );
pParse = pNC->pParse;
assert( pParse==pWalker->pParse );
#ifndef NDEBUG
if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
SrcList *pSrcList = pNC->pSrcList;
int i;
for(i=0; i<pNC->pSrcList->nSrc; i++){
assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
}
}
#endif
switch( pExpr->op ){
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
/* The special operator TK_ROW means use the rowid for the first
** column in the FROM clause. This is used by the LIMIT and ORDER BY
** clause processing on UPDATE and DELETE statements.
*/
case TK_ROW: {
SrcList *pSrcList = pNC->pSrcList;
struct SrcList_item *pItem;
assert( pSrcList && pSrcList->nSrc==1 );
pItem = pSrcList->a;
assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
pExpr->op = TK_COLUMN;
pExpr->y.pTab = pItem->pTab;
pExpr->iTable = pItem->iCursor;
pExpr->iColumn = -1;
pExpr->affExpr = SQLITE_AFF_INTEGER;
break;
}
#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
&& !defined(SQLITE_OMIT_SUBQUERY) */
/* A column name: ID
** Or table name and column name: ID.ID
** Or a database, table and column: ID.ID.ID
**
** The TK_ID and TK_OUT cases are combined so that there will only
** be one call to lookupName(). Then the compiler will in-line
** lookupName() for a size reduction and performance increase.
*/
case TK_ID:
case TK_DOT: {
const char *zColumn;
const char *zTable;
const char *zDb;
Expr *pRight;
if( pExpr->op==TK_ID ){
zDb = 0;
zTable = 0;
zColumn = pExpr->u.zToken;
}else{
Expr *pLeft = pExpr->pLeft;
notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr|NC_GenCol);
pRight = pExpr->pRight;
if( pRight->op==TK_ID ){
zDb = 0;
}else{
assert( pRight->op==TK_DOT );
zDb = pLeft->u.zToken;
pLeft = pRight->pLeft;
pRight = pRight->pRight;
}
zTable = pLeft->u.zToken;
zColumn = pRight->u.zToken;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
}
}
return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
}
/* Resolve function names
*/
case TK_FUNCTION: {
ExprList *pList = pExpr->x.pList; /* The argument list */
int n = pList ? pList->nExpr : 0; /* Number of arguments */
int no_such_func = 0; /* True if no such function exists */
int wrong_num_args = 0; /* True if wrong number of arguments */
int is_agg = 0; /* True if is an aggregate function */
int nId; /* Number of characters in function name */
const char *zId; /* The function name. */
FuncDef *pDef; /* Information about the function */
u8 enc = ENC(pParse->db); /* The database encoding */
int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
#ifndef SQLITE_OMIT_WINDOWFUNC
Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
#endif
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
zId = pExpr->u.zToken;
nId = sqlite3Strlen30(zId);
pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
if( pDef==0 ){
pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
if( pDef==0 ){
no_such_func = 1;
}else{
wrong_num_args = 1;
}
}else{
is_agg = pDef->xFinalize!=0;
if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
ExprSetProperty(pExpr, EP_Unlikely);
if( n==2 ){
pExpr->iTable = exprProbability(pList->a[1].pExpr);
if( pExpr->iTable<0 ){
sqlite3ErrorMsg(pParse,
"second argument to likelihood() must be a "
"constant between 0.0 and 1.0");
pNC->nErr++;
}
}else{
/* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
** equivalent to likelihood(X, 0.0625).
** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
** short-hand for likelihood(X,0.0625).
** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
** for likelihood(X,0.9375).
** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
** to likelihood(X,0.9375). */
/* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
}
}
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
if( auth!=SQLITE_OK ){
if( auth==SQLITE_DENY ){
sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
pDef->zName);
pNC->nErr++;
}
pExpr->op = TK_NULL;
return WRC_Prune;
}
}
#endif
if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
/* For the purposes of the EP_ConstFunc flag, date and time
** functions and other functions that change slowly are considered
** constant because they are constant for the duration of one query.
** This allows them to be factored out of inner loops. */
ExprSetProperty(pExpr,EP_ConstFunc);
}
if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
/* Date/time functions that use 'now', and other functions like
** sqlite_version() that might change over time cannot be used
** in an index. */
notValid(pParse, pNC, "non-deterministic functions", NC_SelfRef);
}else{
assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
pExpr->op2 = pNC->ncFlags & NC_SelfRef;
}
if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
&& pParse->nested==0
&& sqlite3Config.bInternalFunctions==0
){
/* Internal-use-only functions are disallowed unless the
** SQL is being compiled using sqlite3NestedParse() */
no_such_func = 1;
pDef = 0;
}else
if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
&& ExprHasProperty(pExpr, EP_Indirect)
&& !IN_RENAME_OBJECT
){
/* Functions tagged with SQLITE_DIRECTONLY may not be used
** inside of triggers and views */
sqlite3ErrorMsg(pParse, "%s() prohibited in triggers and views",
pDef->zName);
}
}
if( 0==IN_RENAME_OBJECT ){
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
|| (pDef->xValue==0 && pDef->xInverse==0)
|| (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
);
if( pDef && pDef->xValue==0 && pWin ){
sqlite3ErrorMsg(pParse,
"%.*s() may not be used as a window function", nId, zId
);
pNC->nErr++;
}else if(
(is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
|| (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
|| (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
){
const char *zType;
if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
zType = "window";
}else{
zType = "aggregate";
}
sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
pNC->nErr++;
is_agg = 0;
}
#else
if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
pNC->nErr++;
is_agg = 0;
}
#endif
else if( no_such_func && pParse->db->init.busy==0
#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
&& pParse->explain==0
#endif
){
sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
pNC->nErr++;
}else if( wrong_num_args ){
sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
nId, zId);
pNC->nErr++;
}
#ifndef SQLITE_OMIT_WINDOWFUNC
else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
sqlite3ErrorMsg(pParse,
"FILTER may not be used with non-aggregate %.*s()",
nId, zId
);
pNC->nErr++;
}
#endif
if( is_agg ){
/* Window functions may not be arguments of aggregate functions.
** Or arguments of other window functions. But aggregate functions
** may be arguments for window functions. */
#ifndef SQLITE_OMIT_WINDOWFUNC
pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
#else
pNC->ncFlags &= ~NC_AllowAgg;
#endif
}
}
#ifndef SQLITE_OMIT_WINDOWFUNC
else if( ExprHasProperty(pExpr, EP_WinFunc) ){
is_agg = 1;
}
#endif
sqlite3WalkExprList(pWalker, pList);
if( is_agg ){
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pWin ){
Select *pSel = pNC->pWinSelect;
assert( pWin==pExpr->y.pWin );
if( IN_RENAME_OBJECT==0 ){
sqlite3WindowUpdate(pParse, pSel->pWinDefn, pWin, pDef);
}
sqlite3WalkExprList(pWalker, pWin->pPartition);
sqlite3WalkExprList(pWalker, pWin->pOrderBy);
sqlite3WalkExpr(pWalker, pWin->pFilter);
sqlite3WindowLink(pSel, pWin);
pNC->ncFlags |= NC_HasWin;
}else
#endif /* SQLITE_OMIT_WINDOWFUNC */
{
NameContext *pNC2 = pNC;
pExpr->op = TK_AGG_FUNCTION;
pExpr->op2 = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
}
#endif
while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
pExpr->op2++;
pNC2 = pNC2->pNext;
}
assert( pDef!=0 || IN_RENAME_OBJECT );
if( pNC2 && pDef ){
assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
}
}
pNC->ncFlags |= savedAllowFlags;
}
/* FIX ME: Compute pExpr->affinity based on the expected return
** type of the function
*/
return WRC_Prune;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_SELECT:
case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
#endif
case TK_IN: {
testcase( pExpr->op==TK_IN );
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
int nRef = pNC->nRef;
notValid(pParse, pNC, "subqueries",
NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol);
sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
assert( pNC->nRef>=nRef );
if( nRef!=pNC->nRef ){
ExprSetProperty(pExpr, EP_VarSelect);
pNC->ncFlags |= NC_VarSelect;
}
}
break;
}
case TK_VARIABLE: {
notValid(pParse, pNC, "parameters",
NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol);
break;
}
case TK_IS:
case TK_ISNOT: {
Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
assert( !ExprHasProperty(pExpr, EP_Reduced) );
/* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
** and "x IS NOT FALSE". */
if( pRight->op==TK_ID ){
int rc = resolveExprStep(pWalker, pRight);
if( rc==WRC_Abort ) return WRC_Abort;
if( pRight->op==TK_TRUEFALSE ){
pExpr->op2 = pExpr->op;
pExpr->op = TK_TRUTH;
return WRC_Continue;
}
}
/* Fall thru */
}
case TK_BETWEEN:
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE: {
int nLeft, nRight;
if( pParse->db->mallocFailed ) break;
assert( pExpr->pLeft!=0 );
nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
if( pExpr->op==TK_BETWEEN ){
nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
if( nRight==nLeft ){
nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
}
}else{
assert( pExpr->pRight!=0 );
nRight = sqlite3ExprVectorSize(pExpr->pRight);
}
if( nLeft!=nRight ){
testcase( pExpr->op==TK_EQ );
testcase( pExpr->op==TK_NE );
testcase( pExpr->op==TK_LT );
testcase( pExpr->op==TK_LE );
testcase( pExpr->op==TK_GT );
testcase( pExpr->op==TK_GE );
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_ISNOT );
testcase( pExpr->op==TK_BETWEEN );
sqlite3ErrorMsg(pParse, "row value misused");
}
break;
}
}
return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
}
/*
** pEList is a list of expressions which are really the result set of the
** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
** This routine checks to see if pE is a simple identifier which corresponds
** to the AS-name of one of the terms of the expression list. If it is,
** this routine return an integer between 1 and N where N is the number of
** elements in pEList, corresponding to the matching entry. If there is
** no match, or if pE is not a simple identifier, then this routine
** return 0.
**
** pEList has been resolved. pE has not.
*/
static int resolveAsName(
Parse *pParse, /* Parsing context for error messages */
ExprList *pEList, /* List of expressions to scan */
Expr *pE /* Expression we are trying to match */
){
int i; /* Loop counter */
UNUSED_PARAMETER(pParse);
if( pE->op==TK_ID ){
char *zCol = pE->u.zToken;
for(i=0; i<pEList->nExpr; i++){
char *zAs = pEList->a[i].zName;
if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
return i+1;
}
}
}
return 0;
}
/*
** pE is a pointer to an expression which is a single term in the
** ORDER BY of a compound SELECT. The expression has not been
** name resolved.
**
** At the point this routine is called, we already know that the
** ORDER BY term is not an integer index into the result set. That
** case is handled by the calling routine.
**
** Attempt to match pE against result set columns in the left-most
** SELECT statement. Return the index i of the matching column,
** as an indication to the caller that it should sort by the i-th column.
** The left-most column is 1. In other words, the value returned is the
** same integer value that would be used in the SQL statement to indicate
** the column.
**
** If there is no match, return 0. Return -1 if an error occurs.
*/
static int resolveOrderByTermToExprList(
Parse *pParse, /* Parsing context for error messages */
Select *pSelect, /* The SELECT statement with the ORDER BY clause */
Expr *pE /* The specific ORDER BY term */
){
int i; /* Loop counter */
ExprList *pEList; /* The columns of the result set */
NameContext nc; /* Name context for resolving pE */
sqlite3 *db; /* Database connection */
int rc; /* Return code from subprocedures */
u8 savedSuppErr; /* Saved value of db->suppressErr */
assert( sqlite3ExprIsInteger(pE, &i)==0 );
pEList = pSelect->pEList;
/* Resolve all names in the ORDER BY term expression
*/
memset(&nc, 0, sizeof(nc));
nc.pParse = pParse;
nc.pSrcList = pSelect->pSrc;
nc.uNC.pEList = pEList;
nc.ncFlags = NC_AllowAgg|NC_UEList;
nc.nErr = 0;
db = pParse->db;
savedSuppErr = db->suppressErr;
db->suppressErr = 1;
rc = sqlite3ResolveExprNames(&nc, pE);
db->suppressErr = savedSuppErr;
if( rc ) return 0;
/* Try to match the ORDER BY expression against an expression
** in the result set. Return an 1-based index of the matching
** result-set entry.
*/
for(i=0; i<pEList->nExpr; i++){
if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
return i+1;
}
}
/* If no match, return 0. */
return 0;
}
/*
** Generate an ORDER BY or GROUP BY term out-of-range error.
*/
static void resolveOutOfRangeError(
Parse *pParse, /* The error context into which to write the error */
const char *zType, /* "ORDER" or "GROUP" */
int i, /* The index (1-based) of the term out of range */
int mx /* Largest permissible value of i */
){
sqlite3ErrorMsg(pParse,
"%r %s BY term out of range - should be "
"between 1 and %d", i, zType, mx);
}
/*
** Analyze the ORDER BY clause in a compound SELECT statement. Modify
** each term of the ORDER BY clause is a constant integer between 1
** and N where N is the number of columns in the compound SELECT.
**
** ORDER BY terms that are already an integer between 1 and N are
** unmodified. ORDER BY terms that are integers outside the range of
** 1 through N generate an error. ORDER BY terms that are expressions
** are matched against result set expressions of compound SELECT
** beginning with the left-most SELECT and working toward the right.
** At the first match, the ORDER BY expression is transformed into
** the integer column number.
**
** Return the number of errors seen.
*/
static int resolveCompoundOrderBy(
Parse *pParse, /* Parsing context. Leave error messages here */
Select *pSelect /* The SELECT statement containing the ORDER BY */
){
int i;
ExprList *pOrderBy;
ExprList *pEList;
sqlite3 *db;
int moreToDo = 1;
pOrderBy = pSelect->pOrderBy;
if( pOrderBy==0 ) return 0;
db = pParse->db;
if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
return 1;
}
for(i=0; i<pOrderBy->nExpr; i++){
pOrderBy->a[i].done = 0;
}
pSelect->pNext = 0;
while( pSelect->pPrior ){
pSelect->pPrior->pNext = pSelect;
pSelect = pSelect->pPrior;
}
while( pSelect && moreToDo ){
struct ExprList_item *pItem;
moreToDo = 0;
pEList = pSelect->pEList;
assert( pEList!=0 );
for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
int iCol = -1;
Expr *pE, *pDup;
if( pItem->done ) continue;
pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
if( sqlite3ExprIsInteger(pE, &iCol) ){
if( iCol<=0 || iCol>pEList->nExpr ){
resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
return 1;
}
}else{
iCol = resolveAsName(pParse, pEList, pE);
if( iCol==0 ){
/* Now test if expression pE matches one of the values returned
** by pSelect. In the usual case this is done by duplicating the
** expression, resolving any symbols in it, and then comparing
** it against each expression returned by the SELECT statement.
** Once the comparisons are finished, the duplicate expression
** is deleted.
**
** Or, if this is running as part of an ALTER TABLE operation,
** resolve the symbols in the actual expression, not a duplicate.
** And, if one of the comparisons is successful, leave the expression
** as is instead of transforming it to an integer as in the usual
** case. This allows the code in alter.c to modify column
** refererences within the ORDER BY expression as required. */
if( IN_RENAME_OBJECT ){
pDup = pE;
}else{
pDup = sqlite3ExprDup(db, pE, 0);
}
if( !db->mallocFailed ){
assert(pDup);
iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
}
if( !IN_RENAME_OBJECT ){
sqlite3ExprDelete(db, pDup);
}
}
}
if( iCol>0 ){
/* Convert the ORDER BY term into an integer column number iCol,
** taking care to preserve the COLLATE clause if it exists */
if( !IN_RENAME_OBJECT ){
Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
if( pNew==0 ) return 1;
pNew->flags |= EP_IntValue;
pNew->u.iValue = iCol;
if( pItem->pExpr==pE ){
pItem->pExpr = pNew;
}else{
Expr *pParent = pItem->pExpr;
assert( pParent->op==TK_COLLATE );
while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
assert( pParent->pLeft==pE );
pParent->pLeft = pNew;
}
sqlite3ExprDelete(db, pE);
pItem->u.x.iOrderByCol = (u16)iCol;
}
pItem->done = 1;
}else{
moreToDo = 1;
}
}
pSelect = pSelect->pNext;
}
for(i=0; i<pOrderBy->nExpr; i++){
if( pOrderBy->a[i].done==0 ){
sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
"column in the result set", i+1);
return 1;
}
}
return 0;
}
/*
** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
** the SELECT statement pSelect. If any term is reference to a
** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
** field) then convert that term into a copy of the corresponding result set
** column.
**
** If any errors are detected, add an error message to pParse and
** return non-zero. Return zero if no errors are seen.
*/
int sqlite3ResolveOrderGroupBy(
Parse *pParse, /* Parsing context. Leave error messages here */
Select *pSelect, /* The SELECT statement containing the clause */
ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
const char *zType /* "ORDER" or "GROUP" */
){
int i;
sqlite3 *db = pParse->db;
ExprList *pEList;
struct ExprList_item *pItem;
if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
return 1;
}
pEList = pSelect->pEList;
assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
if( pItem->u.x.iOrderByCol ){
if( pItem->u.x.iOrderByCol>pEList->nExpr ){
resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
return 1;
}
resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
zType,0);
}
}
return 0;
}
#ifndef SQLITE_OMIT_WINDOWFUNC
/*
** Walker callback for windowRemoveExprFromSelect().
*/
static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
UNUSED_PARAMETER(pWalker);
if( ExprHasProperty(pExpr, EP_WinFunc) ){
Window *pWin = pExpr->y.pWin;
sqlite3WindowUnlinkFromSelect(pWin);
}
return WRC_Continue;
}
/*
** Remove any Window objects owned by the expression pExpr from the
** Select.pWin list of Select object pSelect.
*/
static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
if( pSelect->pWin ){
Walker sWalker;
memset(&sWalker, 0, sizeof(Walker));
sWalker.xExprCallback = resolveRemoveWindowsCb;
sWalker.u.pSelect = pSelect;
sqlite3WalkExpr(&sWalker, pExpr);
}
}
#else
# define windowRemoveExprFromSelect(a, b)
#endif /* SQLITE_OMIT_WINDOWFUNC */
/*
** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
** The Name context of the SELECT statement is pNC. zType is either
** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
**
** This routine resolves each term of the clause into an expression.
** If the order-by term is an integer I between 1 and N (where N is the
** number of columns in the result set of the SELECT) then the expression
** in the resolution is a copy of the I-th result-set expression. If
** the order-by term is an identifier that corresponds to the AS-name of
** a result-set expression, then the term resolves to a copy of the
** result-set expression. Otherwise, the expression is resolved in
** the usual way - using sqlite3ResolveExprNames().
**
** This routine returns the number of errors. If errors occur, then
** an appropriate error message might be left in pParse. (OOM errors
** excepted.)
*/
static int resolveOrderGroupBy(
NameContext *pNC, /* The name context of the SELECT statement */
Select *pSelect, /* The SELECT statement holding pOrderBy */
ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
const char *zType /* Either "ORDER" or "GROUP", as appropriate */
){
int i, j; /* Loop counters */
int iCol; /* Column number */
struct ExprList_item *pItem; /* A term of the ORDER BY clause */
Parse *pParse; /* Parsing context */
int nResult; /* Number of terms in the result set */
if( pOrderBy==0 ) return 0;
nResult = pSelect->pEList->nExpr;
pParse = pNC->pParse;
for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
Expr *pE = pItem->pExpr;
Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
if( zType[0]!='G' ){
iCol = resolveAsName(pParse, pSelect->pEList, pE2);
if( iCol>0 ){
/* If an AS-name match is found, mark this ORDER BY column as being
** a copy of the iCol-th result-set column. The subsequent call to
** sqlite3ResolveOrderGroupBy() will convert the expression to a
** copy of the iCol-th result-set expression. */
pItem->u.x.iOrderByCol = (u16)iCol;
continue;
}
}
if( sqlite3ExprIsInteger(pE2, &iCol) ){
/* The ORDER BY term is an integer constant. Again, set the column
** number so that sqlite3ResolveOrderGroupBy() will convert the
** order-by term to a copy of the result-set expression */
if( iCol<1 || iCol>0xffff ){
resolveOutOfRangeError(pParse, zType, i+1, nResult);
return 1;
}
pItem->u.x.iOrderByCol = (u16)iCol;
continue;
}
/* Otherwise, treat the ORDER BY term as an ordinary expression */
pItem->u.x.iOrderByCol = 0;
if( sqlite3ResolveExprNames(pNC, pE) ){
return 1;
}
for(j=0; j<pSelect->pEList->nExpr; j++){
if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
/* Since this expresion is being changed into a reference
** to an identical expression in the result set, remove all Window
** objects belonging to the expression from the Select.pWin list. */
windowRemoveExprFromSelect(pSelect, pE);
pItem->u.x.iOrderByCol = j+1;
}
}
}
return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
}
/*
** Resolve names in the SELECT statement p and all of its descendants.
*/
static int resolveSelectStep(Walker *pWalker, Select *p){
NameContext *pOuterNC; /* Context that contains this SELECT */
NameContext sNC; /* Name context of this SELECT */
int isCompound; /* True if p is a compound select */
int nCompound; /* Number of compound terms processed so far */
Parse *pParse; /* Parsing context */
int i; /* Loop counter */
ExprList *pGroupBy; /* The GROUP BY clause */
Select *pLeftmost; /* Left-most of SELECT of a compound */
sqlite3 *db; /* Database connection */
assert( p!=0 );
if( p->selFlags & SF_Resolved ){
return WRC_Prune;
}
pOuterNC = pWalker->u.pNC;
pParse = pWalker->pParse;
db = pParse->db;
/* Normally sqlite3SelectExpand() will be called first and will have
** already expanded this SELECT. However, if this is a subquery within
** an expression, sqlite3ResolveExprNames() will be called without a
** prior call to sqlite3SelectExpand(). When that happens, let
** sqlite3SelectPrep() do all of the processing for this SELECT.
** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
** this routine in the correct order.
*/
if( (p->selFlags & SF_Expanded)==0 ){
sqlite3SelectPrep(pParse, p, pOuterNC);
return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
}
isCompound = p->pPrior!=0;
nCompound = 0;
pLeftmost = p;
while( p ){
assert( (p->selFlags & SF_Expanded)!=0 );
assert( (p->selFlags & SF_Resolved)==0 );
p->selFlags |= SF_Resolved;
/* Resolve the expressions in the LIMIT and OFFSET clauses. These
** are not allowed to refer to any names, so pass an empty NameContext.
*/
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
sNC.pWinSelect = p;
if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
return WRC_Abort;
}
/* If the SF_Converted flags is set, then this Select object was
** was created by the convertCompoundSelectToSubquery() function.
** In this case the ORDER BY clause (p->pOrderBy) should be resolved
** as if it were part of the sub-query, not the parent. This block
** moves the pOrderBy down to the sub-query. It will be moved back
** after the names have been resolved. */
if( p->selFlags & SF_Converted ){
Select *pSub = p->pSrc->a[0].pSelect;
assert( p->pSrc->nSrc==1 && p->pOrderBy );
assert( pSub->pPrior && pSub->pOrderBy==0 );
pSub->pOrderBy = p->pOrderBy;
p->pOrderBy = 0;
}
/* Recursively resolve names in all subqueries
*/
for(i=0; i<p->pSrc->nSrc; i++){
struct SrcList_item *pItem = &p->pSrc->a[i];
if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
NameContext *pNC; /* Used to iterate name contexts */
int nRef = 0; /* Refcount for pOuterNC and outer contexts */
const char *zSavedContext = pParse->zAuthContext;
/* Count the total number of references to pOuterNC and all of its
** parent contexts. After resolving references to expressions in
** pItem->pSelect, check if this value has changed. If so, then
** SELECT statement pItem->pSelect must be correlated. Set the
** pItem->fg.isCorrelated flag if this is the case. */
for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
if( pItem->zName ) pParse->zAuthContext = pItem->zName;
sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
pParse->zAuthContext = zSavedContext;
if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
assert( pItem->fg.isCorrelated==0 && nRef<=0 );
pItem->fg.isCorrelated = (nRef!=0);
}
}
/* Set up the local name-context to pass to sqlite3ResolveExprNames() to
** resolve the result-set expression list.
*/
sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
sNC.pSrcList = p->pSrc;
sNC.pNext = pOuterNC;
/* Resolve names in the result set. */
if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
sNC.ncFlags &= ~NC_AllowWin;
/* If there are no aggregate functions in the result-set, and no GROUP BY
** expression, do not allow aggregates in any of the other expressions.
*/
assert( (p->selFlags & SF_Aggregate)==0 );
pGroupBy = p->pGroupBy;
if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
assert( NC_MinMaxAgg==SF_MinMaxAgg );
p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
}else{
sNC.ncFlags &= ~NC_AllowAgg;
}
/* If a HAVING clause is present, then there must be a GROUP BY clause.
*/
if( p->pHaving && !pGroupBy ){
sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
return WRC_Abort;
}
/* Add the output column list to the name-context before parsing the
** other expressions in the SELECT statement. This is so that
** expressions in the WHERE clause (etc.) can refer to expressions by
** aliases in the result set.
**
** Minor point: If this is the case, then the expression will be
** re-evaluated for each reference to it.
*/
assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
sNC.uNC.pEList = p->pEList;
sNC.ncFlags |= NC_UEList;
if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
/* Resolve names in table-valued-function arguments */
for(i=0; i<p->pSrc->nSrc; i++){
struct SrcList_item *pItem = &p->pSrc->a[i];
if( pItem->fg.isTabFunc
&& sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
){
return WRC_Abort;
}
}
/* The ORDER BY and GROUP BY clauses may not refer to terms in
** outer queries
*/
sNC.pNext = 0;
sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
/* If this is a converted compound query, move the ORDER BY clause from
** the sub-query back to the parent query. At this point each term
** within the ORDER BY clause has been transformed to an integer value.
** These integers will be replaced by copies of the corresponding result
** set expressions by the call to resolveOrderGroupBy() below. */
if( p->selFlags & SF_Converted ){
Select *pSub = p->pSrc->a[0].pSelect;
p->pOrderBy = pSub->pOrderBy;
pSub->pOrderBy = 0;
}
/* Process the ORDER BY clause for singleton SELECT statements.
** The ORDER BY clause for compounds SELECT statements is handled
** below, after all of the result-sets for all of the elements of
** the compound have been resolved.
**
** If there is an ORDER BY clause on a term of a compound-select other
** than the right-most term, then that is a syntax error. But the error
** is not detected until much later, and so we need to go ahead and
** resolve those symbols on the incorrect ORDER BY for consistency.
*/
if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
&& resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
){
return WRC_Abort;
}
if( db->mallocFailed ){
return WRC_Abort;
}
sNC.ncFlags &= ~NC_AllowWin;
/* Resolve the GROUP BY clause. At the same time, make sure
** the GROUP BY clause does not contain aggregate functions.
*/
if( pGroupBy ){
struct ExprList_item *pItem;
if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
return WRC_Abort;
}
for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
"the GROUP BY clause");
return WRC_Abort;
}
}
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( IN_RENAME_OBJECT ){
Window *pWin;
for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
|| sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
){
return WRC_Abort;
}
}
}
#endif
/* If this is part of a compound SELECT, check that it has the right
** number of expressions in the select list. */
if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
sqlite3SelectWrongNumTermsError(pParse, p->pNext);
return WRC_Abort;
}
/* Advance to the next term of the compound
*/
p = p->pPrior;
nCompound++;
}
/* Resolve the ORDER BY on a compound SELECT after all terms of
** the compound have been resolved.
*/
if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
return WRC_Abort;
}
return WRC_Prune;
}
/*
** This routine walks an expression tree and resolves references to
** table columns and result-set columns. At the same time, do error
** checking on function usage and set a flag if any aggregate functions
** are seen.
**
** To resolve table columns references we look for nodes (or subtrees) of the
** form X.Y.Z or Y.Z or just Z where
**
** X: The name of a database. Ex: "main" or "temp" or
** the symbolic name assigned to an ATTACH-ed database.
**
** Y: The name of a table in a FROM clause. Or in a trigger
** one of the special names "old" or "new".
**
** Z: The name of a column in table Y.
**
** The node at the root of the subtree is modified as follows:
**
** Expr.op Changed to TK_COLUMN
** Expr.pTab Points to the Table object for X.Y
** Expr.iColumn The column index in X.Y. -1 for the rowid.
** Expr.iTable The VDBE cursor number for X.Y
**
**
** To resolve result-set references, look for expression nodes of the
** form Z (with no X and Y prefix) where the Z matches the right-hand
** size of an AS clause in the result-set of a SELECT. The Z expression
** is replaced by a copy of the left-hand side of the result-set expression.
** Table-name and function resolution occurs on the substituted expression
** tree. For example, in:
**
** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
**
** The "x" term of the order by is replaced by "a+b" to render:
**
** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
**
** Function calls are checked to make sure that the function is
** defined and that the correct number of arguments are specified.
** If the function is an aggregate function, then the NC_HasAgg flag is
** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
** If an expression contains aggregate functions then the EP_Agg
** property on the expression is set.
**
** An error message is left in pParse if anything is amiss. The number
** if errors is returned.
*/
int sqlite3ResolveExprNames(
NameContext *pNC, /* Namespace to resolve expressions in. */
Expr *pExpr /* The expression to be analyzed. */
){
int savedHasAgg;
Walker w;
if( pExpr==0 ) return SQLITE_OK;
savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
w.pParse = pNC->pParse;
w.xExprCallback = resolveExprStep;
w.xSelectCallback = resolveSelectStep;
w.xSelectCallback2 = 0;
w.u.pNC = pNC;
#if SQLITE_MAX_EXPR_DEPTH>0
w.pParse->nHeight += pExpr->nHeight;
if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
return SQLITE_ERROR;
}
#endif
sqlite3WalkExpr(&w, pExpr);
#if SQLITE_MAX_EXPR_DEPTH>0
w.pParse->nHeight -= pExpr->nHeight;
#endif
assert( EP_Agg==NC_HasAgg );
assert( EP_Win==NC_HasWin );
testcase( pNC->ncFlags & NC_HasAgg );
testcase( pNC->ncFlags & NC_HasWin );
ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
pNC->ncFlags |= savedHasAgg;
return pNC->nErr>0 || w.pParse->nErr>0;
}
/*
** Resolve all names for all expression in an expression list. This is
** just like sqlite3ResolveExprNames() except that it works for an expression
** list rather than a single expression.
*/
int sqlite3ResolveExprListNames(
NameContext *pNC, /* Namespace to resolve expressions in. */
ExprList *pList /* The expression list to be analyzed. */
){
int i;
if( pList ){
for(i=0; i<pList->nExpr; i++){
if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
}
}
return WRC_Continue;
}
/*
** Resolve all names in all expressions of a SELECT and in all
** decendents of the SELECT, including compounds off of p->pPrior,
** subqueries in expressions, and subqueries used as FROM clause
** terms.
**
** See sqlite3ResolveExprNames() for a description of the kinds of
** transformations that occur.
**
** All SELECT statements should have been expanded using
** sqlite3SelectExpand() prior to invoking this routine.
*/
void sqlite3ResolveSelectNames(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
NameContext *pOuterNC /* Name context for parent SELECT statement */
){
Walker w;
assert( p!=0 );
w.xExprCallback = resolveExprStep;
w.xSelectCallback = resolveSelectStep;
w.xSelectCallback2 = 0;
w.pParse = pParse;
w.u.pNC = pOuterNC;
sqlite3WalkSelect(&w, p);
}
/*
** Resolve names in expressions that can only reference a single table
** or which cannot reference any tables at all. Examples:
**
** "type" flag
** ------------
** (1) CHECK constraints NC_IsCheck
** (2) WHERE clauses on partial indices NC_PartIdx
** (3) Expressions in indexes on expressions NC_IdxExpr
** (4) Expression arguments to VACUUM INTO. 0
** (5) GENERATED ALWAYS as expressions NC_GenCol
**
** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
** nodes of the expression is set to -1 and the Expr.iColumn value is
** set to the column number. In case (4), TK_COLUMN nodes cause an error.
**
** Any errors cause an error message to be set in pParse.
*/
int sqlite3ResolveSelfReference(
Parse *pParse, /* Parsing context */
Table *pTab, /* The table being referenced, or NULL */
int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
Expr *pExpr, /* Expression to resolve. May be NULL. */
ExprList *pList /* Expression list to resolve. May be NULL. */
){
SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
NameContext sNC; /* Name context for pParse->pNewTable */
int rc;
assert( type==0 || pTab!=0 );
assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
|| type==NC_GenCol || pTab==0 );
memset(&sNC, 0, sizeof(sNC));
memset(&sSrc, 0, sizeof(sSrc));
if( pTab ){
sSrc.nSrc = 1;
sSrc.a[0].zName = pTab->zName;
sSrc.a[0].pTab = pTab;
sSrc.a[0].iCursor = -1;
}
sNC.pParse = pParse;
sNC.pSrcList = &sSrc;
sNC.ncFlags = type | NC_IsDDL;
if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1284_2 |
crossvul-cpp_data_good_3141_0 | /*
* linux/ipc/shm.c
* Copyright (C) 1992, 1993 Krishna Balasubramanian
* Many improvements/fixes by Bruno Haible.
* Replaced `struct shm_desc' by `struct vm_area_struct', July 1994.
* Fixed the shm swap deallocation (shm_unuse()), August 1998 Andrea Arcangeli.
*
* /proc/sysvipc/shm support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
* BIGMEM support, Andrea Arcangeli <andrea@suse.de>
* SMP thread shm, Jean-Luc Boyard <jean-luc.boyard@siemens.fr>
* HIGHMEM support, Ingo Molnar <mingo@redhat.com>
* Make shmmax, shmall, shmmni sysctl'able, Christoph Rohland <cr@sap.com>
* Shared /dev/zero support, Kanoj Sarcar <kanoj@sgi.com>
* Move the mm functionality over to mm/shmem.c, Christoph Rohland <cr@sap.com>
*
* support for audit of ipc object properties and permission changes
* Dustin Kirkland <dustin.kirkland@us.ibm.com>
*
* namespaces support
* OpenVZ, SWsoft Inc.
* Pavel Emelianov <xemul@openvz.org>
*
* Better ipc lock (kern_ipc_perm.lock) handling
* Davidlohr Bueso <davidlohr.bueso@hp.com>, June 2013.
*/
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/shm.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/mman.h>
#include <linux/shmem_fs.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/ptrace.h>
#include <linux/seq_file.h>
#include <linux/rwsem.h>
#include <linux/nsproxy.h>
#include <linux/mount.h>
#include <linux/ipc_namespace.h>
#include <linux/uaccess.h>
#include "util.h"
struct shm_file_data {
int id;
struct ipc_namespace *ns;
struct file *file;
const struct vm_operations_struct *vm_ops;
};
#define shm_file_data(file) (*((struct shm_file_data **)&(file)->private_data))
static const struct file_operations shm_file_operations;
static const struct vm_operations_struct shm_vm_ops;
#define shm_ids(ns) ((ns)->ids[IPC_SHM_IDS])
#define shm_unlock(shp) \
ipc_unlock(&(shp)->shm_perm)
static int newseg(struct ipc_namespace *, struct ipc_params *);
static void shm_open(struct vm_area_struct *vma);
static void shm_close(struct vm_area_struct *vma);
static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp);
#ifdef CONFIG_PROC_FS
static int sysvipc_shm_proc_show(struct seq_file *s, void *it);
#endif
void shm_init_ns(struct ipc_namespace *ns)
{
ns->shm_ctlmax = SHMMAX;
ns->shm_ctlall = SHMALL;
ns->shm_ctlmni = SHMMNI;
ns->shm_rmid_forced = 0;
ns->shm_tot = 0;
ipc_init_ids(&shm_ids(ns));
}
/*
* Called with shm_ids.rwsem (writer) and the shp structure locked.
* Only shm_ids.rwsem remains locked on exit.
*/
static void do_shm_rmid(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_nattch) {
shp->shm_perm.mode |= SHM_DEST;
/* Do not find it any more */
shp->shm_perm.key = IPC_PRIVATE;
shm_unlock(shp);
} else
shm_destroy(ns, shp);
}
#ifdef CONFIG_IPC_NS
void shm_exit_ns(struct ipc_namespace *ns)
{
free_ipcs(ns, &shm_ids(ns), do_shm_rmid);
idr_destroy(&ns->ids[IPC_SHM_IDS].ipcs_idr);
}
#endif
static int __init ipc_ns_init(void)
{
shm_init_ns(&init_ipc_ns);
return 0;
}
pure_initcall(ipc_ns_init);
void __init shm_init(void)
{
ipc_init_proc_interface("sysvipc/shm",
#if BITS_PER_LONG <= 32
" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n",
#else
" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n",
#endif
IPC_SHM_IDS, sysvipc_shm_proc_show);
}
static inline struct shmid_kernel *shm_obtain_object(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
static inline struct shmid_kernel *shm_obtain_object_check(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
/*
* shm_lock_(check_) routines are called in the paths where the rwsem
* is not necessarily held.
*/
static inline struct shmid_kernel *shm_lock(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_lock(&shm_ids(ns), id);
/*
* Callers of shm_lock() must validate the status of the returned ipc
* object pointer (as returned by ipc_lock()), and error out as
* appropriate.
*/
if (IS_ERR(ipcp))
return (void *)ipcp;
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
static inline void shm_lock_by_ptr(struct shmid_kernel *ipcp)
{
rcu_read_lock();
ipc_lock_object(&ipcp->shm_perm);
}
static void shm_rcu_free(struct rcu_head *head)
{
struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
struct shmid_kernel *shp = ipc_rcu_to_struct(p);
security_shm_free(shp);
ipc_rcu_free(head);
}
static inline void shm_rmid(struct ipc_namespace *ns, struct shmid_kernel *s)
{
list_del(&s->shm_clist);
ipc_rmid(&shm_ids(ns), &s->shm_perm);
}
static int __shm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct shmid_kernel *shp;
shp = shm_lock(sfd->ns, sfd->id);
if (IS_ERR(shp))
return PTR_ERR(shp);
shp->shm_atim = get_seconds();
shp->shm_lprid = task_tgid_vnr(current);
shp->shm_nattch++;
shm_unlock(shp);
return 0;
}
/* This is called by fork, once for every shm attach. */
static void shm_open(struct vm_area_struct *vma)
{
int err = __shm_open(vma);
/*
* We raced in the idr lookup or with shm_destroy().
* Either way, the ID is busted.
*/
WARN_ON_ONCE(err);
}
/*
* shm_destroy - free the struct shmid_kernel
*
* @ns: namespace
* @shp: struct to free
*
* It has to be called with shp and shm_ids.rwsem (writer) locked,
* but returns with shp unlocked and freed.
*/
static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
struct file *shm_file;
shm_file = shp->shm_file;
shp->shm_file = NULL;
ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;
shm_rmid(ns, shp);
shm_unlock(shp);
if (!is_file_hugepages(shm_file))
shmem_lock(shm_file, 0, shp->mlock_user);
else if (shp->mlock_user)
user_shm_unlock(i_size_read(file_inode(shm_file)),
shp->mlock_user);
fput(shm_file);
ipc_rcu_putref(shp, shm_rcu_free);
}
/*
* shm_may_destroy - identifies whether shm segment should be destroyed now
*
* Returns true if and only if there are no active users of the segment and
* one of the following is true:
*
* 1) shmctl(id, IPC_RMID, NULL) was called for this shp
*
* 2) sysctl kernel.shm_rmid_forced is set to 1.
*/
static bool shm_may_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
return (shp->shm_nattch == 0) &&
(ns->shm_rmid_forced ||
(shp->shm_perm.mode & SHM_DEST));
}
/*
* remove the attach descriptor vma.
* free memory for segment if it is marked destroyed.
* The descriptor has already been removed from the current->mm->mmap list
* and will later be kfree()d.
*/
static void shm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct shmid_kernel *shp;
struct ipc_namespace *ns = sfd->ns;
down_write(&shm_ids(ns).rwsem);
/* remove from the list of attaches of the shm segment */
shp = shm_lock(ns, sfd->id);
/*
* We raced in the idr lookup or with shm_destroy().
* Either way, the ID is busted.
*/
if (WARN_ON_ONCE(IS_ERR(shp)))
goto done; /* no-op */
shp->shm_lprid = task_tgid_vnr(current);
shp->shm_dtim = get_seconds();
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
done:
up_write(&shm_ids(ns).rwsem);
}
/* Called with ns->shm_ids(ns).rwsem locked */
static int shm_try_destroy_orphaned(int id, void *p, void *data)
{
struct ipc_namespace *ns = data;
struct kern_ipc_perm *ipcp = p;
struct shmid_kernel *shp = container_of(ipcp, struct shmid_kernel, shm_perm);
/*
* We want to destroy segments without users and with already
* exit'ed originating process.
*
* As shp->* are changed under rwsem, it's safe to skip shp locking.
*/
if (shp->shm_creator != NULL)
return 0;
if (shm_may_destroy(ns, shp)) {
shm_lock_by_ptr(shp);
shm_destroy(ns, shp);
}
return 0;
}
void shm_destroy_orphaned(struct ipc_namespace *ns)
{
down_write(&shm_ids(ns).rwsem);
if (shm_ids(ns).in_use)
idr_for_each(&shm_ids(ns).ipcs_idr, &shm_try_destroy_orphaned, ns);
up_write(&shm_ids(ns).rwsem);
}
/* Locking assumes this will only be called with task == current */
void exit_shm(struct task_struct *task)
{
struct ipc_namespace *ns = task->nsproxy->ipc_ns;
struct shmid_kernel *shp, *n;
if (list_empty(&task->sysvshm.shm_clist))
return;
/*
* If kernel.shm_rmid_forced is not set then only keep track of
* which shmids are orphaned, so that a later set of the sysctl
* can clean them up.
*/
if (!ns->shm_rmid_forced) {
down_read(&shm_ids(ns).rwsem);
list_for_each_entry(shp, &task->sysvshm.shm_clist, shm_clist)
shp->shm_creator = NULL;
/*
* Only under read lock but we are only called on current
* so no entry on the list will be shared.
*/
list_del(&task->sysvshm.shm_clist);
up_read(&shm_ids(ns).rwsem);
return;
}
/*
* Destroy all already created segments, that were not yet mapped,
* and mark any mapped as orphan to cover the sysctl toggling.
* Destroy is skipped if shm_may_destroy() returns false.
*/
down_write(&shm_ids(ns).rwsem);
list_for_each_entry_safe(shp, n, &task->sysvshm.shm_clist, shm_clist) {
shp->shm_creator = NULL;
if (shm_may_destroy(ns, shp)) {
shm_lock_by_ptr(shp);
shm_destroy(ns, shp);
}
}
/* Remove the list head from any segments still attached. */
list_del(&task->sysvshm.shm_clist);
up_write(&shm_ids(ns).rwsem);
}
static int shm_fault(struct vm_fault *vmf)
{
struct file *file = vmf->vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
return sfd->vm_ops->fault(vmf);
}
#ifdef CONFIG_NUMA
static int shm_set_policy(struct vm_area_struct *vma, struct mempolicy *new)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
int err = 0;
if (sfd->vm_ops->set_policy)
err = sfd->vm_ops->set_policy(vma, new);
return err;
}
static struct mempolicy *shm_get_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct mempolicy *pol = NULL;
if (sfd->vm_ops->get_policy)
pol = sfd->vm_ops->get_policy(vma, addr);
else if (vma->vm_policy)
pol = vma->vm_policy;
return pol;
}
#endif
static int shm_mmap(struct file *file, struct vm_area_struct *vma)
{
struct shm_file_data *sfd = shm_file_data(file);
int ret;
/*
* In case of remap_file_pages() emulation, the file can represent
* removed IPC ID: propogate shm_lock() error to caller.
*/
ret = __shm_open(vma);
if (ret)
return ret;
ret = sfd->file->f_op->mmap(sfd->file, vma);
if (ret) {
shm_close(vma);
return ret;
}
sfd->vm_ops = vma->vm_ops;
#ifdef CONFIG_MMU
WARN_ON(!sfd->vm_ops->fault);
#endif
vma->vm_ops = &shm_vm_ops;
return 0;
}
static int shm_release(struct inode *ino, struct file *file)
{
struct shm_file_data *sfd = shm_file_data(file);
put_ipc_ns(sfd->ns);
shm_file_data(file) = NULL;
kfree(sfd);
return 0;
}
static int shm_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
struct shm_file_data *sfd = shm_file_data(file);
if (!sfd->file->f_op->fsync)
return -EINVAL;
return sfd->file->f_op->fsync(sfd->file, start, end, datasync);
}
static long shm_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct shm_file_data *sfd = shm_file_data(file);
if (!sfd->file->f_op->fallocate)
return -EOPNOTSUPP;
return sfd->file->f_op->fallocate(file, mode, offset, len);
}
static unsigned long shm_get_unmapped_area(struct file *file,
unsigned long addr, unsigned long len, unsigned long pgoff,
unsigned long flags)
{
struct shm_file_data *sfd = shm_file_data(file);
return sfd->file->f_op->get_unmapped_area(sfd->file, addr, len,
pgoff, flags);
}
static const struct file_operations shm_file_operations = {
.mmap = shm_mmap,
.fsync = shm_fsync,
.release = shm_release,
.get_unmapped_area = shm_get_unmapped_area,
.llseek = noop_llseek,
.fallocate = shm_fallocate,
};
/*
* shm_file_operations_huge is now identical to shm_file_operations,
* but we keep it distinct for the sake of is_file_shm_hugepages().
*/
static const struct file_operations shm_file_operations_huge = {
.mmap = shm_mmap,
.fsync = shm_fsync,
.release = shm_release,
.get_unmapped_area = shm_get_unmapped_area,
.llseek = noop_llseek,
.fallocate = shm_fallocate,
};
bool is_file_shm_hugepages(struct file *file)
{
return file->f_op == &shm_file_operations_huge;
}
static const struct vm_operations_struct shm_vm_ops = {
.open = shm_open, /* callback for a new vm-area open */
.close = shm_close, /* callback for when the vm-area is released */
.fault = shm_fault,
#if defined(CONFIG_NUMA)
.set_policy = shm_set_policy,
.get_policy = shm_get_policy,
#endif
};
/**
* newseg - Create a new shared memory segment
* @ns: namespace
* @params: ptr to the structure that contains key, size and shmflg
*
* Called with shm_ids.rwsem held as a writer.
*/
static int newseg(struct ipc_namespace *ns, struct ipc_params *params)
{
key_t key = params->key;
int shmflg = params->flg;
size_t size = params->u.size;
int error;
struct shmid_kernel *shp;
size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
struct file *file;
char name[13];
int id;
vm_flags_t acctflag = 0;
if (size < SHMMIN || size > ns->shm_ctlmax)
return -EINVAL;
if (numpages << PAGE_SHIFT < size)
return -ENOSPC;
if (ns->shm_tot + numpages < ns->shm_tot ||
ns->shm_tot + numpages > ns->shm_ctlall)
return -ENOSPC;
shp = ipc_rcu_alloc(sizeof(*shp));
if (!shp)
return -ENOMEM;
shp->shm_perm.key = key;
shp->shm_perm.mode = (shmflg & S_IRWXUGO);
shp->mlock_user = NULL;
shp->shm_perm.security = NULL;
error = security_shm_alloc(shp);
if (error) {
ipc_rcu_putref(shp, ipc_rcu_free);
return error;
}
sprintf(name, "SYSV%08x", key);
if (shmflg & SHM_HUGETLB) {
struct hstate *hs;
size_t hugesize;
hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
if (!hs) {
error = -EINVAL;
goto no_file;
}
hugesize = ALIGN(size, huge_page_size(hs));
/* hugetlb_file_setup applies strict accounting */
if (shmflg & SHM_NORESERVE)
acctflag = VM_NORESERVE;
file = hugetlb_file_setup(name, hugesize, acctflag,
&shp->mlock_user, HUGETLB_SHMFS_INODE,
(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
} else {
/*
* Do not allow no accounting for OVERCOMMIT_NEVER, even
* if it's asked for.
*/
if ((shmflg & SHM_NORESERVE) &&
sysctl_overcommit_memory != OVERCOMMIT_NEVER)
acctflag = VM_NORESERVE;
file = shmem_kernel_file_setup(name, size, acctflag);
}
error = PTR_ERR(file);
if (IS_ERR(file))
goto no_file;
shp->shm_cprid = task_tgid_vnr(current);
shp->shm_lprid = 0;
shp->shm_atim = shp->shm_dtim = 0;
shp->shm_ctim = get_seconds();
shp->shm_segsz = size;
shp->shm_nattch = 0;
shp->shm_file = file;
shp->shm_creator = current;
id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);
if (id < 0) {
error = id;
goto no_id;
}
list_add(&shp->shm_clist, ¤t->sysvshm.shm_clist);
/*
* shmid gets reported as "inode#" in /proc/pid/maps.
* proc-ps tools use this. Changing this will break them.
*/
file_inode(file)->i_ino = shp->shm_perm.id;
ns->shm_tot += numpages;
error = shp->shm_perm.id;
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
return error;
no_id:
if (is_file_hugepages(file) && shp->mlock_user)
user_shm_unlock(size, shp->mlock_user);
fput(file);
no_file:
ipc_rcu_putref(shp, shm_rcu_free);
return error;
}
/*
* Called with shm_ids.rwsem and ipcp locked.
*/
static inline int shm_security(struct kern_ipc_perm *ipcp, int shmflg)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
return security_shm_associate(shp, shmflg);
}
/*
* Called with shm_ids.rwsem and ipcp locked.
*/
static inline int shm_more_checks(struct kern_ipc_perm *ipcp,
struct ipc_params *params)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_segsz < params->u.size)
return -EINVAL;
return 0;
}
SYSCALL_DEFINE3(shmget, key_t, key, size_t, size, int, shmflg)
{
struct ipc_namespace *ns;
static const struct ipc_ops shm_ops = {
.getnew = newseg,
.associate = shm_security,
.more_checks = shm_more_checks,
};
struct ipc_params shm_params;
ns = current->nsproxy->ipc_ns;
shm_params.key = key;
shm_params.flg = shmflg;
shm_params.u.size = size;
return ipcget(ns, &shm_ids(ns), &shm_ops, &shm_params);
}
static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version)
{
switch (version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shmid_ds out;
memset(&out, 0, sizeof(out));
ipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm);
out.shm_segsz = in->shm_segsz;
out.shm_atime = in->shm_atime;
out.shm_dtime = in->shm_dtime;
out.shm_ctime = in->shm_ctime;
out.shm_cpid = in->shm_cpid;
out.shm_lpid = in->shm_lpid;
out.shm_nattch = in->shm_nattch;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
static inline unsigned long
copy_shmid_from_user(struct shmid64_ds *out, void __user *buf, int version)
{
switch (version) {
case IPC_64:
if (copy_from_user(out, buf, sizeof(*out)))
return -EFAULT;
return 0;
case IPC_OLD:
{
struct shmid_ds tbuf_old;
if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
return -EFAULT;
out->shm_perm.uid = tbuf_old.shm_perm.uid;
out->shm_perm.gid = tbuf_old.shm_perm.gid;
out->shm_perm.mode = tbuf_old.shm_perm.mode;
return 0;
}
default:
return -EINVAL;
}
}
static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminfo64 *in, int version)
{
switch (version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shminfo out;
if (in->shmmax > INT_MAX)
out.shmmax = INT_MAX;
else
out.shmmax = (int)in->shmmax;
out.shmmin = in->shmmin;
out.shmmni = in->shmmni;
out.shmseg = in->shmseg;
out.shmall = in->shmall;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
/*
* Calculate and add used RSS and swap pages of a shm.
* Called with shm_ids.rwsem held as a reader
*/
static void shm_add_rss_swap(struct shmid_kernel *shp,
unsigned long *rss_add, unsigned long *swp_add)
{
struct inode *inode;
inode = file_inode(shp->shm_file);
if (is_file_hugepages(shp->shm_file)) {
struct address_space *mapping = inode->i_mapping;
struct hstate *h = hstate_file(shp->shm_file);
*rss_add += pages_per_huge_page(h) * mapping->nrpages;
} else {
#ifdef CONFIG_SHMEM
struct shmem_inode_info *info = SHMEM_I(inode);
spin_lock_irq(&info->lock);
*rss_add += inode->i_mapping->nrpages;
*swp_add += info->swapped;
spin_unlock_irq(&info->lock);
#else
*rss_add += inode->i_mapping->nrpages;
#endif
}
}
/*
* Called with shm_ids.rwsem held as a reader
*/
static void shm_get_stat(struct ipc_namespace *ns, unsigned long *rss,
unsigned long *swp)
{
int next_id;
int total, in_use;
*rss = 0;
*swp = 0;
in_use = shm_ids(ns).in_use;
for (total = 0, next_id = 0; total < in_use; next_id++) {
struct kern_ipc_perm *ipc;
struct shmid_kernel *shp;
ipc = idr_find(&shm_ids(ns).ipcs_idr, next_id);
if (ipc == NULL)
continue;
shp = container_of(ipc, struct shmid_kernel, shm_perm);
shm_add_rss_swap(shp, rss, swp);
total++;
}
}
/*
* This function handles some shmctl commands which require the rwsem
* to be held in write mode.
* NOTE: no locks must be held, the rwsem is taken inside this function.
*/
static int shmctl_down(struct ipc_namespace *ns, int shmid, int cmd,
struct shmid_ds __user *buf, int version)
{
struct kern_ipc_perm *ipcp;
struct shmid64_ds shmid64;
struct shmid_kernel *shp;
int err;
if (cmd == IPC_SET) {
if (copy_shmid_from_user(&shmid64, buf, version))
return -EFAULT;
}
down_write(&shm_ids(ns).rwsem);
rcu_read_lock();
ipcp = ipcctl_pre_down_nolock(ns, &shm_ids(ns), shmid, cmd,
&shmid64.shm_perm, 0);
if (IS_ERR(ipcp)) {
err = PTR_ERR(ipcp);
goto out_unlock1;
}
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
switch (cmd) {
case IPC_RMID:
ipc_lock_object(&shp->shm_perm);
/* do_shm_rmid unlocks the ipc object and rcu */
do_shm_rmid(ns, ipcp);
goto out_up;
case IPC_SET:
ipc_lock_object(&shp->shm_perm);
err = ipc_update_perm(&shmid64.shm_perm, ipcp);
if (err)
goto out_unlock0;
shp->shm_ctim = get_seconds();
break;
default:
err = -EINVAL;
goto out_unlock1;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
out_up:
up_write(&shm_ids(ns).rwsem);
return err;
}
static int shmctl_nolock(struct ipc_namespace *ns, int shmid,
int cmd, int version, void __user *buf)
{
int err;
struct shmid_kernel *shp;
/* preliminary security checks for *_INFO */
if (cmd == IPC_INFO || cmd == SHM_INFO) {
err = security_shm_shmctl(NULL, cmd);
if (err)
return err;
}
switch (cmd) {
case IPC_INFO:
{
struct shminfo64 shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmmni = shminfo.shmseg = ns->shm_ctlmni;
shminfo.shmmax = ns->shm_ctlmax;
shminfo.shmall = ns->shm_ctlall;
shminfo.shmmin = SHMMIN;
if (copy_shminfo_to_user(buf, &shminfo, version))
return -EFAULT;
down_read(&shm_ids(ns).rwsem);
err = ipc_get_maxid(&shm_ids(ns));
up_read(&shm_ids(ns).rwsem);
if (err < 0)
err = 0;
goto out;
}
case SHM_INFO:
{
struct shm_info shm_info;
memset(&shm_info, 0, sizeof(shm_info));
down_read(&shm_ids(ns).rwsem);
shm_info.used_ids = shm_ids(ns).in_use;
shm_get_stat(ns, &shm_info.shm_rss, &shm_info.shm_swp);
shm_info.shm_tot = ns->shm_tot;
shm_info.swap_attempts = 0;
shm_info.swap_successes = 0;
err = ipc_get_maxid(&shm_ids(ns));
up_read(&shm_ids(ns).rwsem);
if (copy_to_user(buf, &shm_info, sizeof(shm_info))) {
err = -EFAULT;
goto out;
}
err = err < 0 ? 0 : err;
goto out;
}
case SHM_STAT:
case IPC_STAT:
{
struct shmid64_ds tbuf;
int result;
rcu_read_lock();
if (cmd == SHM_STAT) {
shp = shm_obtain_object(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
result = shp->shm_perm.id;
} else {
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
result = 0;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, S_IRUGO))
goto out_unlock;
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock;
memset(&tbuf, 0, sizeof(tbuf));
kernel_to_ipc64_perm(&shp->shm_perm, &tbuf.shm_perm);
tbuf.shm_segsz = shp->shm_segsz;
tbuf.shm_atime = shp->shm_atim;
tbuf.shm_dtime = shp->shm_dtim;
tbuf.shm_ctime = shp->shm_ctim;
tbuf.shm_cpid = shp->shm_cprid;
tbuf.shm_lpid = shp->shm_lprid;
tbuf.shm_nattch = shp->shm_nattch;
rcu_read_unlock();
if (copy_shmid_to_user(buf, &tbuf, version))
err = -EFAULT;
else
err = result;
goto out;
}
default:
return -EINVAL;
}
out_unlock:
rcu_read_unlock();
out:
return err;
}
SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf)
{
struct shmid_kernel *shp;
int err, version;
struct ipc_namespace *ns;
if (cmd < 0 || shmid < 0)
return -EINVAL;
version = ipc_parse_version(&cmd);
ns = current->nsproxy->ipc_ns;
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
case SHM_STAT:
case IPC_STAT:
return shmctl_nolock(ns, shmid, cmd, version, buf);
case IPC_RMID:
case IPC_SET:
return shmctl_down(ns, shmid, cmd, buf, version);
case SHM_LOCK:
case SHM_UNLOCK:
{
struct file *shm_file;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock1;
}
audit_ipc_obj(&(shp->shm_perm));
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
err = -EIDRM;
goto out_unlock0;
}
if (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) {
kuid_t euid = current_euid();
if (!uid_eq(euid, shp->shm_perm.uid) &&
!uid_eq(euid, shp->shm_perm.cuid)) {
err = -EPERM;
goto out_unlock0;
}
if (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) {
err = -EPERM;
goto out_unlock0;
}
}
shm_file = shp->shm_file;
if (is_file_hugepages(shm_file))
goto out_unlock0;
if (cmd == SHM_LOCK) {
struct user_struct *user = current_user();
err = shmem_lock(shm_file, 1, user);
if (!err && !(shp->shm_perm.mode & SHM_LOCKED)) {
shp->shm_perm.mode |= SHM_LOCKED;
shp->mlock_user = user;
}
goto out_unlock0;
}
/* SHM_UNLOCK */
if (!(shp->shm_perm.mode & SHM_LOCKED))
goto out_unlock0;
shmem_lock(shm_file, 0, shp->mlock_user);
shp->shm_perm.mode &= ~SHM_LOCKED;
shp->mlock_user = NULL;
get_file(shm_file);
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
shmem_unlock_mapping(shm_file->f_mapping);
fput(shm_file);
return err;
}
default:
return -EINVAL;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
return err;
}
/*
* Fix shmaddr, allocate descriptor, map shm, add attach descriptor to lists.
*
* NOTE! Despite the name, this is NOT a direct system call entrypoint. The
* "raddr" thing points to kernel space, and there has to be a wrapper around
* this.
*/
long do_shmat(int shmid, char __user *shmaddr, int shmflg,
ulong *raddr, unsigned long shmlba)
{
struct shmid_kernel *shp;
unsigned long addr;
unsigned long size;
struct file *file;
int err;
unsigned long flags;
unsigned long prot;
int acc_mode;
struct ipc_namespace *ns;
struct shm_file_data *sfd;
struct path path;
fmode_t f_mode;
unsigned long populate = 0;
err = -EINVAL;
if (shmid < 0)
goto out;
else if ((addr = (ulong)shmaddr)) {
if (addr & (shmlba - 1)) {
/*
* Round down to the nearest multiple of shmlba.
* For sane do_mmap_pgoff() parameters, avoid
* round downs that trigger nil-page and MAP_FIXED.
*/
if ((shmflg & SHM_RND) && addr >= shmlba)
addr &= ~(shmlba - 1);
else
#ifndef __ARCH_FORCE_SHMLBA
if (addr & ~PAGE_MASK)
#endif
goto out;
}
flags = MAP_SHARED | MAP_FIXED;
} else {
if ((shmflg & SHM_REMAP))
goto out;
flags = MAP_SHARED;
}
if (shmflg & SHM_RDONLY) {
prot = PROT_READ;
acc_mode = S_IRUGO;
f_mode = FMODE_READ;
} else {
prot = PROT_READ | PROT_WRITE;
acc_mode = S_IRUGO | S_IWUGO;
f_mode = FMODE_READ | FMODE_WRITE;
}
if (shmflg & SHM_EXEC) {
prot |= PROT_EXEC;
acc_mode |= S_IXUGO;
}
/*
* We cannot rely on the fs check since SYSV IPC does have an
* additional creator id...
*/
ns = current->nsproxy->ipc_ns;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, acc_mode))
goto out_unlock;
err = security_shm_shmat(shp, shmaddr, shmflg);
if (err)
goto out_unlock;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
ipc_unlock_object(&shp->shm_perm);
err = -EIDRM;
goto out_unlock;
}
path = shp->shm_file->f_path;
path_get(&path);
shp->shm_nattch++;
size = i_size_read(d_inode(path.dentry));
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
err = -ENOMEM;
sfd = kzalloc(sizeof(*sfd), GFP_KERNEL);
if (!sfd) {
path_put(&path);
goto out_nattch;
}
file = alloc_file(&path, f_mode,
is_file_hugepages(shp->shm_file) ?
&shm_file_operations_huge :
&shm_file_operations);
err = PTR_ERR(file);
if (IS_ERR(file)) {
kfree(sfd);
path_put(&path);
goto out_nattch;
}
file->private_data = sfd;
file->f_mapping = shp->shm_file->f_mapping;
sfd->id = shp->shm_perm.id;
sfd->ns = get_ipc_ns(ns);
sfd->file = shp->shm_file;
sfd->vm_ops = NULL;
err = security_mmap_file(file, prot, flags);
if (err)
goto out_fput;
if (down_write_killable(¤t->mm->mmap_sem)) {
err = -EINTR;
goto out_fput;
}
if (addr && !(shmflg & SHM_REMAP)) {
err = -EINVAL;
if (addr + size < addr)
goto invalid;
if (find_vma_intersection(current->mm, addr, addr + size))
goto invalid;
}
addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL);
*raddr = addr;
err = 0;
if (IS_ERR_VALUE(addr))
err = (long)addr;
invalid:
up_write(¤t->mm->mmap_sem);
if (populate)
mm_populate(addr, populate);
out_fput:
fput(file);
out_nattch:
down_write(&shm_ids(ns).rwsem);
shp = shm_lock(ns, shmid);
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
up_write(&shm_ids(ns).rwsem);
return err;
out_unlock:
rcu_read_unlock();
out:
return err;
}
SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)
{
unsigned long ret;
long err;
err = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);
if (err)
return err;
force_successful_syscall_return();
return (long)ret;
}
/*
* detach and kill segment if marked destroyed.
* The work is done in shm_close.
*/
SYSCALL_DEFINE1(shmdt, char __user *, shmaddr)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long addr = (unsigned long)shmaddr;
int retval = -EINVAL;
#ifdef CONFIG_MMU
loff_t size = 0;
struct file *file;
struct vm_area_struct *next;
#endif
if (addr & ~PAGE_MASK)
return retval;
if (down_write_killable(&mm->mmap_sem))
return -EINTR;
/*
* This function tries to be smart and unmap shm segments that
* were modified by partial mlock or munmap calls:
* - It first determines the size of the shm segment that should be
* unmapped: It searches for a vma that is backed by shm and that
* started at address shmaddr. It records it's size and then unmaps
* it.
* - Then it unmaps all shm vmas that started at shmaddr and that
* are within the initially determined size and that are from the
* same shm segment from which we determined the size.
* Errors from do_munmap are ignored: the function only fails if
* it's called with invalid parameters or if it's called to unmap
* a part of a vma. Both calls in this function are for full vmas,
* the parameters are directly copied from the vma itself and always
* valid - therefore do_munmap cannot fail. (famous last words?)
*/
/*
* If it had been mremap()'d, the starting address would not
* match the usual checks anyway. So assume all vma's are
* above the starting address given.
*/
vma = find_vma(mm, addr);
#ifdef CONFIG_MMU
while (vma) {
next = vma->vm_next;
/*
* Check if the starting address would match, i.e. it's
* a fragment created by mprotect() and/or munmap(), or it
* otherwise it starts at this address with no hassles.
*/
if ((vma->vm_ops == &shm_vm_ops) &&
(vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) {
/*
* Record the file of the shm segment being
* unmapped. With mremap(), someone could place
* page from another segment but with equal offsets
* in the range we are unmapping.
*/
file = vma->vm_file;
size = i_size_read(file_inode(vma->vm_file));
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
/*
* We discovered the size of the shm segment, so
* break out of here and fall through to the next
* loop that uses the size information to stop
* searching for matching vma's.
*/
retval = 0;
vma = next;
break;
}
vma = next;
}
/*
* We need look no further than the maximum address a fragment
* could possibly have landed at. Also cast things to loff_t to
* prevent overflows and make comparisons vs. equal-width types.
*/
size = PAGE_ALIGN(size);
while (vma && (loff_t)(vma->vm_end - addr) <= size) {
next = vma->vm_next;
/* finding a matching vma now does not alter retval */
if ((vma->vm_ops == &shm_vm_ops) &&
((vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) &&
(vma->vm_file == file))
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
vma = next;
}
#else /* CONFIG_MMU */
/* under NOMMU conditions, the exact address to be destroyed must be
* given
*/
if (vma && vma->vm_start == addr && vma->vm_ops == &shm_vm_ops) {
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
retval = 0;
}
#endif
up_write(&mm->mmap_sem);
return retval;
}
#ifdef CONFIG_PROC_FS
static int sysvipc_shm_proc_show(struct seq_file *s, void *it)
{
struct user_namespace *user_ns = seq_user_ns(s);
struct shmid_kernel *shp = it;
unsigned long rss = 0, swp = 0;
shm_add_rss_swap(shp, &rss, &swp);
#if BITS_PER_LONG <= 32
#define SIZE_SPEC "%10lu"
#else
#define SIZE_SPEC "%21lu"
#endif
seq_printf(s,
"%10d %10d %4o " SIZE_SPEC " %5u %5u "
"%5lu %5u %5u %5u %5u %10lu %10lu %10lu "
SIZE_SPEC " " SIZE_SPEC "\n",
shp->shm_perm.key,
shp->shm_perm.id,
shp->shm_perm.mode,
shp->shm_segsz,
shp->shm_cprid,
shp->shm_lprid,
shp->shm_nattch,
from_kuid_munged(user_ns, shp->shm_perm.uid),
from_kgid_munged(user_ns, shp->shm_perm.gid),
from_kuid_munged(user_ns, shp->shm_perm.cuid),
from_kgid_munged(user_ns, shp->shm_perm.cgid),
shp->shm_atim,
shp->shm_dtim,
shp->shm_ctim,
rss * PAGE_SIZE,
swp * PAGE_SIZE);
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3141_0 |
crossvul-cpp_data_bad_3371_0 | /***
This file is part of systemd.
Copyright 2014 Lennart Poettering
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include "alloc-util.h"
#include "dns-domain.h"
#include "resolved-dns-packet.h"
#include "string-table.h"
#include "strv.h"
#include "unaligned.h"
#include "utf8.h"
#include "util.h"
#define EDNS0_OPT_DO (1<<15)
typedef struct DnsPacketRewinder {
DnsPacket *packet;
size_t saved_rindex;
} DnsPacketRewinder;
static void rewind_dns_packet(DnsPacketRewinder *rewinder) {
if (rewinder->packet)
dns_packet_rewind(rewinder->packet, rewinder->saved_rindex);
}
#define INIT_REWINDER(rewinder, p) do { rewinder.packet = p; rewinder.saved_rindex = p->rindex; } while (0)
#define CANCEL_REWINDER(rewinder) do { rewinder.packet = NULL; } while (0)
int dns_packet_new(DnsPacket **ret, DnsProtocol protocol, size_t mtu) {
DnsPacket *p;
size_t a;
assert(ret);
if (mtu <= UDP_PACKET_HEADER_SIZE)
a = DNS_PACKET_SIZE_START;
else
a = mtu - UDP_PACKET_HEADER_SIZE;
if (a < DNS_PACKET_HEADER_SIZE)
a = DNS_PACKET_HEADER_SIZE;
/* round up to next page size */
a = PAGE_ALIGN(ALIGN(sizeof(DnsPacket)) + a) - ALIGN(sizeof(DnsPacket));
/* make sure we never allocate more than useful */
if (a > DNS_PACKET_SIZE_MAX)
a = DNS_PACKET_SIZE_MAX;
p = malloc0(ALIGN(sizeof(DnsPacket)) + a);
if (!p)
return -ENOMEM;
p->size = p->rindex = DNS_PACKET_HEADER_SIZE;
p->allocated = a;
p->protocol = protocol;
p->opt_start = p->opt_size = (size_t) -1;
p->n_ref = 1;
*ret = p;
return 0;
}
void dns_packet_set_flags(DnsPacket *p, bool dnssec_checking_disabled, bool truncated) {
DnsPacketHeader *h;
assert(p);
h = DNS_PACKET_HEADER(p);
switch(p->protocol) {
case DNS_PROTOCOL_LLMNR:
assert(!truncated);
h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
0 /* opcode */,
0 /* c */,
0 /* tc */,
0 /* t */,
0 /* ra */,
0 /* ad */,
0 /* cd */,
0 /* rcode */));
break;
case DNS_PROTOCOL_MDNS:
h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
0 /* opcode */,
0 /* aa */,
truncated /* tc */,
0 /* rd (ask for recursion) */,
0 /* ra */,
0 /* ad */,
0 /* cd */,
0 /* rcode */));
break;
default:
assert(!truncated);
h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
0 /* opcode */,
0 /* aa */,
0 /* tc */,
1 /* rd (ask for recursion) */,
0 /* ra */,
0 /* ad */,
dnssec_checking_disabled /* cd */,
0 /* rcode */));
}
}
int dns_packet_new_query(DnsPacket **ret, DnsProtocol protocol, size_t mtu, bool dnssec_checking_disabled) {
DnsPacket *p;
int r;
assert(ret);
r = dns_packet_new(&p, protocol, mtu);
if (r < 0)
return r;
/* Always set the TC bit to 0 initially.
* If there are multiple packets later, we'll update the bit shortly before sending.
*/
dns_packet_set_flags(p, dnssec_checking_disabled, false);
*ret = p;
return 0;
}
DnsPacket *dns_packet_ref(DnsPacket *p) {
if (!p)
return NULL;
assert(!p->on_stack);
assert(p->n_ref > 0);
p->n_ref++;
return p;
}
static void dns_packet_free(DnsPacket *p) {
char *s;
assert(p);
dns_question_unref(p->question);
dns_answer_unref(p->answer);
dns_resource_record_unref(p->opt);
while ((s = hashmap_steal_first_key(p->names)))
free(s);
hashmap_free(p->names);
free(p->_data);
if (!p->on_stack)
free(p);
}
DnsPacket *dns_packet_unref(DnsPacket *p) {
if (!p)
return NULL;
assert(p->n_ref > 0);
dns_packet_unref(p->more);
if (p->n_ref == 1)
dns_packet_free(p);
else
p->n_ref--;
return NULL;
}
int dns_packet_validate(DnsPacket *p) {
assert(p);
if (p->size < DNS_PACKET_HEADER_SIZE)
return -EBADMSG;
if (p->size > DNS_PACKET_SIZE_MAX)
return -EBADMSG;
return 1;
}
int dns_packet_validate_reply(DnsPacket *p) {
int r;
assert(p);
r = dns_packet_validate(p);
if (r < 0)
return r;
if (DNS_PACKET_QR(p) != 1)
return 0;
if (DNS_PACKET_OPCODE(p) != 0)
return -EBADMSG;
switch (p->protocol) {
case DNS_PROTOCOL_LLMNR:
/* RFC 4795, Section 2.1.1. says to discard all replies with QDCOUNT != 1 */
if (DNS_PACKET_QDCOUNT(p) != 1)
return -EBADMSG;
break;
case DNS_PROTOCOL_MDNS:
/* RFC 6762, Section 18 */
if (DNS_PACKET_RCODE(p) != 0)
return -EBADMSG;
break;
default:
break;
}
return 1;
}
int dns_packet_validate_query(DnsPacket *p) {
int r;
assert(p);
r = dns_packet_validate(p);
if (r < 0)
return r;
if (DNS_PACKET_QR(p) != 0)
return 0;
if (DNS_PACKET_OPCODE(p) != 0)
return -EBADMSG;
if (DNS_PACKET_TC(p))
return -EBADMSG;
switch (p->protocol) {
case DNS_PROTOCOL_LLMNR:
case DNS_PROTOCOL_DNS:
/* RFC 4795, Section 2.1.1. says to discard all queries with QDCOUNT != 1 */
if (DNS_PACKET_QDCOUNT(p) != 1)
return -EBADMSG;
/* RFC 4795, Section 2.1.1. says to discard all queries with ANCOUNT != 0 */
if (DNS_PACKET_ANCOUNT(p) > 0)
return -EBADMSG;
/* RFC 4795, Section 2.1.1. says to discard all queries with NSCOUNT != 0 */
if (DNS_PACKET_NSCOUNT(p) > 0)
return -EBADMSG;
break;
case DNS_PROTOCOL_MDNS:
/* RFC 6762, Section 18 */
if (DNS_PACKET_AA(p) != 0 ||
DNS_PACKET_RD(p) != 0 ||
DNS_PACKET_RA(p) != 0 ||
DNS_PACKET_AD(p) != 0 ||
DNS_PACKET_CD(p) != 0 ||
DNS_PACKET_RCODE(p) != 0)
return -EBADMSG;
break;
default:
break;
}
return 1;
}
static int dns_packet_extend(DnsPacket *p, size_t add, void **ret, size_t *start) {
assert(p);
if (p->size + add > p->allocated) {
size_t a;
a = PAGE_ALIGN((p->size + add) * 2);
if (a > DNS_PACKET_SIZE_MAX)
a = DNS_PACKET_SIZE_MAX;
if (p->size + add > a)
return -EMSGSIZE;
if (p->_data) {
void *d;
d = realloc(p->_data, a);
if (!d)
return -ENOMEM;
p->_data = d;
} else {
p->_data = malloc(a);
if (!p->_data)
return -ENOMEM;
memcpy(p->_data, (uint8_t*) p + ALIGN(sizeof(DnsPacket)), p->size);
memzero((uint8_t*) p->_data + p->size, a - p->size);
}
p->allocated = a;
}
if (start)
*start = p->size;
if (ret)
*ret = (uint8_t*) DNS_PACKET_DATA(p) + p->size;
p->size += add;
return 0;
}
void dns_packet_truncate(DnsPacket *p, size_t sz) {
Iterator i;
char *s;
void *n;
assert(p);
if (p->size <= sz)
return;
HASHMAP_FOREACH_KEY(n, s, p->names, i) {
if (PTR_TO_SIZE(n) < sz)
continue;
hashmap_remove(p->names, s);
free(s);
}
p->size = sz;
}
int dns_packet_append_blob(DnsPacket *p, const void *d, size_t l, size_t *start) {
void *q;
int r;
assert(p);
r = dns_packet_extend(p, l, &q, start);
if (r < 0)
return r;
memcpy(q, d, l);
return 0;
}
int dns_packet_append_uint8(DnsPacket *p, uint8_t v, size_t *start) {
void *d;
int r;
assert(p);
r = dns_packet_extend(p, sizeof(uint8_t), &d, start);
if (r < 0)
return r;
((uint8_t*) d)[0] = v;
return 0;
}
int dns_packet_append_uint16(DnsPacket *p, uint16_t v, size_t *start) {
void *d;
int r;
assert(p);
r = dns_packet_extend(p, sizeof(uint16_t), &d, start);
if (r < 0)
return r;
unaligned_write_be16(d, v);
return 0;
}
int dns_packet_append_uint32(DnsPacket *p, uint32_t v, size_t *start) {
void *d;
int r;
assert(p);
r = dns_packet_extend(p, sizeof(uint32_t), &d, start);
if (r < 0)
return r;
unaligned_write_be32(d, v);
return 0;
}
int dns_packet_append_string(DnsPacket *p, const char *s, size_t *start) {
assert(p);
assert(s);
return dns_packet_append_raw_string(p, s, strlen(s), start);
}
int dns_packet_append_raw_string(DnsPacket *p, const void *s, size_t size, size_t *start) {
void *d;
int r;
assert(p);
assert(s || size == 0);
if (size > 255)
return -E2BIG;
r = dns_packet_extend(p, 1 + size, &d, start);
if (r < 0)
return r;
((uint8_t*) d)[0] = (uint8_t) size;
memcpy_safe(((uint8_t*) d) + 1, s, size);
return 0;
}
int dns_packet_append_label(DnsPacket *p, const char *d, size_t l, bool canonical_candidate, size_t *start) {
uint8_t *w;
int r;
/* Append a label to a packet. Optionally, does this in DNSSEC
* canonical form, if this label is marked as a candidate for
* it, and the canonical form logic is enabled for the
* packet */
assert(p);
assert(d);
if (l > DNS_LABEL_MAX)
return -E2BIG;
r = dns_packet_extend(p, 1 + l, (void**) &w, start);
if (r < 0)
return r;
*(w++) = (uint8_t) l;
if (p->canonical_form && canonical_candidate) {
size_t i;
/* Generate in canonical form, as defined by DNSSEC
* RFC 4034, Section 6.2, i.e. all lower-case. */
for (i = 0; i < l; i++)
w[i] = (uint8_t) ascii_tolower(d[i]);
} else
/* Otherwise, just copy the string unaltered. This is
* essential for DNS-SD, where the casing of labels
* matters and needs to be retained. */
memcpy(w, d, l);
return 0;
}
int dns_packet_append_name(
DnsPacket *p,
const char *name,
bool allow_compression,
bool canonical_candidate,
size_t *start) {
size_t saved_size;
int r;
assert(p);
assert(name);
if (p->refuse_compression)
allow_compression = false;
saved_size = p->size;
while (!dns_name_is_root(name)) {
const char *z = name;
char label[DNS_LABEL_MAX];
size_t n = 0;
if (allow_compression)
n = PTR_TO_SIZE(hashmap_get(p->names, name));
if (n > 0) {
assert(n < p->size);
if (n < 0x4000) {
r = dns_packet_append_uint16(p, 0xC000 | n, NULL);
if (r < 0)
goto fail;
goto done;
}
}
r = dns_label_unescape(&name, label, sizeof(label));
if (r < 0)
goto fail;
r = dns_packet_append_label(p, label, r, canonical_candidate, &n);
if (r < 0)
goto fail;
if (allow_compression) {
_cleanup_free_ char *s = NULL;
s = strdup(z);
if (!s) {
r = -ENOMEM;
goto fail;
}
r = hashmap_ensure_allocated(&p->names, &dns_name_hash_ops);
if (r < 0)
goto fail;
r = hashmap_put(p->names, s, SIZE_TO_PTR(n));
if (r < 0)
goto fail;
s = NULL;
}
}
r = dns_packet_append_uint8(p, 0, NULL);
if (r < 0)
return r;
done:
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
int dns_packet_append_key(DnsPacket *p, const DnsResourceKey *k, const DnsAnswerFlags flags, size_t *start) {
size_t saved_size;
uint16_t class;
int r;
assert(p);
assert(k);
saved_size = p->size;
r = dns_packet_append_name(p, dns_resource_key_name(k), true, true, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint16(p, k->type, NULL);
if (r < 0)
goto fail;
class = flags & DNS_ANSWER_CACHE_FLUSH ? k->class | MDNS_RR_CACHE_FLUSH : k->class;
r = dns_packet_append_uint16(p, class, NULL);
if (r < 0)
goto fail;
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
static int dns_packet_append_type_window(DnsPacket *p, uint8_t window, uint8_t length, const uint8_t *types, size_t *start) {
size_t saved_size;
int r;
assert(p);
assert(types);
assert(length > 0);
saved_size = p->size;
r = dns_packet_append_uint8(p, window, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, length, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, types, length, NULL);
if (r < 0)
goto fail;
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
static int dns_packet_append_types(DnsPacket *p, Bitmap *types, size_t *start) {
Iterator i;
uint8_t window = 0;
uint8_t entry = 0;
uint8_t bitmaps[32] = {};
unsigned n;
size_t saved_size;
int r;
assert(p);
saved_size = p->size;
BITMAP_FOREACH(n, types, i) {
assert(n <= 0xffff);
if ((n >> 8) != window && bitmaps[entry / 8] != 0) {
r = dns_packet_append_type_window(p, window, entry / 8 + 1, bitmaps, NULL);
if (r < 0)
goto fail;
zero(bitmaps);
}
window = n >> 8;
entry = n & 255;
bitmaps[entry / 8] |= 1 << (7 - (entry % 8));
}
if (bitmaps[entry / 8] != 0) {
r = dns_packet_append_type_window(p, window, entry / 8 + 1, bitmaps, NULL);
if (r < 0)
goto fail;
}
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
/* Append the OPT pseudo-RR described in RFC6891 */
int dns_packet_append_opt(DnsPacket *p, uint16_t max_udp_size, bool edns0_do, int rcode, size_t *start) {
size_t saved_size;
int r;
assert(p);
/* we must never advertise supported packet size smaller than the legacy max */
assert(max_udp_size >= DNS_PACKET_UNICAST_SIZE_MAX);
assert(rcode >= 0);
assert(rcode <= _DNS_RCODE_MAX);
if (p->opt_start != (size_t) -1)
return -EBUSY;
assert(p->opt_size == (size_t) -1);
saved_size = p->size;
/* empty name */
r = dns_packet_append_uint8(p, 0, NULL);
if (r < 0)
return r;
/* type */
r = dns_packet_append_uint16(p, DNS_TYPE_OPT, NULL);
if (r < 0)
goto fail;
/* class: maximum udp packet that can be received */
r = dns_packet_append_uint16(p, max_udp_size, NULL);
if (r < 0)
goto fail;
/* extended RCODE and VERSION */
r = dns_packet_append_uint16(p, ((uint16_t) rcode & 0x0FF0) << 4, NULL);
if (r < 0)
goto fail;
/* flags: DNSSEC OK (DO), see RFC3225 */
r = dns_packet_append_uint16(p, edns0_do ? EDNS0_OPT_DO : 0, NULL);
if (r < 0)
goto fail;
/* RDLENGTH */
if (edns0_do && !DNS_PACKET_QR(p)) {
/* If DO is on and this is not a reply, also append RFC6975 Algorithm data */
static const uint8_t rfc6975[] = {
0, 5, /* OPTION_CODE: DAU */
0, 6, /* LIST_LENGTH */
DNSSEC_ALGORITHM_RSASHA1,
DNSSEC_ALGORITHM_RSASHA1_NSEC3_SHA1,
DNSSEC_ALGORITHM_RSASHA256,
DNSSEC_ALGORITHM_RSASHA512,
DNSSEC_ALGORITHM_ECDSAP256SHA256,
DNSSEC_ALGORITHM_ECDSAP384SHA384,
0, 6, /* OPTION_CODE: DHU */
0, 3, /* LIST_LENGTH */
DNSSEC_DIGEST_SHA1,
DNSSEC_DIGEST_SHA256,
DNSSEC_DIGEST_SHA384,
0, 7, /* OPTION_CODE: N3U */
0, 1, /* LIST_LENGTH */
NSEC3_ALGORITHM_SHA1,
};
r = dns_packet_append_uint16(p, sizeof(rfc6975), NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rfc6975, sizeof(rfc6975), NULL);
} else
r = dns_packet_append_uint16(p, 0, NULL);
if (r < 0)
goto fail;
DNS_PACKET_HEADER(p)->arcount = htobe16(DNS_PACKET_ARCOUNT(p) + 1);
p->opt_start = saved_size;
p->opt_size = p->size - saved_size;
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
int dns_packet_truncate_opt(DnsPacket *p) {
assert(p);
if (p->opt_start == (size_t) -1) {
assert(p->opt_size == (size_t) -1);
return 0;
}
assert(p->opt_size != (size_t) -1);
assert(DNS_PACKET_ARCOUNT(p) > 0);
if (p->opt_start + p->opt_size != p->size)
return -EBUSY;
dns_packet_truncate(p, p->opt_start);
DNS_PACKET_HEADER(p)->arcount = htobe16(DNS_PACKET_ARCOUNT(p) - 1);
p->opt_start = p->opt_size = (size_t) -1;
return 1;
}
int dns_packet_append_rr(DnsPacket *p, const DnsResourceRecord *rr, const DnsAnswerFlags flags, size_t *start, size_t *rdata_start) {
size_t saved_size, rdlength_offset, end, rdlength, rds;
uint32_t ttl;
int r;
assert(p);
assert(rr);
saved_size = p->size;
r = dns_packet_append_key(p, rr->key, flags, NULL);
if (r < 0)
goto fail;
ttl = flags & DNS_ANSWER_GOODBYE ? 0 : rr->ttl;
r = dns_packet_append_uint32(p, ttl, NULL);
if (r < 0)
goto fail;
/* Initially we write 0 here */
r = dns_packet_append_uint16(p, 0, &rdlength_offset);
if (r < 0)
goto fail;
rds = p->size - saved_size;
switch (rr->unparseable ? _DNS_TYPE_INVALID : rr->key->type) {
case DNS_TYPE_SRV:
r = dns_packet_append_uint16(p, rr->srv.priority, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint16(p, rr->srv.weight, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint16(p, rr->srv.port, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_name(p, rr->srv.name, true, false, NULL);
break;
case DNS_TYPE_PTR:
case DNS_TYPE_NS:
case DNS_TYPE_CNAME:
case DNS_TYPE_DNAME:
r = dns_packet_append_name(p, rr->ptr.name, true, false, NULL);
break;
case DNS_TYPE_HINFO:
r = dns_packet_append_string(p, rr->hinfo.cpu, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_string(p, rr->hinfo.os, NULL);
break;
case DNS_TYPE_SPF: /* exactly the same as TXT */
case DNS_TYPE_TXT:
if (!rr->txt.items) {
/* RFC 6763, section 6.1 suggests to generate
* single empty string for an empty array. */
r = dns_packet_append_raw_string(p, NULL, 0, NULL);
if (r < 0)
goto fail;
} else {
DnsTxtItem *i;
LIST_FOREACH(items, i, rr->txt.items) {
r = dns_packet_append_raw_string(p, i->data, i->length, NULL);
if (r < 0)
goto fail;
}
}
r = 0;
break;
case DNS_TYPE_A:
r = dns_packet_append_blob(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
break;
case DNS_TYPE_AAAA:
r = dns_packet_append_blob(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
break;
case DNS_TYPE_SOA:
r = dns_packet_append_name(p, rr->soa.mname, true, false, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_name(p, rr->soa.rname, true, false, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->soa.serial, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->soa.refresh, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->soa.retry, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->soa.expire, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->soa.minimum, NULL);
break;
case DNS_TYPE_MX:
r = dns_packet_append_uint16(p, rr->mx.priority, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_name(p, rr->mx.exchange, true, false, NULL);
break;
case DNS_TYPE_LOC:
r = dns_packet_append_uint8(p, rr->loc.version, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->loc.size, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->loc.horiz_pre, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->loc.vert_pre, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->loc.latitude, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->loc.longitude, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->loc.altitude, NULL);
break;
case DNS_TYPE_DS:
r = dns_packet_append_uint16(p, rr->ds.key_tag, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->ds.algorithm, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->ds.digest_type, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->ds.digest, rr->ds.digest_size, NULL);
break;
case DNS_TYPE_SSHFP:
r = dns_packet_append_uint8(p, rr->sshfp.algorithm, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->sshfp.fptype, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->sshfp.fingerprint, rr->sshfp.fingerprint_size, NULL);
break;
case DNS_TYPE_DNSKEY:
r = dns_packet_append_uint16(p, rr->dnskey.flags, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->dnskey.protocol, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->dnskey.algorithm, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->dnskey.key, rr->dnskey.key_size, NULL);
break;
case DNS_TYPE_RRSIG:
r = dns_packet_append_uint16(p, rr->rrsig.type_covered, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->rrsig.algorithm, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->rrsig.labels, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->rrsig.original_ttl, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->rrsig.expiration, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint32(p, rr->rrsig.inception, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint16(p, rr->rrsig.key_tag, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_name(p, rr->rrsig.signer, false, true, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->rrsig.signature, rr->rrsig.signature_size, NULL);
break;
case DNS_TYPE_NSEC:
r = dns_packet_append_name(p, rr->nsec.next_domain_name, false, false, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_types(p, rr->nsec.types, NULL);
if (r < 0)
goto fail;
break;
case DNS_TYPE_NSEC3:
r = dns_packet_append_uint8(p, rr->nsec3.algorithm, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->nsec3.flags, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint16(p, rr->nsec3.iterations, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->nsec3.salt_size, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->nsec3.salt, rr->nsec3.salt_size, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->nsec3.next_hashed_name_size, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->nsec3.next_hashed_name, rr->nsec3.next_hashed_name_size, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_types(p, rr->nsec3.types, NULL);
if (r < 0)
goto fail;
break;
case DNS_TYPE_TLSA:
r = dns_packet_append_uint8(p, rr->tlsa.cert_usage, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->tlsa.selector, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_uint8(p, rr->tlsa.matching_type, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->tlsa.data, rr->tlsa.data_size, NULL);
break;
case DNS_TYPE_CAA:
r = dns_packet_append_uint8(p, rr->caa.flags, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_string(p, rr->caa.tag, NULL);
if (r < 0)
goto fail;
r = dns_packet_append_blob(p, rr->caa.value, rr->caa.value_size, NULL);
break;
case DNS_TYPE_OPT:
case DNS_TYPE_OPENPGPKEY:
case _DNS_TYPE_INVALID: /* unparseable */
default:
r = dns_packet_append_blob(p, rr->generic.data, rr->generic.data_size, NULL);
break;
}
if (r < 0)
goto fail;
/* Let's calculate the actual data size and update the field */
rdlength = p->size - rdlength_offset - sizeof(uint16_t);
if (rdlength > 0xFFFF) {
r = -ENOSPC;
goto fail;
}
end = p->size;
p->size = rdlength_offset;
r = dns_packet_append_uint16(p, rdlength, NULL);
if (r < 0)
goto fail;
p->size = end;
if (start)
*start = saved_size;
if (rdata_start)
*rdata_start = rds;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
int dns_packet_append_question(DnsPacket *p, DnsQuestion *q) {
DnsResourceKey *key;
int r;
assert(p);
DNS_QUESTION_FOREACH(key, q) {
r = dns_packet_append_key(p, key, 0, NULL);
if (r < 0)
return r;
}
return 0;
}
int dns_packet_append_answer(DnsPacket *p, DnsAnswer *a) {
DnsResourceRecord *rr;
DnsAnswerFlags flags;
int r;
assert(p);
DNS_ANSWER_FOREACH_FLAGS(rr, flags, a) {
r = dns_packet_append_rr(p, rr, flags, NULL, NULL);
if (r < 0)
return r;
}
return 0;
}
int dns_packet_read(DnsPacket *p, size_t sz, const void **ret, size_t *start) {
assert(p);
if (p->rindex + sz > p->size)
return -EMSGSIZE;
if (ret)
*ret = (uint8_t*) DNS_PACKET_DATA(p) + p->rindex;
if (start)
*start = p->rindex;
p->rindex += sz;
return 0;
}
void dns_packet_rewind(DnsPacket *p, size_t idx) {
assert(p);
assert(idx <= p->size);
assert(idx >= DNS_PACKET_HEADER_SIZE);
p->rindex = idx;
}
int dns_packet_read_blob(DnsPacket *p, void *d, size_t sz, size_t *start) {
const void *q;
int r;
assert(p);
assert(d);
r = dns_packet_read(p, sz, &q, start);
if (r < 0)
return r;
memcpy(d, q, sz);
return 0;
}
static int dns_packet_read_memdup(
DnsPacket *p, size_t size,
void **ret, size_t *ret_size,
size_t *ret_start) {
const void *src;
size_t start;
int r;
assert(p);
assert(ret);
r = dns_packet_read(p, size, &src, &start);
if (r < 0)
return r;
if (size <= 0)
*ret = NULL;
else {
void *copy;
copy = memdup(src, size);
if (!copy)
return -ENOMEM;
*ret = copy;
}
if (ret_size)
*ret_size = size;
if (ret_start)
*ret_start = start;
return 0;
}
int dns_packet_read_uint8(DnsPacket *p, uint8_t *ret, size_t *start) {
const void *d;
int r;
assert(p);
r = dns_packet_read(p, sizeof(uint8_t), &d, start);
if (r < 0)
return r;
*ret = ((uint8_t*) d)[0];
return 0;
}
int dns_packet_read_uint16(DnsPacket *p, uint16_t *ret, size_t *start) {
const void *d;
int r;
assert(p);
r = dns_packet_read(p, sizeof(uint16_t), &d, start);
if (r < 0)
return r;
*ret = unaligned_read_be16(d);
return 0;
}
int dns_packet_read_uint32(DnsPacket *p, uint32_t *ret, size_t *start) {
const void *d;
int r;
assert(p);
r = dns_packet_read(p, sizeof(uint32_t), &d, start);
if (r < 0)
return r;
*ret = unaligned_read_be32(d);
return 0;
}
int dns_packet_read_string(DnsPacket *p, char **ret, size_t *start) {
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
const void *d;
char *t;
uint8_t c;
int r;
assert(p);
INIT_REWINDER(rewinder, p);
r = dns_packet_read_uint8(p, &c, NULL);
if (r < 0)
return r;
r = dns_packet_read(p, c, &d, NULL);
if (r < 0)
return r;
if (memchr(d, 0, c))
return -EBADMSG;
t = strndup(d, c);
if (!t)
return -ENOMEM;
if (!utf8_is_valid(t)) {
free(t);
return -EBADMSG;
}
*ret = t;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
int dns_packet_read_raw_string(DnsPacket *p, const void **ret, size_t *size, size_t *start) {
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
uint8_t c;
int r;
assert(p);
INIT_REWINDER(rewinder, p);
r = dns_packet_read_uint8(p, &c, NULL);
if (r < 0)
return r;
r = dns_packet_read(p, c, ret, NULL);
if (r < 0)
return r;
if (size)
*size = c;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
int dns_packet_read_name(
DnsPacket *p,
char **_ret,
bool allow_compression,
size_t *start) {
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
size_t after_rindex = 0, jump_barrier;
_cleanup_free_ char *ret = NULL;
size_t n = 0, allocated = 0;
bool first = true;
int r;
assert(p);
assert(_ret);
INIT_REWINDER(rewinder, p);
jump_barrier = p->rindex;
if (p->refuse_compression)
allow_compression = false;
for (;;) {
uint8_t c, d;
r = dns_packet_read_uint8(p, &c, NULL);
if (r < 0)
return r;
if (c == 0)
/* End of name */
break;
else if (c <= 63) {
const char *label;
/* Literal label */
r = dns_packet_read(p, c, (const void**) &label, NULL);
if (r < 0)
return r;
if (!GREEDY_REALLOC(ret, allocated, n + !first + DNS_LABEL_ESCAPED_MAX))
return -ENOMEM;
if (first)
first = false;
else
ret[n++] = '.';
r = dns_label_escape(label, c, ret + n, DNS_LABEL_ESCAPED_MAX);
if (r < 0)
return r;
n += r;
continue;
} else if (allow_compression && (c & 0xc0) == 0xc0) {
uint16_t ptr;
/* Pointer */
r = dns_packet_read_uint8(p, &d, NULL);
if (r < 0)
return r;
ptr = (uint16_t) (c & ~0xc0) << 8 | (uint16_t) d;
if (ptr < DNS_PACKET_HEADER_SIZE || ptr >= jump_barrier)
return -EBADMSG;
if (after_rindex == 0)
after_rindex = p->rindex;
/* Jumps are limited to a "prior occurrence" (RFC-1035 4.1.4) */
jump_barrier = ptr;
p->rindex = ptr;
} else
return -EBADMSG;
}
if (!GREEDY_REALLOC(ret, allocated, n + 1))
return -ENOMEM;
ret[n] = 0;
if (after_rindex != 0)
p->rindex= after_rindex;
*_ret = ret;
ret = NULL;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
static int dns_packet_read_type_window(DnsPacket *p, Bitmap **types, size_t *start) {
uint8_t window;
uint8_t length;
const uint8_t *bitmap;
uint8_t bit = 0;
unsigned i;
bool found = false;
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
int r;
assert(p);
assert(types);
INIT_REWINDER(rewinder, p);
r = bitmap_ensure_allocated(types);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &window, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &length, NULL);
if (r < 0)
return r;
if (length == 0 || length > 32)
return -EBADMSG;
r = dns_packet_read(p, length, (const void **)&bitmap, NULL);
if (r < 0)
return r;
for (i = 0; i < length; i++) {
uint8_t bitmask = 1 << 7;
if (!bitmap[i]) {
found = false;
bit += 8;
continue;
}
found = true;
while (bitmask) {
if (bitmap[i] & bitmask) {
uint16_t n;
n = (uint16_t) window << 8 | (uint16_t) bit;
/* Ignore pseudo-types. see RFC4034 section 4.1.2 */
if (dns_type_is_pseudo(n))
continue;
r = bitmap_set(*types, n);
if (r < 0)
return r;
}
bit++;
bitmask >>= 1;
}
}
if (!found)
return -EBADMSG;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
static int dns_packet_read_type_windows(DnsPacket *p, Bitmap **types, size_t size, size_t *start) {
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
int r;
INIT_REWINDER(rewinder, p);
while (p->rindex < rewinder.saved_rindex + size) {
r = dns_packet_read_type_window(p, types, NULL);
if (r < 0)
return r;
/* don't read past end of current RR */
if (p->rindex > rewinder.saved_rindex + size)
return -EBADMSG;
}
if (p->rindex != rewinder.saved_rindex + size)
return -EBADMSG;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
int dns_packet_read_key(DnsPacket *p, DnsResourceKey **ret, bool *ret_cache_flush, size_t *start) {
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
_cleanup_free_ char *name = NULL;
bool cache_flush = false;
uint16_t class, type;
DnsResourceKey *key;
int r;
assert(p);
assert(ret);
INIT_REWINDER(rewinder, p);
r = dns_packet_read_name(p, &name, true, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint16(p, &type, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint16(p, &class, NULL);
if (r < 0)
return r;
if (p->protocol == DNS_PROTOCOL_MDNS) {
/* See RFC6762, Section 10.2 */
if (type != DNS_TYPE_OPT && (class & MDNS_RR_CACHE_FLUSH)) {
class &= ~MDNS_RR_CACHE_FLUSH;
cache_flush = true;
}
}
key = dns_resource_key_new_consume(class, type, name);
if (!key)
return -ENOMEM;
name = NULL;
*ret = key;
if (ret_cache_flush)
*ret_cache_flush = cache_flush;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
static bool loc_size_ok(uint8_t size) {
uint8_t m = size >> 4, e = size & 0xF;
return m <= 9 && e <= 9 && (m > 0 || e == 0);
}
int dns_packet_read_rr(DnsPacket *p, DnsResourceRecord **ret, bool *ret_cache_flush, size_t *start) {
_cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
_cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder;
size_t offset;
uint16_t rdlength;
bool cache_flush;
int r;
assert(p);
assert(ret);
INIT_REWINDER(rewinder, p);
r = dns_packet_read_key(p, &key, &cache_flush, NULL);
if (r < 0)
return r;
if (!dns_class_is_valid_rr(key->class) || !dns_type_is_valid_rr(key->type))
return -EBADMSG;
rr = dns_resource_record_new(key);
if (!rr)
return -ENOMEM;
r = dns_packet_read_uint32(p, &rr->ttl, NULL);
if (r < 0)
return r;
/* RFC 2181, Section 8, suggests to
* treat a TTL with the MSB set as a zero TTL. */
if (rr->ttl & UINT32_C(0x80000000))
rr->ttl = 0;
r = dns_packet_read_uint16(p, &rdlength, NULL);
if (r < 0)
return r;
if (p->rindex + rdlength > p->size)
return -EBADMSG;
offset = p->rindex;
switch (rr->key->type) {
case DNS_TYPE_SRV:
r = dns_packet_read_uint16(p, &rr->srv.priority, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint16(p, &rr->srv.weight, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint16(p, &rr->srv.port, NULL);
if (r < 0)
return r;
r = dns_packet_read_name(p, &rr->srv.name, true, NULL);
break;
case DNS_TYPE_PTR:
case DNS_TYPE_NS:
case DNS_TYPE_CNAME:
case DNS_TYPE_DNAME:
r = dns_packet_read_name(p, &rr->ptr.name, true, NULL);
break;
case DNS_TYPE_HINFO:
r = dns_packet_read_string(p, &rr->hinfo.cpu, NULL);
if (r < 0)
return r;
r = dns_packet_read_string(p, &rr->hinfo.os, NULL);
break;
case DNS_TYPE_SPF: /* exactly the same as TXT */
case DNS_TYPE_TXT:
if (rdlength <= 0) {
DnsTxtItem *i;
/* RFC 6763, section 6.1 suggests to treat
* empty TXT RRs as equivalent to a TXT record
* with a single empty string. */
i = malloc0(offsetof(DnsTxtItem, data) + 1); /* for safety reasons we add an extra NUL byte */
if (!i)
return -ENOMEM;
rr->txt.items = i;
} else {
DnsTxtItem *last = NULL;
while (p->rindex < offset + rdlength) {
DnsTxtItem *i;
const void *data;
size_t sz;
r = dns_packet_read_raw_string(p, &data, &sz, NULL);
if (r < 0)
return r;
i = malloc0(offsetof(DnsTxtItem, data) + sz + 1); /* extra NUL byte at the end */
if (!i)
return -ENOMEM;
memcpy(i->data, data, sz);
i->length = sz;
LIST_INSERT_AFTER(items, rr->txt.items, last, i);
last = i;
}
}
r = 0;
break;
case DNS_TYPE_A:
r = dns_packet_read_blob(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
break;
case DNS_TYPE_AAAA:
r = dns_packet_read_blob(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
break;
case DNS_TYPE_SOA:
r = dns_packet_read_name(p, &rr->soa.mname, true, NULL);
if (r < 0)
return r;
r = dns_packet_read_name(p, &rr->soa.rname, true, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->soa.serial, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->soa.refresh, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->soa.retry, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->soa.expire, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->soa.minimum, NULL);
break;
case DNS_TYPE_MX:
r = dns_packet_read_uint16(p, &rr->mx.priority, NULL);
if (r < 0)
return r;
r = dns_packet_read_name(p, &rr->mx.exchange, true, NULL);
break;
case DNS_TYPE_LOC: {
uint8_t t;
size_t pos;
r = dns_packet_read_uint8(p, &t, &pos);
if (r < 0)
return r;
if (t == 0) {
rr->loc.version = t;
r = dns_packet_read_uint8(p, &rr->loc.size, NULL);
if (r < 0)
return r;
if (!loc_size_ok(rr->loc.size))
return -EBADMSG;
r = dns_packet_read_uint8(p, &rr->loc.horiz_pre, NULL);
if (r < 0)
return r;
if (!loc_size_ok(rr->loc.horiz_pre))
return -EBADMSG;
r = dns_packet_read_uint8(p, &rr->loc.vert_pre, NULL);
if (r < 0)
return r;
if (!loc_size_ok(rr->loc.vert_pre))
return -EBADMSG;
r = dns_packet_read_uint32(p, &rr->loc.latitude, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->loc.longitude, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->loc.altitude, NULL);
if (r < 0)
return r;
break;
} else {
dns_packet_rewind(p, pos);
rr->unparseable = true;
goto unparseable;
}
}
case DNS_TYPE_DS:
r = dns_packet_read_uint16(p, &rr->ds.key_tag, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->ds.algorithm, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->ds.digest_type, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p, rdlength - 4,
&rr->ds.digest, &rr->ds.digest_size,
NULL);
if (r < 0)
return r;
if (rr->ds.digest_size <= 0)
/* the accepted size depends on the algorithm, but for now
just ensure that the value is greater than zero */
return -EBADMSG;
break;
case DNS_TYPE_SSHFP:
r = dns_packet_read_uint8(p, &rr->sshfp.algorithm, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->sshfp.fptype, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p, rdlength - 2,
&rr->sshfp.fingerprint, &rr->sshfp.fingerprint_size,
NULL);
if (rr->sshfp.fingerprint_size <= 0)
/* the accepted size depends on the algorithm, but for now
just ensure that the value is greater than zero */
return -EBADMSG;
break;
case DNS_TYPE_DNSKEY:
r = dns_packet_read_uint16(p, &rr->dnskey.flags, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->dnskey.protocol, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->dnskey.algorithm, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p, rdlength - 4,
&rr->dnskey.key, &rr->dnskey.key_size,
NULL);
if (rr->dnskey.key_size <= 0)
/* the accepted size depends on the algorithm, but for now
just ensure that the value is greater than zero */
return -EBADMSG;
break;
case DNS_TYPE_RRSIG:
r = dns_packet_read_uint16(p, &rr->rrsig.type_covered, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->rrsig.algorithm, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->rrsig.labels, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->rrsig.original_ttl, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->rrsig.expiration, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint32(p, &rr->rrsig.inception, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint16(p, &rr->rrsig.key_tag, NULL);
if (r < 0)
return r;
r = dns_packet_read_name(p, &rr->rrsig.signer, false, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p, offset + rdlength - p->rindex,
&rr->rrsig.signature, &rr->rrsig.signature_size,
NULL);
if (rr->rrsig.signature_size <= 0)
/* the accepted size depends on the algorithm, but for now
just ensure that the value is greater than zero */
return -EBADMSG;
break;
case DNS_TYPE_NSEC: {
/*
* RFC6762, section 18.14 explictly states mDNS should use name compression.
* This contradicts RFC3845, section 2.1.1
*/
bool allow_compressed = p->protocol == DNS_PROTOCOL_MDNS;
r = dns_packet_read_name(p, &rr->nsec.next_domain_name, allow_compressed, NULL);
if (r < 0)
return r;
r = dns_packet_read_type_windows(p, &rr->nsec.types, offset + rdlength - p->rindex, NULL);
/* We accept empty NSEC bitmaps. The bit indicating the presence of the NSEC record itself
* is redundant and in e.g., RFC4956 this fact is used to define a use for NSEC records
* without the NSEC bit set. */
break;
}
case DNS_TYPE_NSEC3: {
uint8_t size;
r = dns_packet_read_uint8(p, &rr->nsec3.algorithm, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->nsec3.flags, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint16(p, &rr->nsec3.iterations, NULL);
if (r < 0)
return r;
/* this may be zero */
r = dns_packet_read_uint8(p, &size, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p, size, &rr->nsec3.salt, &rr->nsec3.salt_size, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &size, NULL);
if (r < 0)
return r;
if (size <= 0)
return -EBADMSG;
r = dns_packet_read_memdup(p, size,
&rr->nsec3.next_hashed_name, &rr->nsec3.next_hashed_name_size,
NULL);
if (r < 0)
return r;
r = dns_packet_read_type_windows(p, &rr->nsec3.types, offset + rdlength - p->rindex, NULL);
/* empty non-terminals can have NSEC3 records, so empty bitmaps are allowed */
break;
}
case DNS_TYPE_TLSA:
r = dns_packet_read_uint8(p, &rr->tlsa.cert_usage, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->tlsa.selector, NULL);
if (r < 0)
return r;
r = dns_packet_read_uint8(p, &rr->tlsa.matching_type, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p, rdlength - 3,
&rr->tlsa.data, &rr->tlsa.data_size,
NULL);
if (rr->tlsa.data_size <= 0)
/* the accepted size depends on the algorithm, but for now
just ensure that the value is greater than zero */
return -EBADMSG;
break;
case DNS_TYPE_CAA:
r = dns_packet_read_uint8(p, &rr->caa.flags, NULL);
if (r < 0)
return r;
r = dns_packet_read_string(p, &rr->caa.tag, NULL);
if (r < 0)
return r;
r = dns_packet_read_memdup(p,
rdlength + offset - p->rindex,
&rr->caa.value, &rr->caa.value_size, NULL);
break;
case DNS_TYPE_OPT: /* we only care about the header of OPT for now. */
case DNS_TYPE_OPENPGPKEY:
default:
unparseable:
r = dns_packet_read_memdup(p, rdlength, &rr->generic.data, &rr->generic.data_size, NULL);
break;
}
if (r < 0)
return r;
if (p->rindex != offset + rdlength)
return -EBADMSG;
*ret = rr;
rr = NULL;
if (ret_cache_flush)
*ret_cache_flush = cache_flush;
if (start)
*start = rewinder.saved_rindex;
CANCEL_REWINDER(rewinder);
return 0;
}
static bool opt_is_good(DnsResourceRecord *rr, bool *rfc6975) {
const uint8_t* p;
bool found_dau_dhu_n3u = false;
size_t l;
/* Checks whether the specified OPT RR is well-formed and whether it contains RFC6975 data (which is not OK in
* a reply). */
assert(rr);
assert(rr->key->type == DNS_TYPE_OPT);
/* Check that the version is 0 */
if (((rr->ttl >> 16) & UINT32_C(0xFF)) != 0) {
*rfc6975 = false;
return true; /* if it's not version 0, it's OK, but we will ignore the OPT field contents */
}
p = rr->opt.data;
l = rr->opt.data_size;
while (l > 0) {
uint16_t option_code, option_length;
/* At least four bytes for OPTION-CODE and OPTION-LENGTH are required */
if (l < 4U)
return false;
option_code = unaligned_read_be16(p);
option_length = unaligned_read_be16(p + 2);
if (l < option_length + 4U)
return false;
/* RFC 6975 DAU, DHU or N3U fields found. */
if (IN_SET(option_code, 5, 6, 7))
found_dau_dhu_n3u = true;
p += option_length + 4U;
l -= option_length + 4U;
}
*rfc6975 = found_dau_dhu_n3u;
return true;
}
int dns_packet_extract(DnsPacket *p) {
_cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
_cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
_cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = {};
unsigned n, i;
int r;
if (p->extracted)
return 0;
INIT_REWINDER(rewinder, p);
dns_packet_rewind(p, DNS_PACKET_HEADER_SIZE);
n = DNS_PACKET_QDCOUNT(p);
if (n > 0) {
question = dns_question_new(n);
if (!question)
return -ENOMEM;
for (i = 0; i < n; i++) {
_cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
bool cache_flush;
r = dns_packet_read_key(p, &key, &cache_flush, NULL);
if (r < 0)
return r;
if (cache_flush)
return -EBADMSG;
if (!dns_type_is_valid_query(key->type))
return -EBADMSG;
r = dns_question_add(question, key);
if (r < 0)
return r;
}
}
n = DNS_PACKET_RRCOUNT(p);
if (n > 0) {
_cleanup_(dns_resource_record_unrefp) DnsResourceRecord *previous = NULL;
bool bad_opt = false;
answer = dns_answer_new(n);
if (!answer)
return -ENOMEM;
for (i = 0; i < n; i++) {
_cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
bool cache_flush = false;
r = dns_packet_read_rr(p, &rr, &cache_flush, NULL);
if (r < 0)
return r;
/* Try to reduce memory usage a bit */
if (previous)
dns_resource_key_reduce(&rr->key, &previous->key);
if (rr->key->type == DNS_TYPE_OPT) {
bool has_rfc6975;
if (p->opt || bad_opt) {
/* Multiple OPT RRs? if so, let's ignore all, because there's something wrong
* with the server, and if one is valid we wouldn't know which one. */
log_debug("Multiple OPT RRs detected, ignoring all.");
bad_opt = true;
continue;
}
if (!dns_name_is_root(dns_resource_key_name(rr->key))) {
/* If the OPT RR is not owned by the root domain, then it is bad, let's ignore
* it. */
log_debug("OPT RR is not owned by root domain, ignoring.");
bad_opt = true;
continue;
}
if (i < DNS_PACKET_ANCOUNT(p) + DNS_PACKET_NSCOUNT(p)) {
/* OPT RR is in the wrong section? Some Belkin routers do this. This is a hint
* the EDNS implementation is borked, like the Belkin one is, hence ignore
* it. */
log_debug("OPT RR in wrong section, ignoring.");
bad_opt = true;
continue;
}
if (!opt_is_good(rr, &has_rfc6975)) {
log_debug("Malformed OPT RR, ignoring.");
bad_opt = true;
continue;
}
if (DNS_PACKET_QR(p)) {
/* Additional checks for responses */
if (!DNS_RESOURCE_RECORD_OPT_VERSION_SUPPORTED(rr)) {
/* If this is a reply and we don't know the EDNS version then something
* is weird... */
log_debug("EDNS version newer that our request, bad server.");
return -EBADMSG;
}
if (has_rfc6975) {
/* If the OPT RR contains RFC6975 algorithm data, then this is indication that
* the server just copied the OPT it got from us (which contained that data)
* back into the reply. If so, then it doesn't properly support EDNS, as
* RFC6975 makes it very clear that the algorithm data should only be contained
* in questions, never in replies. Crappy Belkin routers copy the OPT data for
* example, hence let's detect this so that we downgrade early. */
log_debug("OPT RR contained RFC6975 data, ignoring.");
bad_opt = true;
continue;
}
}
p->opt = dns_resource_record_ref(rr);
} else {
/* According to RFC 4795, section 2.9. only the RRs from the Answer section shall be
* cached. Hence mark only those RRs as cacheable by default, but not the ones from the
* Additional or Authority sections. */
r = dns_answer_add(answer, rr, p->ifindex,
(i < DNS_PACKET_ANCOUNT(p) ? DNS_ANSWER_CACHEABLE : 0) |
(p->protocol == DNS_PROTOCOL_MDNS && !cache_flush ? DNS_ANSWER_SHARED_OWNER : 0));
if (r < 0)
return r;
}
/* Remember this RR, so that we potentically can merge it's ->key object with the next RR. Note
* that we only do this if we actually decided to keep the RR around. */
dns_resource_record_unref(previous);
previous = dns_resource_record_ref(rr);
}
if (bad_opt)
p->opt = dns_resource_record_unref(p->opt);
}
p->question = question;
question = NULL;
p->answer = answer;
answer = NULL;
p->extracted = true;
/* no CANCEL, always rewind */
return 0;
}
int dns_packet_is_reply_for(DnsPacket *p, const DnsResourceKey *key) {
int r;
assert(p);
assert(key);
/* Checks if the specified packet is a reply for the specified
* key and the specified key is the only one in the question
* section. */
if (DNS_PACKET_QR(p) != 1)
return 0;
/* Let's unpack the packet, if that hasn't happened yet. */
r = dns_packet_extract(p);
if (r < 0)
return r;
if (p->question->n_keys != 1)
return 0;
return dns_resource_key_equal(p->question->keys[0], key);
}
static const char* const dns_rcode_table[_DNS_RCODE_MAX_DEFINED] = {
[DNS_RCODE_SUCCESS] = "SUCCESS",
[DNS_RCODE_FORMERR] = "FORMERR",
[DNS_RCODE_SERVFAIL] = "SERVFAIL",
[DNS_RCODE_NXDOMAIN] = "NXDOMAIN",
[DNS_RCODE_NOTIMP] = "NOTIMP",
[DNS_RCODE_REFUSED] = "REFUSED",
[DNS_RCODE_YXDOMAIN] = "YXDOMAIN",
[DNS_RCODE_YXRRSET] = "YRRSET",
[DNS_RCODE_NXRRSET] = "NXRRSET",
[DNS_RCODE_NOTAUTH] = "NOTAUTH",
[DNS_RCODE_NOTZONE] = "NOTZONE",
[DNS_RCODE_BADVERS] = "BADVERS",
[DNS_RCODE_BADKEY] = "BADKEY",
[DNS_RCODE_BADTIME] = "BADTIME",
[DNS_RCODE_BADMODE] = "BADMODE",
[DNS_RCODE_BADNAME] = "BADNAME",
[DNS_RCODE_BADALG] = "BADALG",
[DNS_RCODE_BADTRUNC] = "BADTRUNC",
[DNS_RCODE_BADCOOKIE] = "BADCOOKIE",
};
DEFINE_STRING_TABLE_LOOKUP(dns_rcode, int);
static const char* const dns_protocol_table[_DNS_PROTOCOL_MAX] = {
[DNS_PROTOCOL_DNS] = "dns",
[DNS_PROTOCOL_MDNS] = "mdns",
[DNS_PROTOCOL_LLMNR] = "llmnr",
};
DEFINE_STRING_TABLE_LOOKUP(dns_protocol, DnsProtocol);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3371_0 |
crossvul-cpp_data_bad_5285_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 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. |
+----------------------------------------------------------------------+
| Authors: Marcus Boerger <helly@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/php_var.h"
#include "ext/standard/php_smart_str.h"
#include "zend_interfaces.h"
#include "zend_exceptions.h"
#include "php_spl.h"
#include "spl_functions.h"
#include "spl_engine.h"
#include "spl_iterators.h"
#include "spl_array.h"
#include "spl_exceptions.h"
zend_object_handlers spl_handler_ArrayObject;
PHPAPI zend_class_entry *spl_ce_ArrayObject;
zend_object_handlers spl_handler_ArrayIterator;
PHPAPI zend_class_entry *spl_ce_ArrayIterator;
PHPAPI zend_class_entry *spl_ce_RecursiveArrayIterator;
#define SPL_ARRAY_STD_PROP_LIST 0x00000001
#define SPL_ARRAY_ARRAY_AS_PROPS 0x00000002
#define SPL_ARRAY_CHILD_ARRAYS_ONLY 0x00000004
#define SPL_ARRAY_OVERLOADED_REWIND 0x00010000
#define SPL_ARRAY_OVERLOADED_VALID 0x00020000
#define SPL_ARRAY_OVERLOADED_KEY 0x00040000
#define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000
#define SPL_ARRAY_OVERLOADED_NEXT 0x00100000
#define SPL_ARRAY_IS_REF 0x01000000
#define SPL_ARRAY_IS_SELF 0x02000000
#define SPL_ARRAY_USE_OTHER 0x04000000
#define SPL_ARRAY_INT_MASK 0xFFFF0000
#define SPL_ARRAY_CLONE_MASK 0x0300FFFF
#define SPL_ARRAY_METHOD_NO_ARG 0
#define SPL_ARRAY_METHOD_USE_ARG 1
#define SPL_ARRAY_METHOD_MAY_USER_ARG 2
typedef struct _spl_array_object {
zend_object std;
zval *array;
zval *retval;
HashPosition pos;
ulong pos_h;
int ar_flags;
int is_self;
zend_function *fptr_offset_get;
zend_function *fptr_offset_set;
zend_function *fptr_offset_has;
zend_function *fptr_offset_del;
zend_function *fptr_count;
zend_class_entry* ce_get_iterator;
HashTable *debug_info;
unsigned char nApplyCount;
} spl_array_object;
static inline HashTable *spl_array_get_hash_table(spl_array_object* intern, int check_std_props TSRMLS_DC) { /* {{{ */
if ((intern->ar_flags & SPL_ARRAY_IS_SELF) != 0) {
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
return intern->std.properties;
} else if ((intern->ar_flags & SPL_ARRAY_USE_OTHER) && (check_std_props == 0 || (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) == 0) && Z_TYPE_P(intern->array) == IS_OBJECT) {
spl_array_object *other = (spl_array_object*)zend_object_store_get_object(intern->array TSRMLS_CC);
return spl_array_get_hash_table(other, check_std_props TSRMLS_CC);
} else if ((intern->ar_flags & ((check_std_props ? SPL_ARRAY_STD_PROP_LIST : 0) | SPL_ARRAY_IS_SELF)) != 0) {
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
return intern->std.properties;
} else {
return HASH_OF(intern->array);
}
} /* }}} */
static void spl_array_rewind(spl_array_object *intern TSRMLS_DC);
static void spl_array_update_pos(spl_array_object* intern) /* {{{ */
{
Bucket *pos = intern->pos;
if (pos != NULL) {
intern->pos_h = pos->h;
}
} /* }}} */
static void spl_array_set_pos(spl_array_object* intern, HashPosition pos) /* {{{ */
{
intern->pos = pos;
spl_array_update_pos(intern);
} /* }}} */
SPL_API int spl_hash_verify_pos_ex(spl_array_object * intern, HashTable * ht TSRMLS_DC) /* {{{ */
{
Bucket *p;
/* IS_CONSISTENT(ht);*/
/* HASH_PROTECT_RECURSION(ht);*/
p = ht->arBuckets[intern->pos_h & ht->nTableMask];
while (p != NULL) {
if (p == intern->pos) {
return SUCCESS;
}
p = p->pNext;
}
/* HASH_UNPROTECT_RECURSION(ht); */
spl_array_rewind(intern TSRMLS_CC);
return FAILURE;
} /* }}} */
SPL_API int spl_hash_verify_pos(spl_array_object * intern TSRMLS_DC) /* {{{ */
{
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
return spl_hash_verify_pos_ex(intern, ht TSRMLS_CC);
}
/* }}} */
/* {{{ spl_array_object_free_storage */
static void spl_array_object_free_storage(void *object TSRMLS_DC)
{
spl_array_object *intern = (spl_array_object *)object;
zend_object_std_dtor(&intern->std TSRMLS_CC);
zval_ptr_dtor(&intern->array);
zval_ptr_dtor(&intern->retval);
if (intern->debug_info != NULL) {
zend_hash_destroy(intern->debug_info);
efree(intern->debug_info);
}
efree(object);
}
/* }}} */
zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC);
/* {{{ spl_array_object_new_ex */
static zend_object_value spl_array_object_new_ex(zend_class_entry *class_type, spl_array_object **obj, zval *orig, int clone_orig TSRMLS_DC)
{
zend_object_value retval = {0};
spl_array_object *intern;
zval *tmp;
zend_class_entry * parent = class_type;
int inherited = 0;
intern = emalloc(sizeof(spl_array_object));
memset(intern, 0, sizeof(spl_array_object));
*obj = intern;
ALLOC_INIT_ZVAL(intern->retval);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
intern->ar_flags = 0;
intern->debug_info = NULL;
intern->ce_get_iterator = spl_ce_ArrayIterator;
if (orig) {
spl_array_object *other = (spl_array_object*)zend_object_store_get_object(orig TSRMLS_CC);
intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK;
intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK);
intern->ce_get_iterator = other->ce_get_iterator;
if (clone_orig) {
intern->array = other->array;
if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) {
MAKE_STD_ZVAL(intern->array);
array_init(intern->array);
zend_hash_copy(HASH_OF(intern->array), HASH_OF(other->array), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
}
if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator) {
Z_ADDREF_P(other->array);
}
} else {
intern->array = orig;
Z_ADDREF_P(intern->array);
intern->ar_flags |= SPL_ARRAY_IS_REF | SPL_ARRAY_USE_OTHER;
}
} else {
MAKE_STD_ZVAL(intern->array);
array_init(intern->array);
intern->ar_flags &= ~SPL_ARRAY_IS_REF;
}
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_array_object_free_storage, NULL TSRMLS_CC);
while (parent) {
if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) {
retval.handlers = &spl_handler_ArrayIterator;
class_type->get_iterator = spl_array_get_iterator;
break;
} else if (parent == spl_ce_ArrayObject) {
retval.handlers = &spl_handler_ArrayObject;
break;
}
parent = parent->parent;
inherited = 1;
}
if (!parent) { /* this must never happen */
php_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator");
}
if (inherited) {
zend_hash_find(&class_type->function_table, "offsetget", sizeof("offsetget"), (void **) &intern->fptr_offset_get);
if (intern->fptr_offset_get->common.scope == parent) {
intern->fptr_offset_get = NULL;
}
zend_hash_find(&class_type->function_table, "offsetset", sizeof("offsetset"), (void **) &intern->fptr_offset_set);
if (intern->fptr_offset_set->common.scope == parent) {
intern->fptr_offset_set = NULL;
}
zend_hash_find(&class_type->function_table, "offsetexists", sizeof("offsetexists"), (void **) &intern->fptr_offset_has);
if (intern->fptr_offset_has->common.scope == parent) {
intern->fptr_offset_has = NULL;
}
zend_hash_find(&class_type->function_table, "offsetunset", sizeof("offsetunset"), (void **) &intern->fptr_offset_del);
if (intern->fptr_offset_del->common.scope == parent) {
intern->fptr_offset_del = NULL;
}
zend_hash_find(&class_type->function_table, "count", sizeof("count"), (void **) &intern->fptr_count);
if (intern->fptr_count->common.scope == parent) {
intern->fptr_count = NULL;
}
}
/* Cache iterator functions if ArrayIterator or derived. Check current's */
/* cache since only current is always required */
if (retval.handlers == &spl_handler_ArrayIterator) {
if (!class_type->iterator_funcs.zf_current) {
zend_hash_find(&class_type->function_table, "rewind", sizeof("rewind"), (void **) &class_type->iterator_funcs.zf_rewind);
zend_hash_find(&class_type->function_table, "valid", sizeof("valid"), (void **) &class_type->iterator_funcs.zf_valid);
zend_hash_find(&class_type->function_table, "key", sizeof("key"), (void **) &class_type->iterator_funcs.zf_key);
zend_hash_find(&class_type->function_table, "current", sizeof("current"), (void **) &class_type->iterator_funcs.zf_current);
zend_hash_find(&class_type->function_table, "next", sizeof("next"), (void **) &class_type->iterator_funcs.zf_next);
}
if (inherited) {
if (class_type->iterator_funcs.zf_rewind->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND;
if (class_type->iterator_funcs.zf_valid->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID;
if (class_type->iterator_funcs.zf_key->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY;
if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT;
if (class_type->iterator_funcs.zf_next->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT;
}
}
spl_array_rewind(intern TSRMLS_CC);
return retval;
}
/* }}} */
/* {{{ spl_array_object_new */
static zend_object_value spl_array_object_new(zend_class_entry *class_type TSRMLS_DC)
{
spl_array_object *tmp;
return spl_array_object_new_ex(class_type, &tmp, NULL, 0 TSRMLS_CC);
}
/* }}} */
/* {{{ spl_array_object_clone */
static zend_object_value spl_array_object_clone(zval *zobject TSRMLS_DC)
{
zend_object_value new_obj_val;
zend_object *old_object;
zend_object *new_object;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
spl_array_object *intern;
old_object = zend_objects_get_address(zobject TSRMLS_CC);
new_obj_val = spl_array_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC);
new_object = &intern->std;
zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC);
return new_obj_val;
}
/* }}} */
static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **retval;
char *key;
uint len;
long index;
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!offset) {
return &EG(uninitialized_zval_ptr);
}
if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return &EG(error_zval_ptr);;
}
switch (Z_TYPE_P(offset)) {
case IS_STRING:
key = Z_STRVAL_P(offset);
len = Z_STRLEN_P(offset) + 1;
string_offest:
if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined index: %s", key);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE,"Undefined index: %s", key);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
case IS_NULL:
key = "";
len = 1;
goto string_offest;
case IS_RESOURCE:
zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset));
case IS_DOUBLE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
default:
zend_error(E_WARNING, "Illegal offset type");
return (type == BP_VAR_W || type == BP_VAR_RW) ?
&EG(error_zval_ptr) : &EG(uninitialized_zval_ptr);
}
} /* }}} */
static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
zval **ret;
if (check_inherited) {
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (intern->fptr_offset_get) {
zval *rv;
if (!offset) {
ALLOC_INIT_ZVAL(offset);
} else {
SEPARATE_ARG_IF_REF(offset);
}
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset);
zval_ptr_dtor(&offset);
if (rv) {
zval_ptr_dtor(&intern->retval);
MAKE_STD_ZVAL(intern->retval);
ZVAL_ZVAL(intern->retval, rv, 1, 1);
return intern->retval;
}
return EG(uninitialized_zval_ptr);
}
}
ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC);
/* When in a write context,
* ZE has to be fooled into thinking this is in a reference set
* by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */
if ((type == BP_VAR_W || type == BP_VAR_RW || type == BP_VAR_UNSET) && !Z_ISREF_PP(ret) && ret != &EG(uninitialized_zval_ptr)) {
if (Z_REFCOUNT_PP(ret) > 1) {
zval *newval;
/* Separate */
MAKE_STD_ZVAL(newval);
*newval = **ret;
zval_copy_ctor(newval);
Z_SET_REFCOUNT_P(newval, 1);
/* Replace */
Z_DELREF_PP(ret);
*ret = newval;
}
Z_SET_ISREF_PP(ret);
}
return *ret;
} /* }}} */
static zval *spl_array_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
return spl_array_read_dimension_ex(1, object, offset, type TSRMLS_CC);
} /* }}} */
static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
HashTable *ht;
if (check_inherited && intern->fptr_offset_set) {
if (!offset) {
ALLOC_INIT_ZVAL(offset);
} else {
SEPARATE_ARG_IF_REF(offset);
}
zend_call_method_with_2_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value);
zval_ptr_dtor(&offset);
return;
}
if (!offset) {
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
Z_ADDREF_P(value);
zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL);
return;
}
switch(Z_TYPE_P(offset)) {
case IS_STRING:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
Z_ADDREF_P(value);
zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL);
return;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
Z_ADDREF_P(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL);
return;
case IS_NULL:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
Z_ADDREF_P(value);
zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL);
return;
default:
zend_error(E_WARNING, "Illegal offset type");
return;
}
} /* }}} */
static void spl_array_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */
{
spl_array_write_dimension_ex(1, object, offset, value TSRMLS_CC);
} /* }}} */
static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
HashTable *ht;
if (check_inherited && intern->fptr_offset_del) {
SEPARATE_ARG_IF_REF(offset);
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset);
zval_ptr_dtor(&offset);
return;
}
switch(Z_TYPE_P(offset)) {
case IS_STRING:
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
if (ht == &EG(symbol_table)) {
if (zend_delete_global_variable(Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC)) {
zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
}
} else {
if (zend_symtable_del(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1) == FAILURE) {
zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
} else {
spl_array_object *obj = intern;
while (1) {
if ((obj->ar_flags & SPL_ARRAY_IS_SELF) != 0) {
break;
} else if (Z_TYPE_P(obj->array) == IS_OBJECT) {
if ((obj->ar_flags & SPL_ARRAY_USE_OTHER) == 0) {
obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC);
break;
} else {
obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC);
}
} else {
obj = NULL;
break;
}
}
if (obj) {
zend_property_info *property_info = zend_get_property_info(obj->std.ce, offset, 1 TSRMLS_CC);
if (property_info &&
(property_info->flags & ZEND_ACC_STATIC) == 0 &&
property_info->offset >= 0) {
obj->std.properties_table[property_info->offset] = NULL;
}
}
}
}
break;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (ht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
if (zend_hash_index_del(ht, index) == FAILURE) {
zend_error(E_NOTICE,"Undefined offset: %ld", Z_LVAL_P(offset));
}
break;
default:
zend_error(E_WARNING, "Illegal offset type");
return;
}
spl_hash_verify_pos(intern TSRMLS_CC); /* call rewind on FAILURE */
} /* }}} */
static void spl_array_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */
{
spl_array_unset_dimension_ex(1, object, offset TSRMLS_CC);
} /* }}} */
static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
zval *rv, *value = NULL, **tmp;
if (check_inherited && intern->fptr_offset_has) {
zval *offset_tmp = offset;
SEPARATE_ARG_IF_REF(offset_tmp);
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp);
zval_ptr_dtor(&offset_tmp);
if (rv && zend_is_true(rv)) {
zval_ptr_dtor(&rv);
if (check_empty != 1) {
return 1;
} else if (intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
}
} else {
if (rv) {
zval_ptr_dtor(&rv);
}
return 0;
}
}
if (!value) {
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
switch(Z_TYPE_P(offset)) {
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
default:
zend_error(E_WARNING, "Illegal offset type");
return 0;
}
if (check_empty && check_inherited && intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
} else {
value = *tmp;
}
}
return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;
} /* }}} */
static int spl_array_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */
{
return spl_array_has_dimension_ex(1, object, offset, check_empty TSRMLS_CC);
} /* }}} */
/* {{{ spl_array_object_verify_pos_ex */
static inline int spl_array_object_verify_pos_ex(spl_array_object *object, HashTable *ht, const char *msg_prefix TSRMLS_DC)
{
if (!ht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%sArray was modified outside object and is no longer an array", msg_prefix);
return FAILURE;
}
if (object->pos && (object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, ht TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%sArray was modified outside object and internal position is no longer valid", msg_prefix);
return FAILURE;
}
return SUCCESS;
} /* }}} */
/* {{{ spl_array_object_verify_pos */
static inline int spl_array_object_verify_pos(spl_array_object *object, HashTable *ht TSRMLS_DC)
{
return spl_array_object_verify_pos_ex(object, ht, "" TSRMLS_CC);
} /* }}} */
/* {{{ proto bool ArrayObject::offsetExists(mixed $index)
proto bool ArrayIterator::offsetExists(mixed $index)
Returns whether the requested $index exists. */
SPL_METHOD(Array, offsetExists)
{
zval *index;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 2 TSRMLS_CC));
} /* }}} */
/* {{{ proto mixed ArrayObject::offsetGet(mixed $index)
proto mixed ArrayIterator::offsetGet(mixed $index)
Returns the value at the specified $index. */
SPL_METHOD(Array, offsetGet)
{
zval *index, *value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC);
RETURN_ZVAL(value, 1, 0);
} /* }}} */
/* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval)
proto void ArrayIterator::offsetSet(mixed $index, mixed $newval)
Sets the value at the specified $index to $newval. */
SPL_METHOD(Array, offsetSet)
{
zval *index, *value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) == FAILURE) {
return;
}
spl_array_write_dimension_ex(0, getThis(), index, value TSRMLS_CC);
} /* }}} */
void spl_array_iterator_append(zval *object, zval *append_value TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Cannot append properties to objects, use %s::offsetSet() instead", Z_OBJCE_P(object)->name);
return;
}
spl_array_write_dimension(object, NULL, append_value TSRMLS_CC);
if (!intern->pos) {
spl_array_set_pos(intern, aht->pListTail);
}
} /* }}} */
/* {{{ proto void ArrayObject::append(mixed $newval)
proto void ArrayIterator::append(mixed $newval)
Appends the value (cannot be called for objects). */
SPL_METHOD(Array, append)
{
zval *value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) {
return;
}
spl_array_iterator_append(getThis(), value TSRMLS_CC);
} /* }}} */
/* {{{ proto void ArrayObject::offsetUnset(mixed $index)
proto void ArrayIterator::offsetUnset(mixed $index)
Unsets the value at the specified $index. */
SPL_METHOD(Array, offsetUnset)
{
zval *index;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
spl_array_unset_dimension_ex(0, getThis(), index TSRMLS_CC);
} /* }}} */
/* {{{ proto array ArrayObject::getArrayCopy()
proto array ArrayIterator::getArrayCopy()
Return a copy of the contained array */
SPL_METHOD(Array, getArrayCopy)
{
zval *object = getThis(), *tmp;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
array_init(return_value);
zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
} /* }}} */
static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *result;
if (intern->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Nesting level too deep - recursive dependency?");
}
intern->nApplyCount++;
result = spl_array_get_hash_table(intern, 1 TSRMLS_CC);
intern->nApplyCount--;
return result;
} /* }}} */
static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(obj TSRMLS_CC);
zval *tmp, *storage;
int name_len;
char *zname;
zend_class_entry *base;
*is_temp = 0;
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
if (HASH_OF(intern->array) == intern->std.properties) {
return intern->std.properties;
} else {
if (intern->debug_info == NULL) {
ALLOC_HASHTABLE(intern->debug_info);
ZEND_INIT_SYMTABLE_EX(intern->debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0);
}
if (intern->debug_info->nApplyCount == 0) {
zend_hash_clean(intern->debug_info);
zend_hash_copy(intern->debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
storage = intern->array;
zval_add_ref(&storage);
base = (Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator) ? spl_ce_ArrayIterator : spl_ce_ArrayObject;
zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1, &name_len TSRMLS_CC);
zend_symtable_update(intern->debug_info, zname, name_len+1, &storage, sizeof(zval *), NULL);
efree(zname);
}
return intern->debug_info;
}
}
/* }}} */
static HashTable *spl_array_get_gc(zval *object, zval ***gc_data, int *gc_data_count TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
*gc_data = &intern->array;
*gc_data_count = 1;
return zend_std_get_properties(object TSRMLS_CC);
}
/* }}} */
static zval *spl_array_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
return spl_array_read_dimension(object, member, type TSRMLS_CC);
}
return std_object_handlers.read_property(object, member, type, key TSRMLS_CC);
} /* }}} */
static void spl_array_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
spl_array_write_dimension(object, member, value TSRMLS_CC);
return;
}
std_object_handlers.write_property(object, member, value, key TSRMLS_CC);
} /* }}} */
static zval **spl_array_get_property_ptr_ptr(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
return spl_array_get_dimension_ptr_ptr(1, object, member, type TSRMLS_CC);
}
return std_object_handlers.get_property_ptr_ptr(object, member, type, key TSRMLS_CC);
} /* }}} */
static int spl_array_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
return spl_array_has_dimension(object, member, has_set_exists TSRMLS_CC);
}
return std_object_handlers.has_property(object, member, has_set_exists, key TSRMLS_CC);
} /* }}} */
static void spl_array_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
&& !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) {
spl_array_unset_dimension(object, member TSRMLS_CC);
spl_array_rewind(intern TSRMLS_CC); /* because deletion might invalidate position */
return;
}
std_object_handlers.unset_property(object, member, key TSRMLS_CC);
} /* }}} */
static int spl_array_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */
{
HashTable *ht1,
*ht2;
spl_array_object *intern1,
*intern2;
int result = 0;
zval temp_zv;
intern1 = (spl_array_object*)zend_object_store_get_object(o1 TSRMLS_CC);
intern2 = (spl_array_object*)zend_object_store_get_object(o2 TSRMLS_CC);
ht1 = spl_array_get_hash_table(intern1, 0 TSRMLS_CC);
ht2 = spl_array_get_hash_table(intern2, 0 TSRMLS_CC);
zend_compare_symbol_tables(&temp_zv, ht1, ht2 TSRMLS_CC);
result = (int)Z_LVAL(temp_zv);
/* if we just compared std.properties, don't do it again */
if (result == 0 &&
!(ht1 == intern1->std.properties && ht2 == intern2->std.properties)) {
result = std_object_handlers.compare_objects(o1, o2 TSRMLS_CC);
}
return result;
} /* }}} */
static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
char *string_key;
uint string_length;
ulong num_key;
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
do {
if (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 0, &intern->pos) == HASH_KEY_IS_STRING) {
/* zend_hash_get_current_key_ex() should never set
* string_length to 0 when returning HASH_KEY_IS_STRING, but we
* may as well be defensive and consider that successful.
* Beyond that, we're looking for protected keys (which will
* have a null byte at string_key[0]), but want to avoid
* skipping completely empty keys (which will also have the
* null byte, but a string_length of 1). */
if (!string_length || string_key[0] || string_length == 1) {
return SUCCESS;
}
} else {
return SUCCESS;
}
if (zend_hash_has_more_elements_ex(aht, &intern->pos) != SUCCESS) {
return FAILURE;
}
zend_hash_move_forward_ex(aht, &intern->pos);
spl_array_update_pos(intern);
} while (1);
}
return FAILURE;
} /* }}} */
static int spl_array_next_no_verify(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
zend_hash_move_forward_ex(aht, &intern->pos);
spl_array_update_pos(intern);
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
return spl_array_skip_protected(intern, aht TSRMLS_CC);
} else {
return zend_hash_has_more_elements_ex(aht, &intern->pos);
}
} /* }}} */
static int spl_array_next_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid");
return FAILURE;
}
return spl_array_next_no_verify(intern, aht TSRMLS_CC);
} /* }}} */
static int spl_array_next(spl_array_object *intern TSRMLS_DC) /* {{{ */
{
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
return spl_array_next_ex(intern, aht TSRMLS_CC);
} /* }}} */
/* define an overloaded iterator structure */
typedef struct {
zend_user_iterator intern;
spl_array_object *object;
} spl_array_it;
static void spl_array_it_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
zend_user_it_invalidate_current(iter TSRMLS_CC);
zval_ptr_dtor((zval**)&iterator->intern.it.data);
efree(iterator);
}
/* }}} */
static int spl_array_it_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) {
return zend_user_it_valid(iter TSRMLS_CC);
} else {
if (spl_array_object_verify_pos_ex(object, aht, "ArrayIterator::valid(): " TSRMLS_CC) == FAILURE) {
return FAILURE;
}
return zend_hash_has_more_elements_ex(aht, &object->pos);
}
}
/* }}} */
static void spl_array_it_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) {
zend_user_it_get_current_data(iter, data TSRMLS_CC);
} else {
if (zend_hash_get_current_data_ex(aht, (void**)data, &object->pos) == FAILURE) {
*data = NULL;
}
}
}
/* }}} */
static void spl_array_it_get_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) {
zend_user_it_get_current_key(iter, key TSRMLS_CC);
} else {
if (spl_array_object_verify_pos_ex(object, aht, "ArrayIterator::current(): " TSRMLS_CC) == FAILURE) {
ZVAL_NULL(key);
} else {
zend_hash_get_current_key_zval_ex(aht, key, &object->pos);
}
}
}
/* }}} */
static void spl_array_it_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC);
if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) {
zend_user_it_move_forward(iter TSRMLS_CC);
} else {
zend_user_it_invalidate_current(iter TSRMLS_CC);
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array");
return;
}
if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::next(): Array was modified outside object and internal position is no longer valid");
} else {
spl_array_next_no_verify(object, aht TSRMLS_CC);
}
}
}
/* }}} */
static void spl_array_rewind_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */
{
zend_hash_internal_pointer_reset_ex(aht, &intern->pos);
spl_array_update_pos(intern);
spl_array_skip_protected(intern, aht TSRMLS_CC);
} /* }}} */
static void spl_array_rewind(spl_array_object *intern TSRMLS_DC) /* {{{ */
{
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array");
return;
}
spl_array_rewind_ex(intern, aht TSRMLS_CC);
}
/* }}} */
static void spl_array_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator = (spl_array_it *)iter;
spl_array_object *object = iterator->object;
if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) {
zend_user_it_rewind(iter TSRMLS_CC);
} else {
zend_user_it_invalidate_current(iter TSRMLS_CC);
spl_array_rewind(object TSRMLS_CC);
}
}
/* }}} */
/* {{{ spl_array_set_array */
static void spl_array_set_array(zval *object, spl_array_object *intern, zval **array, long ar_flags, int just_array TSRMLS_DC) {
if (Z_TYPE_PP(array) == IS_ARRAY) {
SEPARATE_ZVAL_IF_NOT_REF(array);
}
if (Z_TYPE_PP(array) == IS_OBJECT && (Z_OBJ_HT_PP(array) == &spl_handler_ArrayObject || Z_OBJ_HT_PP(array) == &spl_handler_ArrayIterator)) {
zval_ptr_dtor(&intern->array);
if (just_array) {
spl_array_object *other = (spl_array_object*)zend_object_store_get_object(*array TSRMLS_CC);
ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK;
}
ar_flags |= SPL_ARRAY_USE_OTHER;
intern->array = *array;
} else {
if (Z_TYPE_PP(array) != IS_OBJECT && Z_TYPE_PP(array) != IS_ARRAY) {
zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object, using empty array instead", 0 TSRMLS_CC);
return;
}
zval_ptr_dtor(&intern->array);
intern->array = *array;
}
if (object == *array) {
intern->ar_flags |= SPL_ARRAY_IS_SELF;
intern->ar_flags &= ~SPL_ARRAY_USE_OTHER;
} else {
intern->ar_flags &= ~SPL_ARRAY_IS_SELF;
}
intern->ar_flags |= ar_flags;
Z_ADDREF_P(intern->array);
if (Z_TYPE_PP(array) == IS_OBJECT) {
zend_object_get_properties_t handler = Z_OBJ_HANDLER_PP(array, get_properties);
if ((handler != std_object_handlers.get_properties && handler != spl_array_get_properties)
|| !spl_array_get_hash_table(intern, 0 TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Overloaded object of type %s is not compatible with %s", Z_OBJCE_PP(array)->name, intern->std.ce->name);
}
}
spl_array_rewind(intern TSRMLS_CC);
}
/* }}} */
/* iterator handler table */
zend_object_iterator_funcs spl_array_it_funcs = {
spl_array_it_dtor,
spl_array_it_valid,
spl_array_it_get_current_data,
spl_array_it_get_current_key,
spl_array_it_move_forward,
spl_array_it_rewind
};
zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */
{
spl_array_it *iterator;
spl_array_object *array_object = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
iterator = emalloc(sizeof(spl_array_it));
Z_ADDREF_P(object);
iterator->intern.it.data = (void*)object;
iterator->intern.it.funcs = &spl_array_it_funcs;
iterator->intern.ce = ce;
iterator->intern.value = NULL;
iterator->object = array_object;
return (zend_object_iterator*)iterator;
}
/* }}} */
/* {{{ proto void ArrayObject::__construct(array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]])
proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0])
Constructs a new array iterator from a path. */
SPL_METHOD(Array, __construct)
{
zval *object = getThis();
spl_array_object *intern;
zval **array;
long ar_flags = 0;
zend_class_entry *ce_get_iterator = spl_ce_Iterator;
zend_error_handling error_handling;
if (ZEND_NUM_ARGS() == 0) {
return; /* nothing to do */
}
zend_replace_error_handling(EH_THROW, spl_ce_InvalidArgumentException, &error_handling TSRMLS_CC);
intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (ZEND_NUM_ARGS() > 2) {
intern->ce_get_iterator = ce_get_iterator;
}
ar_flags &= ~SPL_ARRAY_INT_MASK;
spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1 TSRMLS_CC);
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
/* }}} */
/* {{{ proto void ArrayObject::setIteratorClass(string iterator_class)
Set the class used in getIterator. */
SPL_METHOD(Array, setIteratorClass)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zend_class_entry * ce_get_iterator = spl_ce_Iterator;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &ce_get_iterator) == FAILURE) {
return;
}
intern->ce_get_iterator = ce_get_iterator;
}
/* }}} */
/* {{{ proto string ArrayObject::getIteratorClass()
Get the class used in getIterator. */
SPL_METHOD(Array, getIteratorClass)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->ce_get_iterator->name, 1);
}
/* }}} */
/* {{{ proto int ArrayObject::getFlags()
Get flags */
SPL_METHOD(Array, getFlags)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK);
}
/* }}} */
/* {{{ proto void ArrayObject::setFlags(int flags)
Set flags */
SPL_METHOD(Array, setFlags)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long ar_flags = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ar_flags) == FAILURE) {
return;
}
intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK);
}
/* }}} */
/* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array())
Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */
SPL_METHOD(Array, exchangeArray)
{
zval *object = getThis(), *tmp, **array;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
array_init(return_value);
zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &array) == FAILURE) {
return;
}
spl_array_set_array(object, intern, array, 0L, 1 TSRMLS_CC);
}
/* }}} */
/* {{{ proto ArrayIterator ArrayObject::getIterator()
Create a new iterator from a ArrayObject instance */
SPL_METHOD(Array, getIterator)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
spl_array_object *iterator;
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
return_value->type = IS_OBJECT;
return_value->value.obj = spl_array_object_new_ex(intern->ce_get_iterator, &iterator, object, 0 TSRMLS_CC);
Z_SET_REFCOUNT_P(return_value, 1);
Z_SET_ISREF_P(return_value);
}
/* }}} */
/* {{{ proto void ArrayIterator::rewind()
Rewind array back to the start */
SPL_METHOD(Array, rewind)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_array_rewind(intern TSRMLS_CC);
}
/* }}} */
/* {{{ proto void ArrayIterator::seek(int $position)
Seek to position. */
SPL_METHOD(Array, seek)
{
long opos, position;
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
int result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
opos = position;
if (position >= 0) { /* negative values are not supported */
spl_array_rewind(intern TSRMLS_CC);
result = SUCCESS;
while (position-- > 0 && (result = spl_array_next(intern TSRMLS_CC)) == SUCCESS);
if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS) {
return; /* ok */
}
}
zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0 TSRMLS_CC, "Seek position %ld is out of range", opos);
} /* }}} */
int static spl_array_object_count_elements_helper(spl_array_object *intern, long *count TSRMLS_DC) /* {{{ */
{
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
HashPosition pos;
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
*count = 0;
return FAILURE;
}
if (Z_TYPE_P(intern->array) == IS_OBJECT) {
/* We need to store the 'pos' since we'll modify it in the functions
* we're going to call and which do not support 'pos' as parameter. */
pos = intern->pos;
*count = 0;
spl_array_rewind(intern TSRMLS_CC);
while(intern->pos && spl_array_next(intern TSRMLS_CC) == SUCCESS) {
(*count)++;
}
spl_array_set_pos(intern, pos);
return SUCCESS;
} else {
*count = zend_hash_num_elements(aht);
return SUCCESS;
}
} /* }}} */
int spl_array_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
if (intern->fptr_count) {
zval *rv;
zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv);
if (rv) {
zval_ptr_dtor(&intern->retval);
MAKE_STD_ZVAL(intern->retval);
ZVAL_ZVAL(intern->retval, rv, 1, 1);
convert_to_long(intern->retval);
*count = (long) Z_LVAL_P(intern->retval);
return SUCCESS;
}
*count = 0;
return FAILURE;
}
return spl_array_object_count_elements_helper(intern, count TSRMLS_CC);
} /* }}} */
/* {{{ proto int ArrayObject::count()
proto int ArrayIterator::count()
Return the number of elements in the Iterator. */
SPL_METHOD(Array, count)
{
long count;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_array_object_count_elements_helper(intern, &count TSRMLS_CC);
RETURN_LONG(count);
} /* }}} */
static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
zval *tmp, *arg = NULL;
zval *retval_ptr = NULL;
MAKE_STD_ZVAL(tmp);
Z_TYPE_P(tmp) = IS_ARRAY;
Z_ARRVAL_P(tmp) = aht;
if (!use_arg) {
aht->nApplyCount++;
zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 1, tmp, NULL TSRMLS_CC);
aht->nApplyCount--;
} else if (use_arg == SPL_ARRAY_METHOD_MAY_USER_ARG) {
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "|z", &arg) == FAILURE) {
Z_TYPE_P(tmp) = IS_NULL;
zval_ptr_dtor(&tmp);
zend_throw_exception(spl_ce_BadMethodCallException, "Function expects one argument at most", 0 TSRMLS_CC);
return;
}
aht->nApplyCount++;
zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, arg? 2 : 1, tmp, arg TSRMLS_CC);
aht->nApplyCount--;
} else {
if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) {
Z_TYPE_P(tmp) = IS_NULL;
zval_ptr_dtor(&tmp);
zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0 TSRMLS_CC);
return;
}
aht->nApplyCount++;
zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 2, tmp, arg TSRMLS_CC);
aht->nApplyCount--;
}
Z_TYPE_P(tmp) = IS_NULL; /* we want to destroy the zval, not the hashtable */
zval_ptr_dtor(&tmp);
if (retval_ptr) {
COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr);
}
} /* }}} */
#define SPL_ARRAY_METHOD(cname, fname, use_arg) \
SPL_METHOD(cname, fname) \
{ \
spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \
}
/* {{{ proto int ArrayObject::asort([int $sort_flags = SORT_REGULAR ])
proto int ArrayIterator::asort([int $sort_flags = SORT_REGULAR ])
Sort the entries by values. */
SPL_ARRAY_METHOD(Array, asort, SPL_ARRAY_METHOD_MAY_USER_ARG) /* }}} */
/* {{{ proto int ArrayObject::ksort([int $sort_flags = SORT_REGULAR ])
proto int ArrayIterator::ksort([int $sort_flags = SORT_REGULAR ])
Sort the entries by key. */
SPL_ARRAY_METHOD(Array, ksort, SPL_ARRAY_METHOD_MAY_USER_ARG) /* }}} */
/* {{{ proto int ArrayObject::uasort(callback cmp_function)
proto int ArrayIterator::uasort(callback cmp_function)
Sort the entries by values user defined function. */
SPL_ARRAY_METHOD(Array, uasort, SPL_ARRAY_METHOD_USE_ARG) /* }}} */
/* {{{ proto int ArrayObject::uksort(callback cmp_function)
proto int ArrayIterator::uksort(callback cmp_function)
Sort the entries by key using user defined function. */
SPL_ARRAY_METHOD(Array, uksort, SPL_ARRAY_METHOD_USE_ARG) /* }}} */
/* {{{ proto int ArrayObject::natsort()
proto int ArrayIterator::natsort()
Sort the entries by values using "natural order" algorithm. */
SPL_ARRAY_METHOD(Array, natsort, SPL_ARRAY_METHOD_NO_ARG) /* }}} */
/* {{{ proto int ArrayObject::natcasesort()
proto int ArrayIterator::natcasesort()
Sort the entries by key using case insensitive "natural order" algorithm. */
SPL_ARRAY_METHOD(Array, natcasesort, SPL_ARRAY_METHOD_NO_ARG) /* }}} */
/* {{{ proto mixed|NULL ArrayIterator::current()
Return current array entry */
SPL_METHOD(Array, current)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **entry;
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
return;
}
RETVAL_ZVAL(*entry, 1, 0);
}
/* }}} */
/* {{{ proto mixed|NULL ArrayIterator::key()
Return current array key */
SPL_METHOD(Array, key)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_array_iterator_key(getThis(), return_value TSRMLS_CC);
} /* }}} */
void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
zend_hash_get_current_key_zval_ex(aht, return_value, &intern->pos);
}
/* }}} */
/* {{{ proto void ArrayIterator::next()
Move to next entry */
SPL_METHOD(Array, next)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
spl_array_next_no_verify(intern, aht TSRMLS_CC);
}
/* }}} */
/* {{{ proto bool ArrayIterator::valid()
Check whether array contains more entries */
SPL_METHOD(Array, valid)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
} else {
RETURN_BOOL(zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS);
}
}
/* }}} */
/* {{{ proto bool RecursiveArrayIterator::hasChildren()
Check whether current element has children (e.g. is an array) */
SPL_METHOD(Array, hasChildren)
{
zval *object = getThis(), **entry;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
}
if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
RETURN_FALSE;
}
RETURN_BOOL(Z_TYPE_PP(entry) == IS_ARRAY || (Z_TYPE_PP(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0));
}
/* }}} */
/* {{{ proto object RecursiveArrayIterator::getChildren()
Create a sub iterator for the current element (same class as $this) */
SPL_METHOD(Array, getChildren)
{
zval *object = getThis(), **entry, *flags;
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) {
return;
}
if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) {
return;
}
if (Z_TYPE_PP(entry) == IS_OBJECT) {
if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) {
return;
}
if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) {
RETURN_ZVAL(*entry, 1, 0);
}
}
MAKE_STD_ZVAL(flags);
ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC);
zval_ptr_dtor(&flags);
}
/* }}} */
/* {{{ proto string ArrayObject::serialize()
Serialize the object */
SPL_METHOD(Array, serialize)
{
zval *object = getThis();
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
zval members, *pmembers;
php_serialize_data_t var_hash;
smart_str buf = {0};
zval *flags;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!aht) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array");
return;
}
PHP_VAR_SERIALIZE_INIT(var_hash);
MAKE_STD_ZVAL(flags);
ZVAL_LONG(flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK));
/* storage */
smart_str_appendl(&buf, "x:", 2);
php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC);
zval_ptr_dtor(&flags);
if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) {
php_var_serialize(&buf, &intern->array, &var_hash TSRMLS_CC);
smart_str_appendc(&buf, ';');
}
/* members */
smart_str_appendl(&buf, "m:", 2);
INIT_PZVAL(&members);
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
Z_ARRVAL(members) = intern->std.properties;
Z_TYPE(members) = IS_ARRAY;
pmembers = &members;
php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */
/* done */
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (buf.c) {
RETURN_STRINGL(buf.c, buf.len, 0);
}
RETURN_NULL();
} /* }}} */
/* {{{ proto void ArrayObject::unserialize(string serialized)
* unserialize the object
*/
SPL_METHOD(Array, unserialize)
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval *pmembers, *pflags = NULL;
HashTable *aht;
long flags;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (aht->nApplyCount > 0) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pflags);
if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) {
goto outexcept;
}
var_push_dtor(&var_hash, &pflags);
--p; /* for ';' */
flags = Z_LVAL_P(pflags);
/* flags needs to be verified and we also need to verify whether the next
* thing we get is ';'. After that we require an 'm' or somethign else
* where 'm' stands for members and anything else should be an array. If
* neither 'a' or 'm' follows we have an error. */
if (*p != ';') {
goto outexcept;
}
++p;
if (*p!='m') {
if (*p!='a' && *p!='O' && *p!='C' && *p!='r') {
goto outexcept;
}
intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
zval_ptr_dtor(&intern->array);
ALLOC_INIT_ZVAL(intern->array);
if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) {
goto outexcept;
}
var_push_dtor(&var_hash, &intern->array);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
ALLOC_INIT_ZVAL(pmembers);
if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) {
zval_ptr_dtor(&pmembers);
goto outexcept;
}
var_push_dtor(&var_hash, &pmembers);
/* copy members */
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *));
zval_ptr_dtor(&pmembers);
/* done reading $serialized */
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (pflags) {
zval_ptr_dtor(&pflags);
}
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (pflags) {
zval_ptr_dtor(&pflags);
}
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
/* {{{ arginfo and function table */
ZEND_BEGIN_ARG_INFO_EX(arginfo_array___construct, 0, 0, 0)
ZEND_ARG_INFO(0, array)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, index)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2)
ZEND_ARG_INFO(0, index)
ZEND_ARG_INFO(0, newval)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0)
ZEND_ARG_INFO(0, position)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0)
ZEND_ARG_INFO(0, array)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0)
ZEND_ARG_INFO(0, iteratorClass)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0)
ZEND_ARG_INFO(0, cmp_function)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_ArrayObject[] = {
SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC)
SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC)
SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC)
SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC)
/* ArrayObject specific */
SPL_ME(Array, getIterator, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, exchangeArray, arginfo_array_exchangeArray, ZEND_ACC_PUBLIC)
SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC)
SPL_ME(Array, getIteratorClass, arginfo_array_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static const zend_function_entry spl_funcs_ArrayIterator[] = {
SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC)
SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC)
SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC)
SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC)
SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC)
SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC)
SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC)
/* ArrayIterator specific */
SPL_ME(Array, rewind, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, current, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, key, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, next, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, valid, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, seek, arginfo_array_seek, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = {
SPL_ME(Array, hasChildren, arginfo_array_void, ZEND_ACC_PUBLIC)
SPL_ME(Array, getChildren, arginfo_array_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/* {{{ PHP_MINIT_FUNCTION(spl_array) */
PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.get_gc = spl_array_get_gc;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: fdm=marker
* vim: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5285_0 |
crossvul-cpp_data_bad_2891_5 | /* Basic authentication token and access key management
*
* Copyright (C) 2004-2008 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/poison.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <linux/workqueue.h>
#include <linux/random.h>
#include <linux/err.h>
#include "internal.h"
struct kmem_cache *key_jar;
struct rb_root key_serial_tree; /* tree of keys indexed by serial */
DEFINE_SPINLOCK(key_serial_lock);
struct rb_root key_user_tree; /* tree of quota records indexed by UID */
DEFINE_SPINLOCK(key_user_lock);
unsigned int key_quota_root_maxkeys = 1000000; /* root's key count quota */
unsigned int key_quota_root_maxbytes = 25000000; /* root's key space quota */
unsigned int key_quota_maxkeys = 200; /* general key count quota */
unsigned int key_quota_maxbytes = 20000; /* general key space quota */
static LIST_HEAD(key_types_list);
static DECLARE_RWSEM(key_types_sem);
/* We serialise key instantiation and link */
DEFINE_MUTEX(key_construction_mutex);
#ifdef KEY_DEBUGGING
void __key_check(const struct key *key)
{
printk("__key_check: key %p {%08x} should be {%08x}\n",
key, key->magic, KEY_DEBUG_MAGIC);
BUG();
}
#endif
/*
* Get the key quota record for a user, allocating a new record if one doesn't
* already exist.
*/
struct key_user *key_user_lookup(kuid_t uid)
{
struct key_user *candidate = NULL, *user;
struct rb_node *parent, **p;
try_again:
parent = NULL;
p = &key_user_tree.rb_node;
spin_lock(&key_user_lock);
/* search the tree for a user record with a matching UID */
while (*p) {
parent = *p;
user = rb_entry(parent, struct key_user, node);
if (uid_lt(uid, user->uid))
p = &(*p)->rb_left;
else if (uid_gt(uid, user->uid))
p = &(*p)->rb_right;
else
goto found;
}
/* if we get here, we failed to find a match in the tree */
if (!candidate) {
/* allocate a candidate user record if we don't already have
* one */
spin_unlock(&key_user_lock);
user = NULL;
candidate = kmalloc(sizeof(struct key_user), GFP_KERNEL);
if (unlikely(!candidate))
goto out;
/* the allocation may have scheduled, so we need to repeat the
* search lest someone else added the record whilst we were
* asleep */
goto try_again;
}
/* if we get here, then the user record still hadn't appeared on the
* second pass - so we use the candidate record */
refcount_set(&candidate->usage, 1);
atomic_set(&candidate->nkeys, 0);
atomic_set(&candidate->nikeys, 0);
candidate->uid = uid;
candidate->qnkeys = 0;
candidate->qnbytes = 0;
spin_lock_init(&candidate->lock);
mutex_init(&candidate->cons_lock);
rb_link_node(&candidate->node, parent, p);
rb_insert_color(&candidate->node, &key_user_tree);
spin_unlock(&key_user_lock);
user = candidate;
goto out;
/* okay - we found a user record for this UID */
found:
refcount_inc(&user->usage);
spin_unlock(&key_user_lock);
kfree(candidate);
out:
return user;
}
/*
* Dispose of a user structure
*/
void key_user_put(struct key_user *user)
{
if (refcount_dec_and_lock(&user->usage, &key_user_lock)) {
rb_erase(&user->node, &key_user_tree);
spin_unlock(&key_user_lock);
kfree(user);
}
}
/*
* Allocate a serial number for a key. These are assigned randomly to avoid
* security issues through covert channel problems.
*/
static inline void key_alloc_serial(struct key *key)
{
struct rb_node *parent, **p;
struct key *xkey;
/* propose a random serial number and look for a hole for it in the
* serial number tree */
do {
get_random_bytes(&key->serial, sizeof(key->serial));
key->serial >>= 1; /* negative numbers are not permitted */
} while (key->serial < 3);
spin_lock(&key_serial_lock);
attempt_insertion:
parent = NULL;
p = &key_serial_tree.rb_node;
while (*p) {
parent = *p;
xkey = rb_entry(parent, struct key, serial_node);
if (key->serial < xkey->serial)
p = &(*p)->rb_left;
else if (key->serial > xkey->serial)
p = &(*p)->rb_right;
else
goto serial_exists;
}
/* we've found a suitable hole - arrange for this key to occupy it */
rb_link_node(&key->serial_node, parent, p);
rb_insert_color(&key->serial_node, &key_serial_tree);
spin_unlock(&key_serial_lock);
return;
/* we found a key with the proposed serial number - walk the tree from
* that point looking for the next unused serial number */
serial_exists:
for (;;) {
key->serial++;
if (key->serial < 3) {
key->serial = 3;
goto attempt_insertion;
}
parent = rb_next(parent);
if (!parent)
goto attempt_insertion;
xkey = rb_entry(parent, struct key, serial_node);
if (key->serial < xkey->serial)
goto attempt_insertion;
}
}
/**
* key_alloc - Allocate a key of the specified type.
* @type: The type of key to allocate.
* @desc: The key description to allow the key to be searched out.
* @uid: The owner of the new key.
* @gid: The group ID for the new key's group permissions.
* @cred: The credentials specifying UID namespace.
* @perm: The permissions mask of the new key.
* @flags: Flags specifying quota properties.
* @restrict_link: Optional link restriction for new keyrings.
*
* Allocate a key of the specified type with the attributes given. The key is
* returned in an uninstantiated state and the caller needs to instantiate the
* key before returning.
*
* The restrict_link structure (if not NULL) will be freed when the
* keyring is destroyed, so it must be dynamically allocated.
*
* The user's key count quota is updated to reflect the creation of the key and
* the user's key data quota has the default for the key type reserved. The
* instantiation function should amend this as necessary. If insufficient
* quota is available, -EDQUOT will be returned.
*
* The LSM security modules can prevent a key being created, in which case
* -EACCES will be returned.
*
* Returns a pointer to the new key if successful and an error code otherwise.
*
* Note that the caller needs to ensure the key type isn't uninstantiated.
* Internally this can be done by locking key_types_sem. Externally, this can
* be done by either never unregistering the key type, or making sure
* key_alloc() calls don't race with module unloading.
*/
struct key *key_alloc(struct key_type *type, const char *desc,
kuid_t uid, kgid_t gid, const struct cred *cred,
key_perm_t perm, unsigned long flags,
struct key_restriction *restrict_link)
{
struct key_user *user = NULL;
struct key *key;
size_t desclen, quotalen;
int ret;
key = ERR_PTR(-EINVAL);
if (!desc || !*desc)
goto error;
if (type->vet_description) {
ret = type->vet_description(desc);
if (ret < 0) {
key = ERR_PTR(ret);
goto error;
}
}
desclen = strlen(desc);
quotalen = desclen + 1 + type->def_datalen;
/* get hold of the key tracking for this user */
user = key_user_lookup(uid);
if (!user)
goto no_memory_1;
/* check that the user's quota permits allocation of another key and
* its description */
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxkeys : key_quota_maxkeys;
unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxbytes : key_quota_maxbytes;
spin_lock(&user->lock);
if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
if (user->qnkeys + 1 >= maxkeys ||
user->qnbytes + quotalen >= maxbytes ||
user->qnbytes + quotalen < user->qnbytes)
goto no_quota;
}
user->qnkeys++;
user->qnbytes += quotalen;
spin_unlock(&user->lock);
}
/* allocate and initialise the key and its description */
key = kmem_cache_zalloc(key_jar, GFP_KERNEL);
if (!key)
goto no_memory_2;
key->index_key.desc_len = desclen;
key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);
if (!key->index_key.description)
goto no_memory_3;
refcount_set(&key->usage, 1);
init_rwsem(&key->sem);
lockdep_set_class(&key->sem, &type->lock_class);
key->index_key.type = type;
key->user = user;
key->quotalen = quotalen;
key->datalen = type->def_datalen;
key->uid = uid;
key->gid = gid;
key->perm = perm;
key->restrict_link = restrict_link;
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
key->flags |= 1 << KEY_FLAG_IN_QUOTA;
if (flags & KEY_ALLOC_BUILT_IN)
key->flags |= 1 << KEY_FLAG_BUILTIN;
if (flags & KEY_ALLOC_UID_KEYRING)
key->flags |= 1 << KEY_FLAG_UID_KEYRING;
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC;
#endif
/* let the security module know about the key */
ret = security_key_alloc(key, cred, flags);
if (ret < 0)
goto security_error;
/* publish the key by giving it a serial number */
atomic_inc(&user->nkeys);
key_alloc_serial(key);
error:
return key;
security_error:
kfree(key->description);
kmem_cache_free(key_jar, key);
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
key = ERR_PTR(ret);
goto error;
no_memory_3:
kmem_cache_free(key_jar, key);
no_memory_2:
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
no_memory_1:
key = ERR_PTR(-ENOMEM);
goto error;
no_quota:
spin_unlock(&user->lock);
key_user_put(user);
key = ERR_PTR(-EDQUOT);
goto error;
}
EXPORT_SYMBOL(key_alloc);
/**
* key_payload_reserve - Adjust data quota reservation for the key's payload
* @key: The key to make the reservation for.
* @datalen: The amount of data payload the caller now wants.
*
* Adjust the amount of the owning user's key data quota that a key reserves.
* If the amount is increased, then -EDQUOT may be returned if there isn't
* enough free quota available.
*
* If successful, 0 is returned.
*/
int key_payload_reserve(struct key *key, size_t datalen)
{
int delta = (int)datalen - key->datalen;
int ret = 0;
key_check(key);
/* contemplate the quota adjustment */
if (delta != 0 && test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxbytes : key_quota_maxbytes;
spin_lock(&key->user->lock);
if (delta > 0 &&
(key->user->qnbytes + delta >= maxbytes ||
key->user->qnbytes + delta < key->user->qnbytes)) {
ret = -EDQUOT;
}
else {
key->user->qnbytes += delta;
key->quotalen += delta;
}
spin_unlock(&key->user->lock);
}
/* change the recorded data length if that didn't generate an error */
if (ret == 0)
key->datalen = datalen;
return ret;
}
EXPORT_SYMBOL(key_payload_reserve);
/*
* Instantiate a key and link it into the target keyring atomically. Must be
* called with the target keyring's semaphore writelocked. The target key's
* semaphore need not be locked as instantiation is serialised by
* key_construction_mutex.
*/
static int __key_instantiate_and_link(struct key *key,
struct key_preparsed_payload *prep,
struct key *keyring,
struct key *authkey,
struct assoc_array_edit **_edit)
{
int ret, awaken;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* instantiate the key */
ret = key->type->instantiate(key, prep);
if (ret == 0) {
/* mark the key as being instantiated */
atomic_inc(&key->user->nikeys);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
/* and link it into the destination keyring */
if (keyring) {
if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
set_bit(KEY_FLAG_KEEP, &key->flags);
__key_link(key, _edit);
}
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
if (prep->expiry != TIME_T_MAX) {
key->expiry = prep->expiry;
key_schedule_gc(prep->expiry + key_gc_delay);
}
}
}
mutex_unlock(&key_construction_mutex);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret;
}
/**
* key_instantiate_and_link - Instantiate a key and link it into the keyring.
* @key: The key to instantiate.
* @data: The data to use to instantiate the keyring.
* @datalen: The length of @data.
* @keyring: Keyring to create a link in on success (or NULL).
* @authkey: The authorisation token permitting instantiation.
*
* Instantiate a key that's in the uninstantiated state using the provided data
* and, if successful, link it in to the destination keyring if one is
* supplied.
*
* If successful, 0 is returned, the authorisation token is revoked and anyone
* waiting for the key is woken up. If the key was already instantiated,
* -EBUSY will be returned.
*/
int key_instantiate_and_link(struct key *key,
const void *data,
size_t datalen,
struct key *keyring,
struct key *authkey)
{
struct key_preparsed_payload prep;
struct assoc_array_edit *edit;
int ret;
memset(&prep, 0, sizeof(prep));
prep.data = data;
prep.datalen = datalen;
prep.quotalen = key->type->def_datalen;
prep.expiry = TIME_T_MAX;
if (key->type->preparse) {
ret = key->type->preparse(&prep);
if (ret < 0)
goto error;
}
if (keyring) {
ret = __key_link_begin(keyring, &key->index_key, &edit);
if (ret < 0)
goto error;
if (keyring->restrict_link && keyring->restrict_link->check) {
struct key_restriction *keyres = keyring->restrict_link;
ret = keyres->check(keyring, key->type, &prep.payload,
keyres->key);
if (ret < 0)
goto error_link_end;
}
}
ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit);
error_link_end:
if (keyring)
__key_link_end(keyring, &key->index_key, edit);
error:
if (key->type->preparse)
key->type->free_preparse(&prep);
return ret;
}
EXPORT_SYMBOL(key_instantiate_and_link);
/**
* key_reject_and_link - Negatively instantiate a key and link it into the keyring.
* @key: The key to instantiate.
* @timeout: The timeout on the negative key.
* @error: The error to return when the key is hit.
* @keyring: Keyring to create a link in on success (or NULL).
* @authkey: The authorisation token permitting instantiation.
*
* Negatively instantiate a key that's in the uninstantiated state and, if
* successful, set its timeout and stored error and link it in to the
* destination keyring if one is supplied. The key and any links to the key
* will be automatically garbage collected after the timeout expires.
*
* Negative keys are used to rate limit repeated request_key() calls by causing
* them to return the stored error code (typically ENOKEY) until the negative
* key expires.
*
* If successful, 0 is returned, the authorisation token is revoked and anyone
* waiting for the key is woken up. If the key was already instantiated,
* -EBUSY will be returned.
*/
int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
key->reject_error = -error;
smp_wmb();
set_bit(KEY_FLAG_NEGATIVE, &key->flags);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring && link_ret == 0)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
EXPORT_SYMBOL(key_reject_and_link);
/**
* key_put - Discard a reference to a key.
* @key: The key to discard a reference from.
*
* Discard a reference to a key, and when all the references are gone, we
* schedule the cleanup task to come and pull it out of the tree in process
* context at some later time.
*/
void key_put(struct key *key)
{
if (key) {
key_check(key);
if (refcount_dec_and_test(&key->usage))
schedule_work(&key_gc_work);
}
}
EXPORT_SYMBOL(key_put);
/*
* Find a key by its serial number.
*/
struct key *key_lookup(key_serial_t id)
{
struct rb_node *n;
struct key *key;
spin_lock(&key_serial_lock);
/* search the tree for the specified key */
n = key_serial_tree.rb_node;
while (n) {
key = rb_entry(n, struct key, serial_node);
if (id < key->serial)
n = n->rb_left;
else if (id > key->serial)
n = n->rb_right;
else
goto found;
}
not_found:
key = ERR_PTR(-ENOKEY);
goto error;
found:
/* A key is allowed to be looked up only if someone still owns a
* reference to it - otherwise it's awaiting the gc.
*/
if (!refcount_inc_not_zero(&key->usage))
goto not_found;
error:
spin_unlock(&key_serial_lock);
return key;
}
/*
* Find and lock the specified key type against removal.
*
* We return with the sem read-locked if successful. If the type wasn't
* available -ENOKEY is returned instead.
*/
struct key_type *key_type_lookup(const char *type)
{
struct key_type *ktype;
down_read(&key_types_sem);
/* look up the key type to see if it's one of the registered kernel
* types */
list_for_each_entry(ktype, &key_types_list, link) {
if (strcmp(ktype->name, type) == 0)
goto found_kernel_type;
}
up_read(&key_types_sem);
ktype = ERR_PTR(-ENOKEY);
found_kernel_type:
return ktype;
}
void key_set_timeout(struct key *key, unsigned timeout)
{
struct timespec now;
time_t expiry = 0;
/* make the changes with the locks held to prevent races */
down_write(&key->sem);
if (timeout > 0) {
now = current_kernel_time();
expiry = now.tv_sec + timeout;
}
key->expiry = expiry;
key_schedule_gc(key->expiry + key_gc_delay);
up_write(&key->sem);
}
EXPORT_SYMBOL_GPL(key_set_timeout);
/*
* Unlock a key type locked by key_type_lookup().
*/
void key_type_put(struct key_type *ktype)
{
up_read(&key_types_sem);
}
/*
* Attempt to update an existing key.
*
* The key is given to us with an incremented refcount that we need to discard
* if we get an error.
*/
static inline key_ref_t __key_update(key_ref_t key_ref,
struct key_preparsed_payload *prep)
{
struct key *key = key_ref_to_ptr(key_ref);
int ret;
/* need write permission on the key to update it */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
goto error;
ret = -EEXIST;
if (!key->type->update)
goto error;
down_write(&key->sem);
ret = key->type->update(key, prep);
if (ret == 0)
/* updating a negative key instantiates it */
clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
up_write(&key->sem);
if (ret < 0)
goto error;
out:
return key_ref;
error:
key_put(key);
key_ref = ERR_PTR(ret);
goto out;
}
/**
* key_create_or_update - Update or create and instantiate a key.
* @keyring_ref: A pointer to the destination keyring with possession flag.
* @type: The type of key.
* @description: The searchable description for the key.
* @payload: The data to use to instantiate or update the key.
* @plen: The length of @payload.
* @perm: The permissions mask for a new key.
* @flags: The quota flags for a new key.
*
* Search the destination keyring for a key of the same description and if one
* is found, update it, otherwise create and instantiate a new one and create a
* link to it from that keyring.
*
* If perm is KEY_PERM_UNDEF then an appropriate key permissions mask will be
* concocted.
*
* Returns a pointer to the new key if successful, -ENODEV if the key type
* wasn't available, -ENOTDIR if the keyring wasn't a keyring, -EACCES if the
* caller isn't permitted to modify the keyring or the LSM did not permit
* creation of the key.
*
* On success, the possession flag from the keyring ref will be tacked on to
* the key ref before it is returned.
*/
key_ref_t key_create_or_update(key_ref_t keyring_ref,
const char *type,
const char *description,
const void *payload,
size_t plen,
key_perm_t perm,
unsigned long flags)
{
struct keyring_index_key index_key = {
.description = description,
};
struct key_preparsed_payload prep;
struct assoc_array_edit *edit;
const struct cred *cred = current_cred();
struct key *keyring, *key = NULL;
key_ref_t key_ref;
int ret;
struct key_restriction *restrict_link = NULL;
/* look up the key type to see if it's one of the registered kernel
* types */
index_key.type = key_type_lookup(type);
if (IS_ERR(index_key.type)) {
key_ref = ERR_PTR(-ENODEV);
goto error;
}
key_ref = ERR_PTR(-EINVAL);
if (!index_key.type->instantiate ||
(!index_key.description && !index_key.type->preparse))
goto error_put_type;
keyring = key_ref_to_ptr(keyring_ref);
key_check(keyring);
key_ref = ERR_PTR(-EPERM);
if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
restrict_link = keyring->restrict_link;
key_ref = ERR_PTR(-ENOTDIR);
if (keyring->type != &key_type_keyring)
goto error_put_type;
memset(&prep, 0, sizeof(prep));
prep.data = payload;
prep.datalen = plen;
prep.quotalen = index_key.type->def_datalen;
prep.expiry = TIME_T_MAX;
if (index_key.type->preparse) {
ret = index_key.type->preparse(&prep);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_free_prep;
}
if (!index_key.description)
index_key.description = prep.description;
key_ref = ERR_PTR(-EINVAL);
if (!index_key.description)
goto error_free_prep;
}
index_key.desc_len = strlen(index_key.description);
ret = __key_link_begin(keyring, &index_key, &edit);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_free_prep;
}
if (restrict_link && restrict_link->check) {
ret = restrict_link->check(keyring, index_key.type,
&prep.payload, restrict_link->key);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_link_end;
}
}
/* if we're going to allocate a new key, we're going to have
* to modify the keyring */
ret = key_permission(keyring_ref, KEY_NEED_WRITE);
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error_link_end;
}
/* if it's possible to update this type of key, search for an existing
* key of the same type and description in the destination keyring and
* update that instead if possible
*/
if (index_key.type->update) {
key_ref = find_key_to_update(keyring_ref, &index_key);
if (key_ref)
goto found_matching_key;
}
/* if the client doesn't provide, decide on the permissions we want */
if (perm == KEY_PERM_UNDEF) {
perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
perm |= KEY_USR_VIEW;
if (index_key.type->read)
perm |= KEY_POS_READ;
if (index_key.type == &key_type_keyring ||
index_key.type->update)
perm |= KEY_POS_WRITE;
}
/* allocate a new key */
key = key_alloc(index_key.type, index_key.description,
cred->fsuid, cred->fsgid, cred, perm, flags, NULL);
if (IS_ERR(key)) {
key_ref = ERR_CAST(key);
goto error_link_end;
}
/* instantiate it and link it into the target keyring */
ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);
if (ret < 0) {
key_put(key);
key_ref = ERR_PTR(ret);
goto error_link_end;
}
key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
error_link_end:
__key_link_end(keyring, &index_key, edit);
error_free_prep:
if (index_key.type->preparse)
index_key.type->free_preparse(&prep);
error_put_type:
key_type_put(index_key.type);
error:
return key_ref;
found_matching_key:
/* we found a matching key, so we're going to try to update it
* - we can drop the locks first as we have the key pinned
*/
__key_link_end(keyring, &index_key, edit);
key_ref = __key_update(key_ref, &prep);
goto error_free_prep;
}
EXPORT_SYMBOL(key_create_or_update);
/**
* key_update - Update a key's contents.
* @key_ref: The pointer (plus possession flag) to the key.
* @payload: The data to be used to update the key.
* @plen: The length of @payload.
*
* Attempt to update the contents of a key with the given payload data. The
* caller must be granted Write permission on the key. Negative keys can be
* instantiated by this method.
*
* Returns 0 on success, -EACCES if not permitted and -EOPNOTSUPP if the key
* type does not support updating. The key type may return other errors.
*/
int key_update(key_ref_t key_ref, const void *payload, size_t plen)
{
struct key_preparsed_payload prep;
struct key *key = key_ref_to_ptr(key_ref);
int ret;
key_check(key);
/* the key must be writable */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
return ret;
/* attempt to update it if supported */
if (!key->type->update)
return -EOPNOTSUPP;
memset(&prep, 0, sizeof(prep));
prep.data = payload;
prep.datalen = plen;
prep.quotalen = key->type->def_datalen;
prep.expiry = TIME_T_MAX;
if (key->type->preparse) {
ret = key->type->preparse(&prep);
if (ret < 0)
goto error;
}
down_write(&key->sem);
ret = key->type->update(key, &prep);
if (ret == 0)
/* updating a negative key instantiates it */
clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
up_write(&key->sem);
error:
if (key->type->preparse)
key->type->free_preparse(&prep);
return ret;
}
EXPORT_SYMBOL(key_update);
/**
* key_revoke - Revoke a key.
* @key: The key to be revoked.
*
* Mark a key as being revoked and ask the type to free up its resources. The
* revocation timeout is set and the key and all its links will be
* automatically garbage collected after key_gc_delay amount of time if they
* are not manually dealt with first.
*/
void key_revoke(struct key *key)
{
struct timespec now;
time_t time;
key_check(key);
/* make sure no one's trying to change or use the key when we mark it
* - we tell lockdep that we might nest because we might be revoking an
* authorisation key whilst holding the sem on a key we've just
* instantiated
*/
down_write_nested(&key->sem, 1);
if (!test_and_set_bit(KEY_FLAG_REVOKED, &key->flags) &&
key->type->revoke)
key->type->revoke(key);
/* set the death time to no more than the expiry time */
now = current_kernel_time();
time = now.tv_sec;
if (key->revoked_at == 0 || key->revoked_at > time) {
key->revoked_at = time;
key_schedule_gc(key->revoked_at + key_gc_delay);
}
up_write(&key->sem);
}
EXPORT_SYMBOL(key_revoke);
/**
* key_invalidate - Invalidate a key.
* @key: The key to be invalidated.
*
* Mark a key as being invalidated and have it cleaned up immediately. The key
* is ignored by all searches and other operations from this point.
*/
void key_invalidate(struct key *key)
{
kenter("%d", key_serial(key));
key_check(key);
if (!test_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
down_write_nested(&key->sem, 1);
if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags))
key_schedule_gc_links();
up_write(&key->sem);
}
}
EXPORT_SYMBOL(key_invalidate);
/**
* generic_key_instantiate - Simple instantiation of a key from preparsed data
* @key: The key to be instantiated
* @prep: The preparsed data to load.
*
* Instantiate a key from preparsed data. We assume we can just copy the data
* in directly and clear the old pointers.
*
* This can be pointed to directly by the key type instantiate op pointer.
*/
int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
{
int ret;
pr_devel("==>%s()\n", __func__);
ret = key_payload_reserve(key, prep->quotalen);
if (ret == 0) {
rcu_assign_keypointer(key, prep->payload.data[0]);
key->payload.data[1] = prep->payload.data[1];
key->payload.data[2] = prep->payload.data[2];
key->payload.data[3] = prep->payload.data[3];
prep->payload.data[0] = NULL;
prep->payload.data[1] = NULL;
prep->payload.data[2] = NULL;
prep->payload.data[3] = NULL;
}
pr_devel("<==%s() = %d\n", __func__, ret);
return ret;
}
EXPORT_SYMBOL(generic_key_instantiate);
/**
* register_key_type - Register a type of key.
* @ktype: The new key type.
*
* Register a new key type.
*
* Returns 0 on success or -EEXIST if a type of this name already exists.
*/
int register_key_type(struct key_type *ktype)
{
struct key_type *p;
int ret;
memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
ret = -EEXIST;
down_write(&key_types_sem);
/* disallow key types with the same name */
list_for_each_entry(p, &key_types_list, link) {
if (strcmp(p->name, ktype->name) == 0)
goto out;
}
/* store the type */
list_add(&ktype->link, &key_types_list);
pr_notice("Key type %s registered\n", ktype->name);
ret = 0;
out:
up_write(&key_types_sem);
return ret;
}
EXPORT_SYMBOL(register_key_type);
/**
* unregister_key_type - Unregister a type of key.
* @ktype: The key type.
*
* Unregister a key type and mark all the extant keys of this type as dead.
* Those keys of this type are then destroyed to get rid of their payloads and
* they and their links will be garbage collected as soon as possible.
*/
void unregister_key_type(struct key_type *ktype)
{
down_write(&key_types_sem);
list_del_init(&ktype->link);
downgrade_write(&key_types_sem);
key_gc_keytype(ktype);
pr_notice("Key type %s unregistered\n", ktype->name);
up_read(&key_types_sem);
}
EXPORT_SYMBOL(unregister_key_type);
/*
* Initialise the key management state.
*/
void __init key_init(void)
{
/* allocate a slab in which we can store keys */
key_jar = kmem_cache_create("key_jar", sizeof(struct key),
0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
/* add the special key types */
list_add_tail(&key_type_keyring.link, &key_types_list);
list_add_tail(&key_type_dead.link, &key_types_list);
list_add_tail(&key_type_user.link, &key_types_list);
list_add_tail(&key_type_logon.link, &key_types_list);
/* record the root user tracking */
rb_link_node(&root_key_user.node,
NULL,
&key_user_tree.rb_node);
rb_insert_color(&root_key_user.node,
&key_user_tree);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_5 |
crossvul-cpp_data_bad_3365_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/pixel.h"
#include "magick/property.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(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 IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% 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 ReadRLEImage method is:
%
% Image *ReadRLEImage(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 Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
pixel_info_length;
ssize_t
count,
offset,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 22)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum(
ReadBlobLSBShort(image)));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
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);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,pixel_info_length);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
if ((offset < 0) ||
(offset+((size_t) operand*number_planes) > pixel_info_length))
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
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;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
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;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE 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 RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RLE");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Utah Run length encoded image");
entry->module=ConstantString("RLE");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3365_1 |
crossvul-cpp_data_good_5533_1 | #include "redis.h"
#include <sys/uio.h>
void *dupClientReplyValue(void *o) {
incrRefCount((robj*)o);
return o;
}
int listMatchObjects(void *a, void *b) {
return equalStringObjects(a,b);
}
redisClient *createClient(int fd) {
redisClient *c = zmalloc(sizeof(redisClient));
c->bufpos = 0;
anetNonBlock(NULL,fd);
anetTcpNoDelay(NULL,fd);
if (!c) return NULL;
if (aeCreateFileEvent(server.el,fd,AE_READABLE,
readQueryFromClient, c) == AE_ERR)
{
close(fd);
zfree(c);
return NULL;
}
selectDb(c,0);
c->fd = fd;
c->querybuf = sdsempty();
c->reqtype = 0;
c->argc = 0;
c->argv = NULL;
c->multibulklen = 0;
c->bulklen = -1;
c->sentlen = 0;
c->flags = 0;
c->lastinteraction = time(NULL);
c->authenticated = 0;
c->replstate = REDIS_REPL_NONE;
c->reply = listCreate();
listSetFreeMethod(c->reply,decrRefCount);
listSetDupMethod(c->reply,dupClientReplyValue);
c->bpop.keys = NULL;
c->bpop.count = 0;
c->bpop.timeout = 0;
c->bpop.target = NULL;
c->io_keys = listCreate();
c->watched_keys = listCreate();
listSetFreeMethod(c->io_keys,decrRefCount);
c->pubsub_channels = dictCreate(&setDictType,NULL);
c->pubsub_patterns = listCreate();
listSetFreeMethod(c->pubsub_patterns,decrRefCount);
listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
listAddNodeTail(server.clients,c);
initClientMultiState(c);
return c;
}
/* Set the event loop to listen for write events on the client's socket.
* Typically gets called every time a reply is built. */
int _installWriteEvent(redisClient *c) {
/* When CLOSE_AFTER_REPLY is set, no more replies may be added! */
redisAssert(!(c->flags & REDIS_CLOSE_AFTER_REPLY));
if (c->fd <= 0) return REDIS_ERR;
if (c->bufpos == 0 && listLength(c->reply) == 0 &&
(c->replstate == REDIS_REPL_NONE ||
c->replstate == REDIS_REPL_ONLINE) &&
aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
sendReplyToClient, c) == AE_ERR) return REDIS_ERR;
return REDIS_OK;
}
/* Create a duplicate of the last object in the reply list when
* it is not exclusively owned by the reply list. */
robj *dupLastObjectIfNeeded(list *reply) {
robj *new, *cur;
listNode *ln;
redisAssert(listLength(reply) > 0);
ln = listLast(reply);
cur = listNodeValue(ln);
if (cur->refcount > 1) {
new = dupStringObject(cur);
decrRefCount(cur);
listNodeValue(ln) = new;
}
return listNodeValue(ln);
}
int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
size_t available = sizeof(c->buf)-c->bufpos;
/* If there already are entries in the reply list, we cannot
* add anything more to the static buffer. */
if (listLength(c->reply) > 0) return REDIS_ERR;
/* Check that the buffer has enough space available for this string. */
if (len > available) return REDIS_ERR;
memcpy(c->buf+c->bufpos,s,len);
c->bufpos+=len;
return REDIS_OK;
}
void _addReplyObjectToList(redisClient *c, robj *o) {
robj *tail;
if (listLength(c->reply) == 0) {
incrRefCount(o);
listAddNodeTail(c->reply,o);
} else {
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
if (tail->ptr != NULL &&
sdslen(tail->ptr)+sdslen(o->ptr) <= REDIS_REPLY_CHUNK_BYTES)
{
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr));
} else {
incrRefCount(o);
listAddNodeTail(c->reply,o);
}
}
}
/* This method takes responsibility over the sds. When it is no longer
* needed it will be free'd, otherwise it ends up in a robj. */
void _addReplySdsToList(redisClient *c, sds s) {
robj *tail;
if (listLength(c->reply) == 0) {
listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
} else {
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
if (tail->ptr != NULL &&
sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES)
{
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
sdsfree(s);
} else {
listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
}
}
}
void _addReplyStringToList(redisClient *c, char *s, size_t len) {
robj *tail;
if (listLength(c->reply) == 0) {
listAddNodeTail(c->reply,createStringObject(s,len));
} else {
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
if (tail->ptr != NULL &&
sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES)
{
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,s,len);
} else {
listAddNodeTail(c->reply,createStringObject(s,len));
}
}
}
void addReply(redisClient *c, robj *obj) {
if (_installWriteEvent(c) != REDIS_OK) return;
redisAssert(!server.ds_enabled || obj->storage == REDIS_VM_MEMORY);
/* This is an important place where we can avoid copy-on-write
* when there is a saving child running, avoiding touching the
* refcount field of the object if it's not needed.
*
* If the encoding is RAW and there is room in the static buffer
* we'll be able to send the object to the client without
* messing with its page. */
if (obj->encoding == REDIS_ENCODING_RAW) {
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
_addReplyObjectToList(c,obj);
} else {
/* FIXME: convert the long into string and use _addReplyToBuffer()
* instead of calling getDecodedObject. As this place in the
* code is too performance critical. */
obj = getDecodedObject(obj);
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
_addReplyObjectToList(c,obj);
decrRefCount(obj);
}
}
void addReplySds(redisClient *c, sds s) {
if (_installWriteEvent(c) != REDIS_OK) {
/* The caller expects the sds to be free'd. */
sdsfree(s);
return;
}
if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) {
sdsfree(s);
} else {
/* This method free's the sds when it is no longer needed. */
_addReplySdsToList(c,s);
}
}
void addReplyString(redisClient *c, char *s, size_t len) {
if (_installWriteEvent(c) != REDIS_OK) return;
if (_addReplyToBuffer(c,s,len) != REDIS_OK)
_addReplyStringToList(c,s,len);
}
void _addReplyError(redisClient *c, char *s, size_t len) {
addReplyString(c,"-ERR ",5);
addReplyString(c,s,len);
addReplyString(c,"\r\n",2);
}
void addReplyError(redisClient *c, char *err) {
_addReplyError(c,err,strlen(err));
}
void addReplyErrorFormat(redisClient *c, const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
sds s = sdscatvprintf(sdsempty(),fmt,ap);
va_end(ap);
_addReplyError(c,s,sdslen(s));
sdsfree(s);
}
void _addReplyStatus(redisClient *c, char *s, size_t len) {
addReplyString(c,"+",1);
addReplyString(c,s,len);
addReplyString(c,"\r\n",2);
}
void addReplyStatus(redisClient *c, char *status) {
_addReplyStatus(c,status,strlen(status));
}
void addReplyStatusFormat(redisClient *c, const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
sds s = sdscatvprintf(sdsempty(),fmt,ap);
va_end(ap);
_addReplyStatus(c,s,sdslen(s));
sdsfree(s);
}
/* Adds an empty object to the reply list that will contain the multi bulk
* length, which is not known when this function is called. */
void *addDeferredMultiBulkLength(redisClient *c) {
/* Note that we install the write event here even if the object is not
* ready to be sent, since we are sure that before returning to the
* event loop setDeferredMultiBulkLength() will be called. */
if (_installWriteEvent(c) != REDIS_OK) return NULL;
listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL));
return listLast(c->reply);
}
/* Populate the length object and try glueing it to the next chunk. */
void setDeferredMultiBulkLength(redisClient *c, void *node, long length) {
listNode *ln = (listNode*)node;
robj *len, *next;
/* Abort when *node is NULL (see addDeferredMultiBulkLength). */
if (node == NULL) return;
len = listNodeValue(ln);
len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
if (ln->next != NULL) {
next = listNodeValue(ln->next);
/* Only glue when the next node is non-NULL (an sds in this case) */
if (next->ptr != NULL) {
len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
listDelNode(c->reply,ln->next);
}
}
}
/* Add a duble as a bulk reply */
void addReplyDouble(redisClient *c, double d) {
char dbuf[128], sbuf[128];
int dlen, slen;
dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d);
slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf);
addReplyString(c,sbuf,slen);
}
/* Add a long long as integer reply or bulk len / multi bulk count.
* Basically this is used to output <prefix><long long><crlf>. */
void _addReplyLongLong(redisClient *c, long long ll, char prefix) {
char buf[128];
int len;
buf[0] = prefix;
len = ll2string(buf+1,sizeof(buf)-1,ll);
buf[len+1] = '\r';
buf[len+2] = '\n';
addReplyString(c,buf,len+3);
}
void addReplyLongLong(redisClient *c, long long ll) {
_addReplyLongLong(c,ll,':');
}
void addReplyMultiBulkLen(redisClient *c, long length) {
_addReplyLongLong(c,length,'*');
}
/* Create the length prefix of a bulk reply, example: $2234 */
void addReplyBulkLen(redisClient *c, robj *obj) {
size_t len;
if (obj->encoding == REDIS_ENCODING_RAW) {
len = sdslen(obj->ptr);
} else {
long n = (long)obj->ptr;
/* Compute how many bytes will take this integer as a radix 10 string */
len = 1;
if (n < 0) {
len++;
n = -n;
}
while((n = n/10) != 0) {
len++;
}
}
_addReplyLongLong(c,len,'$');
}
/* Add a Redis Object as a bulk reply */
void addReplyBulk(redisClient *c, robj *obj) {
addReplyBulkLen(c,obj);
addReply(c,obj);
addReply(c,shared.crlf);
}
/* Add a C buffer as bulk reply */
void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) {
_addReplyLongLong(c,len,'$');
addReplyString(c,p,len);
addReply(c,shared.crlf);
}
/* Add a C nul term string as bulk reply */
void addReplyBulkCString(redisClient *c, char *s) {
if (s == NULL) {
addReply(c,shared.nullbulk);
} else {
addReplyBulkCBuffer(c,s,strlen(s));
}
}
/* Add a long long as a bulk reply */
void addReplyBulkLongLong(redisClient *c, long long ll) {
char buf[64];
int len;
len = ll2string(buf,64,ll);
addReplyBulkCBuffer(c,buf,len);
}
static void acceptCommonHandler(int fd) {
redisClient *c;
if ((c = createClient(fd)) == NULL) {
redisLog(REDIS_WARNING,"Error allocating resoures for the client");
close(fd); /* May be already closed, just ingore errors */
return;
}
/* If maxclient directive is set and this is one client more... close the
* connection. Note that we create the client instead to check before
* for this condition, since now the socket is already set in nonblocking
* mode and we can send an error for free using the Kernel I/O */
if (server.maxclients && listLength(server.clients) > server.maxclients) {
char *err = "-ERR max number of clients reached\r\n";
/* That's a best effort error message, don't check write errors */
if (write(c->fd,err,strlen(err)) == -1) {
/* Nothing to do, Just to avoid the warning... */
}
freeClient(c);
return;
}
server.stat_numconnections++;
}
void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
int cport, cfd;
char cip[128];
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
REDIS_NOTUSED(privdata);
cfd = anetTcpAccept(server.neterr, fd, cip, &cport);
if (cfd == AE_ERR) {
redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
return;
}
redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
acceptCommonHandler(cfd);
}
void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
int cfd;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
REDIS_NOTUSED(privdata);
cfd = anetUnixAccept(server.neterr, fd);
if (cfd == AE_ERR) {
redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
return;
}
redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket);
acceptCommonHandler(cfd);
}
static void freeClientArgv(redisClient *c) {
int j;
for (j = 0; j < c->argc; j++)
decrRefCount(c->argv[j]);
c->argc = 0;
}
void freeClient(redisClient *c) {
listNode *ln;
/* Note that if the client we are freeing is blocked into a blocking
* call, we have to set querybuf to NULL *before* to call
* unblockClientWaitingData() to avoid processInputBuffer() will get
* called. Also it is important to remove the file events after
* this, because this call adds the READABLE event. */
sdsfree(c->querybuf);
c->querybuf = NULL;
if (c->flags & REDIS_BLOCKED)
unblockClientWaitingData(c);
/* UNWATCH all the keys */
unwatchAllKeys(c);
listRelease(c->watched_keys);
/* Unsubscribe from all the pubsub channels */
pubsubUnsubscribeAllChannels(c,0);
pubsubUnsubscribeAllPatterns(c,0);
dictRelease(c->pubsub_channels);
listRelease(c->pubsub_patterns);
/* Obvious cleanup */
aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
listRelease(c->reply);
freeClientArgv(c);
close(c->fd);
/* Remove from the list of clients */
ln = listSearchKey(server.clients,c);
redisAssert(ln != NULL);
listDelNode(server.clients,ln);
/* Remove from the list of clients waiting for swapped keys, or ready
* to be restarted, but not yet woken up again. */
if (c->flags & REDIS_IO_WAIT) {
redisAssert(server.ds_enabled);
if (listLength(c->io_keys) == 0) {
ln = listSearchKey(server.io_ready_clients,c);
/* When this client is waiting to be woken up (REDIS_IO_WAIT),
* it should be present in the list io_ready_clients */
redisAssert(ln != NULL);
listDelNode(server.io_ready_clients,ln);
} else {
while (listLength(c->io_keys)) {
ln = listFirst(c->io_keys);
dontWaitForSwappedKey(c,ln->value);
}
}
server.cache_blocked_clients--;
}
listRelease(c->io_keys);
/* Master/slave cleanup.
* Case 1: we lost the connection with a slave. */
if (c->flags & REDIS_SLAVE) {
if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
close(c->repldbfd);
list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
ln = listSearchKey(l,c);
redisAssert(ln != NULL);
listDelNode(l,ln);
}
/* Case 2: we lost the connection with the master. */
if (c->flags & REDIS_MASTER) {
server.master = NULL;
/* FIXME */
server.replstate = REDIS_REPL_CONNECT;
/* Since we lost the connection with the master, we should also
* close the connection with all our slaves if we have any, so
* when we'll resync with the master the other slaves will sync again
* with us as well. Note that also when the slave is not connected
* to the master it will keep refusing connections by other slaves. */
while (listLength(server.slaves)) {
ln = listFirst(server.slaves);
freeClient((redisClient*)ln->value);
}
}
/* Release memory */
zfree(c->argv);
freeClientMultiState(c);
zfree(c);
}
void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
redisClient *c = privdata;
int nwritten = 0, totwritten = 0, objlen;
robj *o;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
/* Use writev() if we have enough buffers to send */
if (!server.glueoutputbuf &&
listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
!(c->flags & REDIS_MASTER))
{
sendReplyToClientWritev(el, fd, privdata, mask);
return;
}
while(c->bufpos > 0 || listLength(c->reply)) {
if (c->bufpos > 0) {
if (c->flags & REDIS_MASTER) {
/* Don't reply to a master */
nwritten = c->bufpos - c->sentlen;
} else {
nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen);
if (nwritten <= 0) break;
}
c->sentlen += nwritten;
totwritten += nwritten;
/* If the buffer was sent, set bufpos to zero to continue with
* the remainder of the reply. */
if (c->sentlen == c->bufpos) {
c->bufpos = 0;
c->sentlen = 0;
}
} else {
o = listNodeValue(listFirst(c->reply));
objlen = sdslen(o->ptr);
if (objlen == 0) {
listDelNode(c->reply,listFirst(c->reply));
continue;
}
if (c->flags & REDIS_MASTER) {
/* Don't reply to a master */
nwritten = objlen - c->sentlen;
} else {
nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen);
if (nwritten <= 0) break;
}
c->sentlen += nwritten;
totwritten += nwritten;
/* If we fully sent the object on head go to the next one */
if (c->sentlen == objlen) {
listDelNode(c->reply,listFirst(c->reply));
c->sentlen = 0;
}
}
/* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
* bytes, in a single threaded server it's a good idea to serve
* other clients as well, even if a very large request comes from
* super fast link that is always able to accept data (in real world
* scenario think about 'KEYS *' against the loopback interfae) */
if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
}
if (nwritten == -1) {
if (errno == EAGAIN) {
nwritten = 0;
} else {
redisLog(REDIS_VERBOSE,
"Error writing to client: %s", strerror(errno));
freeClient(c);
return;
}
}
if (totwritten > 0) c->lastinteraction = time(NULL);
if (listLength(c->reply) == 0) {
c->sentlen = 0;
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
/* Close connection after entire reply has been sent. */
if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c);
}
}
void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
{
redisClient *c = privdata;
int nwritten = 0, totwritten = 0, objlen, willwrite;
robj *o;
struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
int offset, ion = 0;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
listNode *node;
while (listLength(c->reply)) {
offset = c->sentlen;
ion = 0;
willwrite = 0;
/* fill-in the iov[] array */
for(node = listFirst(c->reply); node; node = listNextNode(node)) {
o = listNodeValue(node);
objlen = sdslen(o->ptr);
if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
break;
if(ion == REDIS_WRITEV_IOVEC_COUNT)
break; /* no more iovecs */
iov[ion].iov_base = ((char*)o->ptr) + offset;
iov[ion].iov_len = objlen - offset;
willwrite += objlen - offset;
offset = 0; /* just for the first item */
ion++;
}
if(willwrite == 0)
break;
/* write all collected blocks at once */
if((nwritten = writev(fd, iov, ion)) < 0) {
if (errno != EAGAIN) {
redisLog(REDIS_VERBOSE,
"Error writing to client: %s", strerror(errno));
freeClient(c);
return;
}
break;
}
totwritten += nwritten;
offset = c->sentlen;
/* remove written robjs from c->reply */
while (nwritten && listLength(c->reply)) {
o = listNodeValue(listFirst(c->reply));
objlen = sdslen(o->ptr);
if(nwritten >= objlen - offset) {
listDelNode(c->reply, listFirst(c->reply));
nwritten -= objlen - offset;
c->sentlen = 0;
} else {
/* partial write */
c->sentlen += nwritten;
break;
}
offset = 0;
}
}
if (totwritten > 0)
c->lastinteraction = time(NULL);
if (listLength(c->reply) == 0) {
c->sentlen = 0;
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
}
}
/* resetClient prepare the client to process the next command */
void resetClient(redisClient *c) {
freeClientArgv(c);
c->reqtype = 0;
c->multibulklen = 0;
c->bulklen = -1;
}
void closeTimedoutClients(void) {
redisClient *c;
listNode *ln;
time_t now = time(NULL);
listIter li;
listRewind(server.clients,&li);
while ((ln = listNext(&li)) != NULL) {
c = listNodeValue(ln);
if (server.maxidletime &&
!(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
!(c->flags & REDIS_MASTER) && /* no timeout for masters */
!(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */
dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
listLength(c->pubsub_patterns) == 0 &&
(now - c->lastinteraction > server.maxidletime))
{
redisLog(REDIS_VERBOSE,"Closing idle client");
freeClient(c);
} else if (c->flags & REDIS_BLOCKED) {
if (c->bpop.timeout != 0 && c->bpop.timeout < now) {
addReply(c,shared.nullmultibulk);
unblockClientWaitingData(c);
}
}
}
}
int processInlineBuffer(redisClient *c) {
char *newline = strstr(c->querybuf,"\r\n");
int argc, j;
sds *argv;
size_t querylen;
/* Nothing to do without a \r\n */
if (newline == NULL)
return REDIS_ERR;
/* Split the input buffer up to the \r\n */
querylen = newline-(c->querybuf);
argv = sdssplitlen(c->querybuf,querylen," ",1,&argc);
/* Leave data after the first line of the query in the buffer */
c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
/* Setup argv array on client structure */
if (c->argv) zfree(c->argv);
c->argv = zmalloc(sizeof(robj*)*argc);
/* Create redis objects for all arguments. */
for (c->argc = 0, j = 0; j < argc; j++) {
if (sdslen(argv[j])) {
c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
c->argc++;
} else {
sdsfree(argv[j]);
}
}
zfree(argv);
return REDIS_OK;
}
/* Helper function. Trims query buffer to make the function that processes
* multi bulk requests idempotent. */
static void setProtocolError(redisClient *c, int pos) {
c->flags |= REDIS_CLOSE_AFTER_REPLY;
c->querybuf = sdsrange(c->querybuf,pos,-1);
}
int processMultibulkBuffer(redisClient *c) {
char *newline = NULL;
char *eptr;
int pos = 0, tolerr;
long bulklen;
if (c->multibulklen == 0) {
/* The client should have been reset */
redisAssert(c->argc == 0);
/* Multi bulk length cannot be read without a \r\n */
newline = strstr(c->querybuf,"\r\n");
if (newline == NULL)
return REDIS_ERR;
/* We know for sure there is a whole line since newline != NULL,
* so go ahead and find out the multi bulk length. */
redisAssert(c->querybuf[0] == '*');
c->multibulklen = strtol(c->querybuf+1,&eptr,10);
pos = (newline-c->querybuf)+2;
if (c->multibulklen <= 0) {
c->querybuf = sdsrange(c->querybuf,pos,-1);
return REDIS_OK;
} else if (c->multibulklen > 1024*1024) {
addReplyError(c,"Protocol error: invalid multibulk length");
setProtocolError(c,pos);
return REDIS_ERR;
}
/* Setup argv array on client structure */
if (c->argv) zfree(c->argv);
c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
/* Search new newline */
newline = strstr(c->querybuf+pos,"\r\n");
}
redisAssert(c->multibulklen > 0);
while(c->multibulklen) {
/* Read bulk length if unknown */
if (c->bulklen == -1) {
newline = strstr(c->querybuf+pos,"\r\n");
if (newline != NULL) {
if (c->querybuf[pos] != '$') {
addReplyErrorFormat(c,
"Protocol error: expected '$', got '%c'",
c->querybuf[pos]);
setProtocolError(c,pos);
return REDIS_ERR;
}
bulklen = strtol(c->querybuf+pos+1,&eptr,10);
tolerr = (eptr[0] != '\r');
if (tolerr || bulklen == LONG_MIN || bulklen == LONG_MAX ||
bulklen < 0 || bulklen > 512*1024*1024)
{
addReplyError(c,"Protocol error: invalid bulk length");
setProtocolError(c,pos);
return REDIS_ERR;
}
pos += eptr-(c->querybuf+pos)+2;
c->bulklen = bulklen;
} else {
/* No newline in current buffer, so wait for more data */
break;
}
}
/* Read bulk argument */
if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) {
/* Not enough data (+2 == trailing \r\n) */
break;
} else {
c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen);
pos += c->bulklen+2;
c->bulklen = -1;
c->multibulklen--;
}
}
/* Trim to pos */
c->querybuf = sdsrange(c->querybuf,pos,-1);
/* We're done when c->multibulk == 0 */
if (c->multibulklen == 0) {
return REDIS_OK;
}
return REDIS_ERR;
}
void processInputBuffer(redisClient *c) {
/* Keep processing while there is something in the input buffer */
while(sdslen(c->querybuf)) {
/* Immediately abort if the client is in the middle of something. */
if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
/* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
* written to the client. Make sure to not let the reply grow after
* this flag has been set (i.e. don't process more commands). */
if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[0] == '*') {
c->reqtype = REDIS_REQ_MULTIBULK;
} else {
c->reqtype = REDIS_REQ_INLINE;
}
}
if (c->reqtype == REDIS_REQ_INLINE) {
if (processInlineBuffer(c) != REDIS_OK) break;
} else if (c->reqtype == REDIS_REQ_MULTIBULK) {
if (processMultibulkBuffer(c) != REDIS_OK) break;
} else {
redisPanic("Unknown request type");
}
/* Multibulk processing could see a <= 0 length. */
if (c->argc == 0) {
resetClient(c);
} else {
/* Only reset the client when the command was executed. */
if (processCommand(c) == REDIS_OK)
resetClient(c);
}
}
}
void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
redisClient *c = (redisClient*) privdata;
char buf[REDIS_IOBUF_LEN];
int nread;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
nread = read(fd, buf, REDIS_IOBUF_LEN);
if (nread == -1) {
if (errno == EAGAIN) {
nread = 0;
} else {
redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
freeClient(c);
return;
}
} else if (nread == 0) {
redisLog(REDIS_VERBOSE, "Client closed connection");
freeClient(c);
return;
}
if (nread) {
c->querybuf = sdscatlen(c->querybuf,buf,nread);
c->lastinteraction = time(NULL);
} else {
return;
}
processInputBuffer(c);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5533_1 |
crossvul-cpp_data_bad_5844_7 | /*
* File: datagram.c
*
* Datagram (ISI) Phonet sockets
*
* Copyright (C) 2008 Nokia Corporation.
*
* Authors: Sakari Ailus <sakari.ailus@nokia.com>
* Rémi Denis-Courmont
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <asm/ioctls.h>
#include <net/sock.h>
#include <linux/phonet.h>
#include <linux/export.h>
#include <net/phonet/phonet.h>
static int pn_backlog_rcv(struct sock *sk, struct sk_buff *skb);
/* associated socket ceases to exist */
static void pn_sock_close(struct sock *sk, long timeout)
{
sk_common_release(sk);
}
static int pn_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
struct sk_buff *skb;
int answ;
switch (cmd) {
case SIOCINQ:
lock_sock(sk);
skb = skb_peek(&sk->sk_receive_queue);
answ = skb ? skb->len : 0;
release_sock(sk);
return put_user(answ, (int __user *)arg);
case SIOCPNADDRESOURCE:
case SIOCPNDELRESOURCE: {
u32 res;
if (get_user(res, (u32 __user *)arg))
return -EFAULT;
if (res >= 256)
return -EINVAL;
if (cmd == SIOCPNADDRESOURCE)
return pn_sock_bind_res(sk, res);
else
return pn_sock_unbind_res(sk, res);
}
}
return -ENOIOCTLCMD;
}
/* Destroy socket. All references are gone. */
static void pn_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_receive_queue);
}
static int pn_init(struct sock *sk)
{
sk->sk_destruct = pn_destruct;
return 0;
}
static int pn_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len)
{
struct sockaddr_pn *target;
struct sk_buff *skb;
int err;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_NOSIGNAL|
MSG_CMSG_COMPAT))
return -EOPNOTSUPP;
if (msg->msg_name == NULL)
return -EDESTADDRREQ;
if (msg->msg_namelen < sizeof(struct sockaddr_pn))
return -EINVAL;
target = (struct sockaddr_pn *)msg->msg_name;
if (target->spn_family != AF_PHONET)
return -EAFNOSUPPORT;
skb = sock_alloc_send_skb(sk, MAX_PHONET_HEADER + len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
return err;
skb_reserve(skb, MAX_PHONET_HEADER);
err = memcpy_fromiovec((void *)skb_put(skb, len), msg->msg_iov, len);
if (err < 0) {
kfree_skb(skb);
return err;
}
/*
* Fill in the Phonet header and
* finally pass the packet forwards.
*/
err = pn_skb_send(sk, skb, target);
/* If ok, return len. */
return (err >= 0) ? len : err;
}
static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct sk_buff *skb = NULL;
struct sockaddr_pn sa;
int rval = -EOPNOTSUPP;
int copylen;
if (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|
MSG_CMSG_COMPAT))
goto out_nofree;
if (addr_len)
*addr_len = sizeof(sa);
skb = skb_recv_datagram(sk, flags, noblock, &rval);
if (skb == NULL)
goto out_nofree;
pn_skb_get_src_sockaddr(skb, &sa);
copylen = skb->len;
if (len < copylen) {
msg->msg_flags |= MSG_TRUNC;
copylen = len;
}
rval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);
if (rval) {
rval = -EFAULT;
goto out;
}
rval = (flags & MSG_TRUNC) ? skb->len : copylen;
if (msg->msg_name != NULL)
memcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));
out:
skb_free_datagram(sk, skb);
out_nofree:
return rval;
}
/* Queue an skb for a sock. */
static int pn_backlog_rcv(struct sock *sk, struct sk_buff *skb)
{
int err = sock_queue_rcv_skb(sk, skb);
if (err < 0)
kfree_skb(skb);
return err ? NET_RX_DROP : NET_RX_SUCCESS;
}
/* Module registration */
static struct proto pn_proto = {
.close = pn_sock_close,
.ioctl = pn_ioctl,
.init = pn_init,
.sendmsg = pn_sendmsg,
.recvmsg = pn_recvmsg,
.backlog_rcv = pn_backlog_rcv,
.hash = pn_sock_hash,
.unhash = pn_sock_unhash,
.get_port = pn_sock_get_port,
.obj_size = sizeof(struct pn_sock),
.owner = THIS_MODULE,
.name = "PHONET",
};
static struct phonet_protocol pn_dgram_proto = {
.ops = &phonet_dgram_ops,
.prot = &pn_proto,
.sock_type = SOCK_DGRAM,
};
int __init isi_register(void)
{
return phonet_proto_register(PN_PROTO_PHONET, &pn_dgram_proto);
}
void __exit isi_unregister(void)
{
phonet_proto_unregister(PN_PROTO_PHONET, &pn_dgram_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_7 |
crossvul-cpp_data_bad_5794_0 |
/*
* Local APIC virtualization
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright (C) 2007 Novell
* Copyright (C) 2007 Intel
* Copyright 2009 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Dor Laor <dor.laor@qumranet.com>
* Gregory Haskins <ghaskins@novell.com>
* Yaozu (Eddie) Dong <eddie.dong@intel.com>
*
* Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*/
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/hrtimer.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/math64.h>
#include <linux/slab.h>
#include <asm/processor.h>
#include <asm/msr.h>
#include <asm/page.h>
#include <asm/current.h>
#include <asm/apicdef.h>
#include <linux/atomic.h>
#include <linux/jump_label.h>
#include "kvm_cache_regs.h"
#include "irq.h"
#include "trace.h"
#include "x86.h"
#include "cpuid.h"
#ifndef CONFIG_X86_64
#define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
#else
#define mod_64(x, y) ((x) % (y))
#endif
#define PRId64 "d"
#define PRIx64 "llx"
#define PRIu64 "u"
#define PRIo64 "o"
#define APIC_BUS_CYCLE_NS 1
/* #define apic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) */
#define apic_debug(fmt, arg...)
#define APIC_LVT_NUM 6
/* 14 is the version for Xeon and Pentium 8.4.8*/
#define APIC_VERSION (0x14UL | ((APIC_LVT_NUM - 1) << 16))
#define LAPIC_MMIO_LENGTH (1 << 12)
/* followed define is not in apicdef.h */
#define APIC_SHORT_MASK 0xc0000
#define APIC_DEST_NOSHORT 0x0
#define APIC_DEST_MASK 0x800
#define MAX_APIC_VECTOR 256
#define APIC_VECTORS_PER_REG 32
#define VEC_POS(v) ((v) & (32 - 1))
#define REG_POS(v) (((v) >> 5) << 4)
static unsigned int min_timer_period_us = 500;
module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
static inline void apic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
{
*((u32 *) (apic->regs + reg_off)) = val;
}
static inline int apic_test_vector(int vec, void *bitmap)
{
return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
{
struct kvm_lapic *apic = vcpu->arch.apic;
return apic_test_vector(vector, apic->regs + APIC_ISR) ||
apic_test_vector(vector, apic->regs + APIC_IRR);
}
static inline void apic_set_vector(int vec, void *bitmap)
{
set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
static inline void apic_clear_vector(int vec, void *bitmap)
{
clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
static inline int __apic_test_and_set_vector(int vec, void *bitmap)
{
return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
{
return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}
struct static_key_deferred apic_hw_disabled __read_mostly;
struct static_key_deferred apic_sw_disabled __read_mostly;
static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
{
if ((kvm_apic_get_reg(apic, APIC_SPIV) ^ val) & APIC_SPIV_APIC_ENABLED) {
if (val & APIC_SPIV_APIC_ENABLED)
static_key_slow_dec_deferred(&apic_sw_disabled);
else
static_key_slow_inc(&apic_sw_disabled.key);
}
apic_set_reg(apic, APIC_SPIV, val);
}
static inline int apic_enabled(struct kvm_lapic *apic)
{
return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
}
#define LVT_MASK \
(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
#define LINT_MASK \
(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
static inline int kvm_apic_id(struct kvm_lapic *apic)
{
return (kvm_apic_get_reg(apic, APIC_ID) >> 24) & 0xff;
}
static void recalculate_apic_map(struct kvm *kvm)
{
struct kvm_apic_map *new, *old = NULL;
struct kvm_vcpu *vcpu;
int i;
new = kzalloc(sizeof(struct kvm_apic_map), GFP_KERNEL);
mutex_lock(&kvm->arch.apic_map_lock);
if (!new)
goto out;
new->ldr_bits = 8;
/* flat mode is default */
new->cid_shift = 8;
new->cid_mask = 0;
new->lid_mask = 0xff;
kvm_for_each_vcpu(i, vcpu, kvm) {
struct kvm_lapic *apic = vcpu->arch.apic;
u16 cid, lid;
u32 ldr;
if (!kvm_apic_present(vcpu))
continue;
/*
* All APICs have to be configured in the same mode by an OS.
* We take advatage of this while building logical id loockup
* table. After reset APICs are in xapic/flat mode, so if we
* find apic with different setting we assume this is the mode
* OS wants all apics to be in; build lookup table accordingly.
*/
if (apic_x2apic_mode(apic)) {
new->ldr_bits = 32;
new->cid_shift = 16;
new->cid_mask = new->lid_mask = 0xffff;
} else if (kvm_apic_sw_enabled(apic) &&
!new->cid_mask /* flat mode */ &&
kvm_apic_get_reg(apic, APIC_DFR) == APIC_DFR_CLUSTER) {
new->cid_shift = 4;
new->cid_mask = 0xf;
new->lid_mask = 0xf;
}
new->phys_map[kvm_apic_id(apic)] = apic;
ldr = kvm_apic_get_reg(apic, APIC_LDR);
cid = apic_cluster_id(new, ldr);
lid = apic_logical_id(new, ldr);
if (lid)
new->logical_map[cid][ffs(lid) - 1] = apic;
}
out:
old = rcu_dereference_protected(kvm->arch.apic_map,
lockdep_is_held(&kvm->arch.apic_map_lock));
rcu_assign_pointer(kvm->arch.apic_map, new);
mutex_unlock(&kvm->arch.apic_map_lock);
if (old)
kfree_rcu(old, rcu);
kvm_vcpu_request_scan_ioapic(kvm);
}
static inline void kvm_apic_set_id(struct kvm_lapic *apic, u8 id)
{
apic_set_reg(apic, APIC_ID, id << 24);
recalculate_apic_map(apic->vcpu->kvm);
}
static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
{
apic_set_reg(apic, APIC_LDR, id);
recalculate_apic_map(apic->vcpu->kvm);
}
static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
{
return !(kvm_apic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
}
static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
{
return kvm_apic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
}
static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
{
return ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) == APIC_LVT_TIMER_ONESHOT);
}
static inline int apic_lvtt_period(struct kvm_lapic *apic)
{
return ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) == APIC_LVT_TIMER_PERIODIC);
}
static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
{
return ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) ==
APIC_LVT_TIMER_TSCDEADLINE);
}
static inline int apic_lvt_nmi_mode(u32 lvt_val)
{
return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
}
void kvm_apic_set_version(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
struct kvm_cpuid_entry2 *feat;
u32 v = APIC_VERSION;
if (!kvm_vcpu_has_lapic(vcpu))
return;
feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))))
v |= APIC_LVR_DIRECTED_EOI;
apic_set_reg(apic, APIC_LVR, v);
}
static const unsigned int apic_lvt_mask[APIC_LVT_NUM] = {
LVT_MASK , /* part LVTT mask, timer mode mask added at runtime */
LVT_MASK | APIC_MODE_MASK, /* LVTTHMR */
LVT_MASK | APIC_MODE_MASK, /* LVTPC */
LINT_MASK, LINT_MASK, /* LVT0-1 */
LVT_MASK /* LVTERR */
};
static int find_highest_vector(void *bitmap)
{
int vec;
u32 *reg;
for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
vec >= 0; vec -= APIC_VECTORS_PER_REG) {
reg = bitmap + REG_POS(vec);
if (*reg)
return fls(*reg) - 1 + vec;
}
return -1;
}
static u8 count_vectors(void *bitmap)
{
int vec;
u32 *reg;
u8 count = 0;
for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
reg = bitmap + REG_POS(vec);
count += hweight32(*reg);
}
return count;
}
void kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir)
{
u32 i, pir_val;
struct kvm_lapic *apic = vcpu->arch.apic;
for (i = 0; i <= 7; i++) {
pir_val = xchg(&pir[i], 0);
if (pir_val)
*((u32 *)(apic->regs + APIC_IRR + i * 0x10)) |= pir_val;
}
}
EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
static inline void apic_set_irr(int vec, struct kvm_lapic *apic)
{
apic->irr_pending = true;
apic_set_vector(vec, apic->regs + APIC_IRR);
}
static inline int apic_search_irr(struct kvm_lapic *apic)
{
return find_highest_vector(apic->regs + APIC_IRR);
}
static inline int apic_find_highest_irr(struct kvm_lapic *apic)
{
int result;
/*
* Note that irr_pending is just a hint. It will be always
* true with virtual interrupt delivery enabled.
*/
if (!apic->irr_pending)
return -1;
kvm_x86_ops->sync_pir_to_irr(apic->vcpu);
result = apic_search_irr(apic);
ASSERT(result == -1 || result >= 16);
return result;
}
static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
{
apic->irr_pending = false;
apic_clear_vector(vec, apic->regs + APIC_IRR);
if (apic_search_irr(apic) != -1)
apic->irr_pending = true;
}
static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
{
if (!__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
++apic->isr_count;
BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
/*
* ISR (in service register) bit is set when injecting an interrupt.
* The highest vector is injected. Thus the latest bit set matches
* the highest bit in ISR.
*/
apic->highest_isr_cache = vec;
}
static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
{
if (__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
--apic->isr_count;
BUG_ON(apic->isr_count < 0);
apic->highest_isr_cache = -1;
}
int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
{
int highest_irr;
/* This may race with setting of irr in __apic_accept_irq() and
* value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
* will cause vmexit immediately and the value will be recalculated
* on the next vmentry.
*/
if (!kvm_vcpu_has_lapic(vcpu))
return 0;
highest_irr = apic_find_highest_irr(vcpu->arch.apic);
return highest_irr;
}
static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
int vector, int level, int trig_mode,
unsigned long *dest_map);
int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
unsigned long *dest_map)
{
struct kvm_lapic *apic = vcpu->arch.apic;
return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
irq->level, irq->trig_mode, dest_map);
}
static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
{
return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
sizeof(val));
}
static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
{
return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
sizeof(*val));
}
static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
{
return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
}
static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
{
u8 val;
if (pv_eoi_get_user(vcpu, &val) < 0)
apic_debug("Can't read EOI MSR value: 0x%llx\n",
(unsigned long long)vcpi->arch.pv_eoi.msr_val);
return val & 0x1;
}
static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
{
if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
apic_debug("Can't set EOI MSR value: 0x%llx\n",
(unsigned long long)vcpi->arch.pv_eoi.msr_val);
return;
}
__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
}
static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
{
if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
apic_debug("Can't clear EOI MSR value: 0x%llx\n",
(unsigned long long)vcpi->arch.pv_eoi.msr_val);
return;
}
__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
}
static inline int apic_find_highest_isr(struct kvm_lapic *apic)
{
int result;
/* Note that isr_count is always 1 with vid enabled */
if (!apic->isr_count)
return -1;
if (likely(apic->highest_isr_cache != -1))
return apic->highest_isr_cache;
result = find_highest_vector(apic->regs + APIC_ISR);
ASSERT(result == -1 || result >= 16);
return result;
}
void kvm_apic_update_tmr(struct kvm_vcpu *vcpu, u32 *tmr)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int i;
for (i = 0; i < 8; i++)
apic_set_reg(apic, APIC_TMR + 0x10 * i, tmr[i]);
}
static void apic_update_ppr(struct kvm_lapic *apic)
{
u32 tpr, isrv, ppr, old_ppr;
int isr;
old_ppr = kvm_apic_get_reg(apic, APIC_PROCPRI);
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI);
isr = apic_find_highest_isr(apic);
isrv = (isr != -1) ? isr : 0;
if ((tpr & 0xf0) >= (isrv & 0xf0))
ppr = tpr & 0xff;
else
ppr = isrv & 0xf0;
apic_debug("vlapic %p, ppr 0x%x, isr 0x%x, isrv 0x%x",
apic, ppr, isr, isrv);
if (old_ppr != ppr) {
apic_set_reg(apic, APIC_PROCPRI, ppr);
if (ppr < old_ppr)
kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
}
}
static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
{
apic_set_reg(apic, APIC_TASKPRI, tpr);
apic_update_ppr(apic);
}
int kvm_apic_match_physical_addr(struct kvm_lapic *apic, u16 dest)
{
return dest == 0xff || kvm_apic_id(apic) == dest;
}
int kvm_apic_match_logical_addr(struct kvm_lapic *apic, u8 mda)
{
int result = 0;
u32 logical_id;
if (apic_x2apic_mode(apic)) {
logical_id = kvm_apic_get_reg(apic, APIC_LDR);
return logical_id & mda;
}
logical_id = GET_APIC_LOGICAL_ID(kvm_apic_get_reg(apic, APIC_LDR));
switch (kvm_apic_get_reg(apic, APIC_DFR)) {
case APIC_DFR_FLAT:
if (logical_id & mda)
result = 1;
break;
case APIC_DFR_CLUSTER:
if (((logical_id >> 4) == (mda >> 0x4))
&& (logical_id & mda & 0xf))
result = 1;
break;
default:
apic_debug("Bad DFR vcpu %d: %08x\n",
apic->vcpu->vcpu_id, kvm_apic_get_reg(apic, APIC_DFR));
break;
}
return result;
}
int kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
int short_hand, int dest, int dest_mode)
{
int result = 0;
struct kvm_lapic *target = vcpu->arch.apic;
apic_debug("target %p, source %p, dest 0x%x, "
"dest_mode 0x%x, short_hand 0x%x\n",
target, source, dest, dest_mode, short_hand);
ASSERT(target);
switch (short_hand) {
case APIC_DEST_NOSHORT:
if (dest_mode == 0)
/* Physical mode. */
result = kvm_apic_match_physical_addr(target, dest);
else
/* Logical mode. */
result = kvm_apic_match_logical_addr(target, dest);
break;
case APIC_DEST_SELF:
result = (target == source);
break;
case APIC_DEST_ALLINC:
result = 1;
break;
case APIC_DEST_ALLBUT:
result = (target != source);
break;
default:
apic_debug("kvm: apic: Bad dest shorthand value %x\n",
short_hand);
break;
}
return result;
}
bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
struct kvm_lapic_irq *irq, int *r, unsigned long *dest_map)
{
struct kvm_apic_map *map;
unsigned long bitmap = 1;
struct kvm_lapic **dst;
int i;
bool ret = false;
*r = -1;
if (irq->shorthand == APIC_DEST_SELF) {
*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
return true;
}
if (irq->shorthand)
return false;
rcu_read_lock();
map = rcu_dereference(kvm->arch.apic_map);
if (!map)
goto out;
if (irq->dest_mode == 0) { /* physical mode */
if (irq->delivery_mode == APIC_DM_LOWEST ||
irq->dest_id == 0xff)
goto out;
dst = &map->phys_map[irq->dest_id & 0xff];
} else {
u32 mda = irq->dest_id << (32 - map->ldr_bits);
dst = map->logical_map[apic_cluster_id(map, mda)];
bitmap = apic_logical_id(map, mda);
if (irq->delivery_mode == APIC_DM_LOWEST) {
int l = -1;
for_each_set_bit(i, &bitmap, 16) {
if (!dst[i])
continue;
if (l < 0)
l = i;
else if (kvm_apic_compare_prio(dst[i]->vcpu, dst[l]->vcpu) < 0)
l = i;
}
bitmap = (l >= 0) ? 1 << l : 0;
}
}
for_each_set_bit(i, &bitmap, 16) {
if (!dst[i])
continue;
if (*r < 0)
*r = 0;
*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
}
ret = true;
out:
rcu_read_unlock();
return ret;
}
/*
* Add a pending IRQ into lapic.
* Return 1 if successfully added and 0 if discarded.
*/
static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
int vector, int level, int trig_mode,
unsigned long *dest_map)
{
int result = 0;
struct kvm_vcpu *vcpu = apic->vcpu;
switch (delivery_mode) {
case APIC_DM_LOWEST:
vcpu->arch.apic_arb_prio++;
case APIC_DM_FIXED:
/* FIXME add logic for vcpu on reset */
if (unlikely(!apic_enabled(apic)))
break;
result = 1;
if (dest_map)
__set_bit(vcpu->vcpu_id, dest_map);
if (kvm_x86_ops->deliver_posted_interrupt)
kvm_x86_ops->deliver_posted_interrupt(vcpu, vector);
else {
apic_set_irr(vector, apic);
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
}
trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
trig_mode, vector, false);
break;
case APIC_DM_REMRD:
result = 1;
vcpu->arch.pv.pv_unhalted = 1;
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
break;
case APIC_DM_SMI:
apic_debug("Ignoring guest SMI\n");
break;
case APIC_DM_NMI:
result = 1;
kvm_inject_nmi(vcpu);
kvm_vcpu_kick(vcpu);
break;
case APIC_DM_INIT:
if (!trig_mode || level) {
result = 1;
/* assumes that there are only KVM_APIC_INIT/SIPI */
apic->pending_events = (1UL << KVM_APIC_INIT);
/* make sure pending_events is visible before sending
* the request */
smp_wmb();
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
} else {
apic_debug("Ignoring de-assert INIT to vcpu %d\n",
vcpu->vcpu_id);
}
break;
case APIC_DM_STARTUP:
apic_debug("SIPI to vcpu %d vector 0x%02x\n",
vcpu->vcpu_id, vector);
result = 1;
apic->sipi_vector = vector;
/* make sure sipi_vector is visible for the receiver */
smp_wmb();
set_bit(KVM_APIC_SIPI, &apic->pending_events);
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_vcpu_kick(vcpu);
break;
case APIC_DM_EXTINT:
/*
* Should only be called by kvm_apic_local_deliver() with LVT0,
* before NMI watchdog was enabled. Already handled by
* kvm_apic_accept_pic_intr().
*/
break;
default:
printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
delivery_mode);
break;
}
return result;
}
int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
{
return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
}
static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
{
if (!(kvm_apic_get_reg(apic, APIC_SPIV) & APIC_SPIV_DIRECTED_EOI) &&
kvm_ioapic_handles_vector(apic->vcpu->kvm, vector)) {
int trigger_mode;
if (apic_test_vector(vector, apic->regs + APIC_TMR))
trigger_mode = IOAPIC_LEVEL_TRIG;
else
trigger_mode = IOAPIC_EDGE_TRIG;
kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
}
}
static int apic_set_eoi(struct kvm_lapic *apic)
{
int vector = apic_find_highest_isr(apic);
trace_kvm_eoi(apic, vector);
/*
* Not every write EOI will has corresponding ISR,
* one example is when Kernel check timer on setup_IO_APIC
*/
if (vector == -1)
return vector;
apic_clear_isr(vector, apic);
apic_update_ppr(apic);
kvm_ioapic_send_eoi(apic, vector);
kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
return vector;
}
/*
* this interface assumes a trap-like exit, which has already finished
* desired side effect including vISR and vPPR update.
*/
void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
{
struct kvm_lapic *apic = vcpu->arch.apic;
trace_kvm_eoi(apic, vector);
kvm_ioapic_send_eoi(apic, vector);
kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
}
EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
static void apic_send_ipi(struct kvm_lapic *apic)
{
u32 icr_low = kvm_apic_get_reg(apic, APIC_ICR);
u32 icr_high = kvm_apic_get_reg(apic, APIC_ICR2);
struct kvm_lapic_irq irq;
irq.vector = icr_low & APIC_VECTOR_MASK;
irq.delivery_mode = icr_low & APIC_MODE_MASK;
irq.dest_mode = icr_low & APIC_DEST_MASK;
irq.level = icr_low & APIC_INT_ASSERT;
irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
irq.shorthand = icr_low & APIC_SHORT_MASK;
if (apic_x2apic_mode(apic))
irq.dest_id = icr_high;
else
irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
trace_kvm_apic_ipi(icr_low, irq.dest_id);
apic_debug("icr_high 0x%x, icr_low 0x%x, "
"short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
"dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x\n",
icr_high, icr_low, irq.shorthand, irq.dest_id,
irq.trig_mode, irq.level, irq.dest_mode, irq.delivery_mode,
irq.vector);
kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
}
static u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0 ||
apic->lapic_timer.period == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
static void __report_tpr_access(struct kvm_lapic *apic, bool write)
{
struct kvm_vcpu *vcpu = apic->vcpu;
struct kvm_run *run = vcpu->run;
kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
run->tpr_access.rip = kvm_rip_read(vcpu);
run->tpr_access.is_write = write;
}
static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
{
if (apic->vcpu->arch.tpr_access_reporting)
__report_tpr_access(apic, write);
}
static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
{
u32 val = 0;
if (offset >= LAPIC_MMIO_LENGTH)
return 0;
switch (offset) {
case APIC_ID:
if (apic_x2apic_mode(apic))
val = kvm_apic_id(apic);
else
val = kvm_apic_id(apic) << 24;
break;
case APIC_ARBPRI:
apic_debug("Access APIC ARBPRI register which is for P6\n");
break;
case APIC_TMCCT: /* Timer CCR */
if (apic_lvtt_tscdeadline(apic))
return 0;
val = apic_get_tmcct(apic);
break;
case APIC_PROCPRI:
apic_update_ppr(apic);
val = kvm_apic_get_reg(apic, offset);
break;
case APIC_TASKPRI:
report_tpr_access(apic, false);
/* fall thru */
default:
val = kvm_apic_get_reg(apic, offset);
break;
}
return val;
}
static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_lapic, dev);
}
static int apic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
void *data)
{
unsigned char alignment = offset & 0xf;
u32 result;
/* this bitmask has a bit cleared for each reserved register */
static const u64 rmask = 0x43ff01ffffffe70cULL;
if ((alignment + len) > 4) {
apic_debug("KVM_APIC_READ: alignment error %x %d\n",
offset, len);
return 1;
}
if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
apic_debug("KVM_APIC_READ: read reserved register %x\n",
offset);
return 1;
}
result = __apic_read(apic, offset & ~0xf);
trace_kvm_apic_read(offset, result);
switch (len) {
case 1:
case 2:
case 4:
memcpy(data, (char *)&result + alignment, len);
break;
default:
printk(KERN_ERR "Local APIC read with len = %x, "
"should be 1,2, or 4 instead\n", len);
break;
}
return 0;
}
static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
{
return kvm_apic_hw_enabled(apic) &&
addr >= apic->base_address &&
addr < apic->base_address + LAPIC_MMIO_LENGTH;
}
static int apic_mmio_read(struct kvm_io_device *this,
gpa_t address, int len, void *data)
{
struct kvm_lapic *apic = to_lapic(this);
u32 offset = address - apic->base_address;
if (!apic_mmio_in_range(apic, address))
return -EOPNOTSUPP;
apic_reg_read(apic, offset, len, data);
return 0;
}
static void update_divide_count(struct kvm_lapic *apic)
{
u32 tmp1, tmp2, tdcr;
tdcr = kvm_apic_get_reg(apic, APIC_TDCR);
tmp1 = tdcr & 0xf;
tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
apic->divide_count = 0x1 << (tmp2 & 0x7);
apic_debug("timer divide count is 0x%x\n",
apic->divide_count);
}
static void start_apic_timer(struct kvm_lapic *apic)
{
ktime_t now;
atomic_set(&apic->lapic_timer.pending, 0);
if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
/* lapic timer in oneshot or periodic mode */
now = apic->lapic_timer.timer.base->get_time();
apic->lapic_timer.period = (u64)kvm_apic_get_reg(apic, APIC_TMICT)
* APIC_BUS_CYCLE_NS * apic->divide_count;
if (!apic->lapic_timer.period)
return;
/*
* Do not allow the guest to program periodic timers with small
* interval, since the hrtimers are not throttled by the host
* scheduler.
*/
if (apic_lvtt_period(apic)) {
s64 min_period = min_timer_period_us * 1000LL;
if (apic->lapic_timer.period < min_period) {
pr_info_ratelimited(
"kvm: vcpu %i: requested %lld ns "
"lapic timer period limited to %lld ns\n",
apic->vcpu->vcpu_id,
apic->lapic_timer.period, min_period);
apic->lapic_timer.period = min_period;
}
}
hrtimer_start(&apic->lapic_timer.timer,
ktime_add_ns(now, apic->lapic_timer.period),
HRTIMER_MODE_ABS);
apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
PRIx64 ", "
"timer initial count 0x%x, period %lldns, "
"expire @ 0x%016" PRIx64 ".\n", __func__,
APIC_BUS_CYCLE_NS, ktime_to_ns(now),
kvm_apic_get_reg(apic, APIC_TMICT),
apic->lapic_timer.period,
ktime_to_ns(ktime_add_ns(now,
apic->lapic_timer.period)));
} else if (apic_lvtt_tscdeadline(apic)) {
/* lapic timer in tsc deadline mode */
u64 guest_tsc, tscdeadline = apic->lapic_timer.tscdeadline;
u64 ns = 0;
struct kvm_vcpu *vcpu = apic->vcpu;
unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
unsigned long flags;
if (unlikely(!tscdeadline || !this_tsc_khz))
return;
local_irq_save(flags);
now = apic->lapic_timer.timer.base->get_time();
guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu, native_read_tsc());
if (likely(tscdeadline > guest_tsc)) {
ns = (tscdeadline - guest_tsc) * 1000000ULL;
do_div(ns, this_tsc_khz);
}
hrtimer_start(&apic->lapic_timer.timer,
ktime_add_ns(now, ns), HRTIMER_MODE_ABS);
local_irq_restore(flags);
}
}
static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
{
int nmi_wd_enabled = apic_lvt_nmi_mode(kvm_apic_get_reg(apic, APIC_LVT0));
if (apic_lvt_nmi_mode(lvt0_val)) {
if (!nmi_wd_enabled) {
apic_debug("Receive NMI setting on APIC_LVT0 "
"for cpu %d\n", apic->vcpu->vcpu_id);
apic->vcpu->kvm->arch.vapics_in_nmi_mode++;
}
} else if (nmi_wd_enabled)
apic->vcpu->kvm->arch.vapics_in_nmi_mode--;
}
static int apic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
{
int ret = 0;
trace_kvm_apic_write(reg, val);
switch (reg) {
case APIC_ID: /* Local APIC ID */
if (!apic_x2apic_mode(apic))
kvm_apic_set_id(apic, val >> 24);
else
ret = 1;
break;
case APIC_TASKPRI:
report_tpr_access(apic, true);
apic_set_tpr(apic, val & 0xff);
break;
case APIC_EOI:
apic_set_eoi(apic);
break;
case APIC_LDR:
if (!apic_x2apic_mode(apic))
kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
else
ret = 1;
break;
case APIC_DFR:
if (!apic_x2apic_mode(apic)) {
apic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
recalculate_apic_map(apic->vcpu->kvm);
} else
ret = 1;
break;
case APIC_SPIV: {
u32 mask = 0x3ff;
if (kvm_apic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
mask |= APIC_SPIV_DIRECTED_EOI;
apic_set_spiv(apic, val & mask);
if (!(val & APIC_SPIV_APIC_ENABLED)) {
int i;
u32 lvt_val;
for (i = 0; i < APIC_LVT_NUM; i++) {
lvt_val = kvm_apic_get_reg(apic,
APIC_LVTT + 0x10 * i);
apic_set_reg(apic, APIC_LVTT + 0x10 * i,
lvt_val | APIC_LVT_MASKED);
}
atomic_set(&apic->lapic_timer.pending, 0);
}
break;
}
case APIC_ICR:
/* No delay here, so we always clear the pending bit */
apic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
apic_send_ipi(apic);
break;
case APIC_ICR2:
if (!apic_x2apic_mode(apic))
val &= 0xff000000;
apic_set_reg(apic, APIC_ICR2, val);
break;
case APIC_LVT0:
apic_manage_nmi_watchdog(apic, val);
case APIC_LVTTHMR:
case APIC_LVTPC:
case APIC_LVT1:
case APIC_LVTERR:
/* TODO: Check vector */
if (!kvm_apic_sw_enabled(apic))
val |= APIC_LVT_MASKED;
val &= apic_lvt_mask[(reg - APIC_LVTT) >> 4];
apic_set_reg(apic, reg, val);
break;
case APIC_LVTT:
if ((kvm_apic_get_reg(apic, APIC_LVTT) &
apic->lapic_timer.timer_mode_mask) !=
(val & apic->lapic_timer.timer_mode_mask))
hrtimer_cancel(&apic->lapic_timer.timer);
if (!kvm_apic_sw_enabled(apic))
val |= APIC_LVT_MASKED;
val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
apic_set_reg(apic, APIC_LVTT, val);
break;
case APIC_TMICT:
if (apic_lvtt_tscdeadline(apic))
break;
hrtimer_cancel(&apic->lapic_timer.timer);
apic_set_reg(apic, APIC_TMICT, val);
start_apic_timer(apic);
break;
case APIC_TDCR:
if (val & 4)
apic_debug("KVM_WRITE:TDCR %x\n", val);
apic_set_reg(apic, APIC_TDCR, val);
update_divide_count(apic);
break;
case APIC_ESR:
if (apic_x2apic_mode(apic) && val != 0) {
apic_debug("KVM_WRITE:ESR not zero %x\n", val);
ret = 1;
}
break;
case APIC_SELF_IPI:
if (apic_x2apic_mode(apic)) {
apic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
} else
ret = 1;
break;
default:
ret = 1;
break;
}
if (ret)
apic_debug("Local APIC Write to read-only register %x\n", reg);
return ret;
}
static int apic_mmio_write(struct kvm_io_device *this,
gpa_t address, int len, const void *data)
{
struct kvm_lapic *apic = to_lapic(this);
unsigned int offset = address - apic->base_address;
u32 val;
if (!apic_mmio_in_range(apic, address))
return -EOPNOTSUPP;
/*
* APIC register must be aligned on 128-bits boundary.
* 32/64/128 bits registers must be accessed thru 32 bits.
* Refer SDM 8.4.1
*/
if (len != 4 || (offset & 0xf)) {
/* Don't shout loud, $infamous_os would cause only noise. */
apic_debug("apic write: bad size=%d %lx\n", len, (long)address);
return 0;
}
val = *(u32*)data;
/* too common printing */
if (offset != APIC_EOI)
apic_debug("%s: offset 0x%x with length 0x%x, and value is "
"0x%x\n", __func__, offset, len, val);
apic_reg_write(apic, offset & 0xff0, val);
return 0;
}
void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
{
if (kvm_vcpu_has_lapic(vcpu))
apic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
}
EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
/* emulate APIC access in a trap manner */
void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
{
u32 val = 0;
/* hw has done the conditional check and inst decode */
offset &= 0xff0;
apic_reg_read(vcpu->arch.apic, offset, 4, &val);
/* TODO: optimize to just emulate side effect w/o one more write */
apic_reg_write(vcpu->arch.apic, offset, val);
}
EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
void kvm_free_lapic(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!vcpu->arch.apic)
return;
hrtimer_cancel(&apic->lapic_timer.timer);
if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
static_key_slow_dec_deferred(&apic_hw_disabled);
if (!(kvm_apic_get_reg(apic, APIC_SPIV) & APIC_SPIV_APIC_ENABLED))
static_key_slow_dec_deferred(&apic_sw_disabled);
if (apic->regs)
free_page((unsigned long)apic->regs);
kfree(apic);
}
/*
*----------------------------------------------------------------------
* LAPIC interface
*----------------------------------------------------------------------
*/
u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu) || apic_lvtt_oneshot(apic) ||
apic_lvtt_period(apic))
return 0;
return apic->lapic_timer.tscdeadline;
}
void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu) || apic_lvtt_oneshot(apic) ||
apic_lvtt_period(apic))
return;
hrtimer_cancel(&apic->lapic_timer.timer);
apic->lapic_timer.tscdeadline = data;
start_apic_timer(apic);
}
void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu))
return;
apic_set_tpr(apic, ((cr8 & 0x0f) << 4)
| (kvm_apic_get_reg(apic, APIC_TASKPRI) & 4));
}
u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
{
u64 tpr;
if (!kvm_vcpu_has_lapic(vcpu))
return 0;
tpr = (u64) kvm_apic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
return (tpr & 0xf0) >> 4;
}
void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
{
u64 old_value = vcpu->arch.apic_base;
struct kvm_lapic *apic = vcpu->arch.apic;
if (!apic) {
value |= MSR_IA32_APICBASE_BSP;
vcpu->arch.apic_base = value;
return;
}
/* update jump label if enable bit changes */
if ((vcpu->arch.apic_base ^ value) & MSR_IA32_APICBASE_ENABLE) {
if (value & MSR_IA32_APICBASE_ENABLE)
static_key_slow_dec_deferred(&apic_hw_disabled);
else
static_key_slow_inc(&apic_hw_disabled.key);
recalculate_apic_map(vcpu->kvm);
}
if (!kvm_vcpu_is_bsp(apic->vcpu))
value &= ~MSR_IA32_APICBASE_BSP;
vcpu->arch.apic_base = value;
if ((old_value ^ value) & X2APIC_ENABLE) {
if (value & X2APIC_ENABLE) {
u32 id = kvm_apic_id(apic);
u32 ldr = ((id >> 4) << 16) | (1 << (id & 0xf));
kvm_apic_set_ldr(apic, ldr);
kvm_x86_ops->set_virtual_x2apic_mode(vcpu, true);
} else
kvm_x86_ops->set_virtual_x2apic_mode(vcpu, false);
}
apic->base_address = apic->vcpu->arch.apic_base &
MSR_IA32_APICBASE_BASE;
/* with FSB delivery interrupt, we can restart APIC functionality */
apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
"0x%lx.\n", apic->vcpu->arch.apic_base, apic->base_address);
}
void kvm_lapic_reset(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic;
int i;
apic_debug("%s\n", __func__);
ASSERT(vcpu);
apic = vcpu->arch.apic;
ASSERT(apic != NULL);
/* Stop the timer in case it's a reset to an active apic */
hrtimer_cancel(&apic->lapic_timer.timer);
kvm_apic_set_id(apic, vcpu->vcpu_id);
kvm_apic_set_version(apic->vcpu);
for (i = 0; i < APIC_LVT_NUM; i++)
apic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
apic_set_reg(apic, APIC_LVT0,
SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
apic_set_reg(apic, APIC_DFR, 0xffffffffU);
apic_set_spiv(apic, 0xff);
apic_set_reg(apic, APIC_TASKPRI, 0);
kvm_apic_set_ldr(apic, 0);
apic_set_reg(apic, APIC_ESR, 0);
apic_set_reg(apic, APIC_ICR, 0);
apic_set_reg(apic, APIC_ICR2, 0);
apic_set_reg(apic, APIC_TDCR, 0);
apic_set_reg(apic, APIC_TMICT, 0);
for (i = 0; i < 8; i++) {
apic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
apic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
apic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
}
apic->irr_pending = kvm_apic_vid_enabled(vcpu->kvm);
apic->isr_count = kvm_apic_vid_enabled(vcpu->kvm);
apic->highest_isr_cache = -1;
update_divide_count(apic);
atomic_set(&apic->lapic_timer.pending, 0);
if (kvm_vcpu_is_bsp(vcpu))
kvm_lapic_set_base(vcpu,
vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
vcpu->arch.pv_eoi.msr_val = 0;
apic_update_ppr(apic);
vcpu->arch.apic_arb_prio = 0;
vcpu->arch.apic_attention = 0;
apic_debug(KERN_INFO "%s: vcpu=%p, id=%d, base_msr="
"0x%016" PRIx64 ", base_address=0x%0lx.\n", __func__,
vcpu, kvm_apic_id(apic),
vcpu->arch.apic_base, apic->base_address);
}
/*
*----------------------------------------------------------------------
* timer interface
*----------------------------------------------------------------------
*/
static bool lapic_is_periodic(struct kvm_lapic *apic)
{
return apic_lvtt_period(apic);
}
int apic_has_pending_timer(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (kvm_vcpu_has_lapic(vcpu) && apic_enabled(apic) &&
apic_lvt_enabled(apic, APIC_LVTT))
return atomic_read(&apic->lapic_timer.pending);
return 0;
}
int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
{
u32 reg = kvm_apic_get_reg(apic, lvt_type);
int vector, mode, trig_mode;
if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
vector = reg & APIC_VECTOR_MASK;
mode = reg & APIC_MODE_MASK;
trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
NULL);
}
return 0;
}
void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (apic)
kvm_apic_local_deliver(apic, APIC_LVT0);
}
static const struct kvm_io_device_ops apic_mmio_ops = {
.read = apic_mmio_read,
.write = apic_mmio_write,
};
static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
{
struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
struct kvm_vcpu *vcpu = apic->vcpu;
wait_queue_head_t *q = &vcpu->wq;
/*
* There is a race window between reading and incrementing, but we do
* not care about potentially losing timer events in the !reinject
* case anyway. Note: KVM_REQ_PENDING_TIMER is implicitly checked
* in vcpu_enter_guest.
*/
if (!atomic_read(&ktimer->pending)) {
atomic_inc(&ktimer->pending);
/* FIXME: this code should not know anything about vcpus */
kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
}
if (waitqueue_active(q))
wake_up_interruptible(q);
if (lapic_is_periodic(apic)) {
hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
return HRTIMER_RESTART;
} else
return HRTIMER_NORESTART;
}
int kvm_create_lapic(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic;
ASSERT(vcpu != NULL);
apic_debug("apic_init %d\n", vcpu->vcpu_id);
apic = kzalloc(sizeof(*apic), GFP_KERNEL);
if (!apic)
goto nomem;
vcpu->arch.apic = apic;
apic->regs = (void *)get_zeroed_page(GFP_KERNEL);
if (!apic->regs) {
printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
vcpu->vcpu_id);
goto nomem_free_apic;
}
apic->vcpu = vcpu;
hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
HRTIMER_MODE_ABS);
apic->lapic_timer.timer.function = apic_timer_fn;
/*
* APIC is created enabled. This will prevent kvm_lapic_set_base from
* thinking that APIC satet has changed.
*/
vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
kvm_lapic_set_base(vcpu,
APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE);
static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
kvm_lapic_reset(vcpu);
kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
return 0;
nomem_free_apic:
kfree(apic);
nomem:
return -ENOMEM;
}
int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int highest_irr;
if (!kvm_vcpu_has_lapic(vcpu) || !apic_enabled(apic))
return -1;
apic_update_ppr(apic);
highest_irr = apic_find_highest_irr(apic);
if ((highest_irr == -1) ||
((highest_irr & 0xF0) <= kvm_apic_get_reg(apic, APIC_PROCPRI)))
return -1;
return highest_irr;
}
int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
{
u32 lvt0 = kvm_apic_get_reg(vcpu->arch.apic, APIC_LVT0);
int r = 0;
if (!kvm_apic_hw_enabled(vcpu->arch.apic))
r = 1;
if ((lvt0 & APIC_LVT_MASKED) == 0 &&
GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
r = 1;
return r;
}
void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu))
return;
if (atomic_read(&apic->lapic_timer.pending) > 0) {
kvm_apic_local_deliver(apic, APIC_LVTT);
atomic_set(&apic->lapic_timer.pending, 0);
}
}
int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
{
int vector = kvm_apic_has_interrupt(vcpu);
struct kvm_lapic *apic = vcpu->arch.apic;
if (vector == -1)
return -1;
apic_set_isr(vector, apic);
apic_update_ppr(apic);
apic_clear_irr(vector, apic);
return vector;
}
void kvm_apic_post_state_restore(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
struct kvm_lapic *apic = vcpu->arch.apic;
kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
/* set SPIV separately to get count of SW disabled APICs right */
apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
/* call kvm_apic_set_id() to put apic into apic_map */
kvm_apic_set_id(apic, kvm_apic_id(apic));
kvm_apic_set_version(vcpu);
apic_update_ppr(apic);
hrtimer_cancel(&apic->lapic_timer.timer);
update_divide_count(apic);
start_apic_timer(apic);
apic->irr_pending = true;
apic->isr_count = kvm_apic_vid_enabled(vcpu->kvm) ?
1 : count_vectors(apic->regs + APIC_ISR);
apic->highest_isr_cache = -1;
kvm_x86_ops->hwapic_isr_update(vcpu->kvm, apic_find_highest_isr(apic));
kvm_make_request(KVM_REQ_EVENT, vcpu);
kvm_rtc_eoi_tracking_restore_one(vcpu);
}
void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
{
struct hrtimer *timer;
if (!kvm_vcpu_has_lapic(vcpu))
return;
timer = &vcpu->arch.apic->lapic_timer.timer;
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
/*
* apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
*
* Detect whether guest triggered PV EOI since the
* last entry. If yes, set EOI on guests's behalf.
* Clear PV EOI in guest memory in any case.
*/
static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
struct kvm_lapic *apic)
{
bool pending;
int vector;
/*
* PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
* and KVM_PV_EOI_ENABLED in guest memory as follows:
*
* KVM_APIC_PV_EOI_PENDING is unset:
* -> host disabled PV EOI.
* KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
* -> host enabled PV EOI, guest did not execute EOI yet.
* KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
* -> host enabled PV EOI, guest executed EOI.
*/
BUG_ON(!pv_eoi_enabled(vcpu));
pending = pv_eoi_get_pending(vcpu);
/*
* Clear pending bit in any case: it will be set again on vmentry.
* While this might not be ideal from performance point of view,
* this makes sure pv eoi is only enabled when we know it's safe.
*/
pv_eoi_clr_pending(vcpu);
if (pending)
return;
vector = apic_set_eoi(apic);
trace_kvm_pv_eoi(apic, vector);
}
void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
{
u32 data;
void *vapic;
if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
vapic = kmap_atomic(vcpu->arch.apic->vapic_page);
data = *(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr));
kunmap_atomic(vapic);
apic_set_tpr(vcpu->arch.apic, data & 0xff);
}
/*
* apic_sync_pv_eoi_to_guest - called before vmentry
*
* Detect whether it's safe to enable PV EOI and
* if yes do so.
*/
static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
struct kvm_lapic *apic)
{
if (!pv_eoi_enabled(vcpu) ||
/* IRR set or many bits in ISR: could be nested. */
apic->irr_pending ||
/* Cache not set: could be safe but we don't bother. */
apic->highest_isr_cache == -1 ||
/* Need EOI to update ioapic. */
kvm_ioapic_handles_vector(vcpu->kvm, apic->highest_isr_cache)) {
/*
* PV EOI was disabled by apic_sync_pv_eoi_from_guest
* so we need not do anything here.
*/
return;
}
pv_eoi_set_pending(apic->vcpu);
}
void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
{
u32 data, tpr;
int max_irr, max_isr;
struct kvm_lapic *apic = vcpu->arch.apic;
void *vapic;
apic_sync_pv_eoi_to_guest(vcpu, apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
tpr = kvm_apic_get_reg(apic, APIC_TASKPRI) & 0xff;
max_irr = apic_find_highest_irr(apic);
if (max_irr < 0)
max_irr = 0;
max_isr = apic_find_highest_isr(apic);
if (max_isr < 0)
max_isr = 0;
data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
vapic = kmap_atomic(vcpu->arch.apic->vapic_page);
*(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr)) = data;
kunmap_atomic(vapic);
}
void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
{
vcpu->arch.apic->vapic_addr = vapic_addr;
if (vapic_addr)
__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
else
__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
}
int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
u32 reg = (msr - APIC_BASE_MSR) << 4;
if (!irqchip_in_kernel(vcpu->kvm) || !apic_x2apic_mode(apic))
return 1;
/* if this is ICR write vector before command */
if (msr == 0x830)
apic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
return apic_reg_write(apic, reg, (u32)data);
}
int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
if (!irqchip_in_kernel(vcpu->kvm) || !apic_x2apic_mode(apic))
return 1;
if (apic_reg_read(apic, reg, 4, &low))
return 1;
if (msr == 0x830)
apic_reg_read(apic, APIC_ICR2, 4, &high);
*data = (((u64)high) << 32) | low;
return 0;
}
int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
if (!kvm_vcpu_has_lapic(vcpu))
return 1;
/* if this is ICR write vector before command */
if (reg == APIC_ICR)
apic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
return apic_reg_write(apic, reg, (u32)data);
}
int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
{
struct kvm_lapic *apic = vcpu->arch.apic;
u32 low, high = 0;
if (!kvm_vcpu_has_lapic(vcpu))
return 1;
if (apic_reg_read(apic, reg, 4, &low))
return 1;
if (reg == APIC_ICR)
apic_reg_read(apic, APIC_ICR2, 4, &high);
*data = (((u64)high) << 32) | low;
return 0;
}
int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data)
{
u64 addr = data & ~KVM_MSR_ENABLED;
if (!IS_ALIGNED(addr, 4))
return 1;
vcpu->arch.pv_eoi.msr_val = data;
if (!pv_eoi_enabled(vcpu))
return 0;
return kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_eoi.data,
addr, sizeof(u8));
}
void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
unsigned int sipi_vector;
unsigned long pe;
if (!kvm_vcpu_has_lapic(vcpu) || !apic->pending_events)
return;
pe = xchg(&apic->pending_events, 0);
if (test_bit(KVM_APIC_INIT, &pe)) {
kvm_lapic_reset(vcpu);
kvm_vcpu_reset(vcpu);
if (kvm_vcpu_is_bsp(apic->vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
}
if (test_bit(KVM_APIC_SIPI, &pe) &&
vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
/* evaluate pending_events before reading the vector */
smp_rmb();
sipi_vector = apic->sipi_vector;
pr_debug("vcpu %d received sipi with vector # %x\n",
vcpu->vcpu_id, sipi_vector);
kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
}
void kvm_lapic_init(void)
{
/* do not patch jump label more than once per second */
jump_label_rate_limit(&apic_hw_disabled, HZ);
jump_label_rate_limit(&apic_sw_disabled, HZ);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5794_0 |
crossvul-cpp_data_good_5770_2 | /*
* SSLv3/TLSv1 shared functions
*
* Copyright (C) 2006-2012, Brainspark B.V.
*
* This file is part of PolarSSL (http://www.polarssl.org)
* Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* The SSL 3.0 specification was drafted by Netscape in 1996,
* and became an IETF standard in 1999.
*
* http://wp.netscape.com/eng/ssl3/
* http://www.ietf.org/rfc/rfc2246.txt
* http://www.ietf.org/rfc/rfc4346.txt
*/
#include "polarssl/config.h"
#if defined(POLARSSL_SSL_TLS_C)
#include "polarssl/aes.h"
#include "polarssl/arc4.h"
#include "polarssl/camellia.h"
#include "polarssl/des.h"
#include "polarssl/debug.h"
#include "polarssl/ssl.h"
#include "polarssl/sha2.h"
#if defined(POLARSSL_GCM_C)
#include "polarssl/gcm.h"
#endif
#include <stdlib.h>
#include <time.h>
#if defined _MSC_VER && !defined strcasecmp
#define strcasecmp _stricmp
#endif
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
int (*ssl_hw_record_init)(ssl_context *ssl,
const unsigned char *key_enc, const unsigned char *key_dec,
const unsigned char *iv_enc, const unsigned char *iv_dec,
const unsigned char *mac_enc, const unsigned char *mac_dec) = NULL;
int (*ssl_hw_record_reset)(ssl_context *ssl) = NULL;
int (*ssl_hw_record_write)(ssl_context *ssl) = NULL;
int (*ssl_hw_record_read)(ssl_context *ssl) = NULL;
int (*ssl_hw_record_finish)(ssl_context *ssl) = NULL;
#endif
static int ssl_rsa_decrypt( void *ctx, int mode, size_t *olen,
const unsigned char *input, unsigned char *output,
size_t output_max_len )
{
return rsa_pkcs1_decrypt( (rsa_context *) ctx, mode, olen, input, output,
output_max_len );
}
static int ssl_rsa_sign( void *ctx,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
int mode, int hash_id, unsigned int hashlen,
const unsigned char *hash, unsigned char *sig )
{
return rsa_pkcs1_sign( (rsa_context *) ctx, f_rng, p_rng, mode, hash_id,
hashlen, hash, sig );
}
static size_t ssl_rsa_key_len( void *ctx )
{
return ( (rsa_context *) ctx )->len;
}
/*
* Key material generation
*/
static int ssl3_prf( unsigned char *secret, size_t slen, char *label,
unsigned char *random, size_t rlen,
unsigned char *dstbuf, size_t dlen )
{
size_t i;
md5_context md5;
sha1_context sha1;
unsigned char padding[16];
unsigned char sha1sum[20];
((void)label);
/*
* SSLv3:
* block =
* MD5( secret + SHA1( 'A' + secret + random ) ) +
* MD5( secret + SHA1( 'BB' + secret + random ) ) +
* MD5( secret + SHA1( 'CCC' + secret + random ) ) +
* ...
*/
for( i = 0; i < dlen / 16; i++ )
{
memset( padding, 'A' + i, 1 + i );
sha1_starts( &sha1 );
sha1_update( &sha1, padding, 1 + i );
sha1_update( &sha1, secret, slen );
sha1_update( &sha1, random, rlen );
sha1_finish( &sha1, sha1sum );
md5_starts( &md5 );
md5_update( &md5, secret, slen );
md5_update( &md5, sha1sum, 20 );
md5_finish( &md5, dstbuf + i * 16 );
}
memset( &md5, 0, sizeof( md5 ) );
memset( &sha1, 0, sizeof( sha1 ) );
memset( padding, 0, sizeof( padding ) );
memset( sha1sum, 0, sizeof( sha1sum ) );
return( 0 );
}
static int tls1_prf( unsigned char *secret, size_t slen, char *label,
unsigned char *random, size_t rlen,
unsigned char *dstbuf, size_t dlen )
{
size_t nb, hs;
size_t i, j, k;
unsigned char *S1, *S2;
unsigned char tmp[128];
unsigned char h_i[20];
if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
hs = ( slen + 1 ) / 2;
S1 = secret;
S2 = secret + slen - hs;
nb = strlen( label );
memcpy( tmp + 20, label, nb );
memcpy( tmp + 20 + nb, random, rlen );
nb += rlen;
/*
* First compute P_md5(secret,label+random)[0..dlen]
*/
md5_hmac( S1, hs, tmp + 20, nb, 4 + tmp );
for( i = 0; i < dlen; i += 16 )
{
md5_hmac( S1, hs, 4 + tmp, 16 + nb, h_i );
md5_hmac( S1, hs, 4 + tmp, 16, 4 + tmp );
k = ( i + 16 > dlen ) ? dlen % 16 : 16;
for( j = 0; j < k; j++ )
dstbuf[i + j] = h_i[j];
}
/*
* XOR out with P_sha1(secret,label+random)[0..dlen]
*/
sha1_hmac( S2, hs, tmp + 20, nb, tmp );
for( i = 0; i < dlen; i += 20 )
{
sha1_hmac( S2, hs, tmp, 20 + nb, h_i );
sha1_hmac( S2, hs, tmp, 20, tmp );
k = ( i + 20 > dlen ) ? dlen % 20 : 20;
for( j = 0; j < k; j++ )
dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
}
memset( tmp, 0, sizeof( tmp ) );
memset( h_i, 0, sizeof( h_i ) );
return( 0 );
}
static int tls_prf_sha256( unsigned char *secret, size_t slen, char *label,
unsigned char *random, size_t rlen,
unsigned char *dstbuf, size_t dlen )
{
size_t nb;
size_t i, j, k;
unsigned char tmp[128];
unsigned char h_i[32];
if( sizeof( tmp ) < 32 + strlen( label ) + rlen )
return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
nb = strlen( label );
memcpy( tmp + 32, label, nb );
memcpy( tmp + 32 + nb, random, rlen );
nb += rlen;
/*
* Compute P_<hash>(secret, label + random)[0..dlen]
*/
sha2_hmac( secret, slen, tmp + 32, nb, tmp, 0 );
for( i = 0; i < dlen; i += 32 )
{
sha2_hmac( secret, slen, tmp, 32 + nb, h_i, 0 );
sha2_hmac( secret, slen, tmp, 32, tmp, 0 );
k = ( i + 32 > dlen ) ? dlen % 32 : 32;
for( j = 0; j < k; j++ )
dstbuf[i + j] = h_i[j];
}
memset( tmp, 0, sizeof( tmp ) );
memset( h_i, 0, sizeof( h_i ) );
return( 0 );
}
#if defined(POLARSSL_SHA4_C)
static int tls_prf_sha384( unsigned char *secret, size_t slen, char *label,
unsigned char *random, size_t rlen,
unsigned char *dstbuf, size_t dlen )
{
size_t nb;
size_t i, j, k;
unsigned char tmp[128];
unsigned char h_i[48];
if( sizeof( tmp ) < 48 + strlen( label ) + rlen )
return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
nb = strlen( label );
memcpy( tmp + 48, label, nb );
memcpy( tmp + 48 + nb, random, rlen );
nb += rlen;
/*
* Compute P_<hash>(secret, label + random)[0..dlen]
*/
sha4_hmac( secret, slen, tmp + 48, nb, tmp, 1 );
for( i = 0; i < dlen; i += 48 )
{
sha4_hmac( secret, slen, tmp, 48 + nb, h_i, 1 );
sha4_hmac( secret, slen, tmp, 48, tmp, 1 );
k = ( i + 48 > dlen ) ? dlen % 48 : 48;
for( j = 0; j < k; j++ )
dstbuf[i + j] = h_i[j];
}
memset( tmp, 0, sizeof( tmp ) );
memset( h_i, 0, sizeof( h_i ) );
return( 0 );
}
#endif
static void ssl_update_checksum_start(ssl_context *, unsigned char *, size_t);
static void ssl_update_checksum_md5sha1(ssl_context *, unsigned char *, size_t);
static void ssl_update_checksum_sha256(ssl_context *, unsigned char *, size_t);
static void ssl_calc_verify_ssl(ssl_context *,unsigned char *);
static void ssl_calc_verify_tls(ssl_context *,unsigned char *);
static void ssl_calc_verify_tls_sha256(ssl_context *,unsigned char *);
static void ssl_calc_finished_ssl(ssl_context *,unsigned char *,int);
static void ssl_calc_finished_tls(ssl_context *,unsigned char *,int);
static void ssl_calc_finished_tls_sha256(ssl_context *,unsigned char *,int);
#if defined(POLARSSL_SHA4_C)
static void ssl_update_checksum_sha384(ssl_context *, unsigned char *, size_t);
static void ssl_calc_verify_tls_sha384(ssl_context *,unsigned char *);
static void ssl_calc_finished_tls_sha384(ssl_context *,unsigned char *,int);
#endif
int ssl_derive_keys( ssl_context *ssl )
{
unsigned char tmp[64];
unsigned char keyblk[256];
unsigned char *key1;
unsigned char *key2;
unsigned int iv_copy_len;
ssl_session *session = ssl->session_negotiate;
ssl_transform *transform = ssl->transform_negotiate;
ssl_handshake_params *handshake = ssl->handshake;
SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
/*
* Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
*/
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
handshake->tls_prf = ssl3_prf;
handshake->calc_verify = ssl_calc_verify_ssl;
handshake->calc_finished = ssl_calc_finished_ssl;
}
else if( ssl->minor_ver < SSL_MINOR_VERSION_3 )
{
handshake->tls_prf = tls1_prf;
handshake->calc_verify = ssl_calc_verify_tls;
handshake->calc_finished = ssl_calc_finished_tls;
}
#if defined(POLARSSL_SHA4_C)
else if( session->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 ||
session->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 )
{
handshake->tls_prf = tls_prf_sha384;
handshake->calc_verify = ssl_calc_verify_tls_sha384;
handshake->calc_finished = ssl_calc_finished_tls_sha384;
}
#endif
else
{
handshake->tls_prf = tls_prf_sha256;
handshake->calc_verify = ssl_calc_verify_tls_sha256;
handshake->calc_finished = ssl_calc_finished_tls_sha256;
}
/*
* SSLv3:
* master =
* MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
* MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
* MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
*
* TLSv1:
* master = PRF( premaster, "master secret", randbytes )[0..47]
*/
if( handshake->resume == 0 )
{
SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
handshake->pmslen );
handshake->tls_prf( handshake->premaster, handshake->pmslen,
"master secret",
handshake->randbytes, 64, session->master, 48 );
memset( handshake->premaster, 0, sizeof( handshake->premaster ) );
}
else
SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
/*
* Swap the client and server random values.
*/
memcpy( tmp, handshake->randbytes, 64 );
memcpy( handshake->randbytes, tmp + 32, 32 );
memcpy( handshake->randbytes + 32, tmp, 32 );
memset( tmp, 0, sizeof( tmp ) );
/*
* SSLv3:
* key block =
* MD5( master + SHA1( 'A' + master + randbytes ) ) +
* MD5( master + SHA1( 'BB' + master + randbytes ) ) +
* MD5( master + SHA1( 'CCC' + master + randbytes ) ) +
* MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
* ...
*
* TLSv1:
* key block = PRF( master, "key expansion", randbytes )
*/
handshake->tls_prf( session->master, 48, "key expansion",
handshake->randbytes, 64, keyblk, 256 );
SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
ssl_get_ciphersuite_name( session->ciphersuite ) ) );
SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
memset( handshake->randbytes, 0, sizeof( handshake->randbytes ) );
/*
* Determine the appropriate key, IV and MAC length.
*/
switch( session->ciphersuite )
{
#if defined(POLARSSL_ARC4_C)
case TLS_RSA_WITH_RC4_128_MD5:
transform->keylen = 16; transform->minlen = 16;
transform->ivlen = 0; transform->maclen = 16;
break;
case TLS_RSA_WITH_RC4_128_SHA:
transform->keylen = 16; transform->minlen = 20;
transform->ivlen = 0; transform->maclen = 20;
break;
#endif
#if defined(POLARSSL_DES_C)
case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
transform->keylen = 24; transform->minlen = 24;
transform->ivlen = 8; transform->maclen = 20;
break;
#endif
#if defined(POLARSSL_AES_C)
case TLS_RSA_WITH_AES_128_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
transform->keylen = 16; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 20;
break;
case TLS_RSA_WITH_AES_256_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
transform->keylen = 32; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 20;
break;
#if defined(POLARSSL_SHA2_C)
case TLS_RSA_WITH_AES_128_CBC_SHA256:
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
transform->keylen = 16; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 32;
break;
case TLS_RSA_WITH_AES_256_CBC_SHA256:
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
transform->keylen = 32; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 32;
break;
#endif
#if defined(POLARSSL_GCM_C)
case TLS_RSA_WITH_AES_128_GCM_SHA256:
case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
transform->keylen = 16; transform->minlen = 1;
transform->ivlen = 12; transform->maclen = 0;
transform->fixed_ivlen = 4;
break;
case TLS_RSA_WITH_AES_256_GCM_SHA384:
case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
transform->keylen = 32; transform->minlen = 1;
transform->ivlen = 12; transform->maclen = 0;
transform->fixed_ivlen = 4;
break;
#endif
#endif
#if defined(POLARSSL_CAMELLIA_C)
case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
transform->keylen = 16; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 20;
break;
case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
transform->keylen = 32; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 20;
break;
#if defined(POLARSSL_SHA2_C)
case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
transform->keylen = 16; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 32;
break;
case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
transform->keylen = 32; transform->minlen = 32;
transform->ivlen = 16; transform->maclen = 32;
break;
#endif
#endif
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
case TLS_RSA_WITH_NULL_MD5:
transform->keylen = 0; transform->minlen = 0;
transform->ivlen = 0; transform->maclen = 16;
break;
case TLS_RSA_WITH_NULL_SHA:
transform->keylen = 0; transform->minlen = 0;
transform->ivlen = 0; transform->maclen = 20;
break;
case TLS_RSA_WITH_NULL_SHA256:
transform->keylen = 0; transform->minlen = 0;
transform->ivlen = 0; transform->maclen = 32;
break;
#endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */
#if defined(POLARSSL_DES_C)
case TLS_RSA_WITH_DES_CBC_SHA:
case TLS_DHE_RSA_WITH_DES_CBC_SHA:
transform->keylen = 8; transform->minlen = 8;
transform->ivlen = 8; transform->maclen = 20;
break;
#endif
#endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */
default:
SSL_DEBUG_MSG( 1, ( "ciphersuite %s is not available",
ssl_get_ciphersuite_name( session->ciphersuite ) ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
transform->keylen, transform->minlen, transform->ivlen,
transform->maclen ) );
/*
* Finally setup the cipher contexts, IVs and MAC secrets.
*/
if( ssl->endpoint == SSL_IS_CLIENT )
{
key1 = keyblk + transform->maclen * 2;
key2 = keyblk + transform->maclen * 2 + transform->keylen;
memcpy( transform->mac_enc, keyblk, transform->maclen );
memcpy( transform->mac_dec, keyblk + transform->maclen,
transform->maclen );
/*
* This is not used in TLS v1.1.
*/
iv_copy_len = ( transform->fixed_ivlen ) ?
transform->fixed_ivlen : transform->ivlen;
memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len );
memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
iv_copy_len );
}
else
{
key1 = keyblk + transform->maclen * 2 + transform->keylen;
key2 = keyblk + transform->maclen * 2;
memcpy( transform->mac_dec, keyblk, transform->maclen );
memcpy( transform->mac_enc, keyblk + transform->maclen,
transform->maclen );
/*
* This is not used in TLS v1.1.
*/
iv_copy_len = ( transform->fixed_ivlen ) ?
transform->fixed_ivlen : transform->ivlen;
memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len );
memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
iv_copy_len );
}
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
if( ssl_hw_record_init != NULL)
{
int ret = 0;
SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_init()" ) );
if( ( ret = ssl_hw_record_init( ssl, key1, key2, transform->iv_enc,
transform->iv_dec, transform->mac_enc,
transform->mac_dec ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_hw_record_init", ret );
return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
}
}
#endif
switch( session->ciphersuite )
{
#if defined(POLARSSL_ARC4_C)
case TLS_RSA_WITH_RC4_128_MD5:
case TLS_RSA_WITH_RC4_128_SHA:
arc4_setup( (arc4_context *) transform->ctx_enc, key1,
transform->keylen );
arc4_setup( (arc4_context *) transform->ctx_dec, key2,
transform->keylen );
break;
#endif
#if defined(POLARSSL_DES_C)
case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
des3_set3key_enc( (des3_context *) transform->ctx_enc, key1 );
des3_set3key_dec( (des3_context *) transform->ctx_dec, key2 );
break;
#endif
#if defined(POLARSSL_AES_C)
case TLS_RSA_WITH_AES_128_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case TLS_RSA_WITH_AES_128_CBC_SHA256:
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
aes_setkey_enc( (aes_context *) transform->ctx_enc, key1, 128 );
aes_setkey_dec( (aes_context *) transform->ctx_dec, key2, 128 );
break;
case TLS_RSA_WITH_AES_256_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case TLS_RSA_WITH_AES_256_CBC_SHA256:
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
aes_setkey_enc( (aes_context *) transform->ctx_enc, key1, 256 );
aes_setkey_dec( (aes_context *) transform->ctx_dec, key2, 256 );
break;
#if defined(POLARSSL_GCM_C)
case TLS_RSA_WITH_AES_128_GCM_SHA256:
case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
gcm_init( (gcm_context *) transform->ctx_enc, key1, 128 );
gcm_init( (gcm_context *) transform->ctx_dec, key2, 128 );
break;
case TLS_RSA_WITH_AES_256_GCM_SHA384:
case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
gcm_init( (gcm_context *) transform->ctx_enc, key1, 256 );
gcm_init( (gcm_context *) transform->ctx_dec, key2, 256 );
break;
#endif
#endif
#if defined(POLARSSL_CAMELLIA_C)
case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
camellia_setkey_enc( (camellia_context *) transform->ctx_enc, key1, 128 );
camellia_setkey_dec( (camellia_context *) transform->ctx_dec, key2, 128 );
break;
case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
camellia_setkey_enc( (camellia_context *) transform->ctx_enc, key1, 256 );
camellia_setkey_dec( (camellia_context *) transform->ctx_dec, key2, 256 );
break;
#endif
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
case TLS_RSA_WITH_NULL_MD5:
case TLS_RSA_WITH_NULL_SHA:
case TLS_RSA_WITH_NULL_SHA256:
break;
#endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */
#if defined(POLARSSL_DES_C)
case TLS_RSA_WITH_DES_CBC_SHA:
case TLS_DHE_RSA_WITH_DES_CBC_SHA:
des_setkey_enc( (des_context *) transform->ctx_enc, key1 );
des_setkey_dec( (des_context *) transform->ctx_dec, key2 );
break;
#endif
#endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */
default:
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
memset( keyblk, 0, sizeof( keyblk ) );
#if defined(POLARSSL_ZLIB_SUPPORT)
// Initialize compression
//
if( session->compression == SSL_COMPRESS_DEFLATE )
{
SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK ||
inflateInit( &transform->ctx_inflate ) != Z_OK )
{
SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
}
}
#endif /* POLARSSL_ZLIB_SUPPORT */
SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
return( 0 );
}
void ssl_calc_verify_ssl( ssl_context *ssl, unsigned char hash[36] )
{
md5_context md5;
sha1_context sha1;
unsigned char pad_1[48];
unsigned char pad_2[48];
SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) );
memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
memset( pad_1, 0x36, 48 );
memset( pad_2, 0x5C, 48 );
md5_update( &md5, ssl->session_negotiate->master, 48 );
md5_update( &md5, pad_1, 48 );
md5_finish( &md5, hash );
md5_starts( &md5 );
md5_update( &md5, ssl->session_negotiate->master, 48 );
md5_update( &md5, pad_2, 48 );
md5_update( &md5, hash, 16 );
md5_finish( &md5, hash );
sha1_update( &sha1, ssl->session_negotiate->master, 48 );
sha1_update( &sha1, pad_1, 40 );
sha1_finish( &sha1, hash + 16 );
sha1_starts( &sha1 );
sha1_update( &sha1, ssl->session_negotiate->master, 48 );
sha1_update( &sha1, pad_2, 40 );
sha1_update( &sha1, hash + 16, 20 );
sha1_finish( &sha1, hash + 16 );
SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
return;
}
void ssl_calc_verify_tls( ssl_context *ssl, unsigned char hash[36] )
{
md5_context md5;
sha1_context sha1;
SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) );
memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
md5_finish( &md5, hash );
sha1_finish( &sha1, hash + 16 );
SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
return;
}
void ssl_calc_verify_tls_sha256( ssl_context *ssl, unsigned char hash[32] )
{
sha2_context sha2;
SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
memcpy( &sha2, &ssl->handshake->fin_sha2, sizeof(sha2_context) );
sha2_finish( &sha2, hash );
SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
return;
}
#if defined(POLARSSL_SHA4_C)
void ssl_calc_verify_tls_sha384( ssl_context *ssl, unsigned char hash[48] )
{
sha4_context sha4;
SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
memcpy( &sha4, &ssl->handshake->fin_sha4, sizeof(sha4_context) );
sha4_finish( &sha4, hash );
SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
return;
}
#endif
/*
* SSLv3.0 MAC functions
*/
static void ssl_mac_md5( unsigned char *secret,
unsigned char *buf, size_t len,
unsigned char *ctr, int type )
{
unsigned char header[11];
unsigned char padding[48];
md5_context md5;
memcpy( header, ctr, 8 );
header[ 8] = (unsigned char) type;
header[ 9] = (unsigned char)( len >> 8 );
header[10] = (unsigned char)( len );
memset( padding, 0x36, 48 );
md5_starts( &md5 );
md5_update( &md5, secret, 16 );
md5_update( &md5, padding, 48 );
md5_update( &md5, header, 11 );
md5_update( &md5, buf, len );
md5_finish( &md5, buf + len );
memset( padding, 0x5C, 48 );
md5_starts( &md5 );
md5_update( &md5, secret, 16 );
md5_update( &md5, padding, 48 );
md5_update( &md5, buf + len, 16 );
md5_finish( &md5, buf + len );
}
static void ssl_mac_sha1( unsigned char *secret,
unsigned char *buf, size_t len,
unsigned char *ctr, int type )
{
unsigned char header[11];
unsigned char padding[40];
sha1_context sha1;
memcpy( header, ctr, 8 );
header[ 8] = (unsigned char) type;
header[ 9] = (unsigned char)( len >> 8 );
header[10] = (unsigned char)( len );
memset( padding, 0x36, 40 );
sha1_starts( &sha1 );
sha1_update( &sha1, secret, 20 );
sha1_update( &sha1, padding, 40 );
sha1_update( &sha1, header, 11 );
sha1_update( &sha1, buf, len );
sha1_finish( &sha1, buf + len );
memset( padding, 0x5C, 40 );
sha1_starts( &sha1 );
sha1_update( &sha1, secret, 20 );
sha1_update( &sha1, padding, 40 );
sha1_update( &sha1, buf + len, 20 );
sha1_finish( &sha1, buf + len );
}
static void ssl_mac_sha2( unsigned char *secret,
unsigned char *buf, size_t len,
unsigned char *ctr, int type )
{
unsigned char header[11];
unsigned char padding[32];
sha2_context sha2;
memcpy( header, ctr, 8 );
header[ 8] = (unsigned char) type;
header[ 9] = (unsigned char)( len >> 8 );
header[10] = (unsigned char)( len );
memset( padding, 0x36, 32 );
sha2_starts( &sha2, 0 );
sha2_update( &sha2, secret, 32 );
sha2_update( &sha2, padding, 32 );
sha2_update( &sha2, header, 11 );
sha2_update( &sha2, buf, len );
sha2_finish( &sha2, buf + len );
memset( padding, 0x5C, 32 );
sha2_starts( &sha2, 0 );
sha2_update( &sha2, secret, 32 );
sha2_update( &sha2, padding, 32 );
sha2_update( &sha2, buf + len, 32 );
sha2_finish( &sha2, buf + len );
}
/*
* Encryption/decryption functions
*/
static int ssl_encrypt_buf( ssl_context *ssl )
{
size_t i, padlen;
SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
/*
* Add MAC then encrypt
*/
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->transform_out->maclen == 16 )
ssl_mac_md5( ssl->transform_out->mac_enc,
ssl->out_msg, ssl->out_msglen,
ssl->out_ctr, ssl->out_msgtype );
else if( ssl->transform_out->maclen == 20 )
ssl_mac_sha1( ssl->transform_out->mac_enc,
ssl->out_msg, ssl->out_msglen,
ssl->out_ctr, ssl->out_msgtype );
else if( ssl->transform_out->maclen == 32 )
ssl_mac_sha2( ssl->transform_out->mac_enc,
ssl->out_msg, ssl->out_msglen,
ssl->out_ctr, ssl->out_msgtype );
else if( ssl->transform_out->maclen != 0 )
{
SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d",
ssl->transform_out->maclen ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
else
{
if( ssl->transform_out->maclen == 16 )
{
md5_context ctx;
md5_hmac_starts( &ctx, ssl->transform_out->mac_enc, 16 );
md5_hmac_update( &ctx, ssl->out_ctr, 13 );
md5_hmac_update( &ctx, ssl->out_msg, ssl->out_msglen );
md5_hmac_finish( &ctx, ssl->out_msg + ssl->out_msglen );
memset( &ctx, 0, sizeof(md5_context));
}
else if( ssl->transform_out->maclen == 20 )
{
sha1_context ctx;
sha1_hmac_starts( &ctx, ssl->transform_out->mac_enc, 20 );
sha1_hmac_update( &ctx, ssl->out_ctr, 13 );
sha1_hmac_update( &ctx, ssl->out_msg, ssl->out_msglen );
sha1_hmac_finish( &ctx, ssl->out_msg + ssl->out_msglen );
memset( &ctx, 0, sizeof(sha1_context));
}
else if( ssl->transform_out->maclen == 32 )
{
sha2_context ctx;
sha2_hmac_starts( &ctx, ssl->transform_out->mac_enc, 32, 0 );
sha2_hmac_update( &ctx, ssl->out_ctr, 13 );
sha2_hmac_update( &ctx, ssl->out_msg, ssl->out_msglen );
sha2_hmac_finish( &ctx, ssl->out_msg + ssl->out_msglen );
memset( &ctx, 0, sizeof(sha2_context));
}
else if( ssl->transform_out->maclen != 0 )
{
SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d",
ssl->transform_out->maclen ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
SSL_DEBUG_BUF( 4, "computed mac",
ssl->out_msg + ssl->out_msglen, ssl->transform_out->maclen );
ssl->out_msglen += ssl->transform_out->maclen;
if( ssl->transform_out->ivlen == 0 )
{
padlen = 0;
SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
"including %d bytes of padding",
ssl->out_msglen, 0 ) );
SSL_DEBUG_BUF( 4, "before encrypt: output payload",
ssl->out_msg, ssl->out_msglen );
#if defined(POLARSSL_ARC4_C)
if( ssl->session_out->ciphersuite == TLS_RSA_WITH_RC4_128_MD5 ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_RC4_128_SHA )
{
arc4_crypt( (arc4_context *) ssl->transform_out->ctx_enc,
ssl->out_msglen, ssl->out_msg,
ssl->out_msg );
} else
#endif
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
if( ssl->session_out->ciphersuite == TLS_RSA_WITH_NULL_MD5 ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_NULL_SHA ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_NULL_SHA256 )
{
} else
#endif
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
else if( ssl->transform_out->ivlen == 12 )
{
size_t enc_msglen;
unsigned char *enc_msg;
unsigned char add_data[13];
int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
padlen = 0;
enc_msglen = ssl->out_msglen;
memcpy( add_data, ssl->out_ctr, 8 );
add_data[8] = ssl->out_msgtype;
add_data[9] = ssl->major_ver;
add_data[10] = ssl->minor_ver;
add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
add_data[12] = ssl->out_msglen & 0xFF;
SSL_DEBUG_BUF( 4, "additional data used for AEAD",
add_data, 13 );
#if defined(POLARSSL_AES_C) && defined(POLARSSL_GCM_C)
if( ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_128_GCM_SHA256 ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 )
{
/*
* Generate IV
*/
ret = ssl->f_rng( ssl->p_rng,
ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
if( ret != 0 )
return( ret );
/*
* Shift message for ivlen bytes and prepend IV
*/
memmove( ssl->out_msg + ssl->transform_out->ivlen -
ssl->transform_out->fixed_ivlen,
ssl->out_msg, ssl->out_msglen );
memcpy( ssl->out_msg,
ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen,
ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen );
/*
* Fix pointer positions and message length with added IV
*/
enc_msg = ssl->out_msg + ssl->transform_out->ivlen -
ssl->transform_out->fixed_ivlen;
enc_msglen = ssl->out_msglen;
ssl->out_msglen += ssl->transform_out->ivlen -
ssl->transform_out->fixed_ivlen;
SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
"including %d bytes of padding",
ssl->out_msglen, 0 ) );
SSL_DEBUG_BUF( 4, "before encrypt: output payload",
ssl->out_msg, ssl->out_msglen );
/*
* Adjust for tag
*/
ssl->out_msglen += 16;
gcm_crypt_and_tag( (gcm_context *) ssl->transform_out->ctx_enc,
GCM_ENCRYPT, enc_msglen,
ssl->transform_out->iv_enc, ssl->transform_out->ivlen,
add_data, 13,
enc_msg, enc_msg,
16, enc_msg + enc_msglen );
SSL_DEBUG_BUF( 4, "after encrypt: tag",
enc_msg + enc_msglen, 16 );
} else
#endif
return( ret );
}
else
{
unsigned char *enc_msg;
size_t enc_msglen;
padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
ssl->transform_out->ivlen;
if( padlen == ssl->transform_out->ivlen )
padlen = 0;
for( i = 0; i <= padlen; i++ )
ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
ssl->out_msglen += padlen + 1;
enc_msglen = ssl->out_msglen;
enc_msg = ssl->out_msg;
/*
* Prepend per-record IV for block cipher in TLS v1.1 and up as per
* Method 1 (6.2.3.2. in RFC4346 and RFC5246)
*/
if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
{
/*
* Generate IV
*/
int ret = ssl->f_rng( ssl->p_rng, ssl->transform_out->iv_enc,
ssl->transform_out->ivlen );
if( ret != 0 )
return( ret );
/*
* Shift message for ivlen bytes and prepend IV
*/
memmove( ssl->out_msg + ssl->transform_out->ivlen, ssl->out_msg,
ssl->out_msglen );
memcpy( ssl->out_msg, ssl->transform_out->iv_enc,
ssl->transform_out->ivlen );
/*
* Fix pointer positions and message length with added IV
*/
enc_msg = ssl->out_msg + ssl->transform_out->ivlen;
enc_msglen = ssl->out_msglen;
ssl->out_msglen += ssl->transform_out->ivlen;
}
SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
"including %d bytes of IV and %d bytes of padding",
ssl->out_msglen, ssl->transform_out->ivlen, padlen + 1 ) );
SSL_DEBUG_BUF( 4, "before encrypt: output payload",
ssl->out_msg, ssl->out_msglen );
switch( ssl->transform_out->ivlen )
{
#if defined(POLARSSL_DES_C)
case 8:
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
if( ssl->session_out->ciphersuite == TLS_RSA_WITH_DES_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA )
{
des_crypt_cbc( (des_context *) ssl->transform_out->ctx_enc,
DES_ENCRYPT, enc_msglen,
ssl->transform_out->iv_enc, enc_msg, enc_msg );
}
else
#endif
des3_crypt_cbc( (des3_context *) ssl->transform_out->ctx_enc,
DES_ENCRYPT, enc_msglen,
ssl->transform_out->iv_enc, enc_msg, enc_msg );
break;
#endif
case 16:
#if defined(POLARSSL_AES_C)
if ( ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA256 ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA256 ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 )
{
aes_crypt_cbc( (aes_context *) ssl->transform_out->ctx_enc,
AES_ENCRYPT, enc_msglen,
ssl->transform_out->iv_enc, enc_msg, enc_msg);
break;
}
#endif
#if defined(POLARSSL_CAMELLIA_C)
if ( ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||
ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 ||
ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 )
{
camellia_crypt_cbc( (camellia_context *) ssl->transform_out->ctx_enc,
CAMELLIA_ENCRYPT, enc_msglen,
ssl->transform_out->iv_enc, enc_msg, enc_msg );
break;
}
#endif
default:
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
for( i = 8; i > 0; i-- )
if( ++ssl->out_ctr[i - 1] != 0 )
break;
SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
return( 0 );
}
/*
* TODO: Use digest version when integrated!
*/
#define POLARSSL_SSL_MAX_MAC_SIZE 32
static int ssl_decrypt_buf( ssl_context *ssl )
{
size_t i, padlen = 0, correct = 1;
unsigned char tmp[POLARSSL_SSL_MAX_MAC_SIZE];
SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
if( ssl->in_msglen < ssl->transform_in->minlen )
{
SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
ssl->in_msglen, ssl->transform_in->minlen ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
if( ssl->transform_in->ivlen == 0 )
{
#if defined(POLARSSL_ARC4_C)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_RC4_128_MD5 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_RC4_128_SHA )
{
arc4_crypt( (arc4_context *) ssl->transform_in->ctx_dec,
ssl->in_msglen, ssl->in_msg,
ssl->in_msg );
} else
#endif
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_MD5 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_SHA256 )
{
} else
#endif
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
else if( ssl->transform_in->ivlen == 12 )
{
unsigned char *dec_msg;
unsigned char *dec_msg_result;
size_t dec_msglen;
unsigned char add_data[13];
int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
#if defined(POLARSSL_AES_C) && defined(POLARSSL_GCM_C)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_GCM_SHA256 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 )
{
dec_msglen = ssl->in_msglen - ( ssl->transform_in->ivlen -
ssl->transform_in->fixed_ivlen );
dec_msglen -= 16;
dec_msg = ssl->in_msg + ( ssl->transform_in->ivlen -
ssl->transform_in->fixed_ivlen );
dec_msg_result = ssl->in_msg;
ssl->in_msglen = dec_msglen;
memcpy( add_data, ssl->in_ctr, 8 );
add_data[8] = ssl->in_msgtype;
add_data[9] = ssl->major_ver;
add_data[10] = ssl->minor_ver;
add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
add_data[12] = ssl->in_msglen & 0xFF;
SSL_DEBUG_BUF( 4, "additional data used for AEAD",
add_data, 13 );
memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
ssl->in_msg,
ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
ssl->transform_in->ivlen );
SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, 16 );
memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
ssl->in_msg,
ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
ret = gcm_auth_decrypt( (gcm_context *) ssl->transform_in->ctx_dec,
dec_msglen,
ssl->transform_in->iv_dec,
ssl->transform_in->ivlen,
add_data, 13,
dec_msg + dec_msglen, 16,
dec_msg, dec_msg_result );
if( ret != 0 )
{
SSL_DEBUG_MSG( 1, ( "AEAD decrypt failed on validation (ret = -0x%02x)",
-ret ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
} else
#endif
return( ret );
}
else
{
/*
* Decrypt and check the padding
*/
unsigned char *dec_msg;
unsigned char *dec_msg_result;
size_t dec_msglen;
size_t minlen = 0;
/*
* Check immediate ciphertext sanity
*/
if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
{
SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
ssl->in_msglen, ssl->transform_in->ivlen ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
minlen += ssl->transform_in->ivlen;
if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
{
SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) + 1 ) ( + expl IV )",
ssl->in_msglen, ssl->transform_in->ivlen, ssl->transform_in->maclen ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
dec_msglen = ssl->in_msglen;
dec_msg = ssl->in_msg;
dec_msg_result = ssl->in_msg;
/*
* Initialize for prepended IV for block cipher in TLS v1.1 and up
*/
if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
{
dec_msg += ssl->transform_in->ivlen;
dec_msglen -= ssl->transform_in->ivlen;
ssl->in_msglen -= ssl->transform_in->ivlen;
for( i = 0; i < ssl->transform_in->ivlen; i++ )
ssl->transform_in->iv_dec[i] = ssl->in_msg[i];
}
switch( ssl->transform_in->ivlen )
{
#if defined(POLARSSL_DES_C)
case 8:
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_DES_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA )
{
des_crypt_cbc( (des_context *) ssl->transform_in->ctx_dec,
DES_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
}
else
#endif
des3_crypt_cbc( (des3_context *) ssl->transform_in->ctx_dec,
DES_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
break;
#endif
case 16:
#if defined(POLARSSL_AES_C)
if ( ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 )
{
aes_crypt_cbc( (aes_context *) ssl->transform_in->ctx_dec,
AES_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
break;
}
#endif
#if defined(POLARSSL_CAMELLIA_C)
if ( ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 )
{
camellia_crypt_cbc( (camellia_context *) ssl->transform_in->ctx_dec,
CAMELLIA_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
break;
}
#endif
default:
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
if( ssl->in_msglen < ssl->transform_in->maclen + padlen )
{
#if defined(POLARSSL_SSL_DEBUG_ALL)
SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
#endif
padlen = 0;
correct = 0;
}
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( padlen > ssl->transform_in->ivlen )
{
#if defined(POLARSSL_SSL_DEBUG_ALL)
SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
"should be no more than %d",
padlen, ssl->transform_in->ivlen ) );
#endif
correct = 0;
}
}
else
{
/*
* TLSv1+: always check the padding up to the first failure
* and fake check up to 256 bytes of padding
*/
size_t pad_count = 0, fake_pad_count = 0;
size_t padding_idx = ssl->in_msglen - padlen - 1;
for( i = 1; i <= padlen; i++ )
pad_count += ( ssl->in_msg[padding_idx + i] == padlen - 1 );
for( ; i <= 256; i++ )
fake_pad_count += ( ssl->in_msg[padding_idx + i] == padlen - 1 );
correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
correct &= ( pad_count + fake_pad_count < 512 ); /* Always 1 */
#if defined(POLARSSL_SSL_DEBUG_ALL)
if( padlen > 0 && correct == 0)
SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
#endif
padlen &= correct * 0x1FF;
}
}
SSL_DEBUG_BUF( 4, "raw buffer after decryption",
ssl->in_msg, ssl->in_msglen );
/*
* Always compute the MAC (RFC4346, CBCTIME).
*/
ssl->in_msglen -= ( ssl->transform_in->maclen + padlen );
ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 );
ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen );
memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen );
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->transform_in->maclen == 16 )
ssl_mac_md5( ssl->transform_in->mac_dec,
ssl->in_msg, ssl->in_msglen,
ssl->in_ctr, ssl->in_msgtype );
else if( ssl->transform_in->maclen == 20 )
ssl_mac_sha1( ssl->transform_in->mac_dec,
ssl->in_msg, ssl->in_msglen,
ssl->in_ctr, ssl->in_msgtype );
else if( ssl->transform_in->maclen == 32 )
ssl_mac_sha2( ssl->transform_in->mac_dec,
ssl->in_msg, ssl->in_msglen,
ssl->in_ctr, ssl->in_msgtype );
else if( ssl->transform_in->maclen != 0 )
{
SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d",
ssl->transform_in->maclen ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
else
{
/*
* Process MAC and always update for padlen afterwards to make
* total time independent of padlen
*
* extra_run compensates MAC check for padlen
*
* Known timing attacks:
* - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
*
* We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values
* correctly. (We round down instead of up, so -56 is the correct
* value for our calculations instead of -55)
*/
int j, extra_run = 0;
extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
( 13 + ssl->in_msglen + 8 ) / 64;
extra_run &= correct * 0xFF;
if( ssl->transform_in->maclen == 16 )
{
md5_context ctx;
md5_hmac_starts( &ctx, ssl->transform_in->mac_dec, 16 );
md5_hmac_update( &ctx, ssl->in_ctr, ssl->in_msglen + 13 );
md5_hmac_finish( &ctx, ssl->in_msg + ssl->in_msglen );
for( j = 0; j < extra_run; j++ )
md5_process( &ctx, ssl->in_msg );
}
else if( ssl->transform_in->maclen == 20 )
{
sha1_context ctx;
sha1_hmac_starts( &ctx, ssl->transform_in->mac_dec, 20 );
sha1_hmac_update( &ctx, ssl->in_ctr, ssl->in_msglen + 13 );
sha1_hmac_finish( &ctx, ssl->in_msg + ssl->in_msglen );
for( j = 0; j < extra_run; j++ )
sha1_process( &ctx, ssl->in_msg );
}
else if( ssl->transform_in->maclen == 32 )
{
sha2_context ctx;
sha2_hmac_starts( &ctx, ssl->transform_in->mac_dec, 32, 0 );
sha2_hmac_update( &ctx, ssl->in_ctr, ssl->in_msglen + 13 );
sha2_hmac_finish( &ctx, ssl->in_msg + ssl->in_msglen );
for( j = 0; j < extra_run; j++ )
sha2_process( &ctx, ssl->in_msg );
}
else if( ssl->transform_in->maclen != 0 )
{
SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d",
ssl->transform_in->maclen ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen );
SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen,
ssl->transform_in->maclen );
if( memcmp( tmp, ssl->in_msg + ssl->in_msglen,
ssl->transform_in->maclen ) != 0 )
{
#if defined(POLARSSL_SSL_DEBUG_ALL)
SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
#endif
correct = 0;
}
/*
* Finally check the correct flag
*/
if( correct == 0 )
return( POLARSSL_ERR_SSL_INVALID_MAC );
if( ssl->in_msglen == 0 )
{
ssl->nb_zero++;
/*
* Three or more empty messages may be a DoS attack
* (excessive CPU consumption).
*/
if( ssl->nb_zero > 3 )
{
SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
"messages, possible DoS attack" ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
}
else
ssl->nb_zero = 0;
for( i = 8; i > 0; i-- )
if( ++ssl->in_ctr[i - 1] != 0 )
break;
SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
return( 0 );
}
#if defined(POLARSSL_ZLIB_SUPPORT)
/*
* Compression/decompression functions
*/
static int ssl_compress_buf( ssl_context *ssl )
{
int ret;
unsigned char *msg_post = ssl->out_msg;
size_t len_pre = ssl->out_msglen;
unsigned char *msg_pre;
SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
msg_pre = (unsigned char*) malloc( len_pre );
if( msg_pre == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len_pre ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memcpy( msg_pre, ssl->out_msg, len_pre );
SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
ssl->out_msglen ) );
SSL_DEBUG_BUF( 4, "before compression: output payload",
ssl->out_msg, ssl->out_msglen );
ssl->transform_out->ctx_deflate.next_in = msg_pre;
ssl->transform_out->ctx_deflate.avail_in = len_pre;
ssl->transform_out->ctx_deflate.next_out = msg_post;
ssl->transform_out->ctx_deflate.avail_out = SSL_BUFFER_LEN;
ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
if( ret != Z_OK )
{
SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
}
ssl->out_msglen = SSL_BUFFER_LEN - ssl->transform_out->ctx_deflate.avail_out;
free( msg_pre );
SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
ssl->out_msglen ) );
SSL_DEBUG_BUF( 4, "after compression: output payload",
ssl->out_msg, ssl->out_msglen );
SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
return( 0 );
}
static int ssl_decompress_buf( ssl_context *ssl )
{
int ret;
unsigned char *msg_post = ssl->in_msg;
size_t len_pre = ssl->in_msglen;
unsigned char *msg_pre;
SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
msg_pre = (unsigned char*) malloc( len_pre );
if( msg_pre == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len_pre ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memcpy( msg_pre, ssl->in_msg, len_pre );
SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
ssl->in_msglen ) );
SSL_DEBUG_BUF( 4, "before decompression: input payload",
ssl->in_msg, ssl->in_msglen );
ssl->transform_in->ctx_inflate.next_in = msg_pre;
ssl->transform_in->ctx_inflate.avail_in = len_pre;
ssl->transform_in->ctx_inflate.next_out = msg_post;
ssl->transform_in->ctx_inflate.avail_out = SSL_MAX_CONTENT_LEN;
ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
if( ret != Z_OK )
{
SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
return( POLARSSL_ERR_SSL_COMPRESSION_FAILED );
}
ssl->in_msglen = SSL_MAX_CONTENT_LEN - ssl->transform_in->ctx_inflate.avail_out;
free( msg_pre );
SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
ssl->in_msglen ) );
SSL_DEBUG_BUF( 4, "after decompression: input payload",
ssl->in_msg, ssl->in_msglen );
SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
return( 0 );
}
#endif /* POLARSSL_ZLIB_SUPPORT */
/*
* Fill the input message buffer
*/
int ssl_fetch_input( ssl_context *ssl, size_t nb_want )
{
int ret;
size_t len;
SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
while( ssl->in_left < nb_want )
{
len = nb_want - ssl->in_left;
ret = ssl->f_recv( ssl->p_recv, ssl->in_hdr + ssl->in_left, len );
SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
ssl->in_left, nb_want ) );
SSL_DEBUG_RET( 2, "ssl->f_recv", ret );
if( ret == 0 )
return( POLARSSL_ERR_SSL_CONN_EOF );
if( ret < 0 )
return( ret );
ssl->in_left += ret;
}
SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
return( 0 );
}
/*
* Flush any data not yet written
*/
int ssl_flush_output( ssl_context *ssl )
{
int ret;
unsigned char *buf;
SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
while( ssl->out_left > 0 )
{
SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
5 + ssl->out_msglen, ssl->out_left ) );
if( ssl->out_msglen < ssl->out_left )
{
size_t header_left = ssl->out_left - ssl->out_msglen;
buf = ssl->out_hdr + 5 - header_left;
ret = ssl->f_send( ssl->p_send, buf, header_left );
SSL_DEBUG_RET( 2, "ssl->f_send (header)", ret );
if( ret <= 0 )
return( ret );
ssl->out_left -= ret;
}
buf = ssl->out_msg + ssl->out_msglen - ssl->out_left;
ret = ssl->f_send( ssl->p_send, buf, ssl->out_left );
SSL_DEBUG_RET( 2, "ssl->f_send", ret );
if( ret <= 0 )
return( ret );
ssl->out_left -= ret;
}
SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
return( 0 );
}
/*
* Record layer functions
*/
int ssl_write_record( ssl_context *ssl )
{
int ret, done = 0;
size_t len = ssl->out_msglen;
SSL_DEBUG_MSG( 2, ( "=> write record" ) );
if( ssl->out_msgtype == SSL_MSG_HANDSHAKE )
{
ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 );
ssl->out_msg[3] = (unsigned char)( ( len - 4 ) );
ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
}
#if defined(POLARSSL_ZLIB_SUPPORT)
if( ssl->transform_out != NULL &&
ssl->session_out->compression == SSL_COMPRESS_DEFLATE )
{
if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
return( ret );
}
len = ssl->out_msglen;
}
#endif /*POLARSSL_ZLIB_SUPPORT */
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
if( ssl_hw_record_write != NULL)
{
SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_write()" ) );
ret = ssl_hw_record_write( ssl );
if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH )
{
SSL_DEBUG_RET( 1, "ssl_hw_record_write", ret );
return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
}
done = 1;
}
#endif
if( !done )
{
ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
ssl->out_hdr[1] = (unsigned char) ssl->major_ver;
ssl->out_hdr[2] = (unsigned char) ssl->minor_ver;
ssl->out_hdr[3] = (unsigned char)( len >> 8 );
ssl->out_hdr[4] = (unsigned char)( len );
if( ssl->transform_out != NULL )
{
if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
return( ret );
}
len = ssl->out_msglen;
ssl->out_hdr[3] = (unsigned char)( len >> 8 );
ssl->out_hdr[4] = (unsigned char)( len );
}
ssl->out_left = 5 + ssl->out_msglen;
SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
"version = [%d:%d], msglen = %d",
ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
( ssl->out_hdr[3] << 8 ) | ssl->out_hdr[4] ) );
SSL_DEBUG_BUF( 4, "output record header sent to network",
ssl->out_hdr, 5 );
SSL_DEBUG_BUF( 4, "output record sent to network",
ssl->out_hdr + 32, ssl->out_msglen );
}
if( ( ret = ssl_flush_output( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= write record" ) );
return( 0 );
}
int ssl_read_record( ssl_context *ssl )
{
int ret, done = 0;
SSL_DEBUG_MSG( 2, ( "=> read record" ) );
if( ssl->in_hslen != 0 &&
ssl->in_hslen < ssl->in_msglen )
{
/*
* Get next Handshake message in the current record
*/
ssl->in_msglen -= ssl->in_hslen;
memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
ssl->in_msglen );
ssl->in_hslen = 4;
ssl->in_hslen += ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3];
SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
" %d, type = %d, hslen = %d",
ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
if( ssl->in_msglen < 4 || ssl->in_msg[1] != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
if( ssl->in_msglen < ssl->in_hslen )
{
SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
return( 0 );
}
ssl->in_hslen = 0;
/*
* Read the record header and validate it
*/
if( ( ret = ssl_fetch_input( ssl, 5 ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
return( ret );
}
ssl->in_msgtype = ssl->in_hdr[0];
ssl->in_msglen = ( ssl->in_hdr[3] << 8 ) | ssl->in_hdr[4];
SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
"version = [%d:%d], msglen = %d",
ssl->in_hdr[0], ssl->in_hdr[1], ssl->in_hdr[2],
( ssl->in_hdr[3] << 8 ) | ssl->in_hdr[4] ) );
if( ssl->in_hdr[1] != ssl->major_ver )
{
SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
if( ssl->in_hdr[2] > ssl->max_minor_ver )
{
SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
/*
* Make sure the message length is acceptable
*/
if( ssl->transform_in == NULL )
{
if( ssl->in_msglen < 1 ||
ssl->in_msglen > SSL_MAX_CONTENT_LEN )
{
SSL_DEBUG_MSG( 1, ( "bad message length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
}
else
{
if( ssl->in_msglen < ssl->transform_in->minlen )
{
SSL_DEBUG_MSG( 1, ( "bad message length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
if( ssl->minor_ver == SSL_MINOR_VERSION_0 &&
ssl->in_msglen > ssl->transform_in->minlen + SSL_MAX_CONTENT_LEN )
{
SSL_DEBUG_MSG( 1, ( "bad message length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
/*
* TLS encrypted messages can have up to 256 bytes of padding
*/
if( ssl->minor_ver >= SSL_MINOR_VERSION_1 &&
ssl->in_msglen > ssl->transform_in->minlen + SSL_MAX_CONTENT_LEN + 256 )
{
SSL_DEBUG_MSG( 1, ( "bad message length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
}
/*
* Read and optionally decrypt the message contents
*/
if( ( ret = ssl_fetch_input( ssl, 5 + ssl->in_msglen ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_fetch_input", ret );
return( ret );
}
SSL_DEBUG_BUF( 4, "input record from network",
ssl->in_hdr, 5 + ssl->in_msglen );
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
if( ssl_hw_record_read != NULL)
{
SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_read()" ) );
ret = ssl_hw_record_read( ssl );
if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH )
{
SSL_DEBUG_RET( 1, "ssl_hw_record_read", ret );
return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
}
done = 1;
}
#endif
if( !done && ssl->transform_in != NULL )
{
if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
{
#if defined(POLARSSL_SSL_ALERT_MESSAGES)
if( ret == POLARSSL_ERR_SSL_INVALID_MAC )
{
ssl_send_alert_message( ssl,
SSL_ALERT_LEVEL_FATAL,
SSL_ALERT_MSG_BAD_RECORD_MAC );
}
#endif
SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
return( ret );
}
SSL_DEBUG_BUF( 4, "input payload after decrypt",
ssl->in_msg, ssl->in_msglen );
if( ssl->in_msglen > SSL_MAX_CONTENT_LEN )
{
SSL_DEBUG_MSG( 1, ( "bad message length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
}
#if defined(POLARSSL_ZLIB_SUPPORT)
if( ssl->transform_in != NULL &&
ssl->session_in->compression == SSL_COMPRESS_DEFLATE )
{
if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
return( ret );
}
ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 );
ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen );
}
#endif /* POLARSSL_ZLIB_SUPPORT */
if( ssl->in_msgtype != SSL_MSG_HANDSHAKE &&
ssl->in_msgtype != SSL_MSG_ALERT &&
ssl->in_msgtype != SSL_MSG_CHANGE_CIPHER_SPEC &&
ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
{
SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
if( ( ret = ssl_send_alert_message( ssl,
SSL_ALERT_LEVEL_FATAL,
SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 )
{
return( ret );
}
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
if( ssl->in_msgtype == SSL_MSG_HANDSHAKE )
{
ssl->in_hslen = 4;
ssl->in_hslen += ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3];
SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
" %d, type = %d, hslen = %d",
ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
/*
* Additional checks to validate the handshake header
*/
if( ssl->in_msglen < 4 || ssl->in_msg[1] != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
if( ssl->in_msglen < ssl->in_hslen )
{
SSL_DEBUG_MSG( 1, ( "bad handshake length" ) );
return( POLARSSL_ERR_SSL_INVALID_RECORD );
}
if( ssl->state != SSL_HANDSHAKE_OVER )
ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
}
if( ssl->in_msgtype == SSL_MSG_ALERT )
{
SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
ssl->in_msg[0], ssl->in_msg[1] ) );
/*
* Ignore non-fatal alerts, except close_notify
*/
if( ssl->in_msg[0] == SSL_ALERT_LEVEL_FATAL )
{
SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
ssl->in_msg[1] ) );
/**
* Subtract from error code as ssl->in_msg[1] is 7-bit positive
* error identifier.
*/
return( POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE );
}
if( ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING &&
ssl->in_msg[1] == SSL_ALERT_MSG_CLOSE_NOTIFY )
{
SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
return( POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY );
}
}
ssl->in_left = 0;
SSL_DEBUG_MSG( 2, ( "<= read record" ) );
return( 0 );
}
int ssl_send_fatal_handshake_failure( ssl_context *ssl )
{
int ret;
if( ( ret = ssl_send_alert_message( ssl,
SSL_ALERT_LEVEL_FATAL,
SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
{
return( ret );
}
return( 0 );
}
int ssl_send_alert_message( ssl_context *ssl,
unsigned char level,
unsigned char message )
{
int ret;
SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
ssl->out_msgtype = SSL_MSG_ALERT;
ssl->out_msglen = 2;
ssl->out_msg[0] = level;
ssl->out_msg[1] = message;
if( ( ret = ssl_write_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_write_record", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
return( 0 );
}
/*
* Handshake functions
*/
int ssl_write_certificate( ssl_context *ssl )
{
int ret;
size_t i, n;
const x509_cert *crt;
SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
if( ssl->endpoint == SSL_IS_CLIENT )
{
if( ssl->client_auth == 0 )
{
SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
ssl->state++;
return( 0 );
}
/*
* If using SSLv3 and got no cert, send an Alert message
* (otherwise an empty Certificate message will be sent).
*/
if( ssl->own_cert == NULL &&
ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
ssl->out_msglen = 2;
ssl->out_msgtype = SSL_MSG_ALERT;
ssl->out_msg[0] = SSL_ALERT_LEVEL_WARNING;
ssl->out_msg[1] = SSL_ALERT_MSG_NO_CERT;
SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
goto write_msg;
}
}
else /* SSL_IS_SERVER */
{
if( ssl->own_cert == NULL )
{
SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
return( POLARSSL_ERR_SSL_CERTIFICATE_REQUIRED );
}
}
SSL_DEBUG_CRT( 3, "own certificate", ssl->own_cert );
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 6 length of all certs
* 7 . 9 length of cert. 1
* 10 . n-1 peer certificate
* n . n+2 length of cert. 2
* n+3 . ... upper level cert, etc.
*/
i = 7;
crt = ssl->own_cert;
while( crt != NULL )
{
n = crt->raw.len;
if( i + 3 + n > SSL_MAX_CONTENT_LEN )
{
SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
i + 3 + n, SSL_MAX_CONTENT_LEN ) );
return( POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE );
}
ssl->out_msg[i ] = (unsigned char)( n >> 16 );
ssl->out_msg[i + 1] = (unsigned char)( n >> 8 );
ssl->out_msg[i + 2] = (unsigned char)( n );
i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
i += n; crt = crt->next;
}
ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 );
ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 );
ssl->out_msg[6] = (unsigned char)( ( i - 7 ) );
ssl->out_msglen = i;
ssl->out_msgtype = SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = SSL_HS_CERTIFICATE;
write_msg:
ssl->state++;
if( ( ret = ssl_write_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_write_record", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
return( 0 );
}
int ssl_parse_certificate( ssl_context *ssl )
{
int ret;
size_t i, n;
SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->authmode == SSL_VERIFY_NONE )
{
ssl->verify_result = BADCERT_SKIP_VERIFY;
SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
ssl->state++;
return( 0 );
}
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
ssl->state++;
/*
* Check if the client sent an empty certificate
*/
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->in_msglen == 2 &&
ssl->in_msgtype == SSL_MSG_ALERT &&
ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING &&
ssl->in_msg[1] == SSL_ALERT_MSG_NO_CERT )
{
SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_OPTIONAL )
return( 0 );
else
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
}
}
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver != SSL_MINOR_VERSION_0 )
{
if( ssl->in_hslen == 7 &&
ssl->in_msgtype == SSL_MSG_HANDSHAKE &&
ssl->in_msg[0] == SSL_HS_CERTIFICATE &&
memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 )
{
SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_REQUIRED )
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
else
return( 0 );
}
}
if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
/*
* Same message structure as in ssl_write_certificate()
*/
n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6];
if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
if( ( ssl->session_negotiate->peer_cert = (x509_cert *) malloc(
sizeof( x509_cert ) ) ) == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
sizeof( x509_cert ) ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memset( ssl->session_negotiate->peer_cert, 0, sizeof( x509_cert ) );
i = 7;
while( i < ssl->in_hslen )
{
if( ssl->in_msg[i] != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
| (unsigned int) ssl->in_msg[i + 2];
i += 3;
if( n < 128 || i + n > ssl->in_hslen )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
ret = x509parse_crt_der( ssl->session_negotiate->peer_cert,
ssl->in_msg + i, n );
if( ret != 0 )
{
SSL_DEBUG_RET( 1, " x509parse_crt", ret );
return( ret );
}
i += n;
}
SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
if( ssl->authmode != SSL_VERIFY_NONE )
{
if( ssl->ca_chain == NULL )
{
SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED );
}
ret = x509parse_verify( ssl->session_negotiate->peer_cert,
ssl->ca_chain, ssl->ca_crl,
ssl->peer_cn, &ssl->verify_result,
ssl->f_vrfy, ssl->p_vrfy );
if( ret != 0 )
SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
if( ssl->authmode != SSL_VERIFY_REQUIRED )
ret = 0;
}
SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
return( ret );
}
int ssl_write_change_cipher_spec( ssl_context *ssl )
{
int ret;
SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
ssl->out_msgtype = SSL_MSG_CHANGE_CIPHER_SPEC;
ssl->out_msglen = 1;
ssl->out_msg[0] = 1;
ssl->state++;
if( ( ret = ssl_write_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_write_record", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
return( 0 );
}
int ssl_parse_change_cipher_spec( ssl_context *ssl )
{
int ret;
SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != SSL_MSG_CHANGE_CIPHER_SPEC )
{
SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )
{
SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );
}
ssl->state++;
SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
return( 0 );
}
void ssl_optimize_checksum( ssl_context *ssl, int ciphersuite )
{
#if !defined(POLARSSL_SHA4_C)
((void) ciphersuite);
#endif
if( ssl->minor_ver < SSL_MINOR_VERSION_3 )
ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
#if defined(POLARSSL_SHA4_C)
else if ( ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 ||
ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 )
{
ssl->handshake->update_checksum = ssl_update_checksum_sha384;
}
#endif
else
ssl->handshake->update_checksum = ssl_update_checksum_sha256;
}
static void ssl_update_checksum_start( ssl_context *ssl, unsigned char *buf,
size_t len )
{
md5_update( &ssl->handshake->fin_md5 , buf, len );
sha1_update( &ssl->handshake->fin_sha1, buf, len );
sha2_update( &ssl->handshake->fin_sha2, buf, len );
#if defined(POLARSSL_SHA4_C)
sha4_update( &ssl->handshake->fin_sha4, buf, len );
#endif
}
static void ssl_update_checksum_md5sha1( ssl_context *ssl, unsigned char *buf,
size_t len )
{
md5_update( &ssl->handshake->fin_md5 , buf, len );
sha1_update( &ssl->handshake->fin_sha1, buf, len );
}
static void ssl_update_checksum_sha256( ssl_context *ssl, unsigned char *buf,
size_t len )
{
sha2_update( &ssl->handshake->fin_sha2, buf, len );
}
#if defined(POLARSSL_SHA4_C)
static void ssl_update_checksum_sha384( ssl_context *ssl, unsigned char *buf,
size_t len )
{
sha4_update( &ssl->handshake->fin_sha4, buf, len );
}
#endif
static void ssl_calc_finished_ssl(
ssl_context *ssl, unsigned char *buf, int from )
{
const char *sender;
md5_context md5;
sha1_context sha1;
unsigned char padbuf[48];
unsigned char md5sum[16];
unsigned char sha1sum[20];
ssl_session *session = ssl->session_negotiate;
if( !session )
session = ssl->session;
SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) );
memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) );
memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
/*
* SSLv3:
* hash =
* MD5( master + pad2 +
* MD5( handshake + sender + master + pad1 ) )
* + SHA1( master + pad2 +
* SHA1( handshake + sender + master + pad1 ) )
*/
SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
md5.state, sizeof( md5.state ) );
SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
sha1.state, sizeof( sha1.state ) );
sender = ( from == SSL_IS_CLIENT ) ? "CLNT"
: "SRVR";
memset( padbuf, 0x36, 48 );
md5_update( &md5, (const unsigned char *) sender, 4 );
md5_update( &md5, session->master, 48 );
md5_update( &md5, padbuf, 48 );
md5_finish( &md5, md5sum );
sha1_update( &sha1, (const unsigned char *) sender, 4 );
sha1_update( &sha1, session->master, 48 );
sha1_update( &sha1, padbuf, 40 );
sha1_finish( &sha1, sha1sum );
memset( padbuf, 0x5C, 48 );
md5_starts( &md5 );
md5_update( &md5, session->master, 48 );
md5_update( &md5, padbuf, 48 );
md5_update( &md5, md5sum, 16 );
md5_finish( &md5, buf );
sha1_starts( &sha1 );
sha1_update( &sha1, session->master, 48 );
sha1_update( &sha1, padbuf , 40 );
sha1_update( &sha1, sha1sum, 20 );
sha1_finish( &sha1, buf + 16 );
SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
memset( &md5, 0, sizeof( md5_context ) );
memset( &sha1, 0, sizeof( sha1_context ) );
memset( padbuf, 0, sizeof( padbuf ) );
memset( md5sum, 0, sizeof( md5sum ) );
memset( sha1sum, 0, sizeof( sha1sum ) );
SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
}
static void ssl_calc_finished_tls(
ssl_context *ssl, unsigned char *buf, int from )
{
int len = 12;
const char *sender;
md5_context md5;
sha1_context sha1;
unsigned char padbuf[36];
ssl_session *session = ssl->session_negotiate;
if( !session )
session = ssl->session;
SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) );
memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) );
memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) );
/*
* TLSv1:
* hash = PRF( master, finished_label,
* MD5( handshake ) + SHA1( handshake ) )[0..11]
*/
SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *)
md5.state, sizeof( md5.state ) );
SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
sha1.state, sizeof( sha1.state ) );
sender = ( from == SSL_IS_CLIENT )
? "client finished"
: "server finished";
md5_finish( &md5, padbuf );
sha1_finish( &sha1, padbuf + 16 );
ssl->handshake->tls_prf( session->master, 48, (char *) sender,
padbuf, 36, buf, len );
SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
memset( &md5, 0, sizeof( md5_context ) );
memset( &sha1, 0, sizeof( sha1_context ) );
memset( padbuf, 0, sizeof( padbuf ) );
SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
}
static void ssl_calc_finished_tls_sha256(
ssl_context *ssl, unsigned char *buf, int from )
{
int len = 12;
const char *sender;
sha2_context sha2;
unsigned char padbuf[32];
ssl_session *session = ssl->session_negotiate;
if( !session )
session = ssl->session;
SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) );
memcpy( &sha2, &ssl->handshake->fin_sha2, sizeof(sha2_context) );
/*
* TLSv1.2:
* hash = PRF( master, finished_label,
* Hash( handshake ) )[0.11]
*/
SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
sha2.state, sizeof( sha2.state ) );
sender = ( from == SSL_IS_CLIENT )
? "client finished"
: "server finished";
sha2_finish( &sha2, padbuf );
ssl->handshake->tls_prf( session->master, 48, (char *) sender,
padbuf, 32, buf, len );
SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
memset( &sha2, 0, sizeof( sha2_context ) );
memset( padbuf, 0, sizeof( padbuf ) );
SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
}
#if defined(POLARSSL_SHA4_C)
static void ssl_calc_finished_tls_sha384(
ssl_context *ssl, unsigned char *buf, int from )
{
int len = 12;
const char *sender;
sha4_context sha4;
unsigned char padbuf[48];
ssl_session *session = ssl->session_negotiate;
if( !session )
session = ssl->session;
SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) );
memcpy( &sha4, &ssl->handshake->fin_sha4, sizeof(sha4_context) );
/*
* TLSv1.2:
* hash = PRF( master, finished_label,
* Hash( handshake ) )[0.11]
*/
SSL_DEBUG_BUF( 4, "finished sha4 state", (unsigned char *)
sha4.state, sizeof( sha4.state ) );
sender = ( from == SSL_IS_CLIENT )
? "client finished"
: "server finished";
sha4_finish( &sha4, padbuf );
ssl->handshake->tls_prf( session->master, 48, (char *) sender,
padbuf, 48, buf, len );
SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
memset( &sha4, 0, sizeof( sha4_context ) );
memset( padbuf, 0, sizeof( padbuf ) );
SSL_DEBUG_MSG( 2, ( "<= calc finished" ) );
}
#endif
void ssl_handshake_wrapup( ssl_context *ssl )
{
SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
/*
* Free our handshake params
*/
ssl_handshake_free( ssl->handshake );
free( ssl->handshake );
ssl->handshake = NULL;
/*
* Switch in our now active transform context
*/
if( ssl->transform )
{
ssl_transform_free( ssl->transform );
free( ssl->transform );
}
ssl->transform = ssl->transform_negotiate;
ssl->transform_negotiate = NULL;
if( ssl->session )
{
ssl_session_free( ssl->session );
free( ssl->session );
}
ssl->session = ssl->session_negotiate;
ssl->session_negotiate = NULL;
/*
* Add cache entry
*/
if( ssl->f_set_cache != NULL )
if( ssl->f_set_cache( ssl->p_set_cache, ssl->session ) != 0 )
SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
ssl->state++;
SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
}
int ssl_write_finished( ssl_context *ssl )
{
int ret, hash_len;
SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->endpoint );
// TODO TLS/1.2 Hash length is determined by cipher suite (Page 63)
hash_len = ( ssl->minor_ver == SSL_MINOR_VERSION_0 ) ? 36 : 12;
ssl->verify_data_len = hash_len;
memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
ssl->out_msglen = 4 + hash_len;
ssl->out_msgtype = SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = SSL_HS_FINISHED;
/*
* In case of session resuming, invert the client and server
* ChangeCipherSpec messages order.
*/
if( ssl->handshake->resume != 0 )
{
if( ssl->endpoint == SSL_IS_CLIENT )
ssl->state = SSL_HANDSHAKE_WRAPUP;
else
ssl->state = SSL_CLIENT_CHANGE_CIPHER_SPEC;
}
else
ssl->state++;
/*
* Switch to our negotiated transform and session parameters for outbound data.
*/
SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
ssl->transform_out = ssl->transform_negotiate;
ssl->session_out = ssl->session_negotiate;
memset( ssl->out_ctr, 0, 8 );
if( ( ret = ssl_write_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_write_record", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
return( 0 );
}
int ssl_parse_finished( ssl_context *ssl )
{
int ret;
unsigned int hash_len;
unsigned char buf[36];
SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
ssl->handshake->calc_finished( ssl, buf, ssl->endpoint ^ 1 );
/*
* Switch to our negotiated transform and session parameters for inbound data.
*/
SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
ssl->transform_in = ssl->transform_negotiate;
ssl->session_in = ssl->session_negotiate;
memset( ssl->in_ctr, 0, 8 );
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
{
SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
// TODO TLS/1.2 Hash length is determined by cipher suite (Page 63)
hash_len = ( ssl->minor_ver == SSL_MINOR_VERSION_0 ) ? 36 : 12;
if( ssl->in_msg[0] != SSL_HS_FINISHED ||
ssl->in_hslen != 4 + hash_len )
{
SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_FINISHED );
}
if( memcmp( ssl->in_msg + 4, buf, hash_len ) != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_FINISHED );
}
ssl->verify_data_len = hash_len;
memcpy( ssl->peer_verify_data, buf, hash_len );
if( ssl->handshake->resume != 0 )
{
if( ssl->endpoint == SSL_IS_CLIENT )
ssl->state = SSL_CLIENT_CHANGE_CIPHER_SPEC;
if( ssl->endpoint == SSL_IS_SERVER )
ssl->state = SSL_HANDSHAKE_WRAPUP;
}
else
ssl->state++;
SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
return( 0 );
}
int ssl_handshake_init( ssl_context *ssl )
{
if( ssl->transform_negotiate )
ssl_transform_free( ssl->transform_negotiate );
else
ssl->transform_negotiate = malloc( sizeof(ssl_transform) );
if( ssl->session_negotiate )
ssl_session_free( ssl->session_negotiate );
else
ssl->session_negotiate = malloc( sizeof(ssl_session) );
if( ssl->handshake )
ssl_handshake_free( ssl->handshake );
else
ssl->handshake = malloc( sizeof(ssl_handshake_params) );
if( ssl->handshake == NULL ||
ssl->transform_negotiate == NULL ||
ssl->session_negotiate == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc() of ssl sub-contexts failed" ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memset( ssl->handshake, 0, sizeof(ssl_handshake_params) );
memset( ssl->transform_negotiate, 0, sizeof(ssl_transform) );
memset( ssl->session_negotiate, 0, sizeof(ssl_session) );
md5_starts( &ssl->handshake->fin_md5 );
sha1_starts( &ssl->handshake->fin_sha1 );
sha2_starts( &ssl->handshake->fin_sha2, 0 );
#if defined(POLARSSL_SHA4_C)
sha4_starts( &ssl->handshake->fin_sha4, 1 );
#endif
ssl->handshake->update_checksum = ssl_update_checksum_start;
ssl->handshake->sig_alg = SSL_HASH_SHA1;
return( 0 );
}
/*
* Initialize an SSL context
*/
int ssl_init( ssl_context *ssl )
{
int ret;
int len = SSL_BUFFER_LEN;
memset( ssl, 0, sizeof( ssl_context ) );
/*
* Sane defaults
*/
ssl->rsa_decrypt = ssl_rsa_decrypt;
ssl->rsa_sign = ssl_rsa_sign;
ssl->rsa_key_len = ssl_rsa_key_len;
ssl->min_major_ver = SSL_MAJOR_VERSION_3;
ssl->min_minor_ver = SSL_MINOR_VERSION_0;
ssl->ciphersuites = malloc( sizeof(int *) * 4 );
ssl_set_ciphersuites( ssl, ssl_default_ciphersuites );
#if defined(POLARSSL_DHM_C)
if( ( ret = mpi_read_string( &ssl->dhm_P, 16,
POLARSSL_DHM_RFC5114_MODP_1024_P) ) != 0 ||
( ret = mpi_read_string( &ssl->dhm_G, 16,
POLARSSL_DHM_RFC5114_MODP_1024_G) ) != 0 )
{
SSL_DEBUG_RET( 1, "mpi_read_string", ret );
return( ret );
}
#endif
/*
* Prepare base structures
*/
ssl->in_ctr = (unsigned char *) malloc( len );
ssl->in_hdr = ssl->in_ctr + 8;
ssl->in_msg = ssl->in_ctr + 13;
if( ssl->in_ctr == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
ssl->out_ctr = (unsigned char *) malloc( len );
ssl->out_hdr = ssl->out_ctr + 8;
ssl->out_msg = ssl->out_ctr + 40;
if( ssl->out_ctr == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) );
free( ssl-> in_ctr );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memset( ssl-> in_ctr, 0, SSL_BUFFER_LEN );
memset( ssl->out_ctr, 0, SSL_BUFFER_LEN );
ssl->hostname = NULL;
ssl->hostname_len = 0;
if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
return( ret );
return( 0 );
}
/*
* Reset an initialized and used SSL context for re-use while retaining
* all application-set variables, function pointers and data.
*/
int ssl_session_reset( ssl_context *ssl )
{
int ret;
ssl->state = SSL_HELLO_REQUEST;
ssl->renegotiation = SSL_INITIAL_HANDSHAKE;
ssl->secure_renegotiation = SSL_LEGACY_RENEGOTIATION;
ssl->verify_data_len = 0;
memset( ssl->own_verify_data, 0, 36 );
memset( ssl->peer_verify_data, 0, 36 );
ssl->in_offt = NULL;
ssl->in_msgtype = 0;
ssl->in_msglen = 0;
ssl->in_left = 0;
ssl->in_hslen = 0;
ssl->nb_zero = 0;
ssl->out_msgtype = 0;
ssl->out_msglen = 0;
ssl->out_left = 0;
ssl->transform_in = NULL;
ssl->transform_out = NULL;
memset( ssl->out_ctr, 0, SSL_BUFFER_LEN );
memset( ssl->in_ctr, 0, SSL_BUFFER_LEN );
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
if( ssl_hw_record_reset != NULL)
{
SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_reset()" ) );
if( ssl_hw_record_reset( ssl ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_hw_record_reset", ret );
return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED );
}
}
#endif
if( ssl->transform )
{
ssl_transform_free( ssl->transform );
free( ssl->transform );
ssl->transform = NULL;
}
if( ssl->session )
{
ssl_session_free( ssl->session );
free( ssl->session );
ssl->session = NULL;
}
if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
return( ret );
return( 0 );
}
/*
* SSL set accessors
*/
void ssl_set_endpoint( ssl_context *ssl, int endpoint )
{
ssl->endpoint = endpoint;
}
void ssl_set_authmode( ssl_context *ssl, int authmode )
{
ssl->authmode = authmode;
}
void ssl_set_verify( ssl_context *ssl,
int (*f_vrfy)(void *, x509_cert *, int, int *),
void *p_vrfy )
{
ssl->f_vrfy = f_vrfy;
ssl->p_vrfy = p_vrfy;
}
void ssl_set_rng( ssl_context *ssl,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ssl->f_rng = f_rng;
ssl->p_rng = p_rng;
}
void ssl_set_dbg( ssl_context *ssl,
void (*f_dbg)(void *, int, const char *),
void *p_dbg )
{
ssl->f_dbg = f_dbg;
ssl->p_dbg = p_dbg;
}
void ssl_set_bio( ssl_context *ssl,
int (*f_recv)(void *, unsigned char *, size_t), void *p_recv,
int (*f_send)(void *, const unsigned char *, size_t), void *p_send )
{
ssl->f_recv = f_recv;
ssl->f_send = f_send;
ssl->p_recv = p_recv;
ssl->p_send = p_send;
}
void ssl_set_session_cache( ssl_context *ssl,
int (*f_get_cache)(void *, ssl_session *), void *p_get_cache,
int (*f_set_cache)(void *, const ssl_session *), void *p_set_cache )
{
ssl->f_get_cache = f_get_cache;
ssl->p_get_cache = p_get_cache;
ssl->f_set_cache = f_set_cache;
ssl->p_set_cache = p_set_cache;
}
void ssl_set_session( ssl_context *ssl, const ssl_session *session )
{
memcpy( ssl->session_negotiate, session, sizeof(ssl_session) );
ssl->handshake->resume = 1;
}
void ssl_set_ciphersuites( ssl_context *ssl, const int *ciphersuites )
{
ssl->ciphersuites[SSL_MINOR_VERSION_0] = ciphersuites;
ssl->ciphersuites[SSL_MINOR_VERSION_1] = ciphersuites;
ssl->ciphersuites[SSL_MINOR_VERSION_2] = ciphersuites;
ssl->ciphersuites[SSL_MINOR_VERSION_3] = ciphersuites;
}
void ssl_set_ciphersuites_for_version( ssl_context *ssl, const int *ciphersuites,
int major, int minor )
{
if( major != SSL_MAJOR_VERSION_3 )
return;
if( minor < SSL_MINOR_VERSION_0 || minor > SSL_MINOR_VERSION_3 )
return;
ssl->ciphersuites[minor] = ciphersuites;
}
void ssl_set_ca_chain( ssl_context *ssl, x509_cert *ca_chain,
x509_crl *ca_crl, const char *peer_cn )
{
ssl->ca_chain = ca_chain;
ssl->ca_crl = ca_crl;
ssl->peer_cn = peer_cn;
}
void ssl_set_own_cert( ssl_context *ssl, x509_cert *own_cert,
rsa_context *rsa_key )
{
ssl->own_cert = own_cert;
ssl->rsa_key = rsa_key;
}
void ssl_set_own_cert_alt( ssl_context *ssl, x509_cert *own_cert,
void *rsa_key,
rsa_decrypt_func rsa_decrypt,
rsa_sign_func rsa_sign,
rsa_key_len_func rsa_key_len )
{
ssl->own_cert = own_cert;
ssl->rsa_key = rsa_key;
ssl->rsa_decrypt = rsa_decrypt;
ssl->rsa_sign = rsa_sign;
ssl->rsa_key_len = rsa_key_len;
}
#if defined(POLARSSL_DHM_C)
int ssl_set_dh_param( ssl_context *ssl, const char *dhm_P, const char *dhm_G )
{
int ret;
if( ( ret = mpi_read_string( &ssl->dhm_P, 16, dhm_P ) ) != 0 )
{
SSL_DEBUG_RET( 1, "mpi_read_string", ret );
return( ret );
}
if( ( ret = mpi_read_string( &ssl->dhm_G, 16, dhm_G ) ) != 0 )
{
SSL_DEBUG_RET( 1, "mpi_read_string", ret );
return( ret );
}
return( 0 );
}
int ssl_set_dh_param_ctx( ssl_context *ssl, dhm_context *dhm_ctx )
{
int ret;
if( ( ret = mpi_copy(&ssl->dhm_P, &dhm_ctx->P) ) != 0 )
{
SSL_DEBUG_RET( 1, "mpi_copy", ret );
return( ret );
}
if( ( ret = mpi_copy(&ssl->dhm_G, &dhm_ctx->G) ) != 0 )
{
SSL_DEBUG_RET( 1, "mpi_copy", ret );
return( ret );
}
return( 0 );
}
#endif /* POLARSSL_DHM_C */
int ssl_set_hostname( ssl_context *ssl, const char *hostname )
{
if( hostname == NULL )
return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
ssl->hostname_len = strlen( hostname );
ssl->hostname = (unsigned char *) malloc( ssl->hostname_len + 1 );
if( ssl->hostname == NULL )
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
memcpy( ssl->hostname, (const unsigned char *) hostname,
ssl->hostname_len );
ssl->hostname[ssl->hostname_len] = '\0';
return( 0 );
}
void ssl_set_sni( ssl_context *ssl,
int (*f_sni)(void *, ssl_context *,
const unsigned char *, size_t),
void *p_sni )
{
ssl->f_sni = f_sni;
ssl->p_sni = p_sni;
}
void ssl_set_max_version( ssl_context *ssl, int major, int minor )
{
ssl->max_major_ver = major;
ssl->max_minor_ver = minor;
}
void ssl_set_min_version( ssl_context *ssl, int major, int minor )
{
ssl->min_major_ver = major;
ssl->min_minor_ver = minor;
}
void ssl_set_renegotiation( ssl_context *ssl, int renegotiation )
{
ssl->disable_renegotiation = renegotiation;
}
void ssl_legacy_renegotiation( ssl_context *ssl, int allow_legacy )
{
ssl->allow_legacy_renegotiation = allow_legacy;
}
/*
* SSL get accessors
*/
size_t ssl_get_bytes_avail( const ssl_context *ssl )
{
return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
}
int ssl_get_verify_result( const ssl_context *ssl )
{
return( ssl->verify_result );
}
const char *ssl_get_ciphersuite_name( const int ciphersuite_id )
{
switch( ciphersuite_id )
{
#if defined(POLARSSL_ARC4_C)
case TLS_RSA_WITH_RC4_128_MD5:
return( "TLS-RSA-WITH-RC4-128-MD5" );
case TLS_RSA_WITH_RC4_128_SHA:
return( "TLS-RSA-WITH-RC4-128-SHA" );
#endif
#if defined(POLARSSL_DES_C)
case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
return( "TLS-RSA-WITH-3DES-EDE-CBC-SHA" );
case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
return( "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA" );
#endif
#if defined(POLARSSL_AES_C)
case TLS_RSA_WITH_AES_128_CBC_SHA:
return( "TLS-RSA-WITH-AES-128-CBC-SHA" );
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
return( "TLS-DHE-RSA-WITH-AES-128-CBC-SHA" );
case TLS_RSA_WITH_AES_256_CBC_SHA:
return( "TLS-RSA-WITH-AES-256-CBC-SHA" );
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
return( "TLS-DHE-RSA-WITH-AES-256-CBC-SHA" );
#if defined(POLARSSL_SHA2_C)
case TLS_RSA_WITH_AES_128_CBC_SHA256:
return( "TLS-RSA-WITH-AES-128-CBC-SHA256" );
case TLS_RSA_WITH_AES_256_CBC_SHA256:
return( "TLS-RSA-WITH-AES-256-CBC-SHA256" );
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
return( "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256" );
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
return( "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256" );
#endif
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C)
case TLS_RSA_WITH_AES_128_GCM_SHA256:
return( "TLS-RSA-WITH-AES-128-GCM-SHA256" );
case TLS_RSA_WITH_AES_256_GCM_SHA384:
return( "TLS-RSA-WITH-AES-256-GCM-SHA384" );
#endif
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA4_C)
case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
return( "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256" );
case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
return( "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384" );
#endif
#endif /* POLARSSL_AES_C */
#if defined(POLARSSL_CAMELLIA_C)
case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
return( "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA" );
case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
return( "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA" );
case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
return( "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA" );
case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
return( "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA" );
#if defined(POLARSSL_SHA2_C)
case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
return( "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256" );
case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
return( "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256" );
case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
return( "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256" );
case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
return( "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256" );
#endif
#endif
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
case TLS_RSA_WITH_NULL_MD5:
return( "TLS-RSA-WITH-NULL-MD5" );
case TLS_RSA_WITH_NULL_SHA:
return( "TLS-RSA-WITH-NULL-SHA" );
case TLS_RSA_WITH_NULL_SHA256:
return( "TLS-RSA-WITH-NULL-SHA256" );
#endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */
#if defined(POLARSSL_DES_C)
case TLS_RSA_WITH_DES_CBC_SHA:
return( "TLS-RSA-WITH-DES-CBC-SHA" );
case TLS_DHE_RSA_WITH_DES_CBC_SHA:
return( "TLS-DHE-RSA-WITH-DES-CBC-SHA" );
#endif
#endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */
default:
break;
}
return( "unknown" );
}
int ssl_get_ciphersuite_id( const char *ciphersuite_name )
{
#if defined(POLARSSL_ARC4_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-RC4-128-MD5"))
return( TLS_RSA_WITH_RC4_128_MD5 );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-RC4-128-SHA"))
return( TLS_RSA_WITH_RC4_128_SHA );
#endif
#if defined(POLARSSL_DES_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-3DES-EDE-CBC-SHA"))
return( TLS_RSA_WITH_3DES_EDE_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA"))
return( TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA );
#endif
#if defined(POLARSSL_AES_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-128-CBC-SHA"))
return( TLS_RSA_WITH_AES_128_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA"))
return( TLS_DHE_RSA_WITH_AES_128_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-256-CBC-SHA"))
return( TLS_RSA_WITH_AES_256_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-256-CBC-SHA"))
return( TLS_DHE_RSA_WITH_AES_256_CBC_SHA );
#if defined(POLARSSL_SHA2_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-128-CBC-SHA256"))
return( TLS_RSA_WITH_AES_128_CBC_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-256-CBC-SHA256"))
return( TLS_RSA_WITH_AES_256_CBC_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256"))
return( TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"))
return( TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 );
#endif
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-128-GCM-SHA256"))
return( TLS_RSA_WITH_AES_128_GCM_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-256-GCM-SHA384"))
return( TLS_RSA_WITH_AES_256_GCM_SHA384 );
#endif
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256"))
return( TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384"))
return( TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 );
#endif
#endif
#if defined(POLARSSL_CAMELLIA_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA"))
return( TLS_RSA_WITH_CAMELLIA_128_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA"))
return( TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA"))
return( TLS_RSA_WITH_CAMELLIA_256_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA"))
return( TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA );
#if defined(POLARSSL_SHA2_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256"))
return( TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256"))
return( TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256"))
return( TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256"))
return( TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 );
#endif
#endif
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-NULL-MD5"))
return( TLS_RSA_WITH_NULL_MD5 );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-NULL-SHA"))
return( TLS_RSA_WITH_NULL_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-NULL-SHA256"))
return( TLS_RSA_WITH_NULL_SHA256 );
#endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */
#if defined(POLARSSL_DES_C)
if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-DES-CBC-SHA"))
return( TLS_RSA_WITH_DES_CBC_SHA );
if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-DES-CBC-SHA"))
return( TLS_DHE_RSA_WITH_DES_CBC_SHA );
#endif
#endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */
return( 0 );
}
const char *ssl_get_ciphersuite( const ssl_context *ssl )
{
if( ssl == NULL || ssl->session == NULL )
return NULL;
return ssl_get_ciphersuite_name( ssl->session->ciphersuite );
}
const char *ssl_get_version( const ssl_context *ssl )
{
switch( ssl->minor_ver )
{
case SSL_MINOR_VERSION_0:
return( "SSLv3.0" );
case SSL_MINOR_VERSION_1:
return( "TLSv1.0" );
case SSL_MINOR_VERSION_2:
return( "TLSv1.1" );
case SSL_MINOR_VERSION_3:
return( "TLSv1.2" );
default:
break;
}
return( "unknown" );
}
const x509_cert *ssl_get_peer_cert( const ssl_context *ssl )
{
if( ssl == NULL || ssl->session == NULL )
return NULL;
return ssl->session->peer_cert;
}
const int ssl_default_ciphersuites[] =
{
#if defined(POLARSSL_DHM_C)
#if defined(POLARSSL_AES_C)
#if defined(POLARSSL_SHA2_C)
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA4_C)
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
#endif
TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
#if defined(POLARSSL_SHA2_C)
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
#endif
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C)
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
#endif
TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
#endif
#if defined(POLARSSL_CAMELLIA_C)
#if defined(POLARSSL_SHA2_C)
TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
#if defined(POLARSSL_SHA2_C)
TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
#endif
#if defined(POLARSSL_DES_C)
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
#endif
#endif
#if defined(POLARSSL_AES_C)
#if defined(POLARSSL_SHA2_C)
TLS_RSA_WITH_AES_256_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA4_C)
TLS_RSA_WITH_AES_256_GCM_SHA384,
#endif /* POLARSSL_SHA2_C */
TLS_RSA_WITH_AES_256_CBC_SHA,
#endif
#if defined(POLARSSL_CAMELLIA_C)
#if defined(POLARSSL_SHA2_C)
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
#endif
#if defined(POLARSSL_AES_C)
#if defined(POLARSSL_SHA2_C)
TLS_RSA_WITH_AES_128_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
#if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C)
TLS_RSA_WITH_AES_128_GCM_SHA256,
#endif /* POLARSSL_SHA2_C */
TLS_RSA_WITH_AES_128_CBC_SHA,
#endif
#if defined(POLARSSL_CAMELLIA_C)
#if defined(POLARSSL_SHA2_C)
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
#endif /* POLARSSL_SHA2_C */
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
#endif
#if defined(POLARSSL_DES_C)
TLS_RSA_WITH_3DES_EDE_CBC_SHA,
#endif
#if defined(POLARSSL_ARC4_C)
TLS_RSA_WITH_RC4_128_SHA,
TLS_RSA_WITH_RC4_128_MD5,
#endif
0
};
/*
* Perform a single step of the SSL handshake
*/
int ssl_handshake_step( ssl_context *ssl )
{
int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
#if defined(POLARSSL_SSL_CLI_C)
if( ssl->endpoint == SSL_IS_CLIENT )
ret = ssl_handshake_client_step( ssl );
#endif
#if defined(POLARSSL_SSL_SRV_C)
if( ssl->endpoint == SSL_IS_SERVER )
ret = ssl_handshake_server_step( ssl );
#endif
return( ret );
}
/*
* Perform the SSL handshake
*/
int ssl_handshake( ssl_context *ssl )
{
int ret = 0;
SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
while( ssl->state != SSL_HANDSHAKE_OVER )
{
ret = ssl_handshake_step( ssl );
if( ret != 0 )
break;
}
SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
return( ret );
}
/*
* Renegotiate current connection
*/
int ssl_renegotiate( ssl_context *ssl )
{
int ret;
SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
if( ssl->state != SSL_HANDSHAKE_OVER )
return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
ssl->state = SSL_HELLO_REQUEST;
ssl->renegotiation = SSL_RENEGOTIATION;
if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
return( ret );
if( ( ret = ssl_handshake( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_handshake", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
return( 0 );
}
/*
* Receive application data decrypted from the SSL layer
*/
int ssl_read( ssl_context *ssl, unsigned char *buf, size_t len )
{
int ret;
size_t n;
SSL_DEBUG_MSG( 2, ( "=> read" ) );
if( ssl->state != SSL_HANDSHAKE_OVER )
{
if( ( ret = ssl_handshake( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_handshake", ret );
return( ret );
}
}
if( ssl->in_offt == NULL )
{
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
if( ret == POLARSSL_ERR_SSL_CONN_EOF )
return( 0 );
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
if( ssl->in_msglen == 0 &&
ssl->in_msgtype == SSL_MSG_APPLICATION_DATA )
{
/*
* OpenSSL sends empty messages to randomize the IV
*/
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
if( ret == POLARSSL_ERR_SSL_CONN_EOF )
return( 0 );
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
}
if( ssl->in_msgtype == SSL_MSG_HANDSHAKE )
{
SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
if( ssl->endpoint == SSL_IS_CLIENT &&
( ssl->in_msg[0] != SSL_HS_HELLO_REQUEST ||
ssl->in_hslen != 4 ) )
{
SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->disable_renegotiation == SSL_RENEGOTIATION_DISABLED ||
( ssl->secure_renegotiation == SSL_LEGACY_RENEGOTIATION &&
ssl->allow_legacy_renegotiation == SSL_LEGACY_NO_RENEGOTIATION ) )
{
SSL_DEBUG_MSG( 3, ( "ignoring renegotiation, sending alert" ) );
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
/*
* SSLv3 does not have a "no_renegotiation" alert
*/
if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
return( ret );
}
else
{
if( ( ret = ssl_send_alert_message( ssl,
SSL_ALERT_LEVEL_WARNING,
SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
{
return( ret );
}
}
}
else
{
if( ( ret = ssl_renegotiate( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_renegotiate", ret );
return( ret );
}
return( POLARSSL_ERR_NET_WANT_READ );
}
}
else if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
{
SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
ssl->in_offt = ssl->in_msg;
}
n = ( len < ssl->in_msglen )
? len : ssl->in_msglen;
memcpy( buf, ssl->in_offt, n );
ssl->in_msglen -= n;
if( ssl->in_msglen == 0 )
/* all bytes consumed */
ssl->in_offt = NULL;
else
/* more data available */
ssl->in_offt += n;
SSL_DEBUG_MSG( 2, ( "<= read" ) );
return( (int) n );
}
/*
* Send application data to be encrypted by the SSL layer
*/
int ssl_write( ssl_context *ssl, const unsigned char *buf, size_t len )
{
int ret;
size_t n;
SSL_DEBUG_MSG( 2, ( "=> write" ) );
if( ssl->state != SSL_HANDSHAKE_OVER )
{
if( ( ret = ssl_handshake( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_handshake", ret );
return( ret );
}
}
n = ( len < SSL_MAX_CONTENT_LEN )
? len : SSL_MAX_CONTENT_LEN;
if( ssl->out_left != 0 )
{
if( ( ret = ssl_flush_output( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
return( ret );
}
}
else
{
ssl->out_msglen = n;
ssl->out_msgtype = SSL_MSG_APPLICATION_DATA;
memcpy( ssl->out_msg, buf, n );
if( ( ret = ssl_write_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_write_record", ret );
return( ret );
}
}
SSL_DEBUG_MSG( 2, ( "<= write" ) );
return( (int) n );
}
/*
* Notify the peer that the connection is being closed
*/
int ssl_close_notify( ssl_context *ssl )
{
int ret;
SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
if( ( ret = ssl_flush_output( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
return( ret );
}
if( ssl->state == SSL_HANDSHAKE_OVER )
{
if( ( ret = ssl_send_alert_message( ssl,
SSL_ALERT_LEVEL_WARNING,
SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
{
return( ret );
}
}
SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
return( ret );
}
void ssl_transform_free( ssl_transform *transform )
{
#if defined(POLARSSL_ZLIB_SUPPORT)
deflateEnd( &transform->ctx_deflate );
inflateEnd( &transform->ctx_inflate );
#endif
memset( transform, 0, sizeof( ssl_transform ) );
}
void ssl_handshake_free( ssl_handshake_params *handshake )
{
#if defined(POLARSSL_DHM_C)
dhm_free( &handshake->dhm_ctx );
#endif
memset( handshake, 0, sizeof( ssl_handshake_params ) );
}
void ssl_session_free( ssl_session *session )
{
if( session->peer_cert != NULL )
{
x509_free( session->peer_cert );
free( session->peer_cert );
}
memset( session, 0, sizeof( ssl_session ) );
}
/*
* Free an SSL context
*/
void ssl_free( ssl_context *ssl )
{
SSL_DEBUG_MSG( 2, ( "=> free" ) );
free( ssl->ciphersuites );
if( ssl->out_ctr != NULL )
{
memset( ssl->out_ctr, 0, SSL_BUFFER_LEN );
free( ssl->out_ctr );
}
if( ssl->in_ctr != NULL )
{
memset( ssl->in_ctr, 0, SSL_BUFFER_LEN );
free( ssl->in_ctr );
}
#if defined(POLARSSL_DHM_C)
mpi_free( &ssl->dhm_P );
mpi_free( &ssl->dhm_G );
#endif
if( ssl->transform )
{
ssl_transform_free( ssl->transform );
free( ssl->transform );
}
if( ssl->handshake )
{
ssl_handshake_free( ssl->handshake );
ssl_transform_free( ssl->transform_negotiate );
ssl_session_free( ssl->session_negotiate );
free( ssl->handshake );
free( ssl->transform_negotiate );
free( ssl->session_negotiate );
}
if( ssl->session )
{
ssl_session_free( ssl->session );
free( ssl->session );
}
if ( ssl->hostname != NULL)
{
memset( ssl->hostname, 0, ssl->hostname_len );
free( ssl->hostname );
ssl->hostname_len = 0;
}
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
if( ssl_hw_record_finish != NULL )
{
SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_finish()" ) );
ssl_hw_record_finish( ssl );
}
#endif
SSL_DEBUG_MSG( 2, ( "<= free" ) );
/* Actually clear after last debug message */
memset( ssl, 0, sizeof( ssl_context ) );
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5770_2 |
crossvul-cpp_data_bad_3547_2 | /*
* 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)
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/timer.h>
#include <net/ax25.h>
#include <linux/skbuff.h>
#include <net/rose.h>
#include <linux/init.h>
static struct sk_buff_head loopback_queue;
static struct timer_list loopback_timer;
static void rose_set_loopback_timer(void);
void rose_loopback_init(void)
{
skb_queue_head_init(&loopback_queue);
init_timer(&loopback_timer);
}
static int rose_loopback_running(void)
{
return timer_pending(&loopback_timer);
}
int rose_loopback_queue(struct sk_buff *skb, struct rose_neigh *neigh)
{
struct sk_buff *skbn;
skbn = skb_clone(skb, GFP_ATOMIC);
kfree_skb(skb);
if (skbn != NULL) {
skb_queue_tail(&loopback_queue, skbn);
if (!rose_loopback_running())
rose_set_loopback_timer();
}
return 1;
}
static void rose_loopback_timer(unsigned long);
static void rose_set_loopback_timer(void)
{
del_timer(&loopback_timer);
loopback_timer.data = 0;
loopback_timer.function = &rose_loopback_timer;
loopback_timer.expires = jiffies + 10;
add_timer(&loopback_timer);
}
static void rose_loopback_timer(unsigned long param)
{
struct sk_buff *skb;
struct net_device *dev;
rose_address *dest;
struct sock *sk;
unsigned short frametype;
unsigned int lci_i, lci_o;
while ((skb = skb_dequeue(&loopback_queue)) != NULL) {
lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
frametype = skb->data[2];
dest = (rose_address *)(skb->data + 4);
lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i;
skb_reset_transport_header(skb);
sk = rose_find_socket(lci_o, rose_loopback_neigh);
if (sk) {
if (rose_process_rx_frame(sk, skb) == 0)
kfree_skb(skb);
continue;
}
if (frametype == ROSE_CALL_REQUEST) {
if ((dev = rose_dev_get(dest)) != NULL) {
if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0)
kfree_skb(skb);
} else {
kfree_skb(skb);
}
} else {
kfree_skb(skb);
}
}
}
void __exit rose_loopback_clear(void)
{
struct sk_buff *skb;
del_timer(&loopback_timer);
while ((skb = skb_dequeue(&loopback_queue)) != NULL) {
skb->sk = NULL;
kfree_skb(skb);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3547_2 |
crossvul-cpp_data_bad_3025_1 | /*
* IPP routines for the CUPS scheduler.
*
* Copyright 2007-2016 by Apple Inc.
* Copyright 1997-2007 by Easy Software Products, all rights reserved.
*
* This file contains Kerberos support code, copyright 2006 by
* Jelmer Vernooij.
*
* These coded instructions, statements, and computer programs are the
* property of Apple Inc. and are protected by Federal copyright
* law. Distribution and use rights are outlined in the file "LICENSE.txt"
* which should have been included with this file. If this file is
* missing or damaged, see the license at "http://www.cups.org/".
*/
/*
* Include necessary headers...
*/
#include "cupsd.h"
#include <cups/ppd-private.h>
#ifdef __APPLE__
/*# include <ApplicationServices/ApplicationServices.h>
extern CFUUIDRef ColorSyncCreateUUIDFromUInt32(unsigned id);
# include <CoreFoundation/CoreFoundation.h>*/
# ifdef HAVE_MEMBERSHIP_H
# include <membership.h>
# endif /* HAVE_MEMBERSHIP_H */
# ifdef HAVE_MEMBERSHIPPRIV_H
# include <membershipPriv.h>
# else
extern int mbr_user_name_to_uuid(const char* name, uuid_t uu);
extern int mbr_group_name_to_uuid(const char* name, uuid_t uu);
extern int mbr_check_membership_by_id(uuid_t user, gid_t group, int* ismember);
# endif /* HAVE_MEMBERSHIPPRIV_H */
#endif /* __APPLE__ */
/*
* Local functions...
*/
static void accept_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void add_class(cupsd_client_t *con, ipp_attribute_t *uri);
static int add_file(cupsd_client_t *con, cupsd_job_t *job,
mime_type_t *filetype, int compression);
static cupsd_job_t *add_job(cupsd_client_t *con, cupsd_printer_t *printer,
mime_type_t *filetype);
static void add_job_subscriptions(cupsd_client_t *con, cupsd_job_t *job);
static void add_job_uuid(cupsd_job_t *job);
static void add_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void add_printer_state_reasons(cupsd_client_t *con,
cupsd_printer_t *p);
static void add_queued_job_count(cupsd_client_t *con, cupsd_printer_t *p);
static void apply_printer_defaults(cupsd_printer_t *printer,
cupsd_job_t *job);
static void authenticate_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void cancel_all_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void cancel_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void cancel_subscription(cupsd_client_t *con, int id);
static int check_rss_recipient(const char *recipient);
static int check_quotas(cupsd_client_t *con, cupsd_printer_t *p);
static void close_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void copy_attrs(ipp_t *to, ipp_t *from, cups_array_t *ra,
ipp_tag_t group, int quickcopy,
cups_array_t *exclude);
static int copy_banner(cupsd_client_t *con, cupsd_job_t *job,
const char *name);
static int copy_file(const char *from, const char *to, mode_t mode);
static int copy_model(cupsd_client_t *con, const char *from,
const char *to);
static void copy_job_attrs(cupsd_client_t *con,
cupsd_job_t *job,
cups_array_t *ra, cups_array_t *exclude);
static void copy_printer_attrs(cupsd_client_t *con,
cupsd_printer_t *printer,
cups_array_t *ra);
static void copy_subscription_attrs(cupsd_client_t *con,
cupsd_subscription_t *sub,
cups_array_t *ra,
cups_array_t *exclude);
static void create_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void create_local_printer(cupsd_client_t *con);
static cups_array_t *create_requested_array(ipp_t *request);
static void create_subscriptions(cupsd_client_t *con, ipp_attribute_t *uri);
static void delete_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_default(cupsd_client_t *con);
static void get_devices(cupsd_client_t *con);
static void get_document(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_job_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_notifications(cupsd_client_t *con);
static void get_ppd(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_ppds(cupsd_client_t *con);
static void get_printers(cupsd_client_t *con, int type);
static void get_printer_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_printer_supported(cupsd_client_t *con, ipp_attribute_t *uri);
static void get_subscription_attrs(cupsd_client_t *con, int sub_id);
static void get_subscriptions(cupsd_client_t *con, ipp_attribute_t *uri);
static const char *get_username(cupsd_client_t *con);
static void hold_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void hold_new_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void move_job(cupsd_client_t *con, ipp_attribute_t *uri);
static int ppd_parse_line(const char *line, char *option, int olen,
char *choice, int clen);
static void print_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void read_job_ticket(cupsd_client_t *con);
static void reject_jobs(cupsd_client_t *con, ipp_attribute_t *uri);
static void release_held_new_jobs(cupsd_client_t *con,
ipp_attribute_t *uri);
static void release_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void renew_subscription(cupsd_client_t *con, int sub_id);
static void restart_job(cupsd_client_t *con, ipp_attribute_t *uri);
static void save_auth_info(cupsd_client_t *con, cupsd_job_t *job,
ipp_attribute_t *auth_info);
static void send_document(cupsd_client_t *con, ipp_attribute_t *uri);
static void send_http_error(cupsd_client_t *con, http_status_t status,
cupsd_printer_t *printer);
static void send_ipp_status(cupsd_client_t *con, ipp_status_t status,
const char *message, ...)
__attribute__((__format__(__printf__, 3, 4)));
static void set_default(cupsd_client_t *con, ipp_attribute_t *uri);
static void set_job_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static void set_printer_attrs(cupsd_client_t *con, ipp_attribute_t *uri);
static int set_printer_defaults(cupsd_client_t *con, cupsd_printer_t *printer);
static void start_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void stop_printer(cupsd_client_t *con, ipp_attribute_t *uri);
static void url_encode_attr(ipp_attribute_t *attr, char *buffer, size_t bufsize);
static char *url_encode_string(const char *s, char *buffer, size_t bufsize);
static int user_allowed(cupsd_printer_t *p, const char *username);
static void validate_job(cupsd_client_t *con, ipp_attribute_t *uri);
static int validate_name(const char *name);
static int validate_user(cupsd_job_t *job, cupsd_client_t *con, const char *owner, char *username, size_t userlen);
/*
* 'cupsdProcessIPPRequest()' - Process an incoming IPP request.
*/
int /* O - 1 on success, 0 on failure */
cupsdProcessIPPRequest(
cupsd_client_t *con) /* I - Client connection */
{
ipp_tag_t group; /* Current group tag */
ipp_attribute_t *attr; /* Current attribute */
ipp_attribute_t *charset; /* Character set attribute */
ipp_attribute_t *language; /* Language attribute */
ipp_attribute_t *uri = NULL; /* Printer or job URI attribute */
ipp_attribute_t *username; /* requesting-user-name attr */
int sub_id; /* Subscription ID */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdProcessIPPRequest(%p[%d]): operation_id=%04x(%s)", con, con->number, con->request->request.op.operation_id, ippOpString(con->request->request.op.operation_id));
if (LogLevel >= CUPSD_LOG_DEBUG2)
{
for (group = IPP_TAG_ZERO, attr = ippFirstAttribute(con->request); attr; attr = ippNextAttribute(con->request))
{
const char *name; /* Attribute name */
char value[1024]; /* Attribute value */
if (group != ippGetGroupTag(attr))
{
group = ippGetGroupTag(attr);
if (group != IPP_TAG_ZERO)
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdProcessIPPRequest: %s", ippTagString(group));
}
if ((name = ippGetName(attr)) == NULL)
continue;
ippAttributeString(attr, value, sizeof(value));
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdProcessIPPRequest: %s %s%s '%s'", name, ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)), value);
}
}
/*
* First build an empty response message for this request...
*/
con->response = ippNew();
con->response->request.status.version[0] =
con->request->request.op.version[0];
con->response->request.status.version[1] =
con->request->request.op.version[1];
con->response->request.status.request_id =
con->request->request.op.request_id;
/*
* Then validate the request header and required attributes...
*/
if (con->request->request.any.version[0] != 1 &&
con->request->request.any.version[0] != 2)
{
/*
* Return an error, since we only support IPP 1.x and 2.x.
*/
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Bad request version number %d.%d",
IPP_VERSION_NOT_SUPPORTED, con->http->hostname,
con->request->request.any.version[0],
con->request->request.any.version[1]);
send_ipp_status(con, IPP_VERSION_NOT_SUPPORTED,
_("Bad request version number %d.%d."),
con->request->request.any.version[0],
con->request->request.any.version[1]);
}
else if (con->request->request.any.request_id < 1)
{
/*
* Return an error, since request IDs must be between 1 and 2^31-1
*/
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Bad request ID %d",
IPP_BAD_REQUEST, con->http->hostname,
con->request->request.any.request_id);
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad request ID %d."),
con->request->request.any.request_id);
}
else if (!con->request->attrs)
{
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s No attributes in request",
IPP_BAD_REQUEST, con->http->hostname);
send_ipp_status(con, IPP_BAD_REQUEST, _("No attributes in request."));
}
else
{
/*
* Make sure that the attributes are provided in the correct order and
* don't repeat groups...
*/
for (attr = con->request->attrs, group = attr->group_tag;
attr;
attr = attr->next)
if (attr->group_tag < group && attr->group_tag != IPP_TAG_ZERO)
{
/*
* Out of order; return an error...
*/
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Attribute groups are out of order",
IPP_BAD_REQUEST, con->http->hostname);
send_ipp_status(con, IPP_BAD_REQUEST,
_("Attribute groups are out of order (%x < %x)."),
attr->group_tag, group);
break;
}
else
group = attr->group_tag;
if (!attr)
{
/*
* Then make sure that the first three attributes are:
*
* attributes-charset
* attributes-natural-language
* printer-uri/job-uri
*/
attr = con->request->attrs;
if (attr && attr->name &&
!strcmp(attr->name, "attributes-charset") &&
(attr->value_tag & IPP_TAG_MASK) == IPP_TAG_CHARSET)
charset = attr;
else
charset = NULL;
if (attr)
attr = attr->next;
if (attr && attr->name &&
!strcmp(attr->name, "attributes-natural-language") &&
(attr->value_tag & IPP_TAG_MASK) == IPP_TAG_LANGUAGE)
{
language = attr;
/*
* Reset language for this request if different from Accept-Language.
*/
if (!con->language ||
strcmp(attr->values[0].string.text, con->language->language))
{
cupsLangFree(con->language);
con->language = cupsLangGet(attr->values[0].string.text);
}
}
else
language = NULL;
if ((attr = ippFindAttribute(con->request, "printer-uri",
IPP_TAG_URI)) != NULL)
uri = attr;
else if ((attr = ippFindAttribute(con->request, "job-uri",
IPP_TAG_URI)) != NULL)
uri = attr;
else if (con->request->request.op.operation_id == CUPS_GET_PPD)
uri = ippFindAttribute(con->request, "ppd-name", IPP_TAG_NAME);
else
uri = NULL;
if (charset)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
"attributes-charset", NULL,
charset->values[0].string.text);
else
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
"attributes-charset", NULL, "utf-8");
if (language)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
"attributes-natural-language", NULL,
language->values[0].string.text);
else
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
"attributes-natural-language", NULL, DefaultLanguage);
if (charset &&
_cups_strcasecmp(charset->values[0].string.text, "us-ascii") &&
_cups_strcasecmp(charset->values[0].string.text, "utf-8"))
{
/*
* Bad character set...
*/
cupsdLogMessage(CUPSD_LOG_ERROR, "Unsupported character set \"%s\"",
charset->values[0].string.text);
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Unsupported attributes-charset value \"%s\"",
IPP_CHARSET, con->http->hostname,
charset->values[0].string.text);
send_ipp_status(con, IPP_BAD_REQUEST,
_("Unsupported character set \"%s\"."),
charset->values[0].string.text);
}
else if (!charset || !language ||
(!uri &&
con->request->request.op.operation_id != CUPS_GET_DEFAULT &&
con->request->request.op.operation_id != CUPS_GET_PRINTERS &&
con->request->request.op.operation_id != CUPS_GET_CLASSES &&
con->request->request.op.operation_id != CUPS_GET_DEVICES &&
con->request->request.op.operation_id != CUPS_GET_PPDS))
{
/*
* Return an error, since attributes-charset,
* attributes-natural-language, and printer-uri/job-uri are required
* for all operations.
*/
if (!charset)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Missing attributes-charset attribute");
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Missing attributes-charset attribute",
IPP_BAD_REQUEST, con->http->hostname);
}
if (!language)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Missing attributes-natural-language attribute");
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Missing attributes-natural-language attribute",
IPP_BAD_REQUEST, con->http->hostname);
}
if (!uri)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Missing printer-uri, job-uri, or ppd-name "
"attribute");
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Missing printer-uri, job-uri, or ppd-name "
"attribute", IPP_BAD_REQUEST, con->http->hostname);
}
cupsdLogMessage(CUPSD_LOG_DEBUG, "Request attributes follow...");
for (attr = con->request->attrs; attr; attr = attr->next)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"attr \"%s\": group_tag = %x, value_tag = %x",
attr->name ? attr->name : "(null)", attr->group_tag,
attr->value_tag);
cupsdLogMessage(CUPSD_LOG_DEBUG, "End of attributes...");
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing required attributes."));
}
else
{
/*
* OK, all the checks pass so far; make sure requesting-user-name is
* not "root" from a remote host...
*/
if ((username = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
{
/*
* Check for root user...
*/
if (!strcmp(username->values[0].string.text, "root") &&
_cups_strcasecmp(con->http->hostname, "localhost") &&
strcmp(con->username, "root"))
{
/*
* Remote unauthenticated user masquerading as local root...
*/
ippSetString(con->request, &username, 0, RemoteRoot);
}
}
if ((attr = ippFindAttribute(con->request, "notify-subscription-id",
IPP_TAG_INTEGER)) != NULL)
sub_id = attr->values[0].integer;
else
sub_id = 0;
/*
* Then try processing the operation...
*/
if (uri)
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s %s",
ippOpString(con->request->request.op.operation_id),
uri->values[0].string.text);
else
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s",
ippOpString(con->request->request.op.operation_id));
switch (con->request->request.op.operation_id)
{
case IPP_OP_PRINT_JOB :
print_job(con, uri);
break;
case IPP_OP_VALIDATE_JOB :
validate_job(con, uri);
break;
case IPP_OP_CREATE_JOB :
create_job(con, uri);
break;
case IPP_OP_SEND_DOCUMENT :
send_document(con, uri);
break;
case IPP_OP_CANCEL_JOB :
cancel_job(con, uri);
break;
case IPP_OP_GET_JOB_ATTRIBUTES :
get_job_attrs(con, uri);
break;
case IPP_OP_GET_JOBS :
get_jobs(con, uri);
break;
case IPP_OP_GET_PRINTER_ATTRIBUTES :
get_printer_attrs(con, uri);
break;
case IPP_OP_GET_PRINTER_SUPPORTED_VALUES :
get_printer_supported(con, uri);
break;
case IPP_OP_HOLD_JOB :
hold_job(con, uri);
break;
case IPP_OP_RELEASE_JOB :
release_job(con, uri);
break;
case IPP_OP_RESTART_JOB :
restart_job(con, uri);
break;
case IPP_OP_PAUSE_PRINTER :
stop_printer(con, uri);
break;
case IPP_OP_RESUME_PRINTER :
start_printer(con, uri);
break;
case IPP_OP_PURGE_JOBS :
case IPP_OP_CANCEL_JOBS :
case IPP_OP_CANCEL_MY_JOBS :
cancel_all_jobs(con, uri);
break;
case IPP_OP_SET_JOB_ATTRIBUTES :
set_job_attrs(con, uri);
break;
case IPP_OP_SET_PRINTER_ATTRIBUTES :
set_printer_attrs(con, uri);
break;
case IPP_OP_HOLD_NEW_JOBS :
hold_new_jobs(con, uri);
break;
case IPP_OP_RELEASE_HELD_NEW_JOBS :
release_held_new_jobs(con, uri);
break;
case IPP_OP_CLOSE_JOB :
close_job(con, uri);
break;
case IPP_OP_CUPS_GET_DEFAULT :
get_default(con);
break;
case IPP_OP_CUPS_GET_PRINTERS :
get_printers(con, 0);
break;
case IPP_OP_CUPS_GET_CLASSES :
get_printers(con, CUPS_PRINTER_CLASS);
break;
case IPP_OP_CUPS_ADD_MODIFY_PRINTER :
add_printer(con, uri);
break;
case IPP_OP_CUPS_DELETE_PRINTER :
delete_printer(con, uri);
break;
case IPP_OP_CUPS_ADD_MODIFY_CLASS :
add_class(con, uri);
break;
case IPP_OP_CUPS_DELETE_CLASS :
delete_printer(con, uri);
break;
case IPP_OP_CUPS_ACCEPT_JOBS :
case IPP_OP_ENABLE_PRINTER :
accept_jobs(con, uri);
break;
case IPP_OP_CUPS_REJECT_JOBS :
case IPP_OP_DISABLE_PRINTER :
reject_jobs(con, uri);
break;
case IPP_OP_CUPS_SET_DEFAULT :
set_default(con, uri);
break;
case IPP_OP_CUPS_GET_DEVICES :
get_devices(con);
break;
case IPP_OP_CUPS_GET_DOCUMENT :
get_document(con, uri);
break;
case IPP_OP_CUPS_GET_PPD :
get_ppd(con, uri);
break;
case IPP_OP_CUPS_GET_PPDS :
get_ppds(con);
break;
case IPP_OP_CUPS_MOVE_JOB :
move_job(con, uri);
break;
case IPP_OP_CUPS_AUTHENTICATE_JOB :
authenticate_job(con, uri);
break;
case IPP_OP_CREATE_PRINTER_SUBSCRIPTIONS :
case IPP_OP_CREATE_JOB_SUBSCRIPTIONS :
create_subscriptions(con, uri);
break;
case IPP_OP_GET_SUBSCRIPTION_ATTRIBUTES :
get_subscription_attrs(con, sub_id);
break;
case IPP_OP_GET_SUBSCRIPTIONS :
get_subscriptions(con, uri);
break;
case IPP_OP_RENEW_SUBSCRIPTION :
renew_subscription(con, sub_id);
break;
case IPP_OP_CANCEL_SUBSCRIPTION :
cancel_subscription(con, sub_id);
break;
case IPP_OP_GET_NOTIFICATIONS :
get_notifications(con);
break;
case IPP_OP_CUPS_CREATE_LOCAL_PRINTER :
create_local_printer(con);
break;
default :
cupsdAddEvent(CUPSD_EVENT_SERVER_AUDIT, NULL, NULL,
"%04X %s Operation %04X (%s) not supported",
IPP_OPERATION_NOT_SUPPORTED, con->http->hostname,
con->request->request.op.operation_id,
ippOpString(con->request->request.op.operation_id));
send_ipp_status(con, IPP_OPERATION_NOT_SUPPORTED,
_("%s not supported."),
ippOpString(
con->request->request.op.operation_id));
break;
}
}
}
}
if (con->response)
{
/*
* Sending data from the scheduler...
*/
cupsdLogMessage(con->response->request.status.status_code
>= IPP_BAD_REQUEST &&
con->response->request.status.status_code
!= IPP_NOT_FOUND ? CUPSD_LOG_ERROR : CUPSD_LOG_DEBUG,
"[Client %d] Returning IPP %s for %s (%s) from %s",
con->number,
ippErrorString(con->response->request.status.status_code),
ippOpString(con->request->request.op.operation_id),
uri ? uri->values[0].string.text : "no URI",
con->http->hostname);
httpClearFields(con->http);
#ifdef CUPSD_USE_CHUNKING
/*
* Because older versions of CUPS (1.1.17 and older) and some IPP
* clients do not implement chunking properly, we cannot use
* chunking by default. This may become the default in future
* CUPS releases, or we might add a configuration directive for
* it.
*/
if (con->http->version == HTTP_1_1)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[Client %d] Transfer-Encoding: chunked",
con->number);
cupsdSetLength(con->http, 0);
}
else
#endif /* CUPSD_USE_CHUNKING */
{
size_t length; /* Length of response */
length = ippLength(con->response);
if (con->file >= 0 && !con->pipe_pid)
{
struct stat fileinfo; /* File information */
if (!fstat(con->file, &fileinfo))
length += (size_t)fileinfo.st_size;
}
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[Client %d] Content-Length: " CUPS_LLFMT,
con->number, CUPS_LLCAST length);
httpSetLength(con->http, length);
}
if (cupsdSendHeader(con, HTTP_OK, "application/ipp", CUPSD_AUTH_NONE))
{
/*
* Tell the caller the response header was sent successfully...
*/
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
(cupsd_selfunc_t)cupsdWriteClient, con);
return (1);
}
else
{
/*
* Tell the caller the response header could not be sent...
*/
return (0);
}
}
else
{
/*
* Sending data from a subprocess like cups-deviced; tell the caller
* everything is A-OK so far...
*/
return (1);
}
}
/*
* 'cupsdTimeoutJob()' - Timeout a job waiting on job files.
*/
int /* O - 0 on success, -1 on error */
cupsdTimeoutJob(cupsd_job_t *job) /* I - Job to timeout */
{
cupsd_printer_t *printer; /* Destination printer or class */
ipp_attribute_t *attr; /* job-sheets attribute */
int kbytes; /* Kilobytes in banner */
job->pending_timeout = 0;
/*
* See if we need to add the ending sheet...
*/
if (!cupsdLoadJob(job))
return (-1);
printer = cupsdFindDest(job->dest);
attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_NAME);
if (printer && !(printer->type & CUPS_PRINTER_REMOTE) &&
attr && attr->num_values > 1)
{
/*
* Yes...
*/
cupsdLogJob(job, CUPSD_LOG_INFO, "Adding end banner page \"%s\".",
attr->values[1].string.text);
if ((kbytes = copy_banner(NULL, job, attr->values[1].string.text)) < 0)
return (-1);
cupsdUpdateQuota(printer, job->username, 0, kbytes);
}
return (0);
}
/*
* 'accept_jobs()' - Accept print jobs to a printer.
*/
static void
accept_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer or class URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "accept_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Accept jobs sent to the printer...
*/
printer->accepting = 1;
printer->state_message[0] = '\0';
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"Now accepting jobs.");
if (dtype & CUPS_PRINTER_CLASS)
{
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" now accepting jobs (\"%s\").",
printer->name, get_username(con));
}
else
{
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" now accepting jobs (\"%s\").",
printer->name, get_username(con));
}
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'add_class()' - Add a class to the system.
*/
static void
add_class(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - URI of class */
{
http_status_t status; /* Policy status */
int i; /* Looping var */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *pclass, /* Class */
*member; /* Member printer/class */
cups_ptype_t dtype; /* Destination type */
ipp_attribute_t *attr; /* Printer attribute */
int modify; /* Non-zero if we just modified */
int need_restart_job; /* Need to restart job? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_class(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Do we have a valid URI?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/classes/", 9) || strlen(resource) == 9)
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri must be of the form "
"\"ipp://HOSTNAME/classes/CLASSNAME\"."));
return;
}
/*
* Do we have a valid printer name?
*/
if (!validate_name(resource + 9))
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri \"%s\" contains invalid characters."),
uri->values[0].string.text);
return;
}
/*
* See if the class already exists; if not, create a new class...
*/
if ((pclass = cupsdFindClass(resource + 9)) == NULL)
{
/*
* Class doesn't exist; see if we have a printer of the same name...
*/
if ((pclass = cupsdFindPrinter(resource + 9)) != NULL)
{
/*
* Yes, return an error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("A printer named \"%s\" already exists."),
resource + 9);
return;
}
/*
* No, check the default policy and then add the class...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
pclass = cupsdAddClass(resource + 9);
modify = 0;
}
else if ((status = cupsdCheckPolicy(pclass->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, pclass);
return;
}
else
modify = 1;
/*
* Look for attributes and copy them over as needed...
*/
need_restart_job = 0;
if ((attr = ippFindAttribute(con->request, "printer-location", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI)) != NULL && !strncmp(attr->values[0].string.text, "geo:", 4))
cupsdSetString(&pclass->geo_location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organization", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->organization, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organizational-unit", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->organizational_unit, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-info",
IPP_TAG_TEXT)) != NULL)
cupsdSetString(&pclass->info, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-is-accepting-jobs",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean != pclass->accepting)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-accepting-jobs to %d (was %d.)",
pclass->name, attr->values[0].boolean, pclass->accepting);
pclass->accepting = attr->values[0].boolean;
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, pclass, NULL, "%s accepting jobs.",
pclass->accepting ? "Now" : "No longer");
}
if ((attr = ippFindAttribute(con->request, "printer-is-shared", IPP_TAG_BOOLEAN)) != NULL)
{
if (pclass->type & CUPS_PRINTER_REMOTE)
{
/*
* Cannot re-share remote printers.
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Cannot change printer-is-shared for remote queues."));
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
if (pclass->shared && !ippGetBoolean(attr, 0))
cupsdDeregisterPrinter(pclass, 1);
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-shared to %d (was %d.)",
pclass->name, attr->values[0].boolean, pclass->shared);
pclass->shared = ippGetBoolean(attr, 0);
}
if ((attr = ippFindAttribute(con->request, "printer-state",
IPP_TAG_ENUM)) != NULL)
{
if (attr->values[0].integer != IPP_PRINTER_IDLE &&
attr->values[0].integer != IPP_PRINTER_STOPPED)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Attempt to set %s printer-state to bad value %d."),
pclass->name, attr->values[0].integer);
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_INFO, "Setting %s printer-state to %d (was %d.)",
pclass->name, attr->values[0].integer, pclass->state);
if (attr->values[0].integer == IPP_PRINTER_STOPPED)
cupsdStopPrinter(pclass, 0);
else
{
cupsdSetPrinterState(pclass, (ipp_pstate_t)(attr->values[0].integer), 0);
need_restart_job = 1;
}
}
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) != NULL)
{
strlcpy(pclass->state_message, attr->values[0].string.text,
sizeof(pclass->state_message));
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, pclass, NULL, "%s",
pclass->state_message);
}
if ((attr = ippFindAttribute(con->request, "member-uris",
IPP_TAG_URI)) != NULL)
{
/*
* Clear the printer array as needed...
*/
need_restart_job = 1;
if (pclass->num_printers > 0)
{
free(pclass->printers);
pclass->num_printers = 0;
}
/*
* Add each printer or class that is listed...
*/
for (i = 0; i < attr->num_values; i ++)
{
/*
* Search for the printer or class URI...
*/
if (!cupsdValidateDest(attr->values[i].string.text, &dtype, &member))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
else if (dtype & CUPS_PRINTER_CLASS)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Nested classes are not allowed."));
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
/*
* Add it to the class...
*/
cupsdAddPrinterToClass(pclass, member);
}
}
if (!set_printer_defaults(con, pclass))
{
if (!modify)
cupsdDeletePrinter(pclass, 0);
return;
}
if ((attr = ippFindAttribute(con->request, "auth-info-required",
IPP_TAG_KEYWORD)) != NULL)
cupsdSetAuthInfoRequired(pclass, NULL, attr);
pclass->config_time = time(NULL);
/*
* Update the printer class attributes and return...
*/
cupsdSetPrinterAttrs(pclass);
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
if (need_restart_job && pclass->job)
{
/*
* Reset the current job to a "pending" status...
*/
cupsdSetJobState(pclass->job, IPP_JOB_PENDING, CUPSD_JOB_FORCE,
"Job restarted because the class was modified.");
}
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
if (modify)
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_MODIFIED,
pclass, NULL, "Class \"%s\" modified by \"%s\".",
pclass->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" modified by \"%s\".",
pclass->name, get_username(con));
}
else
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED,
pclass, NULL, "New class \"%s\" added by \"%s\".",
pclass->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "New class \"%s\" added by \"%s\".",
pclass->name, get_username(con));
}
con->response->request.status.status_code = IPP_OK;
}
/*
* 'add_file()' - Add a file to a job.
*/
static int /* O - 0 on success, -1 on error */
add_file(cupsd_client_t *con, /* I - Connection to client */
cupsd_job_t *job, /* I - Job to add to */
mime_type_t *filetype, /* I - Type of file */
int compression) /* I - Compression */
{
mime_type_t **filetypes; /* New filetypes array... */
int *compressions; /* New compressions array... */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"add_file(con=%p[%d], job=%d, filetype=%s/%s, "
"compression=%d)", con, con ? con->number : -1, job->id,
filetype->super, filetype->type, compression);
/*
* Add the file to the job...
*/
if (job->num_files == 0)
{
compressions = (int *)malloc(sizeof(int));
filetypes = (mime_type_t **)malloc(sizeof(mime_type_t *));
}
else
{
compressions = (int *)realloc(job->compressions,
(size_t)(job->num_files + 1) * sizeof(int));
filetypes = (mime_type_t **)realloc(job->filetypes,
(size_t)(job->num_files + 1) *
sizeof(mime_type_t *));
}
if (compressions)
job->compressions = compressions;
if (filetypes)
job->filetypes = filetypes;
if (!compressions || !filetypes)
{
cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
"Job aborted because the scheduler ran out of memory.");
if (con)
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("Unable to allocate memory for file types."));
return (-1);
}
job->compressions[job->num_files] = compression;
job->filetypes[job->num_files] = filetype;
job->num_files ++;
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
return (0);
}
/*
* 'add_job()' - Add a job to a print queue.
*/
static cupsd_job_t * /* O - Job object */
add_job(cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer, /* I - Destination printer */
mime_type_t *filetype) /* I - First print file type, if any */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr, /* Current attribute */
*auth_info; /* auth-info attribute */
const char *mandatory; /* Current mandatory job attribute */
const char *val; /* Default option value */
int priority; /* Job priority */
cupsd_job_t *job; /* Current job */
char job_uri[HTTP_MAX_URI]; /* Job URI */
int kbytes; /* Size of print file */
int i; /* Looping var */
int lowerpagerange; /* Page range bound */
int exact; /* Did we have an exact match? */
ipp_attribute_t *media_col, /* media-col attribute */
*media_margin; /* media-*-margin attribute */
ipp_t *unsup_col; /* media-col in unsupported response */
static const char * const readonly[] =/* List of read-only attributes */
{
"date-time-at-completed",
"date-time-at-creation",
"date-time-at-processing",
"job-detailed-status-messages",
"job-document-access-errors",
"job-id",
"job-impressions-completed",
"job-k-octets-completed",
"job-media-sheets-completed",
"job-pages-completed",
"job-printer-up-time",
"job-printer-uri",
"job-state",
"job-state-message",
"job-state-reasons",
"job-uri",
"number-of-documents",
"number-of-intervening-jobs",
"output-device-assigned",
"time-at-completed",
"time-at-creation",
"time-at-processing"
};
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))",
con, con->number, printer, printer->name,
filetype, filetype ? filetype->super : "none",
filetype ? filetype->type : "none");
/*
* Check remote printing to non-shared printer...
*/
if (!printer->shared &&
_cups_strcasecmp(con->http->hostname, "localhost") &&
_cups_strcasecmp(con->http->hostname, ServerName))
{
send_ipp_status(con, IPP_NOT_AUTHORIZED,
_("The printer or class is not shared."));
return (NULL);
}
/*
* Check policy...
*/
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return (NULL);
}
else if (printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
!con->username[0])
{
send_http_error(con, HTTP_UNAUTHORIZED, printer);
return (NULL);
}
#ifdef HAVE_SSL
else if (auth_info && !con->http->tls &&
!httpAddrLocalhost(con->http->hostaddr))
{
/*
* Require encryption of auth-info over non-local connections...
*/
send_http_error(con, HTTP_UPGRADE_REQUIRED, printer);
return (NULL);
}
#endif /* HAVE_SSL */
/*
* See if the printer is accepting jobs...
*/
if (!printer->accepting)
{
send_ipp_status(con, IPP_NOT_ACCEPTING,
_("Destination \"%s\" is not accepting jobs."),
printer->name);
return (NULL);
}
/*
* Validate job template attributes; for now just document-format,
* copies, job-sheets, number-up, page-ranges, mandatory attributes, and
* media...
*/
for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++)
{
if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL)
{
ippDeleteAttribute(con->request, attr);
if (StrictConformance)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]);
return (NULL);
}
cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]);
}
}
if (printer->pc)
{
for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory);
mandatory;
mandatory = (char *)cupsArrayNext(printer->pc->mandatory))
{
if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO))
{
/*
* Missing a required attribute...
*/
send_ipp_status(con, IPP_CONFLICT,
_("The \"%s\" attribute is required for print jobs."),
mandatory);
return (NULL);
}
}
}
if (filetype && printer->filetypes &&
!cupsArrayFind(printer->filetypes, filetype))
{
char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* MIME media type string */
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported format \"%s\"."), mimetype);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
return (NULL);
}
if ((attr = ippFindAttribute(con->request, "copies",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"copies", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "job-sheets",
IPP_TAG_ZERO)) != NULL)
{
if (attr->value_tag != IPP_TAG_KEYWORD &&
attr->value_tag != IPP_TAG_NAME)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type."));
return (NULL);
}
if (attr->num_values > 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Too many job-sheets values (%d > 2)."),
attr->num_values);
return (NULL);
}
for (i = 0; i < attr->num_values; i ++)
if (strcmp(attr->values[i].string.text, "none") &&
!cupsdFindBanner(attr->values[i].string.text))
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."),
attr->values[i].string.text);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "number-up",
IPP_TAG_INTEGER)) != NULL)
{
if (attr->values[0].integer != 1 &&
attr->values[0].integer != 2 &&
attr->values[0].integer != 4 &&
attr->values[0].integer != 6 &&
attr->values[0].integer != 9 &&
attr->values[0].integer != 16)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."),
attr->values[0].integer);
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER,
"number-up", attr->values[0].integer);
return (NULL);
}
}
if ((attr = ippFindAttribute(con->request, "page-ranges",
IPP_TAG_RANGE)) != NULL)
{
for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++)
{
if (attr->values[i].range.lower < lowerpagerange ||
attr->values[i].range.lower > attr->values[i].range.upper)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad page-ranges values %d-%d."),
attr->values[i].range.lower,
attr->values[i].range.upper);
return (NULL);
}
lowerpagerange = attr->values[i].range.upper + 1;
}
}
/*
* Do media selection as needed...
*/
if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) &&
!ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) &&
_ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact))
{
if (!exact &&
(media_col = ippFindAttribute(con->request, "media-col",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins."));
unsup_col = ippNew();
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-bottom-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-bottom-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-left-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-left-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-right-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-right-margin", media_margin->values[0].integer);
if ((media_margin = ippFindAttribute(media_col->values[0].collection,
"media-top-margin",
IPP_TAG_INTEGER)) != NULL)
ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
"media-top-margin", media_margin->values[0].integer);
ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col",
unsup_col);
ippDelete(unsup_col);
}
}
/*
* Make sure we aren't over our limit...
*/
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
cupsdCleanJobs();
if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs."));
return (NULL);
}
if ((i = check_quotas(con, printer)) < 0)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached."));
return (NULL);
}
else if (i == 0)
{
send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print."));
return (NULL);
}
/*
* Create the job and set things up...
*/
if ((attr = ippFindAttribute(con->request, "job-priority",
IPP_TAG_INTEGER)) != NULL)
priority = attr->values[0].integer;
else
{
if ((val = cupsGetOption("job-priority", printer->num_options,
printer->options)) != NULL)
priority = atoi(val);
else
priority = 50;
ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority",
priority);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL)
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled");
else if ((attr->value_tag != IPP_TAG_NAME &&
attr->value_tag != IPP_TAG_NAMELANG) ||
attr->num_values != 1)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Bad job-name value: Wrong type or count."));
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
else if (!ippValidateAttribute(attr))
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"),
cupsLastErrorString());
if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL)
attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP;
return (NULL);
}
if ((job = cupsdAddJob(priority, printer->name)) == NULL)
{
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("Unable to add job for destination \"%s\"."),
printer->name);
return (NULL);
}
job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE);
job->attrs = con->request;
job->dirty = 1;
con->request = ippNewRequest(job->attrs->request.op.operation_id);
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
add_job_uuid(job);
apply_printer_defaults(printer, job);
attr = ippFindAttribute(job->attrs, "requesting-user-name", IPP_TAG_NAME);
if (con->username[0])
{
cupsdSetString(&job->username, con->username);
if (attr)
ippSetString(job->attrs, &attr, 0, con->username);
}
else if (attr)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"add_job: requesting-user-name=\"%s\"",
attr->values[0].string.text);
cupsdSetString(&job->username, attr->values[0].string.text);
}
else
cupsdSetString(&job->username, "anonymous");
if (!attr)
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-user-name", NULL, job->username);
else
{
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
ippSetName(job->attrs, &attr, "job-originating-user-name");
}
if (con->username[0] || auth_info)
{
save_auth_info(con, job, auth_info);
/*
* Remove the auth-info attribute from the attribute data...
*/
if (auth_info)
ippDeleteAttribute(job->attrs, auth_info);
}
if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL)
cupsdSetString(&(job->name), attr->values[0].string.text);
if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name",
IPP_TAG_ZERO)) != NULL)
{
/*
* Request contains a job-originating-host-name attribute; validate it...
*/
if (attr->value_tag != IPP_TAG_NAME ||
attr->num_values != 1 ||
strcmp(con->http->hostname, "localhost"))
{
/*
* Can't override the value if we aren't connected via localhost.
* Also, we can only have 1 value and it must be a name value.
*/
ippDeleteAttribute(job->attrs, attr);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname);
}
else
ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB);
}
else
{
/*
* No job-originating-host-name attribute, so use the hostname from
* the connection...
*/
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME,
"job-originating-host-name", NULL, con->http->hostname);
}
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed");
ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL)));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing");
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed");
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL));
ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing");
/*
* Add remaining job attributes...
*/
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM,
"job-state", IPP_JOB_STOPPED);
job->state_value = (ipp_jstate_t)job->state->values[0].integer;
job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-state-reasons", NULL, "job-incoming");
job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0);
job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-media-sheets-completed", 0);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL,
printer->uri);
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer = 0;
else
ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0);
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr)
{
if ((val = cupsGetOption("job-hold-until", printer->num_options,
printer->options)) == NULL)
val = "no-hold";
attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
"job-hold-until", NULL, val);
}
if (printer->holding_new_jobs)
{
/*
* Hold all new jobs on this printer...
*/
if (attr && strcmp(attr->values[0].string.text, "no-hold"))
cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0);
else
cupsdSetJobHoldUntil(job, "indefinite", 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create");
}
else if (attr && strcmp(attr->values[0].string.text, "no-hold"))
{
/*
* Hold job until specified time...
*/
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
}
else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB)
{
job->hold_until = time(NULL) + MultipleOperationTimeout;
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
}
else
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification)
{
/*
* Add job sheets options...
*/
if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Adding default job-sheets values \"%s,%s\"...",
printer->job_sheets[0], printer->job_sheets[1]);
attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets",
2, NULL, NULL);
ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]);
ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]);
}
job->job_sheets = attr;
/*
* Enforce classification level if set...
*/
if (Classification)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Classification=\"%s\", ClassifyOverride=%d",
Classification ? Classification : "(null)",
ClassifyOverride);
if (ClassifyOverride)
{
if (!strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
!strcmp(attr->values[1].string.text, "none")))
{
/*
* Force the leading banner to have the classification on it...
*/
ippSetString(job->attrs, &attr, 0, Classification);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,none\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
else if (attr->num_values == 2 &&
strcmp(attr->values[0].string.text,
attr->values[1].string.text) &&
strcmp(attr->values[0].string.text, "none") &&
strcmp(attr->values[1].string.text, "none"))
{
/*
* Can't put two different security markings on the same document!
*/
ippSetString(job->attrs, &attr, 1, attr->values[0].string.text);
cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
else if (strcmp(attr->values[0].string.text, Classification) &&
strcmp(attr->values[0].string.text, "none") &&
(attr->num_values == 1 ||
(strcmp(attr->values[1].string.text, Classification) &&
strcmp(attr->values[1].string.text, "none"))))
{
if (attr->num_values == 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION OVERRIDDEN "
"job-sheets=\"%s,%s\",fffff "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
}
}
else if (strcmp(attr->values[0].string.text, Classification) &&
(attr->num_values == 1 ||
strcmp(attr->values[1].string.text, Classification)))
{
/*
* Force the banner to have the classification on it...
*/
if (attr->num_values > 1 &&
!strcmp(attr->values[0].string.text, attr->values[1].string.text))
{
ippSetString(job->attrs, &attr, 0, Classification);
ippSetString(job->attrs, &attr, 1, Classification);
}
else
{
if (attr->num_values == 1 ||
strcmp(attr->values[0].string.text, "none"))
ippSetString(job->attrs, &attr, 0, Classification);
if (attr->num_values > 1 &&
strcmp(attr->values[1].string.text, "none"))
ippSetString(job->attrs, &attr, 1, Classification);
}
if (attr->num_values > 1)
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s,%s\", "
"job-originating-user-name=\"%s\"",
attr->values[0].string.text,
attr->values[1].string.text, job->username);
else
cupsdLogJob(job, CUPSD_LOG_NOTICE,
"CLASSIFICATION FORCED "
"job-sheets=\"%s\", "
"job-originating-user-name=\"%s\"",
Classification, job->username);
}
}
/*
* See if we need to add the starting sheet...
*/
if (!(printer->type & CUPS_PRINTER_REMOTE))
{
cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".",
attr->values[0].string.text);
if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0)
{
cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
"Aborting job because the start banner could not be "
"copied.");
return (NULL);
}
cupsdUpdateQuota(printer, job->username, 0, kbytes);
}
}
else if ((attr = ippFindAttribute(job->attrs, "job-sheets",
IPP_TAG_ZERO)) != NULL)
job->job_sheets = attr;
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, "");
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons",
NULL, job->reasons->values[0].string.text);
con->response->request.status.status_code = IPP_OK;
/*
* Add any job subscriptions...
*/
add_job_subscriptions(con, job);
/*
* Set all but the first two attributes to the job attributes group...
*/
for (attr = job->attrs->attrs->next->next; attr; attr = attr->next)
attr->group_tag = IPP_TAG_JOB;
/*
* Fire the "job created" event...
*/
cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created.");
/*
* Return the new job...
*/
return (job);
}
/*
* 'add_job_subscriptions()' - Add any subscriptions for a job.
*/
static void
add_job_subscriptions(
cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job) /* I - Newly created job */
{
int i; /* Looping var */
ipp_attribute_t *prev, /* Previous attribute */
*next, /* Next attribute */
*attr; /* Current attribute */
cupsd_subscription_t *sub; /* Subscription object */
const char *recipient, /* notify-recipient-uri */
*pullmethod; /* notify-pull-method */
ipp_attribute_t *user_data; /* notify-user-data */
int interval; /* notify-time-interval */
unsigned mask; /* notify-events */
/*
* Find the first subscription group attribute; return if we have
* none...
*/
for (attr = job->attrs->attrs; attr; attr = attr->next)
if (attr->group_tag == IPP_TAG_SUBSCRIPTION)
break;
if (!attr)
return;
/*
* Process the subscription attributes in the request...
*/
while (attr)
{
recipient = NULL;
pullmethod = NULL;
user_data = NULL;
interval = 0;
mask = CUPSD_EVENT_NONE;
while (attr && attr->group_tag != IPP_TAG_ZERO)
{
if (!strcmp(attr->name, "notify-recipient-uri") &&
attr->value_tag == IPP_TAG_URI)
{
/*
* Validate the recipient scheme against the ServerBin/notifier
* directory...
*/
char notifier[1024], /* Notifier filename */
scheme[HTTP_MAX_URI], /* Scheme portion of URI */
userpass[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
recipient = attr->values[0].string.text;
if (httpSeparateURI(HTTP_URI_CODING_ALL, recipient,
scheme, sizeof(scheme), userpass, sizeof(userpass),
host, sizeof(host), &port,
resource, sizeof(resource)) < HTTP_URI_OK)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-recipient-uri \"%s\"."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
snprintf(notifier, sizeof(notifier), "%s/notifier/%s", ServerBin,
scheme);
if (access(notifier, X_OK))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" uses unknown "
"scheme."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
if (!strcmp(scheme, "rss") && !check_rss_recipient(recipient))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" is already used."),
recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-pull-method") &&
attr->value_tag == IPP_TAG_KEYWORD)
{
pullmethod = attr->values[0].string.text;
if (strcmp(pullmethod, "ippget"))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-pull-method \"%s\"."), pullmethod);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-charset") &&
attr->value_tag == IPP_TAG_CHARSET &&
strcmp(attr->values[0].string.text, "us-ascii") &&
strcmp(attr->values[0].string.text, "utf-8"))
{
send_ipp_status(con, IPP_CHARSET,
_("Character set \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-natural-language") &&
(attr->value_tag != IPP_TAG_LANGUAGE ||
strcmp(attr->values[0].string.text, DefaultLanguage)))
{
send_ipp_status(con, IPP_CHARSET,
_("Language \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-user-data") &&
attr->value_tag == IPP_TAG_STRING)
{
if (attr->num_values > 1 || attr->values[0].unknown.length > 63)
{
send_ipp_status(con, IPP_REQUEST_VALUE,
_("The notify-user-data value is too large "
"(%d > 63 octets)."),
attr->values[0].unknown.length);
return;
}
user_data = attr;
}
else if (!strcmp(attr->name, "notify-events") &&
attr->value_tag == IPP_TAG_KEYWORD)
{
for (i = 0; i < attr->num_values; i ++)
mask |= cupsdEventValue(attr->values[i].string.text);
}
else if (!strcmp(attr->name, "notify-lease-duration"))
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("The notify-lease-duration attribute cannot be "
"used with job subscriptions."));
return;
}
else if (!strcmp(attr->name, "notify-time-interval") &&
attr->value_tag == IPP_TAG_INTEGER)
interval = attr->values[0].integer;
attr = attr->next;
}
if (!recipient && !pullmethod)
break;
if (mask == CUPSD_EVENT_NONE)
mask = CUPSD_EVENT_JOB_COMPLETED;
if ((sub = cupsdAddSubscription(mask, cupsdFindDest(job->dest), job,
recipient, 0)) != NULL)
{
sub->interval = interval;
cupsdSetString(&sub->owner, job->username);
if (user_data)
{
sub->user_data_len = user_data->values[0].unknown.length;
memcpy(sub->user_data, user_data->values[0].unknown.data,
(size_t)sub->user_data_len);
}
ippAddSeparator(con->response);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-subscription-id", sub->id);
cupsdLogMessage(CUPSD_LOG_DEBUG, "Added subscription %d for job %d",
sub->id, job->id);
}
if (attr)
attr = attr->next;
}
cupsdMarkDirty(CUPSD_DIRTY_SUBSCRIPTIONS);
/*
* Remove all of the subscription attributes from the job request...
*
* TODO: Optimize this since subscription groups have to come at the
* end of the request...
*/
for (attr = job->attrs->attrs, prev = NULL; attr; attr = next)
{
next = attr->next;
if (attr->group_tag == IPP_TAG_SUBSCRIPTION ||
attr->group_tag == IPP_TAG_ZERO)
{
/*
* Free and remove this attribute...
*/
ippDeleteAttribute(NULL, attr);
if (prev)
prev->next = next;
else
job->attrs->attrs = next;
}
else
prev = attr;
}
job->attrs->last = prev;
job->attrs->current = prev;
}
/*
* 'add_job_uuid()' - Add job-uuid attribute to a job.
*
* See RFC 4122 for the definition of UUIDs and the format.
*/
static void
add_job_uuid(cupsd_job_t *job) /* I - Job */
{
char uuid[64]; /* job-uuid string */
/*
* Add a job-uuid attribute if none exists...
*/
if (!ippFindAttribute(job->attrs, "job-uuid", IPP_TAG_URI))
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-uuid", NULL,
httpAssembleUUID(ServerName, RemotePort, job->dest, job->id,
uuid, sizeof(uuid)));
}
/*
* 'add_printer()' - Add a printer to the system.
*/
static void
add_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - URI of printer */
{
http_status_t status; /* Policy status */
int i; /* Looping var */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *printer; /* Printer/class */
ipp_attribute_t *attr; /* Printer attribute */
cups_file_t *fp; /* Script/PPD file */
char line[1024]; /* Line from file... */
char srcfile[1024], /* Source Script/PPD file */
dstfile[1024]; /* Destination Script/PPD file */
int modify; /* Non-zero if we are modifying */
int changed_driver, /* Changed the PPD? */
need_restart_job, /* Need to restart job? */
set_device_uri, /* Did we set the device URI? */
set_port_monitor; /* Did we set the port monitor? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Do we have a valid URI?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/printers/", 10) || strlen(resource) == 10)
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri must be of the form "
"\"ipp://HOSTNAME/printers/PRINTERNAME\"."));
return;
}
/*
* Do we have a valid printer name?
*/
if (!validate_name(resource + 10))
{
/*
* No, return an error...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri \"%s\" contains invalid characters."),
uri->values[0].string.text);
return;
}
/*
* See if the printer already exists; if not, create a new printer...
*/
if ((printer = cupsdFindPrinter(resource + 10)) == NULL)
{
/*
* Printer doesn't exist; see if we have a class of the same name...
*/
if ((printer = cupsdFindClass(resource + 10)) != NULL)
{
/*
* Yes, return an error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("A class named \"%s\" already exists."),
resource + 10);
return;
}
/*
* No, check the default policy then add the printer...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
printer = cupsdAddPrinter(resource + 10);
modify = 0;
}
else if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
else
modify = 1;
/*
* Look for attributes and copy them over as needed...
*/
changed_driver = 0;
need_restart_job = 0;
if ((attr = ippFindAttribute(con->request, "printer-is-temporary", IPP_TAG_BOOLEAN)) != NULL)
printer->temporary = ippGetBoolean(attr, 0);
if ((attr = ippFindAttribute(con->request, "printer-location",
IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI)) != NULL && !strncmp(attr->values[0].string.text, "geo:", 4))
cupsdSetString(&printer->geo_location, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organization", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->organization, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-organizational-unit", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->organizational_unit, attr->values[0].string.text);
if ((attr = ippFindAttribute(con->request, "printer-info",
IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->info, attr->values[0].string.text);
set_device_uri = 0;
if ((attr = ippFindAttribute(con->request, "device-uri",
IPP_TAG_URI)) != NULL)
{
/*
* Do we have a valid device URI?
*/
http_uri_status_t uri_status; /* URI separation status */
char old_device_uri[1024];
/* Old device URI */
need_restart_job = 1;
uri_status = httpSeparateURI(HTTP_URI_CODING_ALL,
attr->values[0].string.text,
scheme, sizeof(scheme),
username, sizeof(username),
host, sizeof(host), &port,
resource, sizeof(resource));
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s device-uri: %s", printer->name, httpURIStatusString(uri_status));
if (uri_status < HTTP_URI_OK)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Bad device-uri \"%s\"."),
attr->values[0].string.text);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if (!strcmp(scheme, "file"))
{
/*
* See if the administrator has enabled file devices...
*/
if (!FileDevice && strcmp(resource, "/dev/null"))
{
/*
* File devices are disabled and the URL is not file:/dev/null...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("File device URIs have been disabled. "
"To enable, see the FileDevice directive in "
"\"%s/cups-files.conf\"."),
ServerRoot);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
}
else
{
/*
* See if the backend exists and is executable...
*/
snprintf(srcfile, sizeof(srcfile), "%s/backend/%s", ServerBin, scheme);
if (access(srcfile, X_OK))
{
/*
* Could not find device in list!
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad device-uri scheme \"%s\"."), scheme);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
}
if (printer->sanitized_device_uri)
strlcpy(old_device_uri, printer->sanitized_device_uri,
sizeof(old_device_uri));
else
old_device_uri[0] = '\0';
cupsdSetDeviceURI(printer, attr->values[0].string.text);
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s device-uri to \"%s\" (was \"%s\".)",
printer->name, printer->sanitized_device_uri,
old_device_uri);
set_device_uri = 1;
}
set_port_monitor = 0;
if ((attr = ippFindAttribute(con->request, "port-monitor",
IPP_TAG_NAME)) != NULL)
{
ipp_attribute_t *supported; /* port-monitor-supported attribute */
need_restart_job = 1;
supported = ippFindAttribute(printer->ppd_attrs, "port-monitor-supported",
IPP_TAG_NAME);
if (supported)
{
for (i = 0; i < supported->num_values; i ++)
if (!strcmp(supported->values[i].string.text,
attr->values[0].string.text))
break;
}
if (!supported || i >= supported->num_values)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Bad port-monitor \"%s\"."),
attr->values[0].string.text);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s port-monitor to \"%s\" (was \"%s\".)",
printer->name, attr->values[0].string.text,
printer->port_monitor ? printer->port_monitor : "none");
if (strcmp(attr->values[0].string.text, "none"))
cupsdSetString(&printer->port_monitor, attr->values[0].string.text);
else
cupsdClearString(&printer->port_monitor);
set_port_monitor = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-is-accepting-jobs",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean != printer->accepting)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-accepting-jobs to %d (was %d.)",
printer->name, attr->values[0].boolean, printer->accepting);
printer->accepting = attr->values[0].boolean;
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"%s accepting jobs.",
printer->accepting ? "Now" : "No longer");
}
if ((attr = ippFindAttribute(con->request, "printer-is-shared", IPP_TAG_BOOLEAN)) != NULL)
{
if (ippGetBoolean(attr, 0) &&
printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate"))
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Cannot share a remote Kerberized printer."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if (printer->type & CUPS_PRINTER_REMOTE)
{
/*
* Cannot re-share remote printers.
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Cannot change printer-is-shared for remote queues."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if (printer->shared && !ippGetBoolean(attr, 0))
cupsdDeregisterPrinter(printer, 1);
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-is-shared to %d (was %d.)",
printer->name, attr->values[0].boolean, printer->shared);
printer->shared = ippGetBoolean(attr, 0);
if (printer->shared && printer->temporary)
printer->temporary = 0;
}
if ((attr = ippFindAttribute(con->request, "printer-state",
IPP_TAG_ENUM)) != NULL)
{
if (attr->values[0].integer != IPP_PRINTER_IDLE &&
attr->values[0].integer != IPP_PRINTER_STOPPED)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad printer-state value %d."),
attr->values[0].integer);
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_INFO, "Setting %s printer-state to %d (was %d.)",
printer->name, attr->values[0].integer, printer->state);
if (attr->values[0].integer == IPP_PRINTER_STOPPED)
cupsdStopPrinter(printer, 0);
else
{
need_restart_job = 1;
cupsdSetPrinterState(printer, (ipp_pstate_t)(attr->values[0].integer), 0);
}
}
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) != NULL)
{
strlcpy(printer->state_message, attr->values[0].string.text,
sizeof(printer->state_message));
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL, "%s",
printer->state_message);
}
if ((attr = ippFindAttribute(con->request, "printer-state-reasons",
IPP_TAG_KEYWORD)) != NULL)
{
if (attr->num_values >
(int)(sizeof(printer->reasons) / sizeof(printer->reasons[0])))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Too many printer-state-reasons values (%d > %d)."),
attr->num_values,
(int)(sizeof(printer->reasons) /
sizeof(printer->reasons[0])));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
for (i = 0; i < printer->num_reasons; i ++)
_cupsStrFree(printer->reasons[i]);
printer->num_reasons = 0;
for (i = 0; i < attr->num_values; i ++)
{
if (!strcmp(attr->values[i].string.text, "none"))
continue;
printer->reasons[printer->num_reasons] =
_cupsStrRetain(attr->values[i].string.text);
printer->num_reasons ++;
if (!strcmp(attr->values[i].string.text, "paused") &&
printer->state != IPP_PRINTER_STOPPED)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s printer-state to %d (was %d.)",
printer->name, IPP_PRINTER_STOPPED, printer->state);
cupsdStopPrinter(printer, 0);
}
}
if (PrintcapFormat == PRINTCAP_PLIST)
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"Printer \"%s\" state changed.", printer->name);
}
if (!set_printer_defaults(con, printer))
{
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
if ((attr = ippFindAttribute(con->request, "auth-info-required",
IPP_TAG_KEYWORD)) != NULL)
cupsdSetAuthInfoRequired(printer, NULL, attr);
/*
* See if we have all required attributes...
*/
if (!printer->device_uri)
cupsdSetString(&printer->device_uri, "file:///dev/null");
/*
* See if we have a PPD file attached to the request...
*/
if (con->filename)
{
need_restart_job = 1;
changed_driver = 1;
strlcpy(srcfile, con->filename, sizeof(srcfile));
if ((fp = cupsFileOpen(srcfile, "rb")))
{
/*
* Yes; get the first line from it...
*/
line[0] = '\0';
cupsFileGets(fp, line, sizeof(line));
cupsFileClose(fp);
/*
* Then see what kind of file it is...
*/
if (strncmp(line, "*PPD-Adobe", 10))
{
send_ipp_status(con, IPP_STATUS_ERROR_DOCUMENT_FORMAT_NOT_SUPPORTED, _("Bad PPD file."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
snprintf(dstfile, sizeof(dstfile), "%s/ppd/%s.ppd", ServerRoot,
printer->name);
/*
* The new file is a PPD file, so move the file over to the ppd
* directory...
*/
if (copy_file(srcfile, dstfile, ConfigFilePerm))
{
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to copy PPD file - %s"), strerror(errno));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_DEBUG, "Copied PPD file successfully");
}
}
else if ((attr = ippFindAttribute(con->request, "ppd-name", IPP_TAG_NAME)) != NULL)
{
const char *ppd_name = ippGetString(attr, 0, NULL);
/* ppd-name value */
need_restart_job = 1;
changed_driver = 1;
if (!strcmp(ppd_name, "raw"))
{
/*
* Raw driver, remove any existing PPD file.
*/
snprintf(dstfile, sizeof(dstfile), "%s/ppd/%s.ppd", ServerRoot, printer->name);
unlink(dstfile);
}
else if (strstr(ppd_name, "../"))
{
send_ipp_status(con, IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES, _("Invalid ppd-name value."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
else
{
/*
* PPD model file...
*/
snprintf(dstfile, sizeof(dstfile), "%s/ppd/%s.ppd", ServerRoot, printer->name);
if (copy_model(con, ppd_name, dstfile))
{
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to copy PPD file."));
if (!modify)
cupsdDeletePrinter(printer, 0);
return;
}
cupsdLogMessage(CUPSD_LOG_DEBUG, "Copied PPD file successfully");
}
}
if (changed_driver)
{
/*
* If we changed the PPD, then remove the printer's cache file and clear the
* printer-state-reasons...
*/
char cache_name[1024]; /* Cache filename for printer attrs */
snprintf(cache_name, sizeof(cache_name), "%s/%s.data", CacheDir, printer->name);
unlink(cache_name);
cupsdSetPrinterReasons(printer, "none");
/*
* (Re)register color profiles...
*/
cupsdRegisterColor(printer);
}
/*
* If we set the device URI but not the port monitor, check which port
* monitor to use by default...
*/
if (set_device_uri && !set_port_monitor)
{
ppd_file_t *ppd; /* PPD file */
ppd_attr_t *ppdattr; /* cupsPortMonitor attribute */
httpSeparateURI(HTTP_URI_CODING_ALL, printer->device_uri, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
snprintf(srcfile, sizeof(srcfile), "%s/ppd/%s.ppd", ServerRoot,
printer->name);
if ((ppd = _ppdOpenFile(srcfile, _PPD_LOCALIZATION_NONE)) != NULL)
{
for (ppdattr = ppdFindAttr(ppd, "cupsPortMonitor", NULL);
ppdattr;
ppdattr = ppdFindNextAttr(ppd, "cupsPortMonitor", NULL))
if (!strcmp(scheme, ppdattr->spec))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Setting %s port-monitor to \"%s\" (was \"%s\".)",
printer->name, ppdattr->value,
printer->port_monitor ? printer->port_monitor
: "none");
if (strcmp(ppdattr->value, "none"))
cupsdSetString(&printer->port_monitor, ppdattr->value);
else
cupsdClearString(&printer->port_monitor);
break;
}
ppdClose(ppd);
}
}
printer->config_time = time(NULL);
/*
* Update the printer attributes and return...
*/
cupsdSetPrinterAttrs(printer);
if (!printer->temporary)
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
if (need_restart_job && printer->job)
{
/*
* Restart the current job...
*/
cupsdSetJobState(printer->job, IPP_JOB_PENDING, CUPSD_JOB_FORCE,
"Job restarted because the printer was modified.");
}
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
if (modify)
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_MODIFIED,
printer, NULL, "Printer \"%s\" modified by \"%s\".",
printer->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" modified by \"%s\".",
printer->name, get_username(con));
}
else
{
cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED,
printer, NULL, "New printer \"%s\" added by \"%s\".",
printer->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO, "New printer \"%s\" added by \"%s\".",
printer->name, get_username(con));
}
con->response->request.status.status_code = IPP_OK;
}
/*
* 'add_printer_state_reasons()' - Add the "printer-state-reasons" attribute
* based upon the printer state...
*/
static void
add_printer_state_reasons(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *p) /* I - Printer info */
{
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"add_printer_state_reasons(%p[%d], %p[%s])",
con, con->number, p, p->name);
if (p->num_reasons == 0)
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD,
"printer-state-reasons", NULL, "none");
else
ippAddStrings(con->response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD,
"printer-state-reasons", p->num_reasons, NULL,
(const char * const *)p->reasons);
}
/*
* 'add_queued_job_count()' - Add the "queued-job-count" attribute for
* the specified printer or class.
*/
static void
add_queued_job_count(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *p) /* I - Printer or class */
{
int count; /* Number of jobs on destination */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_queued_job_count(%p[%d], %p[%s])",
con, con->number, p, p->name);
count = cupsdGetPrinterJobCount(p->name);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"queued-job-count", count);
}
/*
* 'apply_printer_defaults()' - Apply printer default options to a job.
*/
static void
apply_printer_defaults(
cupsd_printer_t *printer, /* I - Printer */
cupsd_job_t *job) /* I - Job */
{
int i, /* Looping var */
num_options; /* Number of default options */
cups_option_t *options, /* Default options */
*option; /* Current option */
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Applying default options...");
/*
* Collect all of the default options and add the missing ones to the
* job object...
*/
for (i = printer->num_options, num_options = 0, options = NULL,
option = printer->options;
i > 0;
i --, option ++)
if (!ippFindAttribute(job->attrs, option->name, IPP_TAG_ZERO))
{
if (!strcmp(option->name, "print-quality") && ippFindAttribute(job->attrs, "cupsPrintQuality", IPP_TAG_NAME))
continue; /* Don't override cupsPrintQuality */
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Adding default %s=%s", option->name, option->value);
num_options = cupsAddOption(option->name, option->value, num_options, &options);
}
/*
* Encode these options as attributes in the job object...
*/
cupsEncodeOptions2(job->attrs, num_options, options, IPP_TAG_JOB);
cupsFreeOptions(num_options, options);
}
/*
* 'authenticate_job()' - Set job authentication info.
*/
static void
authenticate_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
ipp_attribute_t *attr, /* job-id attribute */
*auth_info; /* auth-info attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
char scheme[HTTP_MAX_URI],
/* Method portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "authenticate_job(%p[%d], %s)",
con, con->number, uri->values[0].string.text);
/*
* Start with "everything is OK" status...
*/
con->response->request.status.status_code = IPP_OK;
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job has been completed...
*/
if (job->state_value != IPP_JOB_HELD)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is not held for authentication."),
jobid);
return;
}
/*
* See if we have already authenticated...
*/
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
if (!con->username[0] && !auth_info)
{
cupsd_printer_t *printer; /* Job destination */
/*
* No auth data. If we need to authenticate via Kerberos, send a
* HTTP auth challenge, otherwise just return an IPP error...
*/
printer = cupsdFindDest(job->dest);
if (printer && printer->num_auth_info_required > 0 &&
!strcmp(printer->auth_info_required[0], "negotiate"))
send_http_error(con, HTTP_UNAUTHORIZED, printer);
else
send_ipp_status(con, IPP_NOT_AUTHORIZED,
_("No authentication information provided."));
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Save the authentication information for this job...
*/
save_auth_info(con, job, auth_info);
/*
* Reset the job-hold-until value to "no-hold"...
*/
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (attr)
{
ippSetValueTag(job->attrs, &attr, IPP_TAG_KEYWORD);
ippSetString(job->attrs, &attr, 0, "no-hold");
}
/*
* Release the job and return...
*/
cupsdReleaseJob(job);
cupsdAddEvent(CUPSD_EVENT_JOB_STATE, NULL, job, "Job authenticated by user");
cupsdLogJob(job, CUPSD_LOG_INFO, "Authenticated by \"%s\".", con->username);
cupsdCheckJobs();
}
/*
* 'cancel_all_jobs()' - Cancel all or selected print jobs.
*/
static void
cancel_all_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
int i; /* Looping var */
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
userpass[HTTP_MAX_URI], /* Username portion of URI */
hostname[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
ipp_attribute_t *attr; /* Attribute in request */
const char *username = NULL; /* Username */
cupsd_jobaction_t purge = CUPSD_JOB_DEFAULT;
/* Purge? */
cupsd_printer_t *printer; /* Printer */
ipp_attribute_t *job_ids; /* job-ids attribute */
cupsd_job_t *job; /* Job */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cancel_all_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Get the jobs to cancel/purge...
*/
switch (con->request->request.op.operation_id)
{
case IPP_PURGE_JOBS :
/*
* Get the username (if any) for the jobs we want to cancel (only if
* "my-jobs" is specified...
*/
if ((attr = ippFindAttribute(con->request, "my-jobs",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean)
{
if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
username = attr->values[0].string.text;
else
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing requesting-user-name attribute."));
return;
}
}
/*
* Look for the "purge-jobs" attribute...
*/
if ((attr = ippFindAttribute(con->request, "purge-jobs",
IPP_TAG_BOOLEAN)) != NULL)
purge = attr->values[0].boolean ? CUPSD_JOB_PURGE : CUPSD_JOB_DEFAULT;
else
purge = CUPSD_JOB_PURGE;
break;
case IPP_CANCEL_MY_JOBS :
if (con->username[0])
username = con->username;
else if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
username = attr->values[0].string.text;
else
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing requesting-user-name attribute."));
return;
}
default :
break;
}
job_ids = ippFindAttribute(con->request, "job-ids", IPP_TAG_INTEGER);
/*
* See if we have a printer URI...
*/
if (strcmp(uri->name, "printer-uri"))
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("The printer-uri attribute is required."));
return;
}
/*
* And if the destination is valid...
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text,
scheme, sizeof(scheme), userpass, sizeof(userpass),
hostname, sizeof(hostname), &port,
resource, sizeof(resource));
if ((!strncmp(resource, "/printers/", 10) && resource[10]) ||
(!strncmp(resource, "/classes/", 9) && resource[9]))
{
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
if (job_ids)
{
for (i = 0; i < job_ids->num_values; i ++)
{
if ((job = cupsdFindJob(job_ids->values[i].integer)) == NULL)
break;
if (con->request->request.op.operation_id == IPP_CANCEL_MY_JOBS &&
_cups_strcasecmp(job->username, username))
break;
}
if (i < job_ids->num_values)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
job_ids->values[i].integer);
return;
}
for (i = 0; i < job_ids->num_values; i ++)
{
job = cupsdFindJob(job_ids->values[i].integer);
cupsdSetJobState(job, IPP_JOB_CANCELED, purge,
purge == CUPSD_JOB_PURGE ? "Job purged by user." :
"Job canceled by user.");
}
cupsdLogMessage(CUPSD_LOG_INFO, "Selected jobs were %s by \"%s\".",
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
else
{
/*
* Cancel all jobs on all printers...
*/
cupsdCancelJobs(NULL, username, purge);
cupsdLogMessage(CUPSD_LOG_INFO, "All jobs were %s by \"%s\".",
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
}
else
{
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
if (job_ids)
{
for (i = 0; i < job_ids->num_values; i ++)
{
if ((job = cupsdFindJob(job_ids->values[i].integer)) == NULL ||
_cups_strcasecmp(job->dest, printer->name))
break;
if (con->request->request.op.operation_id == IPP_CANCEL_MY_JOBS &&
_cups_strcasecmp(job->username, username))
break;
}
if (i < job_ids->num_values)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
job_ids->values[i].integer);
return;
}
for (i = 0; i < job_ids->num_values; i ++)
{
job = cupsdFindJob(job_ids->values[i].integer);
cupsdSetJobState(job, IPP_JOB_CANCELED, purge,
purge == CUPSD_JOB_PURGE ? "Job purged by user." :
"Job canceled by user.");
}
cupsdLogMessage(CUPSD_LOG_INFO, "Selected jobs were %s by \"%s\".",
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
else
{
/*
* Cancel all of the jobs on the named printer...
*/
cupsdCancelJobs(printer->name, username, purge);
cupsdLogMessage(CUPSD_LOG_INFO, "All jobs on \"%s\" were %s by \"%s\".",
printer->name,
purge == CUPSD_JOB_PURGE ? "purged" : "canceled",
get_username(con));
}
}
con->response->request.status.status_code = IPP_OK;
cupsdCheckJobs();
}
/*
* 'cancel_job()' - Cancel a print job.
*/
static void
cancel_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job information */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsd_jobaction_t purge; /* Purge the job? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cancel_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
if ((jobid = attr->values[0].integer) == 0)
{
/*
* Find the current job on the specified printer...
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* See if there are any pending jobs...
*/
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value <= IPP_JOB_PROCESSING &&
!_cups_strcasecmp(job->dest, printer->name))
break;
if (job)
jobid = job->id;
else
{
/*
* No, try stopped jobs...
*/
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value == IPP_JOB_STOPPED &&
!_cups_strcasecmp(job->dest, printer->name))
break;
if (job)
jobid = job->id;
else
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("No active jobs on %s."),
printer->name);
return;
}
}
}
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* Look for the "purge-job" attribute...
*/
if ((attr = ippFindAttribute(con->request, "purge-job",
IPP_TAG_BOOLEAN)) != NULL)
purge = attr->values[0].boolean ? CUPSD_JOB_PURGE : CUPSD_JOB_DEFAULT;
else
purge = CUPSD_JOB_DEFAULT;
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See if the job is already completed, canceled, or aborted; if so,
* we can't cancel...
*/
if (job->state_value >= IPP_JOB_CANCELED && purge != CUPSD_JOB_PURGE)
{
switch (job->state_value)
{
case IPP_JOB_CANCELED :
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is already canceled - can\'t cancel."),
jobid);
break;
case IPP_JOB_ABORTED :
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is already aborted - can\'t cancel."),
jobid);
break;
default :
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is already completed - can\'t cancel."),
jobid);
break;
}
return;
}
/*
* Cancel the job and return...
*/
cupsdSetJobState(job, IPP_JOB_CANCELED, purge,
purge == CUPSD_JOB_PURGE ? "Job purged by \"%s\"" :
"Job canceled by \"%s\"",
username);
cupsdCheckJobs();
if (purge == CUPSD_JOB_PURGE)
cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Purged by \"%s\".", jobid,
username);
else
cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Canceled by \"%s\".", jobid,
username);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'cancel_subscription()' - Cancel a subscription.
*/
static void
cancel_subscription(
cupsd_client_t *con, /* I - Client connection */
int sub_id) /* I - Subscription ID */
{
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"cancel_subscription(con=%p[%d], sub_id=%d)",
con, con->number, sub_id);
/*
* Is the subscription ID valid?
*/
if ((sub = cupsdFindSubscription(sub_id)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("Subscription #%d does not exist."), sub_id);
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(sub->dest ? sub->dest->op_policy_ptr :
DefaultPolicyPtr,
con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
/*
* Cancel the subscription...
*/
cupsdDeleteSubscription(sub, 1);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'check_rss_recipient()' - Check that we do not have a duplicate RSS feed URI.
*/
static int /* O - 1 if OK, 0 if not */
check_rss_recipient(
const char *recipient) /* I - Recipient URI */
{
cupsd_subscription_t *sub; /* Current subscription */
for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
sub;
sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
if (sub->recipient)
{
/*
* Compare the URIs up to the first ?...
*/
const char *r1, *r2;
for (r1 = recipient, r2 = sub->recipient;
*r1 == *r2 && *r1 && *r1 != '?' && *r2 && *r2 != '?';
r1 ++, r2 ++);
if (*r1 == *r2)
return (0);
}
return (1);
}
/*
* 'check_quotas()' - Check quotas for a printer and user.
*/
static int /* O - 1 if OK, 0 if forbidden,
-1 if limit reached */
check_quotas(cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *p) /* I - Printer or class */
{
char username[33], /* Username */
*name; /* Current user name */
cupsd_quota_t *q; /* Quota data */
#ifdef HAVE_MBR_UID_TO_UUID
/*
* Use Apple membership APIs which require that all names represent
* valid user account or group records accessible by the server.
*/
uuid_t usr_uuid; /* UUID for job requesting user */
uuid_t usr2_uuid; /* UUID for ACL user name entry */
uuid_t grp_uuid; /* UUID for ACL group name entry */
int mbr_err; /* Error from membership function */
int is_member; /* Is this user a member? */
#else
/*
* Use standard POSIX APIs for checking users and groups...
*/
struct passwd *pw; /* User password data */
#endif /* HAVE_MBR_UID_TO_UUID */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "check_quotas(%p[%d], %p[%s])",
con, con->number, p, p->name);
/*
* Figure out who is printing...
*/
strlcpy(username, get_username(con), sizeof(username));
if ((name = strchr(username, '@')) != NULL)
*name = '\0'; /* Strip @REALM */
/*
* Check global active job limits for printers and users...
*/
if (MaxJobsPerPrinter)
{
/*
* Check if there are too many pending jobs on this printer...
*/
if (cupsdGetPrinterJobCount(p->name) >= MaxJobsPerPrinter)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Too many jobs for printer \"%s\"...",
p->name);
return (-1);
}
}
if (MaxJobsPerUser)
{
/*
* Check if there are too many pending jobs for this user...
*/
if (cupsdGetUserJobCount(username) >= MaxJobsPerUser)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Too many jobs for user \"%s\"...",
username);
return (-1);
}
}
/*
* Check against users...
*/
if (cupsArrayCount(p->users) == 0 && p->k_limit == 0 && p->page_limit == 0)
return (1);
if (cupsArrayCount(p->users))
{
#ifdef HAVE_MBR_UID_TO_UUID
/*
* Get UUID for job requesting user...
*/
if (mbr_user_name_to_uuid((char *)username, usr_uuid))
{
/*
* Unknown user...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: UUID lookup failed for user \"%s\"",
username);
cupsdLogMessage(CUPSD_LOG_INFO,
"Denying user \"%s\" access to printer \"%s\" "
"(unknown user)...",
username, p->name);
return (0);
}
#else
/*
* Get UID and GID of requesting user...
*/
pw = getpwnam(username);
endpwent();
#endif /* HAVE_MBR_UID_TO_UUID */
for (name = (char *)cupsArrayFirst(p->users);
name;
name = (char *)cupsArrayNext(p->users))
if (name[0] == '@')
{
/*
* Check group membership...
*/
#ifdef HAVE_MBR_UID_TO_UUID
if (name[1] == '#')
{
if (uuid_parse(name + 2, grp_uuid))
uuid_clear(grp_uuid);
}
else if ((mbr_err = mbr_group_name_to_uuid(name + 1, grp_uuid)) != 0)
{
/*
* Invalid ACL entries are ignored for matching; just record a
* warning in the log...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: UUID lookup failed for ACL entry "
"\"%s\" (err=%d)", name, mbr_err);
cupsdLogMessage(CUPSD_LOG_WARN,
"Access control entry \"%s\" not a valid group name; "
"entry ignored", name);
}
if ((mbr_err = mbr_check_membership(usr_uuid, grp_uuid,
&is_member)) != 0)
{
/*
* At this point, there should be no errors, but check anyways...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: group \"%s\" membership check "
"failed (err=%d)", name + 1, mbr_err);
is_member = 0;
}
/*
* Stop if we found a match...
*/
if (is_member)
break;
#else
if (cupsdCheckGroup(username, pw, name + 1))
break;
#endif /* HAVE_MBR_UID_TO_UUID */
}
#ifdef HAVE_MBR_UID_TO_UUID
else
{
if (name[0] == '#')
{
if (uuid_parse(name + 1, usr2_uuid))
uuid_clear(usr2_uuid);
}
else if ((mbr_err = mbr_user_name_to_uuid(name, usr2_uuid)) != 0)
{
/*
* Invalid ACL entries are ignored for matching; just record a
* warning in the log...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG,
"check_quotas: UUID lookup failed for ACL entry "
"\"%s\" (err=%d)", name, mbr_err);
cupsdLogMessage(CUPSD_LOG_WARN,
"Access control entry \"%s\" not a valid user name; "
"entry ignored", name);
}
if (!uuid_compare(usr_uuid, usr2_uuid))
break;
}
#else
else if (!_cups_strcasecmp(username, name))
break;
#endif /* HAVE_MBR_UID_TO_UUID */
if ((name != NULL) == p->deny_users)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Denying user \"%s\" access to printer \"%s\"...",
username, p->name);
return (0);
}
}
/*
* Check quotas...
*/
if (p->k_limit || p->page_limit)
{
if ((q = cupsdUpdateQuota(p, username, 0, 0)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to allocate quota data for user \"%s\"",
username);
return (-1);
}
if ((q->k_count >= p->k_limit && p->k_limit) ||
(q->page_count >= p->page_limit && p->page_limit))
{
cupsdLogMessage(CUPSD_LOG_INFO, "User \"%s\" is over the quota limit...",
username);
return (-1);
}
}
/*
* If we have gotten this far, we're done!
*/
return (1);
}
/*
* 'close_job()' - Close a multi-file job.
*/
static void
close_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
cupsd_job_t *job; /* Job */
ipp_attribute_t *attr; /* Attribute */
char job_uri[HTTP_MAX_URI],
/* Job URI */
username[256]; /* User name */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "close_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (strcmp(uri->name, "printer-uri"))
{
/*
* job-uri is not supported by Close-Job!
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("Close-Job doesn't support the job-uri attribute."));
return;
}
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
if ((job = cupsdFindJob(attr->values[0].integer)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
attr->values[0].integer);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Add any ending sheet...
*/
if (cupsdTimeoutJob(job))
return;
if (job->state_value == IPP_JOB_STOPPED)
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
}
else if (job->state_value == IPP_JOB_HELD)
{
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr || !strcmp(attr->values[0].string.text, "no-hold"))
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
}
}
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
con->response->request.status.status_code = IPP_OK;
/*
* Start the job if necessary...
*/
cupsdCheckJobs();
}
/*
* 'copy_attrs()' - Copy attributes from one request to another.
*/
static void
copy_attrs(ipp_t *to, /* I - Destination request */
ipp_t *from, /* I - Source request */
cups_array_t *ra, /* I - Requested attributes */
ipp_tag_t group, /* I - Group to copy */
int quickcopy, /* I - Do a quick copy? */
cups_array_t *exclude) /* I - Attributes to exclude? */
{
ipp_attribute_t *fromattr; /* Source attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"copy_attrs(to=%p, from=%p, ra=%p, group=%x, quickcopy=%d)",
to, from, ra, group, quickcopy);
if (!to || !from)
return;
for (fromattr = from->attrs; fromattr; fromattr = fromattr->next)
{
/*
* Filter attributes as needed...
*/
if ((group != IPP_TAG_ZERO && fromattr->group_tag != group &&
fromattr->group_tag != IPP_TAG_ZERO) || !fromattr->name)
continue;
if (!strcmp(fromattr->name, "document-password") ||
!strcmp(fromattr->name, "job-authorization-uri") ||
!strcmp(fromattr->name, "job-password") ||
!strcmp(fromattr->name, "job-password-encryption") ||
!strcmp(fromattr->name, "job-printer-uri"))
continue;
if (exclude &&
(cupsArrayFind(exclude, fromattr->name) ||
cupsArrayFind(exclude, "all")))
{
/*
* We need to exclude this attribute for security reasons; we require the
* job-id attribute regardless of the security settings for IPP
* conformance.
*
* The job-printer-uri attribute is handled by copy_job_attrs().
*
* Subscription attribute security is handled by copy_subscription_attrs().
*/
if (strcmp(fromattr->name, "job-id"))
continue;
}
if (!ra || cupsArrayFind(ra, fromattr->name))
{
/*
* Don't send collection attributes by default to IPP/1.x clients
* since many do not support collections. Also don't send
* media-col-database unless specifically requested by the client.
*/
if (fromattr->value_tag == IPP_TAG_BEGIN_COLLECTION &&
!ra &&
(to->request.status.version[0] == 1 ||
!strcmp(fromattr->name, "media-col-database")))
continue;
ippCopyAttribute(to, fromattr, quickcopy);
}
}
}
/*
* 'copy_banner()' - Copy a banner file to the requests directory for the
* specified job.
*/
static int /* O - Size of banner file in kbytes */
copy_banner(cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job, /* I - Job information */
const char *name) /* I - Name of banner */
{
int i; /* Looping var */
int kbytes; /* Size of banner file in kbytes */
char filename[1024]; /* Job filename */
cupsd_banner_t *banner; /* Pointer to banner */
cups_file_t *in; /* Input file */
cups_file_t *out; /* Output file */
int ch; /* Character from file */
char attrname[255], /* Name of attribute */
*s; /* Pointer into name */
ipp_attribute_t *attr; /* Attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"copy_banner(con=%p[%d], job=%p[%d], name=\"%s\")",
con, con ? con->number : -1, job, job->id,
name ? name : "(null)");
/*
* Find the banner; return if not found or "none"...
*/
if (!name || !strcmp(name, "none") ||
(banner = cupsdFindBanner(name)) == NULL)
return (0);
/*
* Open the banner and job files...
*/
if (add_file(con, job, banner->filetype, 0))
return (-1);
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id,
job->num_files);
if ((out = cupsFileOpen(filename, "w")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to create banner job file %s - %s",
filename, strerror(errno));
job->num_files --;
return (0);
}
fchmod(cupsFileNumber(out), 0640);
fchown(cupsFileNumber(out), RunUser, Group);
/*
* Try the localized banner file under the subdirectory...
*/
strlcpy(attrname, job->attrs->attrs->next->values[0].string.text,
sizeof(attrname));
if (strlen(attrname) > 2 && attrname[2] == '-')
{
/*
* Convert ll-cc to ll_CC...
*/
attrname[2] = '_';
attrname[3] = (char)toupper(attrname[3] & 255);
attrname[4] = (char)toupper(attrname[4] & 255);
}
snprintf(filename, sizeof(filename), "%s/banners/%s/%s", DataDir,
attrname, name);
if (access(filename, 0) && strlen(attrname) > 2)
{
/*
* Wasn't able to find "ll_CC" locale file; try the non-national
* localization banner directory.
*/
attrname[2] = '\0';
snprintf(filename, sizeof(filename), "%s/banners/%s/%s", DataDir,
attrname, name);
}
if (access(filename, 0))
{
/*
* Use the non-localized banner file.
*/
snprintf(filename, sizeof(filename), "%s/banners/%s", DataDir, name);
}
if ((in = cupsFileOpen(filename, "r")) == NULL)
{
cupsFileClose(out);
unlink(filename);
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open banner template file %s - %s",
filename, strerror(errno));
job->num_files --;
return (0);
}
/*
* Parse the file to the end...
*/
while ((ch = cupsFileGetChar(in)) != EOF)
if (ch == '{')
{
/*
* Get an attribute name...
*/
for (s = attrname; (ch = cupsFileGetChar(in)) != EOF;)
if (!isalpha(ch & 255) && ch != '-' && ch != '?')
break;
else if (s < (attrname + sizeof(attrname) - 1))
*s++ = (char)ch;
else
break;
*s = '\0';
if (ch != '}')
{
/*
* Ignore { followed by stuff that is not an attribute name...
*/
cupsFilePrintf(out, "{%s%c", attrname, ch);
continue;
}
/*
* See if it is defined...
*/
if (attrname[0] == '?')
s = attrname + 1;
else
s = attrname;
if (!strcmp(s, "printer-name"))
{
cupsFilePuts(out, job->dest);
continue;
}
else if ((attr = ippFindAttribute(job->attrs, s, IPP_TAG_ZERO)) == NULL)
{
/*
* See if we have a leading question mark...
*/
if (attrname[0] != '?')
{
/*
* Nope, write to file as-is; probably a PostScript procedure...
*/
cupsFilePrintf(out, "{%s}", attrname);
}
continue;
}
/*
* Output value(s)...
*/
for (i = 0; i < attr->num_values; i ++)
{
if (i)
cupsFilePutChar(out, ',');
switch (attr->value_tag)
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
if (!strncmp(s, "time-at-", 8))
{
struct timeval tv; /* Time value */
tv.tv_sec = attr->values[i].integer;
tv.tv_usec = 0;
cupsFilePuts(out, cupsdGetDateTime(&tv, CUPSD_TIME_STANDARD));
}
else
cupsFilePrintf(out, "%d", attr->values[i].integer);
break;
case IPP_TAG_BOOLEAN :
cupsFilePrintf(out, "%d", attr->values[i].boolean);
break;
case IPP_TAG_NOVALUE :
cupsFilePuts(out, "novalue");
break;
case IPP_TAG_RANGE :
cupsFilePrintf(out, "%d-%d", attr->values[i].range.lower,
attr->values[i].range.upper);
break;
case IPP_TAG_RESOLUTION :
cupsFilePrintf(out, "%dx%d%s", attr->values[i].resolution.xres,
attr->values[i].resolution.yres,
attr->values[i].resolution.units == IPP_RES_PER_INCH ?
"dpi" : "dpcm");
break;
case IPP_TAG_URI :
case IPP_TAG_STRING :
case IPP_TAG_TEXT :
case IPP_TAG_NAME :
case IPP_TAG_KEYWORD :
case IPP_TAG_CHARSET :
case IPP_TAG_LANGUAGE :
if (!_cups_strcasecmp(banner->filetype->type, "postscript"))
{
/*
* Need to quote strings for PS banners...
*/
const char *p;
for (p = attr->values[i].string.text; *p; p ++)
{
if (*p == '(' || *p == ')' || *p == '\\')
{
cupsFilePutChar(out, '\\');
cupsFilePutChar(out, *p);
}
else if (*p < 32 || *p > 126)
cupsFilePrintf(out, "\\%03o", *p & 255);
else
cupsFilePutChar(out, *p);
}
}
else
cupsFilePuts(out, attr->values[i].string.text);
break;
default :
break; /* anti-compiler-warning-code */
}
}
}
else if (ch == '\\') /* Quoted char */
{
ch = cupsFileGetChar(in);
if (ch != '{') /* Only do special handling for \{ */
cupsFilePutChar(out, '\\');
cupsFilePutChar(out, ch);
}
else
cupsFilePutChar(out, ch);
cupsFileClose(in);
kbytes = (cupsFileTell(out) + 1023) / 1024;
job->koctets += kbytes;
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer += kbytes;
cupsFileClose(out);
return (kbytes);
}
/*
* 'copy_file()' - Copy a PPD file...
*/
static int /* O - 0 = success, -1 = error */
copy_file(const char *from, /* I - Source file */
const char *to, /* I - Destination file */
mode_t mode) /* I - Permissions */
{
cups_file_t *src, /* Source file */
*dst; /* Destination file */
int bytes; /* Bytes to read/write */
char buffer[2048]; /* Copy buffer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_file(\"%s\", \"%s\")", from, to);
/*
* Open the source and destination file for a copy...
*/
if ((src = cupsFileOpen(from, "rb")) == NULL)
return (-1);
if ((dst = cupsdCreateConfFile(to, mode)) == NULL)
{
cupsFileClose(src);
return (-1);
}
/*
* Copy the source file to the destination...
*/
while ((bytes = cupsFileRead(src, buffer, sizeof(buffer))) > 0)
if (cupsFileWrite(dst, buffer, (size_t)bytes) < bytes)
{
cupsFileClose(src);
cupsFileClose(dst);
return (-1);
}
/*
* Close both files and return...
*/
cupsFileClose(src);
return (cupsdCloseCreatedConfFile(dst, to));
}
/*
* 'copy_model()' - Copy a PPD model file, substituting default values
* as needed...
*/
static int /* O - 0 = success, -1 = error */
copy_model(cupsd_client_t *con, /* I - Client connection */
const char *from, /* I - Source file */
const char *to) /* I - Destination file */
{
fd_set input; /* select() input set */
struct timeval timeout; /* select() timeout */
int maxfd; /* Max file descriptor for select() */
char tempfile[1024]; /* Temporary PPD file */
int tempfd; /* Temporary PPD file descriptor */
int temppid; /* Process ID of cups-driverd */
int temppipe[2]; /* Temporary pipes */
char *argv[4], /* Command-line arguments */
*envp[MAX_ENV]; /* Environment */
cups_file_t *src, /* Source file */
*dst; /* Destination file */
ppd_file_t *ppd; /* PPD file */
int bytes, /* Bytes from pipe */
total; /* Total bytes from pipe */
char buffer[2048]; /* Copy buffer */
int i; /* Looping var */
char option[PPD_MAX_NAME], /* Option name */
choice[PPD_MAX_NAME]; /* Choice name */
ppd_size_t *size; /* Default size */
int num_defaults; /* Number of default options */
cups_option_t *defaults; /* Default options */
char cups_protocol[PPD_MAX_LINE];
/* cupsProtocol attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_model(con=%p, from=\"%s\", to=\"%s\")", con, from, to);
/*
* Run cups-driverd to get the PPD file...
*/
argv[0] = "cups-driverd";
argv[1] = "cat";
argv[2] = (char *)from;
argv[3] = NULL;
cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
snprintf(buffer, sizeof(buffer), "%s/daemon/cups-driverd", ServerBin);
snprintf(tempfile, sizeof(tempfile), "%s/%d.ppd", TempDir, con->number);
tempfd = open(tempfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (tempfd < 0 || cupsdOpenPipe(temppipe))
return (-1);
cupsdLogMessage(CUPSD_LOG_DEBUG,
"copy_model: Running \"cups-driverd cat %s\"...", from);
if (!cupsdStartProcess(buffer, argv, envp, -1, temppipe[1], CGIPipes[1],
-1, -1, 0, DefaultProfile, NULL, &temppid))
{
close(tempfd);
unlink(tempfile);
return (-1);
}
close(temppipe[1]);
/*
* Wait up to 30 seconds for the PPD file to be copied...
*/
total = 0;
if (temppipe[0] > CGIPipes[0])
maxfd = temppipe[0] + 1;
else
maxfd = CGIPipes[0] + 1;
for (;;)
{
/*
* See if we have data ready...
*/
FD_ZERO(&input);
FD_SET(temppipe[0], &input);
FD_SET(CGIPipes[0], &input);
timeout.tv_sec = 30;
timeout.tv_usec = 0;
if ((i = select(maxfd, &input, NULL, NULL, &timeout)) < 0)
{
if (errno == EINTR)
continue;
else
break;
}
else if (i == 0)
{
/*
* We have timed out...
*/
break;
}
if (FD_ISSET(temppipe[0], &input))
{
/*
* Read the PPD file from the pipe, and write it to the PPD file.
*/
if ((bytes = read(temppipe[0], buffer, sizeof(buffer))) > 0)
{
if (write(tempfd, buffer, (size_t)bytes) < bytes)
break;
total += bytes;
}
else
break;
}
if (FD_ISSET(CGIPipes[0], &input))
cupsdUpdateCGI();
}
close(temppipe[0]);
close(tempfd);
if (!total)
{
/*
* No data from cups-deviced...
*/
cupsdLogMessage(CUPSD_LOG_ERROR, "copy_model: empty PPD file");
unlink(tempfile);
return (-1);
}
/*
* Open the source file for a copy...
*/
if ((src = cupsFileOpen(tempfile, "rb")) == NULL)
{
unlink(tempfile);
return (-1);
}
/*
* Read the source file and see what page sizes are supported...
*/
if ((ppd = _ppdOpen(src, _PPD_LOCALIZATION_NONE)) == NULL)
{
cupsFileClose(src);
unlink(tempfile);
return (-1);
}
/*
* Open the destination (if possible) and set the default options...
*/
num_defaults = 0;
defaults = NULL;
cups_protocol[0] = '\0';
if ((dst = cupsFileOpen(to, "rb")) != NULL)
{
/*
* Read all of the default lines from the old PPD...
*/
while (cupsFileGets(dst, buffer, sizeof(buffer)))
if (!strncmp(buffer, "*Default", 8))
{
/*
* Add the default option...
*/
if (!ppd_parse_line(buffer, option, sizeof(option),
choice, sizeof(choice)))
{
ppd_option_t *ppdo; /* PPD option */
/*
* Only add the default if the default hasn't already been
* set and the choice exists in the new PPD...
*/
if (!cupsGetOption(option, num_defaults, defaults) &&
(ppdo = ppdFindOption(ppd, option)) != NULL &&
ppdFindChoice(ppdo, choice))
num_defaults = cupsAddOption(option, choice, num_defaults,
&defaults);
}
}
else if (!strncmp(buffer, "*cupsProtocol:", 14))
strlcpy(cups_protocol, buffer, sizeof(cups_protocol));
cupsFileClose(dst);
}
else if ((size = ppdPageSize(ppd, DefaultPaperSize)) != NULL)
{
/*
* Add the default media sizes...
*/
num_defaults = cupsAddOption("PageSize", size->name,
num_defaults, &defaults);
num_defaults = cupsAddOption("PageRegion", size->name,
num_defaults, &defaults);
num_defaults = cupsAddOption("PaperDimension", size->name,
num_defaults, &defaults);
num_defaults = cupsAddOption("ImageableArea", size->name,
num_defaults, &defaults);
}
ppdClose(ppd);
/*
* Open the destination file for a copy...
*/
if ((dst = cupsdCreateConfFile(to, ConfigFilePerm)) == NULL)
{
cupsFreeOptions(num_defaults, defaults);
cupsFileClose(src);
unlink(tempfile);
return (-1);
}
/*
* Copy the source file to the destination...
*/
cupsFileRewind(src);
while (cupsFileGets(src, buffer, sizeof(buffer)))
{
if (!strncmp(buffer, "*Default", 8))
{
/*
* Check for an previous default option choice...
*/
if (!ppd_parse_line(buffer, option, sizeof(option),
choice, sizeof(choice)))
{
const char *val; /* Default option value */
if ((val = cupsGetOption(option, num_defaults, defaults)) != NULL)
{
/*
* Substitute the previous choice...
*/
snprintf(buffer, sizeof(buffer), "*Default%s: %s", option, val);
}
}
}
cupsFilePrintf(dst, "%s\n", buffer);
}
if (cups_protocol[0])
cupsFilePrintf(dst, "%s\n", cups_protocol);
cupsFreeOptions(num_defaults, defaults);
/*
* Close both files and return...
*/
cupsFileClose(src);
unlink(tempfile);
return (cupsdCloseCreatedConfFile(dst, to));
}
/*
* 'copy_job_attrs()' - Copy job attributes.
*/
static void
copy_job_attrs(cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job, /* I - Job */
cups_array_t *ra, /* I - Requested attributes array */
cups_array_t *exclude) /* I - Private attributes array */
{
char job_uri[HTTP_MAX_URI]; /* Job URI */
/*
* Send the requested attributes for each job...
*/
if (!cupsArrayFind(exclude, "all"))
{
if ((!exclude || !cupsArrayFind(exclude, "number-of-documents")) &&
(!ra || cupsArrayFind(ra, "number-of-documents")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER,
"number-of-documents", job->num_files);
if ((!exclude || !cupsArrayFind(exclude, "job-media-progress")) &&
(!ra || cupsArrayFind(ra, "job-media-progress")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-media-progress", job->progress);
if ((!exclude || !cupsArrayFind(exclude, "job-more-info")) &&
(!ra || cupsArrayFind(ra, "job-more-info")))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "http",
NULL, con->clientname, con->clientport, "/jobs/%d",
job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI,
"job-more-info", NULL, job_uri);
}
if (job->state_value > IPP_JOB_PROCESSING &&
(!exclude || !cupsArrayFind(exclude, "job-preserved")) &&
(!ra || cupsArrayFind(ra, "job-preserved")))
ippAddBoolean(con->response, IPP_TAG_JOB, "job-preserved",
job->num_files > 0);
if ((!exclude || !cupsArrayFind(exclude, "job-printer-up-time")) &&
(!ra || cupsArrayFind(ra, "job-printer-up-time")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER,
"job-printer-up-time", time(NULL));
}
if (!ra || cupsArrayFind(ra, "job-printer-uri"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport,
(job->dtype & CUPS_PRINTER_CLASS) ? "/classes/%s" :
"/printers/%s",
job->dest);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI,
"job-printer-uri", NULL, job_uri);
}
if (!ra || cupsArrayFind(ra, "job-uri"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d",
job->id);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI,
"job-uri", NULL, job_uri);
}
if (job->attrs)
{
copy_attrs(con->response, job->attrs, ra, IPP_TAG_JOB, 0, exclude);
}
else
{
/*
* Generate attributes from the job structure...
*/
if (job->completed_time && (!ra || cupsArrayFind(ra, "date-time-at-completed")))
ippAddDate(con->response, IPP_TAG_JOB, "date-time-at-completed", ippTimeToDate(job->completed_time));
if (job->creation_time && (!ra || cupsArrayFind(ra, "date-time-at-creation")))
ippAddDate(con->response, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(job->creation_time));
if (!ra || cupsArrayFind(ra, "job-id"))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id);
if (!ra || cupsArrayFind(ra, "job-k-octets"))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", job->koctets);
if (job->name && (!ra || cupsArrayFind(ra, "job-name")))
ippAddString(con->response, IPP_TAG_JOB, IPP_CONST_TAG(IPP_TAG_NAME), "job-name", NULL, job->name);
if (job->username && (!ra || cupsArrayFind(ra, "job-originating-user-name")))
ippAddString(con->response, IPP_TAG_JOB, IPP_CONST_TAG(IPP_TAG_NAME), "job-originating-user-name", NULL, job->username);
if (!ra || cupsArrayFind(ra, "job-state"))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", (int)job->state_value);
if (!ra || cupsArrayFind(ra, "job-state-reasons"))
{
switch (job->state_value)
{
default : /* Should never get here for processing, pending, held, or stopped jobs since they don't get unloaded... */
break;
case IPP_JSTATE_ABORTED :
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-aborted-by-system");
break;
case IPP_JSTATE_CANCELED :
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-canceled-by-user");
break;
case IPP_JSTATE_COMPLETED :
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-completed-successfully");
break;
}
}
if (job->completed_time && (!ra || cupsArrayFind(ra, "time-at-completed")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-completed", (int)job->completed_time);
if (job->creation_time && (!ra || cupsArrayFind(ra, "time-at-creation")))
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", (int)job->creation_time);
}
}
/*
* 'copy_printer_attrs()' - Copy printer attributes.
*/
static void
copy_printer_attrs(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer, /* I - Printer */
cups_array_t *ra) /* I - Requested attributes array */
{
char printer_uri[HTTP_MAX_URI];
/* Printer URI */
char printer_icons[HTTP_MAX_URI];
/* Printer icons */
time_t curtime; /* Current time */
int i; /* Looping var */
/*
* Copy the printer attributes to the response using requested-attributes
* and document-format attributes that may be provided by the client.
*/
curtime = time(NULL);
if (!ra || cupsArrayFind(ra, "marker-change-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"marker-change-time", printer->marker_time);
if (printer->num_printers > 0 &&
(!ra || cupsArrayFind(ra, "member-uris")))
{
ipp_attribute_t *member_uris; /* member-uris attribute */
cupsd_printer_t *p2; /* Printer in class */
ipp_attribute_t *p2_uri; /* printer-uri-supported for class printer */
if ((member_uris = ippAddStrings(con->response, IPP_TAG_PRINTER,
IPP_TAG_URI, "member-uris",
printer->num_printers, NULL,
NULL)) != NULL)
{
for (i = 0; i < printer->num_printers; i ++)
{
p2 = printer->printers[i];
if ((p2_uri = ippFindAttribute(p2->attrs, "printer-uri-supported",
IPP_TAG_URI)) != NULL)
member_uris->values[i].string.text =
_cupsStrRetain(p2_uri->values[0].string.text);
else
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri,
sizeof(printer_uri), "ipp", NULL, con->clientname,
con->clientport,
(p2->type & CUPS_PRINTER_CLASS) ?
"/classes/%s" : "/printers/%s", p2->name);
member_uris->values[i].string.text = _cupsStrAlloc(printer_uri);
}
}
}
}
if (printer->alert && (!ra || cupsArrayFind(ra, "printer-alert")))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_STRING,
"printer-alert", NULL, printer->alert);
if (printer->alert_description &&
(!ra || cupsArrayFind(ra, "printer-alert-description")))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_TEXT,
"printer-alert-description", NULL,
printer->alert_description);
if (!ra || cupsArrayFind(ra, "printer-config-change-date-time"))
ippAddDate(con->response, IPP_TAG_PRINTER, "printer-config-change-date-time", ippTimeToDate(printer->config_time));
if (!ra || cupsArrayFind(ra, "printer-config-change-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"printer-config-change-time", printer->config_time);
if (!ra || cupsArrayFind(ra, "printer-current-time"))
ippAddDate(con->response, IPP_TAG_PRINTER, "printer-current-time",
ippTimeToDate(curtime));
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
if (!ra || cupsArrayFind(ra, "printer-dns-sd-name"))
{
if (printer->reg_name)
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME,
"printer-dns-sd-name", NULL, printer->reg_name);
else
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_NOVALUE,
"printer-dns-sd-name", 0);
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
if (!ra || cupsArrayFind(ra, "printer-error-policy"))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME,
"printer-error-policy", NULL, printer->error_policy);
if (!ra || cupsArrayFind(ra, "printer-error-policy-supported"))
{
static const char * const errors[] =/* printer-error-policy-supported values */
{
"abort-job",
"retry-current-job",
"retry-job",
"stop-printer"
};
if (printer->type & CUPS_PRINTER_CLASS)
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME | IPP_TAG_COPY,
"printer-error-policy-supported", NULL, "retry-current-job");
else
ippAddStrings(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME | IPP_TAG_COPY,
"printer-error-policy-supported",
sizeof(errors) / sizeof(errors[0]), NULL, errors);
}
if (!ra || cupsArrayFind(ra, "printer-icons"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_icons, sizeof(printer_icons),
"http", NULL, con->clientname, con->clientport,
"/icons/%s.png", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI, "printer-icons",
NULL, printer_icons);
cupsdLogMessage(CUPSD_LOG_DEBUG2, "printer-icons=\"%s\"", printer_icons);
}
if (!ra || cupsArrayFind(ra, "printer-is-accepting-jobs"))
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-accepting-jobs", (char)printer->accepting);
if (!ra || cupsArrayFind(ra, "printer-is-shared"))
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-shared", (char)printer->shared);
if (!ra || cupsArrayFind(ra, "printer-is-temporary"))
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-temporary", (char)printer->temporary);
if (!ra || cupsArrayFind(ra, "printer-more-info"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, sizeof(printer_uri),
"http", NULL, con->clientname, con->clientport,
(printer->type & CUPS_PRINTER_CLASS) ?
"/classes/%s" : "/printers/%s", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI,
"printer-more-info", NULL, printer_uri);
}
if (!ra || cupsArrayFind(ra, "printer-op-policy"))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_NAME,
"printer-op-policy", NULL, printer->op_policy);
if (!ra || cupsArrayFind(ra, "printer-state"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state",
printer->state);
if (!ra || cupsArrayFind(ra, "printer-state-change-date-time"))
ippAddDate(con->response, IPP_TAG_PRINTER, "printer-state-change-date-time", ippTimeToDate(printer->state_time));
if (!ra || cupsArrayFind(ra, "printer-state-change-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"printer-state-change-time", printer->state_time);
if (!ra || cupsArrayFind(ra, "printer-state-message"))
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_TEXT,
"printer-state-message", NULL, printer->state_message);
if (!ra || cupsArrayFind(ra, "printer-state-reasons"))
add_printer_state_reasons(con, printer);
if (!ra || cupsArrayFind(ra, "printer-type"))
{
cups_ptype_t type; /* printer-type value */
/*
* Add the CUPS-specific printer-type attribute...
*/
type = printer->type;
if (printer == DefaultPrinter)
type |= CUPS_PRINTER_DEFAULT;
if (!printer->accepting)
type |= CUPS_PRINTER_REJECTING;
if (!printer->shared)
type |= CUPS_PRINTER_NOT_SHARED;
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-type", (int)type);
}
if (!ra || cupsArrayFind(ra, "printer-up-time"))
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"printer-up-time", curtime);
if (!ra || cupsArrayFind(ra, "printer-uri-supported"))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, sizeof(printer_uri),
"ipp", NULL, con->clientname, con->clientport,
(printer->type & CUPS_PRINTER_CLASS) ?
"/classes/%s" : "/printers/%s", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI,
"printer-uri-supported", NULL, printer_uri);
cupsdLogMessage(CUPSD_LOG_DEBUG2, "printer-uri-supported=\"%s\"",
printer_uri);
}
if (!ra || cupsArrayFind(ra, "queued-job-count"))
add_queued_job_count(con, printer);
copy_attrs(con->response, printer->attrs, ra, IPP_TAG_ZERO, 0, NULL);
if (printer->ppd_attrs)
copy_attrs(con->response, printer->ppd_attrs, ra, IPP_TAG_ZERO, 0, NULL);
copy_attrs(con->response, CommonData, ra, IPP_TAG_ZERO, IPP_TAG_COPY, NULL);
}
/*
* 'copy_subscription_attrs()' - Copy subscription attributes.
*/
static void
copy_subscription_attrs(
cupsd_client_t *con, /* I - Client connection */
cupsd_subscription_t *sub, /* I - Subscription */
cups_array_t *ra, /* I - Requested attributes array */
cups_array_t *exclude) /* I - Private attributes array */
{
ipp_attribute_t *attr; /* Current attribute */
char printer_uri[HTTP_MAX_URI];
/* Printer URI */
int count; /* Number of events */
unsigned mask; /* Current event mask */
const char *name; /* Current event name */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"copy_subscription_attrs(con=%p, sub=%p, ra=%p, exclude=%p)",
con, sub, ra, exclude);
/*
* Copy the subscription attributes to the response using the
* requested-attributes attribute that may be provided by the client.
*/
if (!exclude || !cupsArrayFind(exclude, "all"))
{
if ((!exclude || !cupsArrayFind(exclude, "notify-events")) &&
(!ra || cupsArrayFind(ra, "notify-events")))
{
cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_subscription_attrs: notify-events");
if ((name = cupsdEventName((cupsd_eventmask_t)sub->mask)) != NULL)
{
/*
* Simple event list...
*/
ippAddString(con->response, IPP_TAG_SUBSCRIPTION,
(ipp_tag_t)(IPP_TAG_KEYWORD | IPP_TAG_COPY),
"notify-events", NULL, name);
}
else
{
/*
* Complex event list...
*/
for (mask = 1, count = 0; mask < CUPSD_EVENT_ALL; mask <<= 1)
if (sub->mask & mask)
count ++;
attr = ippAddStrings(con->response, IPP_TAG_SUBSCRIPTION,
(ipp_tag_t)(IPP_TAG_KEYWORD | IPP_TAG_COPY),
"notify-events", count, NULL, NULL);
for (mask = 1, count = 0; mask < CUPSD_EVENT_ALL; mask <<= 1)
if (sub->mask & mask)
{
attr->values[count].string.text =
(char *)cupsdEventName((cupsd_eventmask_t)mask);
count ++;
}
}
}
if ((!exclude || !cupsArrayFind(exclude, "notify-lease-duration")) &&
(!sub->job && (!ra || cupsArrayFind(ra, "notify-lease-duration"))))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-lease-duration", sub->lease);
if ((!exclude || !cupsArrayFind(exclude, "notify-recipient-uri")) &&
(sub->recipient && (!ra || cupsArrayFind(ra, "notify-recipient-uri"))))
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI,
"notify-recipient-uri", NULL, sub->recipient);
else if ((!exclude || !cupsArrayFind(exclude, "notify-pull-method")) &&
(!ra || cupsArrayFind(ra, "notify-pull-method")))
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD,
"notify-pull-method", NULL, "ippget");
if ((!exclude || !cupsArrayFind(exclude, "notify-subscriber-user-name")) &&
(!ra || cupsArrayFind(ra, "notify-subscriber-user-name")))
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_NAME,
"notify-subscriber-user-name", NULL, sub->owner);
if ((!exclude || !cupsArrayFind(exclude, "notify-time-interval")) &&
(!ra || cupsArrayFind(ra, "notify-time-interval")))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-time-interval", sub->interval);
if (sub->user_data_len > 0 &&
(!exclude || !cupsArrayFind(exclude, "notify-user-data")) &&
(!ra || cupsArrayFind(ra, "notify-user-data")))
ippAddOctetString(con->response, IPP_TAG_SUBSCRIPTION, "notify-user-data",
sub->user_data, sub->user_data_len);
}
if (sub->job && (!ra || cupsArrayFind(ra, "notify-job-id")))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-job-id", sub->job->id);
if (sub->dest && (!ra || cupsArrayFind(ra, "notify-printer-uri")))
{
httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, sizeof(printer_uri),
"ipp", NULL, con->clientname, con->clientport,
"/printers/%s", sub->dest->name);
ippAddString(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI,
"notify-printer-uri", NULL, printer_uri);
}
if (!ra || cupsArrayFind(ra, "notify-subscription-id"))
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-subscription-id", sub->id);
}
/*
* 'create_job()' - Print a file to a printer or class.
*/
static void
create_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
int i; /* Looping var */
cupsd_printer_t *printer; /* Printer */
cupsd_job_t *job; /* New job */
static const char * const forbidden_attrs[] =
{ /* List of forbidden attributes */
"compression",
"document-format",
"document-name",
"document-natural-language"
};
cupsdLogMessage(CUPSD_LOG_DEBUG2, "create_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, NULL, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check for invalid Create-Job attributes and log a warning or error depending
* on whether cupsd is running in "strict conformance" mode...
*/
for (i = 0;
i < (int)(sizeof(forbidden_attrs) / sizeof(forbidden_attrs[0]));
i ++)
if (ippFindAttribute(con->request, forbidden_attrs[i], IPP_TAG_ZERO))
{
if (StrictConformance)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("The '%s' operation attribute cannot be supplied in a "
"Create-Job request."), forbidden_attrs[i]);
return;
}
cupsdLogMessage(CUPSD_LOG_WARN,
"Unexpected '%s' operation attribute in a Create-Job "
"request.", forbidden_attrs[i]);
}
/*
* Create the job object...
*/
if ((job = add_job(con, printer, NULL)) == NULL)
return;
job->pending_timeout = 1;
/*
* Save and log the job...
*/
cupsdLogJob(job, CUPSD_LOG_INFO, "Queued on \"%s\" by \"%s\".",
job->dest, job->username);
}
/*
* 'create_local_bg_thread()' - Background thread for creating a local print queue.
*/
static void * /* O - Exit status */
create_local_bg_thread(
cupsd_printer_t *printer) /* I - Printer */
{
cups_file_t *from, /* Source file */
*to; /* Destination file */
char fromppd[1024], /* Source PPD */
toppd[1024], /* Destination PPD */
scheme[32], /* URI scheme */
userpass[256], /* User:pass */
host[256], /* Hostname */
resource[1024], /* Resource path */
line[1024]; /* Line from PPD */
int port; /* Port number */
http_encryption_t encryption; /* Type of encryption to use */
http_t *http; /* Connection to printer */
ipp_t *request, /* Request to printer */
*response; /* Response from printer */
ipp_attribute_t *attr; /* Attribute in response */
/*
* Try connecting to the printer...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s: Generating PPD file from \"%s\"...", printer->name, printer->device_uri);
if (httpSeparateURI(HTTP_URI_CODING_ALL, printer->device_uri, scheme, sizeof(scheme), userpass, sizeof(userpass), host, sizeof(host), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Bad device URI \"%s\".", printer->name, printer->device_uri);
return (NULL);
}
if (!strcmp(scheme, "ipps") || port == 443)
encryption = HTTP_ENCRYPTION_ALWAYS;
else
encryption = HTTP_ENCRYPTION_IF_REQUESTED;
if ((http = httpConnect2(host, port, NULL, AF_UNSPEC, encryption, 1, 30000, NULL)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Unable to connect to %s:%d: %s", printer->name, host, port, cupsLastErrorString());
return (NULL);
}
/*
* Query the printer for its capabilities...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s: Connected to %s:%d, sending Get-Printer-Attributes request...", printer->name, host, port);
request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer->device_uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", NULL, "all");
response = cupsDoRequest(http, request, resource);
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s: Get-Printer-Attributes returned %s", printer->name, ippErrorString(cupsLastError()));
// TODO: Grab printer icon file...
httpClose(http);
/*
* Write the PPD for the queue...
*/
if (_ppdCreateFromIPP(fromppd, sizeof(fromppd), response))
{
if ((!printer->info || !*(printer->info)) && (attr = ippFindAttribute(response, "printer-info", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->info, ippGetString(attr, 0, NULL));
if ((!printer->location || !*(printer->location)) && (attr = ippFindAttribute(response, "printer-location", IPP_TAG_TEXT)) != NULL)
cupsdSetString(&printer->location, ippGetString(attr, 0, NULL));
if ((!printer->geo_location || !*(printer->geo_location)) && (attr = ippFindAttribute(response, "printer-geo-location", IPP_TAG_URI)) != NULL)
cupsdSetString(&printer->geo_location, ippGetString(attr, 0, NULL));
if ((from = cupsFileOpen(fromppd, "r")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Unable to read generated PPD: %s", printer->name, strerror(errno));
return (NULL);
}
snprintf(toppd, sizeof(toppd), "%s/ppd/%s.ppd", ServerRoot, printer->name);
if ((to = cupsdCreateConfFile(toppd, ConfigFilePerm)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Unable to create PPD for printer: %s", printer->name, strerror(errno));
cupsFileClose(from);
return (NULL);
}
while (cupsFileGets(from, line, sizeof(line)))
cupsFilePrintf(to, "%s\n", line);
cupsFileClose(from);
if (!cupsdCloseCreatedConfFile(to, toppd))
{
printer->config_time = time(NULL);
printer->state = IPP_PSTATE_IDLE;
printer->accepting = 1;
cupsdSetPrinterAttrs(printer);
cupsdAddEvent(CUPSD_EVENT_PRINTER_CONFIG, printer, NULL, "Printer \"%s\" is now available.", printer->name);
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" is now available.", printer->name);
}
}
else
cupsdLogMessage(CUPSD_LOG_ERROR, "%s: PPD creation failed: %s", printer->name, cupsLastErrorString());
return (NULL);
}
/*
* 'create_local_printer()' - Create a local (temporary) print queue.
*/
static void
create_local_printer(
cupsd_client_t *con) /* I - Client connection */
{
ipp_attribute_t *device_uri, /* device-uri attribute */
*printer_geo_location, /* printer-geo-location attribute */
*printer_info, /* printer-info attribute */
*printer_location, /* printer-location attribute */
*printer_name; /* printer-name attribute */
cupsd_printer_t *printer; /* New printer */
http_status_t status; /* Policy status */
char name[128], /* Sanitized printer name */
*nameptr, /* Pointer into name */
uri[1024]; /* printer-uri-supported value */
const char *ptr; /* Pointer into attribute value */
/*
* Require local access to create a local printer...
*/
if (!httpAddrLocalhost(httpGetAddress(con->http)))
{
send_ipp_status(con, IPP_STATUS_ERROR_FORBIDDEN, _("Only local users can create a local printer."));
return;
}
/*
* Check any other policy limits...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Grab needed attributes...
*/
if ((printer_name = ippFindAttribute(con->request, "printer-name", IPP_TAG_ZERO)) == NULL || ippGetGroupTag(printer_name) != IPP_TAG_PRINTER || ippGetValueTag(printer_name) != IPP_TAG_NAME)
{
if (!printer_name)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Missing required attribute \"%s\"."), "printer-name");
else if (ippGetGroupTag(printer_name) != IPP_TAG_PRINTER)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is in the wrong group."), "printer-name");
else
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is the wrong value type."), "printer-name");
return;
}
for (nameptr = name, ptr = ippGetString(printer_name, 0, NULL); *ptr && nameptr < (name + sizeof(name) - 1); ptr ++)
{
/*
* Sanitize the printer name...
*/
if (_cups_isalnum(*ptr))
*nameptr++ = *ptr;
else if (nameptr == name || nameptr[-1] != '_')
*nameptr++ = '_';
}
*nameptr = '\0';
if ((device_uri = ippFindAttribute(con->request, "device-uri", IPP_TAG_ZERO)) == NULL || ippGetGroupTag(device_uri) != IPP_TAG_PRINTER || ippGetValueTag(device_uri) != IPP_TAG_URI)
{
if (!device_uri)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Missing required attribute \"%s\"."), "device-uri");
else if (ippGetGroupTag(device_uri) != IPP_TAG_PRINTER)
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is in the wrong group."), "device-uri");
else
send_ipp_status(con, IPP_STATUS_ERROR_BAD_REQUEST, _("Attribute \"%s\" is the wrong value type."), "device-uri");
return;
}
printer_geo_location = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI);
printer_info = ippFindAttribute(con->request, "printer-info", IPP_TAG_TEXT);
printer_location = ippFindAttribute(con->request, "printer-location", IPP_TAG_TEXT);
/*
* See if the printer already exists...
*/
if ((printer = cupsdFindDest(name)) != NULL)
{
send_ipp_status(con, IPP_STATUS_ERROR_NOT_POSSIBLE, _("Printer \"%s\" already exists."), name);
goto add_printer_attributes;
}
/*
* Create the printer...
*/
if ((printer = cupsdAddPrinter(name)) == NULL)
{
send_ipp_status(con, IPP_STATUS_ERROR_INTERNAL, _("Unable to create printer."));
return;
}
printer->shared = 0;
printer->temporary = 1;
cupsdSetDeviceURI(printer, ippGetString(device_uri, 0, NULL));
if (printer_geo_location)
cupsdSetString(&printer->geo_location, ippGetString(printer_geo_location, 0, NULL));
if (printer_info)
cupsdSetString(&printer->info, ippGetString(printer_info, 0, NULL));
if (printer_location)
cupsdSetString(&printer->location, ippGetString(printer_location, 0, NULL));
cupsdSetPrinterAttrs(printer);
/*
* Run a background thread to create the PPD...
*/
_cupsThreadCreate((_cups_thread_func_t)create_local_bg_thread, printer);
/*
* Return printer attributes...
*/
send_ipp_status(con, IPP_STATUS_OK, _("Local printer created."));
add_printer_attributes:
ippAddBoolean(con->response, IPP_TAG_PRINTER, "printer-is-accepting-jobs", (char)printer->accepting);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", printer->state);
add_printer_state_reasons(con, printer);
httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), httpIsEncrypted(con->http) ? "ipps" : "ipp", NULL, con->clientname, con->clientport, "/printers/%s", printer->name);
ippAddString(con->response, IPP_TAG_PRINTER, IPP_TAG_URI, "printer-uri-supported", NULL, uri);
}
/*
* 'create_requested_array()' - Create an array for the requested-attributes.
*/
static cups_array_t * /* O - Array of attributes or NULL */
create_requested_array(ipp_t *request) /* I - IPP request */
{
cups_array_t *ra; /* Requested attributes array */
/*
* Create the array for standard attributes...
*/
ra = ippCreateRequestedArray(request);
/*
* Add CUPS defaults as needed...
*/
if (cupsArrayFind(ra, "printer-defaults"))
{
/*
* Include user-set defaults...
*/
char *name; /* Option name */
cupsArrayRemove(ra, "printer-defaults");
for (name = (char *)cupsArrayFirst(CommonDefaults);
name;
name = (char *)cupsArrayNext(CommonDefaults))
if (!cupsArrayFind(ra, name))
cupsArrayAdd(ra, name);
}
return (ra);
}
/*
* 'create_subscriptions()' - Create one or more notification subscriptions.
*/
static void
create_subscriptions(
cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
int i; /* Looping var */
ipp_attribute_t *attr; /* Current attribute */
cups_ptype_t dtype; /* Destination type (printer/class) */
char scheme[HTTP_MAX_URI],
/* Scheme portion of URI */
userpass[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *printer; /* Printer/class */
cupsd_job_t *job; /* Job */
int jobid; /* Job ID */
cupsd_subscription_t *sub; /* Subscription object */
const char *username, /* requesting-user-name or
authenticated username */
*recipient, /* notify-recipient-uri */
*pullmethod; /* notify-pull-method */
ipp_attribute_t *user_data; /* notify-user-data */
int interval, /* notify-time-interval */
lease; /* notify-lease-duration */
unsigned mask; /* notify-events */
ipp_attribute_t *notify_events,/* notify-events(-default) */
*notify_lease; /* notify-lease-duration(-default) */
#ifdef DEBUG
for (attr = con->request->attrs; attr; attr = attr->next)
{
if (attr->group_tag != IPP_TAG_ZERO)
cupsdLogMessage(CUPSD_LOG_DEBUG2, "g%04x v%04x %s", attr->group_tag,
attr->value_tag, attr->name);
else
cupsdLogMessage(CUPSD_LOG_DEBUG2, "----SEP----");
}
#endif /* DEBUG */
/*
* Is the destination valid?
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "create_subscriptions(con=%p(%d), uri=\"%s\")", con, con->number, uri->values[0].string.text);
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), userpass, sizeof(userpass), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(resource, "/"))
{
dtype = (cups_ptype_t)0;
printer = NULL;
}
else if (!strncmp(resource, "/printers", 9) && strlen(resource) <= 10)
{
dtype = (cups_ptype_t)0;
printer = NULL;
}
else if (!strncmp(resource, "/classes", 8) && strlen(resource) <= 9)
{
dtype = CUPS_PRINTER_CLASS;
printer = NULL;
}
else if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if (printer)
{
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con,
NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
}
else if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Get the user that is requesting the subscription...
*/
username = get_username(con);
/*
* Find the first subscription group attribute; return if we have
* none...
*/
for (attr = con->request->attrs; attr; attr = attr->next)
if (attr->group_tag == IPP_TAG_SUBSCRIPTION)
break;
if (!attr)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("No subscription attributes in request."));
return;
}
/*
* Process the subscription attributes in the request...
*/
con->response->request.status.status_code = IPP_BAD_REQUEST;
while (attr)
{
recipient = NULL;
pullmethod = NULL;
user_data = NULL;
interval = 0;
lease = DefaultLeaseDuration;
jobid = 0;
mask = CUPSD_EVENT_NONE;
if (printer)
{
notify_events = ippFindAttribute(printer->attrs, "notify-events-default",
IPP_TAG_KEYWORD);
notify_lease = ippFindAttribute(printer->attrs,
"notify-lease-duration-default",
IPP_TAG_INTEGER);
if (notify_lease)
lease = notify_lease->values[0].integer;
}
else
{
notify_events = NULL;
notify_lease = NULL;
}
while (attr && attr->group_tag != IPP_TAG_ZERO)
{
if (!strcmp(attr->name, "notify-recipient-uri") &&
attr->value_tag == IPP_TAG_URI)
{
/*
* Validate the recipient scheme against the ServerBin/notifier
* directory...
*/
char notifier[1024]; /* Notifier filename */
recipient = attr->values[0].string.text;
if (httpSeparateURI(HTTP_URI_CODING_ALL, recipient,
scheme, sizeof(scheme), userpass, sizeof(userpass),
host, sizeof(host), &port,
resource, sizeof(resource)) < HTTP_URI_OK)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-recipient-uri \"%s\"."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
snprintf(notifier, sizeof(notifier), "%s/notifier/%s", ServerBin,
scheme);
if (access(notifier, X_OK))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" uses unknown "
"scheme."), recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_URI_SCHEME);
return;
}
if (!strcmp(scheme, "rss") && !check_rss_recipient(recipient))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("notify-recipient-uri URI \"%s\" is already used."),
recipient);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-pull-method") &&
attr->value_tag == IPP_TAG_KEYWORD)
{
pullmethod = attr->values[0].string.text;
if (strcmp(pullmethod, "ippget"))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Bad notify-pull-method \"%s\"."), pullmethod);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_ENUM,
"notify-status-code", IPP_ATTRIBUTES);
return;
}
}
else if (!strcmp(attr->name, "notify-charset") &&
attr->value_tag == IPP_TAG_CHARSET &&
strcmp(attr->values[0].string.text, "us-ascii") &&
strcmp(attr->values[0].string.text, "utf-8"))
{
send_ipp_status(con, IPP_CHARSET,
_("Character set \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-natural-language") &&
(attr->value_tag != IPP_TAG_LANGUAGE ||
strcmp(attr->values[0].string.text, DefaultLanguage)))
{
send_ipp_status(con, IPP_CHARSET,
_("Language \"%s\" not supported."),
attr->values[0].string.text);
return;
}
else if (!strcmp(attr->name, "notify-user-data") &&
attr->value_tag == IPP_TAG_STRING)
{
if (attr->num_values > 1 || attr->values[0].unknown.length > 63)
{
send_ipp_status(con, IPP_REQUEST_VALUE,
_("The notify-user-data value is too large "
"(%d > 63 octets)."),
attr->values[0].unknown.length);
return;
}
user_data = attr;
}
else if (!strcmp(attr->name, "notify-events") &&
attr->value_tag == IPP_TAG_KEYWORD)
notify_events = attr;
else if (!strcmp(attr->name, "notify-lease-duration") &&
attr->value_tag == IPP_TAG_INTEGER)
lease = attr->values[0].integer;
else if (!strcmp(attr->name, "notify-time-interval") &&
attr->value_tag == IPP_TAG_INTEGER)
interval = attr->values[0].integer;
else if (!strcmp(attr->name, "notify-job-id") &&
attr->value_tag == IPP_TAG_INTEGER)
jobid = attr->values[0].integer;
attr = attr->next;
}
if (notify_events)
{
for (i = 0; i < notify_events->num_values; i ++)
mask |= cupsdEventValue(notify_events->values[i].string.text);
}
if (recipient)
cupsdLogMessage(CUPSD_LOG_DEBUG, "recipient=\"%s\"", recipient);
if (pullmethod)
cupsdLogMessage(CUPSD_LOG_DEBUG, "pullmethod=\"%s\"", pullmethod);
cupsdLogMessage(CUPSD_LOG_DEBUG, "notify-lease-duration=%d", lease);
cupsdLogMessage(CUPSD_LOG_DEBUG, "notify-time-interval=%d", interval);
if (!recipient && !pullmethod)
break;
if (mask == CUPSD_EVENT_NONE)
{
if (jobid)
mask = CUPSD_EVENT_JOB_COMPLETED;
else if (printer)
mask = CUPSD_EVENT_PRINTER_STATE_CHANGED;
else
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("notify-events not specified."));
return;
}
}
if (MaxLeaseDuration && (lease == 0 || lease > MaxLeaseDuration))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"create_subscriptions: Limiting notify-lease-duration to "
"%d seconds.",
MaxLeaseDuration);
lease = MaxLeaseDuration;
}
if (jobid)
{
if ((job = cupsdFindJob(jobid)) == NULL)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
jobid);
return;
}
}
else
job = NULL;
if ((sub = cupsdAddSubscription(mask, printer, job, recipient, 0)) == NULL)
{
send_ipp_status(con, IPP_TOO_MANY_SUBSCRIPTIONS,
_("There are too many subscriptions."));
return;
}
if (job)
cupsdLogMessage(CUPSD_LOG_DEBUG, "Added subscription #%d for job %d.",
sub->id, job->id);
else if (printer)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Added subscription #%d for printer \"%s\".",
sub->id, printer->name);
else
cupsdLogMessage(CUPSD_LOG_DEBUG, "Added subscription #%d for server.",
sub->id);
sub->interval = interval;
sub->lease = lease;
sub->expire = lease ? time(NULL) + lease : 0;
cupsdSetString(&sub->owner, username);
if (user_data)
{
sub->user_data_len = user_data->values[0].unknown.length;
memcpy(sub->user_data, user_data->values[0].unknown.data,
(size_t)sub->user_data_len);
}
ippAddSeparator(con->response);
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-subscription-id", sub->id);
con->response->request.status.status_code = IPP_OK;
if (attr)
attr = attr->next;
}
cupsdMarkDirty(CUPSD_DIRTY_SUBSCRIPTIONS);
}
/*
* 'delete_printer()' - Remove a printer or class from the system.
*/
static void
delete_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - URI of printer or class */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
char filename[1024]; /* Script/PPD filename */
int temporary; /* Temporary queue? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "delete_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Do we have a valid URI?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Remove old jobs...
*/
cupsdCancelJobs(printer->name, NULL, 1);
/*
* Remove old subscriptions and send a "deleted printer" event...
*/
cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, printer, NULL,
"%s \"%s\" deleted by \"%s\".",
(dtype & CUPS_PRINTER_CLASS) ? "Class" : "Printer",
printer->name, get_username(con));
cupsdExpireSubscriptions(printer, NULL);
/*
* Remove any old PPD or script files...
*/
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd", ServerRoot,
printer->name);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd.O", ServerRoot,
printer->name);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/%s.png", CacheDir, printer->name);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/%s.data", CacheDir, printer->name);
unlink(filename);
/*
* Unregister color profiles...
*/
cupsdUnregisterColor(printer);
temporary = printer->temporary;
if (dtype & CUPS_PRINTER_CLASS)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" deleted by \"%s\".",
printer->name, get_username(con));
cupsdDeletePrinter(printer, 0);
if (!temporary)
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
}
else
{
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" deleted by \"%s\".",
printer->name, get_username(con));
if (cupsdDeletePrinter(printer, 0) && !temporary)
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
if (!temporary)
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
}
if (!temporary)
cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
/*
* Return with no errors...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_default()' - Get the default destination.
*/
static void
get_default(cupsd_client_t *con) /* I - Client connection */
{
http_status_t status; /* Policy status */
cups_array_t *ra; /* Requested attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_default(%p[%d])", con, con->number);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
if (DefaultPrinter)
{
ra = create_requested_array(con->request);
copy_printer_attrs(con, DefaultPrinter, ra);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
else
send_ipp_status(con, IPP_NOT_FOUND, _("No default printer."));
}
/*
* 'get_devices()' - Get the list of available devices on the local system.
*/
static void
get_devices(cupsd_client_t *con) /* I - Client connection */
{
http_status_t status; /* Policy status */
ipp_attribute_t *limit, /* limit attribute */
*timeout, /* timeout attribute */
*requested, /* requested-attributes attribute */
*exclude, /* exclude-schemes attribute */
*include; /* include-schemes attribute */
char command[1024], /* cups-deviced command */
options[2048], /* Options to pass to command */
requested_str[256],
/* String for requested attributes */
exclude_str[512],
/* String for excluded schemes */
include_str[512];
/* String for included schemes */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_devices(%p[%d])", con, con->number);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Run cups-deviced command with the given options...
*/
limit = ippFindAttribute(con->request, "limit", IPP_TAG_INTEGER);
timeout = ippFindAttribute(con->request, "timeout", IPP_TAG_INTEGER);
requested = ippFindAttribute(con->request, "requested-attributes",
IPP_TAG_KEYWORD);
exclude = ippFindAttribute(con->request, "exclude-schemes", IPP_TAG_NAME);
include = ippFindAttribute(con->request, "include-schemes", IPP_TAG_NAME);
if (requested)
url_encode_attr(requested, requested_str, sizeof(requested_str));
else
strlcpy(requested_str, "requested-attributes=all", sizeof(requested_str));
if (exclude)
url_encode_attr(exclude, exclude_str, sizeof(exclude_str));
else
exclude_str[0] = '\0';
if (include)
url_encode_attr(include, include_str, sizeof(include_str));
else
include_str[0] = '\0';
snprintf(command, sizeof(command), "%s/daemon/cups-deviced", ServerBin);
snprintf(options, sizeof(options),
"%d+%d+%d+%d+%s%s%s%s%s",
con->request->request.op.request_id,
limit ? limit->values[0].integer : 0,
timeout ? timeout->values[0].integer : 15,
(int)User,
requested_str,
exclude_str[0] ? "%20" : "", exclude_str,
include_str[0] ? "%20" : "", include_str);
if (cupsdSendCommand(con, command, options, 1))
{
/*
* Command started successfully, don't send an IPP response here...
*/
ippDelete(con->response);
con->response = NULL;
}
else
{
/*
* Command failed, return "internal error" so the user knows something
* went wrong...
*/
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("cups-deviced failed to execute."));
}
}
/*
* 'get_document()' - Get a copy of a job file.
*/
static void
get_document(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
int docnum; /* Document number */
cupsd_job_t *job; /* Current job */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
char filename[1024], /* Filename for document */
format[1024]; /* Format for document */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_document(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con,
job->username)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Get the document number...
*/
if ((attr = ippFindAttribute(con->request, "document-number",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing document-number attribute."));
return;
}
if ((docnum = attr->values[0].integer) < 1 || docnum > job->num_files ||
attr->num_values > 1)
{
send_ipp_status(con, IPP_NOT_FOUND,
_("Document #%d does not exist in job #%d."), docnum,
jobid);
return;
}
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, jobid,
docnum);
if ((con->file = open(filename, O_RDONLY)) == -1)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open document %d in job %d - %s", docnum, jobid,
strerror(errno));
send_ipp_status(con, IPP_NOT_FOUND,
_("Unable to open document #%d in job #%d."), docnum,
jobid);
return;
}
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
cupsdLoadJob(job);
snprintf(format, sizeof(format), "%s/%s", job->filetypes[docnum - 1]->super,
job->filetypes[docnum - 1]->type);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format",
NULL, format);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "document-number",
docnum);
if ((attr = ippFindAttribute(job->attrs, "document-name",
IPP_TAG_NAME)) != NULL)
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_NAME, "document-name",
NULL, attr->values[0].string.text);
}
/*
* 'get_job_attrs()' - Get job attributes.
*/
static void
get_job_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
cupsd_printer_t *printer; /* Current printer */
cupsd_policy_t *policy; /* Current security policy */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cups_array_t *ra, /* Requested attributes array */
*exclude; /* Private attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_job_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* Check policy...
*/
if ((printer = job->printer) == NULL)
printer = cupsdFindDest(job->dest);
if (printer)
policy = printer->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, job->username)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
exclude = cupsdGetPrivateAttrs(policy, con, printer, job->username);
/*
* Copy attributes...
*/
cupsdLoadJob(job);
ra = create_requested_array(con->request);
copy_job_attrs(con, job, ra, exclude);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_jobs()' - Get a list of jobs for the specified printer.
*/
static void
get_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
const char *dest; /* Destination */
cups_ptype_t dtype; /* Destination type (printer/class) */
cups_ptype_t dmask; /* Destination type mask */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
int job_comparison; /* Job comparison */
ipp_jstate_t job_state; /* job-state value */
int first_job_id = 1, /* First job ID */
first_index = 1, /* First index */
limit = 0, /* Maximum number of jobs to return */
count, /* Number of jobs that match */
need_load_job = 0; /* Do we need to load the job? */
const char *job_attr; /* Job attribute requested */
ipp_attribute_t *job_ids; /* job-ids attribute */
cupsd_job_t *job; /* Current job pointer */
cupsd_printer_t *printer; /* Printer */
cups_array_t *list; /* Which job list... */
int delete_list = 0; /* Delete the list afterwards? */
cups_array_t *ra, /* Requested attributes array */
*exclude; /* Private attributes array */
cupsd_policy_t *policy; /* Current policy */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (strcmp(uri->name, "printer-uri"))
{
send_ipp_status(con, IPP_BAD_REQUEST, _("No printer-uri in request."));
return;
}
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(resource, "/") || !strcmp(resource, "/jobs"))
{
dest = NULL;
dtype = (cups_ptype_t)0;
dmask = (cups_ptype_t)0;
printer = NULL;
}
else if (!strncmp(resource, "/printers", 9) && strlen(resource) <= 10)
{
dest = NULL;
dtype = (cups_ptype_t)0;
dmask = CUPS_PRINTER_CLASS;
printer = NULL;
}
else if (!strncmp(resource, "/classes", 8) && strlen(resource) <= 9)
{
dest = NULL;
dtype = CUPS_PRINTER_CLASS;
dmask = CUPS_PRINTER_CLASS;
printer = NULL;
}
else if ((dest = cupsdValidateDest(uri->values[0].string.text, &dtype,
&printer)) == NULL)
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
else
{
dtype &= CUPS_PRINTER_CLASS;
dmask = CUPS_PRINTER_CLASS;
}
/*
* Check policy...
*/
if (printer)
policy = printer->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
job_ids = ippFindAttribute(con->request, "job-ids", IPP_TAG_INTEGER);
/*
* See if the "which-jobs" attribute have been specified...
*/
if ((attr = ippFindAttribute(con->request, "which-jobs",
IPP_TAG_KEYWORD)) != NULL && job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"which-jobs");
return;
}
else if (!attr || !strcmp(attr->values[0].string.text, "not-completed"))
{
job_comparison = -1;
job_state = IPP_JOB_STOPPED;
list = ActiveJobs;
}
else if (!strcmp(attr->values[0].string.text, "completed"))
{
job_comparison = 1;
job_state = IPP_JOB_CANCELED;
list = cupsdGetCompletedJobs(printer);
delete_list = 1;
}
else if (!strcmp(attr->values[0].string.text, "aborted"))
{
job_comparison = 0;
job_state = IPP_JOB_ABORTED;
list = cupsdGetCompletedJobs(printer);
delete_list = 1;
}
else if (!strcmp(attr->values[0].string.text, "all"))
{
job_comparison = 1;
job_state = IPP_JOB_PENDING;
list = Jobs;
}
else if (!strcmp(attr->values[0].string.text, "canceled"))
{
job_comparison = 0;
job_state = IPP_JOB_CANCELED;
list = cupsdGetCompletedJobs(printer);
delete_list = 1;
}
else if (!strcmp(attr->values[0].string.text, "pending"))
{
job_comparison = 0;
job_state = IPP_JOB_PENDING;
list = ActiveJobs;
}
else if (!strcmp(attr->values[0].string.text, "pending-held"))
{
job_comparison = 0;
job_state = IPP_JOB_HELD;
list = ActiveJobs;
}
else if (!strcmp(attr->values[0].string.text, "processing"))
{
job_comparison = 0;
job_state = IPP_JOB_PROCESSING;
list = PrintingJobs;
}
else if (!strcmp(attr->values[0].string.text, "processing-stopped"))
{
job_comparison = 0;
job_state = IPP_JOB_STOPPED;
list = ActiveJobs;
}
else
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("The which-jobs value \"%s\" is not supported."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"which-jobs", NULL, attr->values[0].string.text);
return;
}
/*
* See if they want to limit the number of jobs reported...
*/
if ((attr = ippFindAttribute(con->request, "limit", IPP_TAG_INTEGER)) != NULL)
{
if (job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"limit");
return;
}
limit = attr->values[0].integer;
}
if ((attr = ippFindAttribute(con->request, "first-index", IPP_TAG_INTEGER)) != NULL)
{
if (job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"first-index");
return;
}
first_index = attr->values[0].integer;
}
else if ((attr = ippFindAttribute(con->request, "first-job-id", IPP_TAG_INTEGER)) != NULL)
{
if (job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"first-job-id");
return;
}
first_job_id = attr->values[0].integer;
}
/*
* See if we only want to see jobs for a specific user...
*/
if ((attr = ippFindAttribute(con->request, "my-jobs", IPP_TAG_BOOLEAN)) != NULL && job_ids)
{
send_ipp_status(con, IPP_CONFLICT,
_("The %s attribute cannot be provided with job-ids."),
"my-jobs");
return;
}
else if (attr && attr->values[0].boolean)
strlcpy(username, get_username(con), sizeof(username));
else
username[0] = '\0';
ra = create_requested_array(con->request);
for (job_attr = (char *)cupsArrayFirst(ra); job_attr; job_attr = (char *)cupsArrayNext(ra))
if (strcmp(job_attr, "job-id") &&
strcmp(job_attr, "job-k-octets") &&
strcmp(job_attr, "job-media-progress") &&
strcmp(job_attr, "job-more-info") &&
strcmp(job_attr, "job-name") &&
strcmp(job_attr, "job-originating-user-name") &&
strcmp(job_attr, "job-preserved") &&
strcmp(job_attr, "job-printer-up-time") &&
strcmp(job_attr, "job-printer-uri") &&
strcmp(job_attr, "job-state") &&
strcmp(job_attr, "job-state-reasons") &&
strcmp(job_attr, "job-uri") &&
strcmp(job_attr, "time-at-completed") &&
strcmp(job_attr, "time-at-creation") &&
strcmp(job_attr, "number-of-documents"))
{
need_load_job = 1;
break;
}
if (need_load_job && (limit == 0 || limit > 500) && (list == Jobs || delete_list))
{
/*
* Limit expensive Get-Jobs for job history to 500 jobs...
*/
ippAddInteger(con->response, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "limit", 500);
if (limit)
ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "limit", limit);
limit = 500;
cupsdLogClient(con, CUPSD_LOG_INFO, "Limiting Get-Jobs response to %d jobs.", limit);
}
/*
* OK, build a list of jobs for this printer...
*/
if (job_ids)
{
int i; /* Looping var */
for (i = 0; i < job_ids->num_values; i ++)
{
if (!cupsdFindJob(job_ids->values[i].integer))
break;
}
if (i < job_ids->num_values)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
job_ids->values[i].integer);
return;
}
for (i = 0; i < job_ids->num_values; i ++)
{
job = cupsdFindJob(job_ids->values[i].integer);
if (need_load_job && !job->attrs)
{
cupsdLoadJob(job);
if (!job->attrs)
{
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs: No attributes for job %d", job->id);
continue;
}
}
if (i > 0)
ippAddSeparator(con->response);
exclude = cupsdGetPrivateAttrs(job->printer ?
job->printer->op_policy_ptr :
policy, con, job->printer,
job->username);
copy_job_attrs(con, job, ra, exclude);
}
}
else
{
if (first_index > 1)
job = (cupsd_job_t *)cupsArrayIndex(list, first_index - 1);
else
job = (cupsd_job_t *)cupsArrayFirst(list);
for (count = 0; (limit <= 0 || count < limit) && job; job = (cupsd_job_t *)cupsArrayNext(list))
{
/*
* Filter out jobs that don't match...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"get_jobs: job->id=%d, dest=\"%s\", username=\"%s\", "
"state_value=%d, attrs=%p", job->id, job->dest,
job->username, job->state_value, job->attrs);
if (!job->dest || !job->username)
cupsdLoadJob(job);
if (!job->dest || !job->username)
continue;
if ((dest && strcmp(job->dest, dest)) &&
(!job->printer || !dest || strcmp(job->printer->name, dest)))
continue;
if ((job->dtype & dmask) != dtype &&
(!job->printer || (job->printer->type & dmask) != dtype))
continue;
if ((job_comparison < 0 && job->state_value > job_state) ||
(job_comparison == 0 && job->state_value != job_state) ||
(job_comparison > 0 && job->state_value < job_state))
continue;
if (job->id < first_job_id)
continue;
if (need_load_job && !job->attrs)
{
cupsdLoadJob(job);
if (!job->attrs)
{
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs: No attributes for job %d", job->id);
continue;
}
}
if (username[0] && _cups_strcasecmp(username, job->username))
continue;
if (count > 0)
ippAddSeparator(con->response);
count ++;
exclude = cupsdGetPrivateAttrs(job->printer ?
job->printer->op_policy_ptr :
policy, con, job->printer,
job->username);
copy_job_attrs(con, job, ra, exclude);
}
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_jobs: count=%d", count);
}
cupsArrayDelete(ra);
if (delete_list)
cupsArrayDelete(list);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_notifications()' - Get events for a subscription.
*/
static void
get_notifications(cupsd_client_t *con) /* I - Client connection */
{
int i, j; /* Looping vars */
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
ipp_attribute_t *ids, /* notify-subscription-ids */
*sequences; /* notify-sequence-numbers */
int min_seq; /* Minimum sequence number */
int interval; /* Poll interval */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_notifications(con=%p[%d])",
con, con->number);
/*
* Get subscription attributes...
*/
ids = ippFindAttribute(con->request, "notify-subscription-ids",
IPP_TAG_INTEGER);
sequences = ippFindAttribute(con->request, "notify-sequence-numbers",
IPP_TAG_INTEGER);
if (!ids)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing notify-subscription-ids attribute."));
return;
}
/*
* Are the subscription IDs valid?
*/
for (i = 0, interval = 60; i < ids->num_values; i ++)
{
if ((sub = cupsdFindSubscription(ids->values[i].integer)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Subscription #%d does not exist."),
ids->values[i].integer);
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(sub->dest ? sub->dest->op_policy_ptr :
DefaultPolicyPtr,
con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
/*
* Check the subscription type and update the interval accordingly.
*/
if (sub->job && sub->job->state_value == IPP_JOB_PROCESSING &&
interval > 10)
interval = 10;
else if (sub->job && sub->job->state_value >= IPP_JOB_STOPPED)
interval = 0;
else if (sub->dest && sub->dest->state == IPP_PRINTER_PROCESSING &&
interval > 30)
interval = 30;
}
/*
* Tell the client to poll again in N seconds...
*/
if (interval > 0)
ippAddInteger(con->response, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
"notify-get-interval", interval);
ippAddInteger(con->response, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
"printer-up-time", time(NULL));
/*
* Copy the subscription event attributes to the response.
*/
con->response->request.status.status_code =
interval ? IPP_OK : IPP_OK_EVENTS_COMPLETE;
for (i = 0; i < ids->num_values; i ++)
{
/*
* Get the subscription and sequence number...
*/
sub = cupsdFindSubscription(ids->values[i].integer);
if (sequences && i < sequences->num_values)
min_seq = sequences->values[i].integer;
else
min_seq = 1;
/*
* If we don't have any new events, nothing to do here...
*/
if (min_seq > (sub->first_event_id + cupsArrayCount(sub->events)))
continue;
/*
* Otherwise copy all of the new events...
*/
if (sub->first_event_id > min_seq)
j = 0;
else
j = min_seq - sub->first_event_id;
for (; j < cupsArrayCount(sub->events); j ++)
{
ippAddSeparator(con->response);
copy_attrs(con->response,
((cupsd_event_t *)cupsArrayIndex(sub->events, j))->attrs, NULL,
IPP_TAG_EVENT_NOTIFICATION, 0, NULL);
}
}
}
/*
* 'get_ppd()' - Get a named PPD from the local system.
*/
static void
get_ppd(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI or PPD name */
{
http_status_t status; /* Policy status */
cupsd_printer_t *dest; /* Destination */
cups_ptype_t dtype; /* Destination type */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_ppd(%p[%d], %p[%s=%s])", con,
con->number, uri, uri->name, uri->values[0].string.text);
if (!strcmp(ippGetName(uri), "ppd-name"))
{
/*
* Return a PPD file from cups-driverd...
*/
const char *ppd_name = ippGetString(uri, 0, NULL);
/* ppd-name value */
char command[1024], /* cups-driverd command */
options[1024], /* Options to pass to command */
oppd_name[1024]; /* Escaped ppd-name */
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Check ppd-name value...
*/
if (strstr(ppd_name, "../"))
{
send_ipp_status(con, IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES, _("Invalid ppd-name value."));
return;
}
/*
* Run cups-driverd command with the given options...
*/
snprintf(command, sizeof(command), "%s/daemon/cups-driverd", ServerBin);
url_encode_string(ppd_name, oppd_name, sizeof(oppd_name));
snprintf(options, sizeof(options), "get+%d+%s", ippGetRequestId(con->request), oppd_name);
if (cupsdSendCommand(con, command, options, 0))
{
/*
* Command started successfully, don't send an IPP response here...
*/
ippDelete(con->response);
con->response = NULL;
}
else
{
/*
* Command failed, return "internal error" so the user knows something
* went wrong...
*/
send_ipp_status(con, IPP_INTERNAL_ERROR, _("cups-driverd failed to execute."));
}
}
else if (!strcmp(ippGetName(uri), "printer-uri") && cupsdValidateDest(ippGetString(uri, 0, NULL), &dtype, &dest))
{
int i; /* Looping var */
char filename[1024]; /* PPD filename */
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(dest->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, dest);
return;
}
/*
* See if we need the PPD for a class or remote printer...
*/
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd", ServerRoot, dest->name);
if ((dtype & CUPS_PRINTER_REMOTE) && access(filename, 0))
{
send_ipp_status(con, IPP_STATUS_CUPS_SEE_OTHER, _("See remote printer."));
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, dest->uri);
return;
}
else if (dtype & CUPS_PRINTER_CLASS)
{
for (i = 0; i < dest->num_printers; i ++)
if (!(dest->printers[i]->type & CUPS_PRINTER_CLASS))
{
snprintf(filename, sizeof(filename), "%s/ppd/%s.ppd", ServerRoot, dest->printers[i]->name);
if (!access(filename, 0))
break;
}
if (i < dest->num_printers)
dest = dest->printers[i];
else
{
send_ipp_status(con, IPP_STATUS_CUPS_SEE_OTHER, _("See remote printer."));
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, dest->printers[0]->uri);
return;
}
}
/*
* Found the printer with the PPD file, now see if there is one...
*/
if ((con->file = open(filename, O_RDONLY)) < 0)
{
send_ipp_status(con, IPP_STATUS_ERROR_NOT_FOUND, _("The PPD file \"%s\" could not be opened: %s"), ippGetString(uri, 0, NULL), strerror(errno));
return;
}
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
con->pipe_pid = 0;
ippSetStatusCode(con->response, IPP_STATUS_OK);
}
else
send_ipp_status(con, IPP_STATUS_ERROR_NOT_FOUND, _("The PPD file \"%s\" could not be found."), ippGetString(uri, 0, NULL));
}
/*
* 'get_ppds()' - Get the list of PPD files on the local system.
*/
static void
get_ppds(cupsd_client_t *con) /* I - Client connection */
{
http_status_t status; /* Policy status */
ipp_attribute_t *limit, /* Limit attribute */
*device, /* ppd-device-id attribute */
*language, /* ppd-natural-language attribute */
*make, /* ppd-make attribute */
*model, /* ppd-make-and-model attribute */
*model_number, /* ppd-model-number attribute */
*product, /* ppd-product attribute */
*psversion, /* ppd-psverion attribute */
*type, /* ppd-type attribute */
*requested, /* requested-attributes attribute */
*exclude, /* exclude-schemes attribute */
*include; /* include-schemes attribute */
char command[1024], /* cups-driverd command */
options[4096], /* Options to pass to command */
device_str[256],/* Escaped ppd-device-id string */
language_str[256],
/* Escaped ppd-natural-language */
make_str[256], /* Escaped ppd-make string */
model_str[256], /* Escaped ppd-make-and-model string */
model_number_str[256],
/* ppd-model-number string */
product_str[256],
/* Escaped ppd-product string */
psversion_str[256],
/* Escaped ppd-psversion string */
type_str[256], /* Escaped ppd-type string */
requested_str[256],
/* String for requested attributes */
exclude_str[512],
/* String for excluded schemes */
include_str[512];
/* String for included schemes */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_ppds(%p[%d])", con, con->number);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Run cups-driverd command with the given options...
*/
limit = ippFindAttribute(con->request, "limit", IPP_TAG_INTEGER);
device = ippFindAttribute(con->request, "ppd-device-id", IPP_TAG_TEXT);
language = ippFindAttribute(con->request, "ppd-natural-language",
IPP_TAG_LANGUAGE);
make = ippFindAttribute(con->request, "ppd-make", IPP_TAG_TEXT);
model = ippFindAttribute(con->request, "ppd-make-and-model",
IPP_TAG_TEXT);
model_number = ippFindAttribute(con->request, "ppd-model-number",
IPP_TAG_INTEGER);
product = ippFindAttribute(con->request, "ppd-product", IPP_TAG_TEXT);
psversion = ippFindAttribute(con->request, "ppd-psversion", IPP_TAG_TEXT);
type = ippFindAttribute(con->request, "ppd-type", IPP_TAG_KEYWORD);
requested = ippFindAttribute(con->request, "requested-attributes",
IPP_TAG_KEYWORD);
exclude = ippFindAttribute(con->request, "exclude-schemes",
IPP_TAG_NAME);
include = ippFindAttribute(con->request, "include-schemes",
IPP_TAG_NAME);
if (requested)
url_encode_attr(requested, requested_str, sizeof(requested_str));
else
strlcpy(requested_str, "requested-attributes=all", sizeof(requested_str));
if (device)
url_encode_attr(device, device_str, sizeof(device_str));
else
device_str[0] = '\0';
if (language)
url_encode_attr(language, language_str, sizeof(language_str));
else
language_str[0] = '\0';
if (make)
url_encode_attr(make, make_str, sizeof(make_str));
else
make_str[0] = '\0';
if (model)
url_encode_attr(model, model_str, sizeof(model_str));
else
model_str[0] = '\0';
if (model_number)
snprintf(model_number_str, sizeof(model_number_str), "ppd-model-number=%d",
model_number->values[0].integer);
else
model_number_str[0] = '\0';
if (product)
url_encode_attr(product, product_str, sizeof(product_str));
else
product_str[0] = '\0';
if (psversion)
url_encode_attr(psversion, psversion_str, sizeof(psversion_str));
else
psversion_str[0] = '\0';
if (type)
url_encode_attr(type, type_str, sizeof(type_str));
else
type_str[0] = '\0';
if (exclude)
url_encode_attr(exclude, exclude_str, sizeof(exclude_str));
else
exclude_str[0] = '\0';
if (include)
url_encode_attr(include, include_str, sizeof(include_str));
else
include_str[0] = '\0';
snprintf(command, sizeof(command), "%s/daemon/cups-driverd", ServerBin);
snprintf(options, sizeof(options),
"list+%d+%d+%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
con->request->request.op.request_id,
limit ? limit->values[0].integer : 0,
requested_str,
device ? "%20" : "", device_str,
language ? "%20" : "", language_str,
make ? "%20" : "", make_str,
model ? "%20" : "", model_str,
model_number ? "%20" : "", model_number_str,
product ? "%20" : "", product_str,
psversion ? "%20" : "", psversion_str,
type ? "%20" : "", type_str,
exclude_str[0] ? "%20" : "", exclude_str,
include_str[0] ? "%20" : "", include_str);
if (cupsdSendCommand(con, command, options, 0))
{
/*
* Command started successfully, don't send an IPP response here...
*/
ippDelete(con->response);
con->response = NULL;
}
else
{
/*
* Command failed, return "internal error" so the user knows something
* went wrong...
*/
send_ipp_status(con, IPP_INTERNAL_ERROR,
_("cups-driverd failed to execute."));
}
}
/*
* 'get_printer_attrs()' - Get printer attributes.
*/
static void
get_printer_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
cups_array_t *ra; /* Requested attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_printer_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Send the attributes...
*/
ra = create_requested_array(con->request);
copy_printer_attrs(con, printer, ra);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_printer_supported()' - Get printer supported values.
*/
static void
get_printer_supported(
cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_printer_supported(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Return a list of attributes that can be set via Set-Printer-Attributes.
*/
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-geo-location", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-info", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-location", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-organization", 0);
ippAddInteger(con->response, IPP_TAG_PRINTER, IPP_TAG_ADMINDEFINE,
"printer-organizational-unit", 0);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_printers()' - Get a list of printers or classes.
*/
static void
get_printers(cupsd_client_t *con, /* I - Client connection */
int type) /* I - 0 or CUPS_PRINTER_CLASS */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int limit; /* Max number of printers to return */
int count; /* Number of printers that match */
cupsd_printer_t *printer; /* Current printer pointer */
cups_ptype_t printer_type, /* printer-type attribute */
printer_mask; /* printer-type-mask attribute */
char *location; /* Location string */
const char *username; /* Current user */
char *first_printer_name; /* first-printer-name attribute */
cups_array_t *ra; /* Requested attributes array */
int local; /* Local connection? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "get_printers(%p[%d], %x)", con,
con->number, type);
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Check for printers...
*/
if (!Printers || !cupsArrayCount(Printers))
{
send_ipp_status(con, IPP_NOT_FOUND, _("No destinations added."));
return;
}
/*
* See if they want to limit the number of printers reported...
*/
if ((attr = ippFindAttribute(con->request, "limit",
IPP_TAG_INTEGER)) != NULL)
limit = attr->values[0].integer;
else
limit = 10000000;
if ((attr = ippFindAttribute(con->request, "first-printer-name",
IPP_TAG_NAME)) != NULL)
first_printer_name = attr->values[0].string.text;
else
first_printer_name = NULL;
/*
* Support filtering...
*/
if ((attr = ippFindAttribute(con->request, "printer-type",
IPP_TAG_ENUM)) != NULL)
printer_type = (cups_ptype_t)attr->values[0].integer;
else
printer_type = (cups_ptype_t)0;
if ((attr = ippFindAttribute(con->request, "printer-type-mask",
IPP_TAG_ENUM)) != NULL)
printer_mask = (cups_ptype_t)attr->values[0].integer;
else
printer_mask = (cups_ptype_t)0;
local = httpAddrLocalhost(&(con->clientaddr));
if ((attr = ippFindAttribute(con->request, "printer-location",
IPP_TAG_TEXT)) != NULL)
location = attr->values[0].string.text;
else
location = NULL;
if (con->username[0])
username = con->username;
else if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
username = attr->values[0].string.text;
else
username = NULL;
ra = create_requested_array(con->request);
/*
* OK, build a list of printers for this printer...
*/
if (first_printer_name)
{
if ((printer = cupsdFindDest(first_printer_name)) == NULL)
printer = (cupsd_printer_t *)cupsArrayFirst(Printers);
}
else
printer = (cupsd_printer_t *)cupsArrayFirst(Printers);
for (count = 0;
count < limit && printer;
printer = (cupsd_printer_t *)cupsArrayNext(Printers))
{
if (!local && !printer->shared)
continue;
if ((!type || (printer->type & CUPS_PRINTER_CLASS) == type) &&
(printer->type & printer_mask) == printer_type &&
(!location ||
(printer->location && !_cups_strcasecmp(printer->location, location))))
{
/*
* If a username is specified, see if it is allowed or denied
* access...
*/
if (cupsArrayCount(printer->users) && username &&
!user_allowed(printer, username))
continue;
/*
* Add the group separator as needed...
*/
if (count > 0)
ippAddSeparator(con->response);
count ++;
/*
* Send the attributes...
*/
copy_printer_attrs(con, printer, ra);
}
}
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_subscription_attrs()' - Get subscription attributes.
*/
static void
get_subscription_attrs(
cupsd_client_t *con, /* I - Client connection */
int sub_id) /* I - Subscription ID */
{
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
cupsd_policy_t *policy; /* Current security policy */
cups_array_t *ra, /* Requested attributes array */
*exclude; /* Private attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"get_subscription_attrs(con=%p[%d], sub_id=%d)",
con, con->number, sub_id);
/*
* Expire subscriptions as needed...
*/
cupsdExpireSubscriptions(NULL, NULL);
/*
* Is the subscription ID valid?
*/
if ((sub = cupsdFindSubscription(sub_id)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Subscription #%d does not exist."),
sub_id);
return;
}
/*
* Check policy...
*/
if (sub->dest)
policy = sub->dest->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
exclude = cupsdGetPrivateAttrs(policy, con, sub->dest, sub->owner);
/*
* Copy the subscription attributes to the response using the
* requested-attributes attribute that may be provided by the client.
*/
ra = create_requested_array(con->request);
copy_subscription_attrs(con, sub, ra, exclude);
cupsArrayDelete(ra);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'get_subscriptions()' - Get subscriptions.
*/
static void
get_subscriptions(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer/job URI */
{
http_status_t status; /* Policy status */
int count; /* Number of subscriptions */
int limit; /* Limit */
cupsd_subscription_t *sub; /* Subscription */
cups_array_t *ra; /* Requested attributes array */
ipp_attribute_t *attr; /* Attribute */
cups_ptype_t dtype; /* Destination type (printer/class) */
char scheme[HTTP_MAX_URI],
/* Scheme portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job pointer */
cupsd_printer_t *printer; /* Printer */
cupsd_policy_t *policy; /* Policy */
cups_array_t *exclude; /* Private attributes array */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"get_subscriptions(con=%p[%d], uri=%s)",
con, con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(resource, "/") ||
(!strncmp(resource, "/jobs", 5) && strlen(resource) <= 6) ||
(!strncmp(resource, "/printers", 9) && strlen(resource) <= 10) ||
(!strncmp(resource, "/classes", 8) && strlen(resource) <= 9))
{
printer = NULL;
job = NULL;
}
else if (!strncmp(resource, "/jobs/", 6) && resource[6])
{
printer = NULL;
job = cupsdFindJob(atoi(resource + 6));
if (!job)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
atoi(resource + 6));
return;
}
}
else if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
else if ((attr = ippFindAttribute(con->request, "notify-job-id",
IPP_TAG_INTEGER)) != NULL)
{
job = cupsdFindJob(attr->values[0].integer);
if (!job)
{
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."),
attr->values[0].integer);
return;
}
}
else
job = NULL;
/*
* Check policy...
*/
if (printer)
policy = printer->op_policy_ptr;
else
policy = DefaultPolicyPtr;
if ((status = cupsdCheckPolicy(policy, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Expire subscriptions as needed...
*/
cupsdExpireSubscriptions(NULL, NULL);
/*
* Copy the subscription attributes to the response using the
* requested-attributes attribute that may be provided by the client.
*/
ra = create_requested_array(con->request);
if ((attr = ippFindAttribute(con->request, "limit",
IPP_TAG_INTEGER)) != NULL)
limit = attr->values[0].integer;
else
limit = 0;
/*
* See if we only want to see subscriptions for a specific user...
*/
if ((attr = ippFindAttribute(con->request, "my-subscriptions",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean)
strlcpy(username, get_username(con), sizeof(username));
else
username[0] = '\0';
for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions), count = 0;
sub;
sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
if ((!printer || sub->dest == printer) && (!job || sub->job == job) &&
(!username[0] || !_cups_strcasecmp(username, sub->owner)))
{
ippAddSeparator(con->response);
exclude = cupsdGetPrivateAttrs(sub->dest ? sub->dest->op_policy_ptr :
policy, con, sub->dest,
sub->owner);
copy_subscription_attrs(con, sub, ra, exclude);
count ++;
if (limit && count >= limit)
break;
}
cupsArrayDelete(ra);
if (count)
con->response->request.status.status_code = IPP_OK;
else
send_ipp_status(con, IPP_NOT_FOUND, _("No subscriptions found."));
}
/*
* 'get_username()' - Get the username associated with a request.
*/
static const char * /* O - Username */
get_username(cupsd_client_t *con) /* I - Connection */
{
ipp_attribute_t *attr; /* Attribute */
if (con->username[0])
return (con->username);
else if ((attr = ippFindAttribute(con->request, "requesting-user-name",
IPP_TAG_NAME)) != NULL)
return (attr->values[0].string.text);
else
return ("anonymous");
}
/*
* 'hold_job()' - Hold a print job.
*/
static void
hold_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current job-hold-until */
const char *when; /* New value */
int jobid; /* Job ID */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job information */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "hold_job(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See if the job is in a state that allows holding...
*/
if (job->state_value > IPP_JOB_STOPPED)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is finished and cannot be altered."),
job->id);
return;
}
/*
* Hold the job and return...
*/
if ((attr = ippFindAttribute(con->request, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(con->request, "job-hold-until", IPP_TAG_NAME);
if (attr)
{
when = attr->values[0].string.text;
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, cupsdFindDest(job->dest), job,
"Job job-hold-until value changed by user.");
}
else
when = "indefinite";
cupsdSetJobHoldUntil(job, when, 1);
cupsdSetJobState(job, IPP_JOB_HELD, CUPSD_JOB_DEFAULT, "Job held by \"%s\".",
username);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'hold_new_jobs()' - Hold pending/new jobs on a printer or class.
*/
static void
hold_new_jobs(cupsd_client_t *con, /* I - Connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "hold_new_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Hold pending/new jobs sent to the printer...
*/
printer->holding_new_jobs = 1;
cupsdSetPrinterReasons(printer, "+hold-new-jobs");
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO,
"Class \"%s\" now holding pending/new jobs (\"%s\").",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" now holding pending/new jobs (\"%s\").",
printer->name, get_username(con));
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'move_job()' - Move a job to a new destination.
*/
static void
move_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
const char *src; /* Source printer/class */
cups_ptype_t stype, /* Source type (printer or class) */
dtype; /* Destination type (printer/class) */
char scheme[HTTP_MAX_URI], /* Scheme portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_printer_t *sprinter, /* Source printer */
*dprinter; /* Destination printer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "move_job(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* Get the new printer or class...
*/
if ((attr = ippFindAttribute(con->request, "job-printer-uri",
IPP_TAG_URI)) == NULL)
{
/*
* Need job-printer-uri...
*/
send_ipp_status(con, IPP_BAD_REQUEST,
_("job-printer-uri attribute missing."));
return;
}
if (!cupsdValidateDest(attr->values[0].string.text, &dtype, &dprinter))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* See if we have a job URI or a printer URI...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
/*
* Move all jobs...
*/
if ((src = cupsdValidateDest(uri->values[0].string.text, &stype,
&sprinter)) == NULL)
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
job = NULL;
}
else
{
/*
* Otherwise, just move a single job...
*/
if ((job = cupsdFindJob(attr->values[0].integer)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("Job #%d does not exist."), attr->values[0].integer);
return;
}
else
{
/*
* Job found, initialize source pointers...
*/
src = NULL;
sprinter = NULL;
}
}
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
/*
* See if the job exists...
*/
jobid = atoi(resource + 6);
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
else
{
/*
* Job found, initialize source pointers...
*/
src = NULL;
sprinter = NULL;
}
}
/*
* Check the policy of the destination printer...
*/
if ((status = cupsdCheckPolicy(dprinter->op_policy_ptr, con,
job ? job->username : NULL)) != HTTP_OK)
{
send_http_error(con, status, dprinter);
return;
}
/*
* Now move the job or jobs...
*/
if (job)
{
/*
* See if the job has been completed...
*/
if (job->state_value > IPP_JOB_STOPPED)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is finished and cannot be altered."),
job->id);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Move the job to a different printer or class...
*/
cupsdMoveJob(job, dprinter);
}
else
{
/*
* Got the source printer, now look through the jobs...
*/
for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
job;
job = (cupsd_job_t *)cupsArrayNext(Jobs))
{
/*
* See if the job is pointing at the source printer or has not been
* completed...
*/
if (_cups_strcasecmp(job->dest, src) ||
job->state_value > IPP_JOB_STOPPED)
continue;
/*
* See if the job can be moved by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
continue;
/*
* Move the job to a different printer or class...
*/
cupsdMoveJob(job, dprinter);
}
}
/*
* Start jobs if possible...
*/
cupsdCheckJobs();
/*
* Return with "everything is OK" status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'ppd_parse_line()' - Parse a PPD default line.
*/
static int /* O - 0 on success, -1 on failure */
ppd_parse_line(const char *line, /* I - Line */
char *option, /* O - Option name */
int olen, /* I - Size of option name */
char *choice, /* O - Choice name */
int clen) /* I - Size of choice name */
{
/*
* Verify this is a default option line...
*/
if (strncmp(line, "*Default", 8))
return (-1);
/*
* Read the option name...
*/
for (line += 8, olen --;
*line > ' ' && *line < 0x7f && *line != ':' && *line != '/';
line ++)
if (olen > 0)
{
*option++ = *line;
olen --;
}
*option = '\0';
/*
* Skip everything else up to the colon (:)...
*/
while (*line && *line != ':')
line ++;
if (!*line)
return (-1);
line ++;
/*
* Now grab the option choice, skipping leading whitespace...
*/
while (isspace(*line & 255))
line ++;
for (clen --;
*line > ' ' && *line < 0x7f && *line != ':' && *line != '/';
line ++)
if (clen > 0)
{
*choice++ = *line;
clen --;
}
*choice = '\0';
/*
* Return with no errors...
*/
return (0);
}
/*
* 'print_job()' - Print a file to a printer or class.
*/
static void
print_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
ipp_attribute_t *doc_name; /* document-name attribute */
ipp_attribute_t *format; /* Document-format attribute */
const char *default_format; /* document-format-default value */
cupsd_job_t *job; /* New job */
char filename[1024]; /* Job filename */
mime_type_t *filetype; /* Type of file */
char super[MIME_MAX_SUPER], /* Supertype of file */
type[MIME_MAX_TYPE], /* Subtype of file */
mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* Textual name of mime type */
cupsd_printer_t *printer; /* Printer data */
struct stat fileinfo; /* File information */
int kbytes; /* Size of file */
int compression; /* Document compression */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "print_job(%p[%d], %s)", con, con->number,
uri->values[0].string.text);
/*
* Validate print file attributes, for now just document-format and
* compression (CUPS only supports "none" and "gzip")...
*/
compression = CUPS_FILE_NONE;
if ((attr = ippFindAttribute(con->request, "compression",
IPP_TAG_KEYWORD)) != NULL)
{
if (strcmp(attr->values[0].string.text, "none")
#ifdef HAVE_LIBZ
&& strcmp(attr->values[0].string.text, "gzip")
#endif /* HAVE_LIBZ */
)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Unsupported compression \"%s\"."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"compression", NULL, attr->values[0].string.text);
return;
}
#ifdef HAVE_LIBZ
if (!strcmp(attr->values[0].string.text, "gzip"))
compression = CUPS_FILE_GZIP;
#endif /* HAVE_LIBZ */
}
/*
* Do we have a file to print?
*/
if (!con->filename)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("No file in print request."));
return;
}
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, NULL, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Is it a format we support?
*/
doc_name = ippFindAttribute(con->request, "document-name", IPP_TAG_NAME);
if (doc_name)
ippSetName(con->request, &doc_name, "document-name-supplied");
if ((format = ippFindAttribute(con->request, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
{
/*
* Grab format from client...
*/
if (sscanf(format->values[0].string.text, "%15[^/]/%255[^;]", super,
type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad document-format \"%s\"."),
format->values[0].string.text);
return;
}
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-supplied", NULL, ippGetString(format, 0, NULL));
}
else if ((default_format = cupsGetOption("document-format",
printer->num_options,
printer->options)) != NULL)
{
/*
* Use default document format...
*/
if (sscanf(default_format, "%15[^/]/%255[^;]", super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad document-format \"%s\"."),
default_format);
return;
}
}
else
{
/*
* Auto-type it!
*/
strlcpy(super, "application", sizeof(super));
strlcpy(type, "octet-stream", sizeof(type));
}
if (!strcmp(super, "application") && !strcmp(type, "octet-stream"))
{
/*
* Auto-type the file...
*/
cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job ???] Auto-typing file...");
filetype = mimeFileType(MimeDatabase, con->filename,
doc_name ? doc_name->values[0].string.text : NULL,
&compression);
if (!filetype)
filetype = mimeType(MimeDatabase, super, type);
cupsdLogMessage(CUPSD_LOG_INFO, "[Job ???] Request file type is %s/%s.",
filetype->super, filetype->type);
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type);
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-detected", NULL, mimetype);
}
else
filetype = mimeType(MimeDatabase, super, type);
if (filetype &&
(!format ||
(!strcmp(super, "application") && !strcmp(type, "octet-stream"))))
{
/*
* Replace the document-format attribute value with the auto-typed or
* default one.
*/
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
if (format)
ippSetString(con->request, &format, 0, mimetype);
else
ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
}
else if (!filetype)
{
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported document-format \"%s\"."),
format ? format->values[0].string.text :
"application/octet-stream");
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Do you have the raw file printing rules enabled?");
if (format)
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, format->values[0].string.text);
return;
}
/*
* Read any embedded job ticket info from PS files...
*/
if (!_cups_strcasecmp(filetype->super, "application") &&
(!_cups_strcasecmp(filetype->type, "postscript") ||
!_cups_strcasecmp(filetype->type, "pdf")))
read_job_ticket(con);
/*
* Create the job object...
*/
if ((job = add_job(con, printer, filetype)) == NULL)
return;
/*
* Update quota data...
*/
if (stat(con->filename, &fileinfo))
kbytes = 0;
else
kbytes = (fileinfo.st_size + 1023) / 1024;
cupsdUpdateQuota(printer, job->username, 0, kbytes);
job->koctets += kbytes;
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer += kbytes;
/*
* Add the job file...
*/
if (add_file(con, job, filetype, compression))
return;
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id, job->num_files);
if (rename(con->filename, filename))
{
cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to rename job document file \"%s\": %s", filename, strerror(errno));
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to rename job document file."));
return;
}
cupsdClearString(&con->filename);
/*
* See if we need to add the ending sheet...
*/
if (cupsdTimeoutJob(job))
return;
/*
* Log and save the job...
*/
cupsdLogJob(job, CUPSD_LOG_INFO,
"File of type %s/%s queued by \"%s\".",
filetype->super, filetype->type, job->username);
cupsdLogJob(job, CUPSD_LOG_DEBUG, "hold_until=%d", (int)job->hold_until);
cupsdLogJob(job, CUPSD_LOG_INFO, "Queued on \"%s\" by \"%s\".",
job->dest, job->username);
/*
* Start the job if possible...
*/
cupsdCheckJobs();
}
/*
* 'read_job_ticket()' - Read a job ticket embedded in a print file.
*
* This function only gets called when printing a single PDF or PostScript
* file using the Print-Job operation. It doesn't work for Create-Job +
* Send-File, since the job attributes need to be set at job creation
* time for banners to work. The embedded job ticket stuff is here
* primarily to allow the Windows printer driver for CUPS to pass in JCL
* options and IPP attributes which otherwise would be lost.
*
* The format of a job ticket is simple:
*
* %cupsJobTicket: attr1=value1 attr2=value2 ... attrN=valueN
*
* %cupsJobTicket: attr1=value1
* %cupsJobTicket: attr2=value2
* ...
* %cupsJobTicket: attrN=valueN
*
* Job ticket lines must appear immediately after the first line that
* specifies PostScript (%!PS-Adobe-3.0) or PDF (%PDF) format, and CUPS
* stops looking for job ticket info when it finds a line that does not begin
* with "%cupsJobTicket:".
*
* The maximum length of a job ticket line, including the prefix, is
* 255 characters to conform with the Adobe DSC.
*
* Read-only attributes are rejected with a notice to the error log in
* case a malicious user tries anything. Since the job ticket is read
* prior to attribute validation in print_job(), job ticket attributes
* will go through the same validation as IPP attributes...
*/
static void
read_job_ticket(cupsd_client_t *con) /* I - Client connection */
{
cups_file_t *fp; /* File to read from */
char line[256]; /* Line data */
int num_options; /* Number of options */
cups_option_t *options; /* Options */
ipp_t *ticket; /* New attributes */
ipp_attribute_t *attr, /* Current attribute */
*attr2, /* Job attribute */
*prev2; /* Previous job attribute */
/*
* First open the print file...
*/
if ((fp = cupsFileOpen(con->filename, "rb")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open print file for job ticket - %s",
strerror(errno));
return;
}
/*
* Skip the first line...
*/
if (cupsFileGets(fp, line, sizeof(line)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to read from print file for job ticket - %s",
strerror(errno));
cupsFileClose(fp);
return;
}
if (strncmp(line, "%!PS-Adobe-", 11) && strncmp(line, "%PDF-", 5))
{
/*
* Not a DSC-compliant file, so no job ticket info will be available...
*/
cupsFileClose(fp);
return;
}
/*
* Read job ticket info from the file...
*/
num_options = 0;
options = NULL;
while (cupsFileGets(fp, line, sizeof(line)))
{
/*
* Stop at the first non-ticket line...
*/
if (strncmp(line, "%cupsJobTicket:", 15))
break;
/*
* Add the options to the option array...
*/
num_options = cupsParseOptions(line + 15, num_options, &options);
}
/*
* Done with the file; see if we have any options...
*/
cupsFileClose(fp);
if (num_options == 0)
return;
/*
* OK, convert the options to an attribute list, and apply them to
* the request...
*/
ticket = ippNew();
cupsEncodeOptions(ticket, num_options, options);
/*
* See what the user wants to change.
*/
for (attr = ticket->attrs; attr; attr = attr->next)
{
if (attr->group_tag != IPP_TAG_JOB || !attr->name)
continue;
if (!strncmp(attr->name, "date-time-at-", 13) ||
!strcmp(attr->name, "job-impressions-completed") ||
!strcmp(attr->name, "job-media-sheets-completed") ||
!strncmp(attr->name, "job-k-octets", 12) ||
!strcmp(attr->name, "job-id") ||
!strcmp(attr->name, "job-originating-host-name") ||
!strcmp(attr->name, "job-originating-user-name") ||
!strcmp(attr->name, "job-pages-completed") ||
!strcmp(attr->name, "job-printer-uri") ||
!strncmp(attr->name, "job-state", 9) ||
!strcmp(attr->name, "job-uri") ||
!strncmp(attr->name, "time-at-", 8))
continue; /* Read-only attrs */
if ((attr2 = ippFindAttribute(con->request, attr->name,
IPP_TAG_ZERO)) != NULL)
{
/*
* Some other value; first free the old value...
*/
if (con->request->attrs == attr2)
{
con->request->attrs = attr2->next;
prev2 = NULL;
}
else
{
for (prev2 = con->request->attrs; prev2; prev2 = prev2->next)
if (prev2->next == attr2)
{
prev2->next = attr2->next;
break;
}
}
if (con->request->last == attr2)
con->request->last = prev2;
ippDeleteAttribute(NULL, attr2);
}
/*
* Add new option by copying it...
*/
ippCopyAttribute(con->request, attr, 0);
}
/*
* Then free the attribute list and option array...
*/
ippDelete(ticket);
cupsFreeOptions(num_options, options);
}
/*
* 'reject_jobs()' - Reject print jobs to a printer.
*/
static void
reject_jobs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer or class URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
ipp_attribute_t *attr; /* printer-state-message text */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "reject_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Reject jobs sent to the printer...
*/
printer->accepting = 0;
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) == NULL)
strlcpy(printer->state_message, "Rejecting Jobs",
sizeof(printer->state_message));
else
strlcpy(printer->state_message, attr->values[0].string.text,
sizeof(printer->state_message));
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"No longer accepting jobs.");
if (dtype & CUPS_PRINTER_CLASS)
{
cupsdMarkDirty(CUPSD_DIRTY_CLASSES);
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" rejecting jobs (\"%s\").",
printer->name, get_username(con));
}
else
{
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" rejecting jobs (\"%s\").",
printer->name, get_username(con));
}
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'release_held_new_jobs()' - Release pending/new jobs on a printer or class.
*/
static void
release_held_new_jobs(
cupsd_client_t *con, /* I - Connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "release_held_new_jobs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Hold pending/new jobs sent to the printer...
*/
printer->holding_new_jobs = 0;
cupsdSetPrinterReasons(printer, "-hold-new-jobs");
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO,
"Class \"%s\" now printing pending/new jobs (\"%s\").",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" now printing pending/new jobs (\"%s\").",
printer->name, get_username(con));
cupsdCheckJobs();
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'release_job()' - Release a held print job.
*/
static void
release_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsd_job_t *job; /* Job information */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "release_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if job is "held"...
*/
if (job->state_value != IPP_JOB_HELD)
{
/*
* Nope - return a "not possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Job #%d is not held."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* Reset the job-hold-until value to "no-hold"...
*/
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (attr)
{
ippSetValueTag(job->attrs, &attr, IPP_TAG_KEYWORD);
ippSetString(job->attrs, &attr, 0, "no-hold");
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, cupsdFindDest(job->dest), job,
"Job job-hold-until value changed by user.");
ippSetString(job->attrs, &job->reasons, 0, "none");
}
/*
* Release the job and return...
*/
cupsdReleaseJob(job);
cupsdAddEvent(CUPSD_EVENT_JOB_STATE, cupsdFindDest(job->dest), job,
"Job released by user.");
cupsdLogJob(job, CUPSD_LOG_INFO, "Released by \"%s\".", username);
con->response->request.status.status_code = IPP_OK;
cupsdCheckJobs();
}
/*
* 'renew_subscription()' - Renew an existing subscription...
*/
static void
renew_subscription(
cupsd_client_t *con, /* I - Client connection */
int sub_id) /* I - Subscription ID */
{
http_status_t status; /* Policy status */
cupsd_subscription_t *sub; /* Subscription */
ipp_attribute_t *lease; /* notify-lease-duration */
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"renew_subscription(con=%p[%d], sub_id=%d)",
con, con->number, sub_id);
/*
* Is the subscription ID valid?
*/
if ((sub = cupsdFindSubscription(sub_id)) == NULL)
{
/*
* Bad subscription ID...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Subscription #%d does not exist."),
sub_id);
return;
}
if (sub->job)
{
/*
* Job subscriptions cannot be renewed...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job subscriptions cannot be renewed."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(sub->dest ? sub->dest->op_policy_ptr :
DefaultPolicyPtr,
con, sub->owner)) != HTTP_OK)
{
send_http_error(con, status, sub->dest);
return;
}
/*
* Renew the subscription...
*/
lease = ippFindAttribute(con->request, "notify-lease-duration",
IPP_TAG_INTEGER);
sub->lease = lease ? lease->values[0].integer : DefaultLeaseDuration;
if (MaxLeaseDuration && (sub->lease == 0 || sub->lease > MaxLeaseDuration))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"renew_subscription: Limiting notify-lease-duration to "
"%d seconds.",
MaxLeaseDuration);
sub->lease = MaxLeaseDuration;
}
sub->expire = sub->lease ? time(NULL) + sub->lease : 0;
cupsdMarkDirty(CUPSD_DIRTY_SUBSCRIPTIONS);
con->response->request.status.status_code = IPP_OK;
ippAddInteger(con->response, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
"notify-lease-duration", sub->lease);
}
/*
* 'restart_job()' - Restart an old print job.
*/
static void
restart_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job or Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Job information */
char scheme[HTTP_MAX_URI], /* Method portion of URI */
username[HTTP_MAX_URI], /* Username portion of URI */
host[HTTP_MAX_URI], /* Host portion of URI */
resource[HTTP_MAX_URI]; /* Resource portion of URI */
int port; /* Port portion of URI */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "restart_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if job is in any of the "completed" states...
*/
if (job->state_value <= IPP_JOB_PROCESSING)
{
/*
* Nope - return a "not possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Job #%d is not complete."),
jobid);
return;
}
/*
* See if we have retained the job files...
*/
cupsdLoadJob(job);
if (!job->attrs || job->num_files == 0)
{
/*
* Nope - return a "not possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d cannot be restarted - no files."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See if the job-hold-until attribute is specified...
*/
if ((attr = ippFindAttribute(con->request, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(con->request, "job-hold-until", IPP_TAG_NAME);
if (attr && strcmp(attr->values[0].string.text, "no-hold"))
{
/*
* Return the job to a held state...
*/
cupsdLogJob(job, CUPSD_LOG_DEBUG,
"Restarted by \"%s\" with job-hold-until=%s.",
username, attr->values[0].string.text);
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED | CUPSD_EVENT_JOB_STATE,
NULL, job, "Job restarted by user with job-hold-until=%s",
attr->values[0].string.text);
}
else
{
/*
* Restart the job...
*/
cupsdRestartJob(job);
cupsdCheckJobs();
}
cupsdLogJob(job, CUPSD_LOG_INFO, "Restarted by \"%s\".", username);
con->response->request.status.status_code = IPP_OK;
}
/*
* 'save_auth_info()' - Save authentication information for a job.
*/
static void
save_auth_info(
cupsd_client_t *con, /* I - Client connection */
cupsd_job_t *job, /* I - Job */
ipp_attribute_t *auth_info) /* I - auth-info attribute, if any */
{
int i; /* Looping var */
char filename[1024]; /* Job authentication filename */
cups_file_t *fp; /* Job authentication file */
char line[65536]; /* Line for file */
cupsd_printer_t *dest; /* Destination printer/class */
/*
* This function saves the in-memory authentication information for
* a job so that it can be used to authenticate with a remote host.
* The information is stored in a file that is readable only by the
* root user. The fields are Base-64 encoded, each on a separate line,
* followed by random number (up to 1024) of newlines to limit the
* amount of information that is exposed.
*
* Because of the potential for exposing of authentication information,
* this functionality is only enabled when running cupsd as root.
*
* This caching only works for the Basic and BasicDigest authentication
* types. Digest authentication cannot be cached this way, and in
* the future Kerberos authentication may make all of this obsolete.
*
* Authentication information is saved whenever an authenticated
* Print-Job, Create-Job, or CUPS-Authenticate-Job operation is
* performed.
*
* This information is deleted after a job is completed or canceled,
* so reprints may require subsequent re-authentication.
*/
if (RunUser)
return;
if ((dest = cupsdFindDest(job->dest)) == NULL)
return;
/*
* Create the authentication file and change permissions...
*/
snprintf(filename, sizeof(filename), "%s/a%05d", RequestRoot, job->id);
if ((fp = cupsFileOpen(filename, "w")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to save authentication info to \"%s\" - %s",
filename, strerror(errno));
return;
}
fchown(cupsFileNumber(fp), 0, 0);
fchmod(cupsFileNumber(fp), 0400);
cupsFilePuts(fp, "CUPSD-AUTH-V3\n");
for (i = 0;
i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
i ++)
cupsdClearString(job->auth_env + i);
if (auth_info && auth_info->num_values == dest->num_auth_info_required)
{
/*
* Write 1 to 3 auth values...
*/
for (i = 0;
i < auth_info->num_values &&
i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
i ++)
{
if (strcmp(dest->auth_info_required[i], "negotiate"))
{
httpEncode64_2(line, sizeof(line), auth_info->values[i].string.text, (int)strlen(auth_info->values[i].string.text));
cupsFilePutConf(fp, dest->auth_info_required[i], line);
}
else
cupsFilePutConf(fp, dest->auth_info_required[i],
auth_info->values[i].string.text);
if (!strcmp(dest->auth_info_required[i], "username"))
cupsdSetStringf(job->auth_env + i, "AUTH_USERNAME=%s",
auth_info->values[i].string.text);
else if (!strcmp(dest->auth_info_required[i], "domain"))
cupsdSetStringf(job->auth_env + i, "AUTH_DOMAIN=%s",
auth_info->values[i].string.text);
else if (!strcmp(dest->auth_info_required[i], "password"))
cupsdSetStringf(job->auth_env + i, "AUTH_PASSWORD=%s",
auth_info->values[i].string.text);
else if (!strcmp(dest->auth_info_required[i], "negotiate"))
cupsdSetStringf(job->auth_env + i, "AUTH_NEGOTIATE=%s",
auth_info->values[i].string.text);
else
i --;
}
}
else if (auth_info && auth_info->num_values == 2 &&
dest->num_auth_info_required == 1 &&
!strcmp(dest->auth_info_required[0], "negotiate"))
{
/*
* Allow fallback to username+password for Kerberized queues...
*/
httpEncode64_2(line, sizeof(line), auth_info->values[0].string.text, (int)strlen(auth_info->values[0].string.text));
cupsFilePutConf(fp, "username", line);
cupsdSetStringf(job->auth_env + 0, "AUTH_USERNAME=%s",
auth_info->values[0].string.text);
httpEncode64_2(line, sizeof(line), auth_info->values[1].string.text, (int)strlen(auth_info->values[1].string.text));
cupsFilePutConf(fp, "password", line);
cupsdSetStringf(job->auth_env + 1, "AUTH_PASSWORD=%s",
auth_info->values[1].string.text);
}
else if (con->username[0])
{
/*
* Write the authenticated username...
*/
httpEncode64_2(line, sizeof(line), con->username, (int)strlen(con->username));
cupsFilePutConf(fp, "username", line);
cupsdSetStringf(job->auth_env + 0, "AUTH_USERNAME=%s", con->username);
/*
* Write the authenticated password...
*/
httpEncode64_2(line, sizeof(line), con->password, (int)strlen(con->password));
cupsFilePutConf(fp, "password", line);
cupsdSetStringf(job->auth_env + 1, "AUTH_PASSWORD=%s", con->password);
}
#ifdef HAVE_GSSAPI
if (con->gss_uid > 0)
{
cupsFilePrintf(fp, "uid %d\n", (int)con->gss_uid);
cupsdSetStringf(&job->auth_uid, "AUTH_UID=%d", (int)con->gss_uid);
}
#endif /* HAVE_GSSAPI */
/*
* Write a random number of newlines to the end of the file...
*/
for (i = (CUPS_RAND() % 1024); i >= 0; i --)
cupsFilePutChar(fp, '\n');
/*
* Close the file and return...
*/
cupsFileClose(fp);
}
/*
* 'send_document()' - Send a file to a printer or class.
*/
static void
send_document(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
ipp_attribute_t *attr; /* Current attribute */
ipp_attribute_t *format; /* Request's document-format attribute */
ipp_attribute_t *jformat; /* Job's document-format attribute */
const char *default_format;/* document-format-default value */
int jobid; /* Job ID number */
cupsd_job_t *job; /* Current job */
char job_uri[HTTP_MAX_URI],
/* Job URI */
scheme[HTTP_MAX_URI],
/* Method portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
mime_type_t *filetype; /* Type of file */
char super[MIME_MAX_SUPER],
/* Supertype of file */
type[MIME_MAX_TYPE],
/* Subtype of file */
mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2];
/* Textual name of mime type */
char filename[1024]; /* Job filename */
cupsd_printer_t *printer; /* Current printer */
struct stat fileinfo; /* File information */
int kbytes; /* Size of file */
int compression; /* Type of compression */
int start_job; /* Start the job? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_document(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
printer = cupsdFindDest(job->dest);
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* OK, see if the client is sending the document compressed - CUPS
* only supports "none" and "gzip".
*/
compression = CUPS_FILE_NONE;
if ((attr = ippFindAttribute(con->request, "compression",
IPP_TAG_KEYWORD)) != NULL)
{
if (strcmp(attr->values[0].string.text, "none")
#ifdef HAVE_LIBZ
&& strcmp(attr->values[0].string.text, "gzip")
#endif /* HAVE_LIBZ */
)
{
send_ipp_status(con, IPP_ATTRIBUTES, _("Unsupported compression \"%s\"."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"compression", NULL, attr->values[0].string.text);
return;
}
#ifdef HAVE_LIBZ
if (!strcmp(attr->values[0].string.text, "gzip"))
compression = CUPS_FILE_GZIP;
#endif /* HAVE_LIBZ */
}
/*
* Do we have a file to print?
*/
if ((attr = ippFindAttribute(con->request, "last-document",
IPP_TAG_BOOLEAN)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Missing last-document attribute in request."));
return;
}
if (!con->filename)
{
/*
* Check for an empty request with "last-document" set to true, which is
* used to close an "open" job by RFC 2911, section 3.3.2.
*/
if (job->num_files > 0 && attr->values[0].boolean)
goto last_document;
send_ipp_status(con, IPP_BAD_REQUEST, _("No file in print request."));
return;
}
/*
* Is it a format we support?
*/
cupsdLoadJob(job);
if ((format = ippFindAttribute(con->request, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
{
/*
* Grab format from client...
*/
if (sscanf(format->values[0].string.text, "%15[^/]/%255[^;]",
super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad document-format \"%s\"."),
format->values[0].string.text);
return;
}
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-supplied", NULL, ippGetString(format, 0, NULL));
}
else if ((default_format = cupsGetOption("document-format",
printer->num_options,
printer->options)) != NULL)
{
/*
* Use default document format...
*/
if (sscanf(default_format, "%15[^/]/%255[^;]", super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad document-format-default \"%s\"."), default_format);
return;
}
}
else
{
/*
* No document format attribute? Auto-type it!
*/
strlcpy(super, "application", sizeof(super));
strlcpy(type, "octet-stream", sizeof(type));
}
if (!strcmp(super, "application") && !strcmp(type, "octet-stream"))
{
/*
* Auto-type the file...
*/
ipp_attribute_t *doc_name; /* document-name attribute */
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Auto-typing file...");
doc_name = ippFindAttribute(con->request, "document-name", IPP_TAG_NAME);
filetype = mimeFileType(MimeDatabase, con->filename,
doc_name ? doc_name->values[0].string.text : NULL,
&compression);
if (!filetype)
filetype = mimeType(MimeDatabase, super, type);
if (filetype)
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Request file type is %s/%s.",
filetype->super, filetype->type);
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type);
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format-detected", NULL, mimetype);
}
else
filetype = mimeType(MimeDatabase, super, type);
if (filetype)
{
/*
* Replace the document-format attribute value with the auto-typed or
* default one.
*/
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
if ((jformat = ippFindAttribute(job->attrs, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
ippSetString(job->attrs, &jformat, 0, mimetype);
else
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
}
else if (!filetype)
{
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported document-format \"%s/%s\"."), super, type);
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Do you have the raw file printing rules enabled?");
if (format)
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, format->values[0].string.text);
return;
}
if (printer->filetypes && !cupsArrayFind(printer->filetypes, filetype))
{
snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super,
filetype->type);
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported document-format \"%s\"."), mimetype);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, mimetype);
return;
}
/*
* Add the file to the job...
*/
if (add_file(con, job, filetype, compression))
return;
if ((attr = ippFindAttribute(con->request, "document-name", IPP_TAG_NAME)) != NULL)
ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "document-name-supplied", NULL, ippGetString(attr, 0, NULL));
if (stat(con->filename, &fileinfo))
kbytes = 0;
else
kbytes = (fileinfo.st_size + 1023) / 1024;
cupsdUpdateQuota(printer, job->username, 0, kbytes);
job->koctets += kbytes;
if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
attr->values[0].integer += kbytes;
snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id, job->num_files);
if (rename(con->filename, filename))
{
cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to rename job document file \"%s\": %s", filename, strerror(errno));
send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to rename job document file."));
return;
}
cupsdClearString(&con->filename);
cupsdLogJob(job, CUPSD_LOG_INFO, "File of type %s/%s queued by \"%s\".",
filetype->super, filetype->type, job->username);
/*
* Start the job if this is the last document...
*/
last_document:
if ((attr = ippFindAttribute(con->request, "last-document",
IPP_TAG_BOOLEAN)) != NULL &&
attr->values[0].boolean)
{
/*
* See if we need to add the ending sheet...
*/
if (cupsdTimeoutJob(job))
return;
if (job->state_value == IPP_JOB_STOPPED)
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
else if (job->state_value == IPP_JOB_HELD)
{
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr || !strcmp(attr->values[0].string.text, "no-hold"))
{
job->state->values[0].integer = IPP_JOB_PENDING;
job->state_value = IPP_JOB_PENDING;
ippSetString(job->attrs, &job->reasons, 0, "none");
}
else
ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
}
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
start_job = 1;
}
else
{
if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
IPP_TAG_KEYWORD)) == NULL)
attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
if (!attr || !strcmp(attr->values[0].string.text, "no-hold"))
{
job->state->values[0].integer = IPP_JOB_HELD;
job->state_value = IPP_JOB_HELD;
job->hold_until = time(NULL) + MultipleOperationTimeout;
ippSetString(job->attrs, &job->reasons, 0, "job-incoming");
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
}
start_job = 0;
}
/*
* Fill in the response info...
*/
httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL,
con->clientname, con->clientport, "/jobs/%d", jobid);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL,
job_uri);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", jobid);
ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state",
job->state_value);
ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons",
NULL, job->reasons->values[0].string.text);
con->response->request.status.status_code = IPP_OK;
/*
* Start the job if necessary...
*/
if (start_job)
cupsdCheckJobs();
}
/*
* 'send_http_error()' - Send a HTTP error back to the IPP client.
*/
static void
send_http_error(
cupsd_client_t *con, /* I - Client connection */
http_status_t status, /* I - HTTP status code */
cupsd_printer_t *printer) /* I - Printer, if any */
{
ipp_attribute_t *uri; /* Request URI, if any */
if ((uri = ippFindAttribute(con->request, "printer-uri",
IPP_TAG_URI)) == NULL)
uri = ippFindAttribute(con->request, "job-uri", IPP_TAG_URI);
cupsdLogMessage(status == HTTP_FORBIDDEN ? CUPSD_LOG_ERROR : CUPSD_LOG_DEBUG,
"[Client %d] Returning HTTP %s for %s (%s) from %s",
con->number, httpStatus(status),
con->request ?
ippOpString(con->request->request.op.operation_id) :
"no operation-id",
uri ? uri->values[0].string.text : "no URI",
con->http->hostname);
if (printer)
{
int auth_type; /* Type of authentication required */
auth_type = CUPSD_AUTH_NONE;
if (status == HTTP_UNAUTHORIZED &&
printer->num_auth_info_required > 0 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
con->request &&
(con->request->request.op.operation_id == IPP_PRINT_JOB ||
con->request->request.op.operation_id == IPP_CREATE_JOB ||
con->request->request.op.operation_id == CUPS_AUTHENTICATE_JOB))
{
/*
* Creating and authenticating jobs requires Kerberos...
*/
auth_type = CUPSD_AUTH_NEGOTIATE;
}
else
{
/*
* Use policy/location-defined authentication requirements...
*/
char resource[HTTP_MAX_URI]; /* Resource portion of URI */
cupsd_location_t *auth; /* Pointer to authentication element */
if (printer->type & CUPS_PRINTER_CLASS)
snprintf(resource, sizeof(resource), "/classes/%s", printer->name);
else
snprintf(resource, sizeof(resource), "/printers/%s", printer->name);
if ((auth = cupsdFindBest(resource, HTTP_POST)) == NULL ||
auth->type == CUPSD_AUTH_NONE)
auth = cupsdFindPolicyOp(printer->op_policy_ptr,
con->request ?
con->request->request.op.operation_id :
IPP_PRINT_JOB);
if (auth)
{
if (auth->type == CUPSD_AUTH_DEFAULT)
auth_type = cupsdDefaultAuthType();
else
auth_type = auth->type;
}
}
cupsdSendError(con, status, auth_type);
}
else
cupsdSendError(con, status, CUPSD_AUTH_NONE);
ippDelete(con->response);
con->response = NULL;
return;
}
/*
* 'send_ipp_status()' - Send a status back to the IPP client.
*/
static void
send_ipp_status(cupsd_client_t *con, /* I - Client connection */
ipp_status_t status, /* I - IPP status code */
const char *message,/* I - Status message */
...) /* I - Additional args as needed */
{
va_list ap; /* Pointer to additional args */
char formatted[1024]; /* Formatted errror message */
va_start(ap, message);
vsnprintf(formatted, sizeof(formatted),
_cupsLangString(con->language, message), ap);
va_end(ap);
cupsdLogMessage(CUPSD_LOG_DEBUG, "%s %s: %s",
ippOpString(con->request->request.op.operation_id),
ippErrorString(status), formatted);
con->response->request.status.status_code = status;
if (ippFindAttribute(con->response, "attributes-charset",
IPP_TAG_ZERO) == NULL)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
"attributes-charset", NULL, "utf-8");
if (ippFindAttribute(con->response, "attributes-natural-language",
IPP_TAG_ZERO) == NULL)
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
"attributes-natural-language", NULL, DefaultLanguage);
ippAddString(con->response, IPP_TAG_OPERATION, IPP_TAG_TEXT,
"status-message", NULL, formatted);
}
/*
* 'set_default()' - Set the default destination...
*/
static void
set_default(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer, /* Printer */
*oldprinter; /* Old default printer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_default(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(DefaultPolicyPtr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, NULL);
return;
}
/*
* Set it as the default...
*/
oldprinter = DefaultPrinter;
DefaultPrinter = printer;
if (oldprinter)
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, oldprinter, NULL,
"%s is no longer the default printer.", oldprinter->name);
cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, printer, NULL,
"%s is now the default printer.", printer->name);
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS | CUPSD_DIRTY_CLASSES |
CUPSD_DIRTY_PRINTCAP);
cupsdLogMessage(CUPSD_LOG_INFO,
"Default destination set to \"%s\" by \"%s\".",
printer->name, get_username(con));
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'set_job_attrs()' - Set job attributes.
*/
static void
set_job_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Job URI */
{
ipp_attribute_t *attr, /* Current attribute */
*attr2; /* Job attribute */
int jobid; /* Job ID */
cupsd_job_t *job; /* Current job */
char scheme[HTTP_MAX_URI],
/* Method portion of URI */
username[HTTP_MAX_URI],
/* Username portion of URI */
host[HTTP_MAX_URI],
/* Host portion of URI */
resource[HTTP_MAX_URI];
/* Resource portion of URI */
int port; /* Port portion of URI */
int event; /* Events? */
int check_jobs; /* Check jobs? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_job_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Start with "everything is OK" status...
*/
con->response->request.status.status_code = IPP_OK;
/*
* See if we have a job URI or a printer URI...
*/
if (!strcmp(uri->name, "printer-uri"))
{
/*
* Got a printer URI; see if we also have a job-id attribute...
*/
if ((attr = ippFindAttribute(con->request, "job-id",
IPP_TAG_INTEGER)) == NULL)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Got a printer-uri attribute but no job-id."));
return;
}
jobid = attr->values[0].integer;
}
else
{
/*
* Got a job URI; parse it to get the job ID...
*/
httpSeparateURI(HTTP_URI_CODING_ALL, uri->values[0].string.text, scheme,
sizeof(scheme), username, sizeof(username), host,
sizeof(host), &port, resource, sizeof(resource));
if (strncmp(resource, "/jobs/", 6))
{
/*
* Not a valid URI!
*/
send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-uri \"%s\"."),
uri->values[0].string.text);
return;
}
jobid = atoi(resource + 6);
}
/*
* See if the job exists...
*/
if ((job = cupsdFindJob(jobid)) == NULL)
{
/*
* Nope - return a "not found" error...
*/
send_ipp_status(con, IPP_NOT_FOUND, _("Job #%d does not exist."), jobid);
return;
}
/*
* See if the job has been completed...
*/
if (job->state_value > IPP_JOB_STOPPED)
{
/*
* Return a "not-possible" error...
*/
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job #%d is finished and cannot be altered."), jobid);
return;
}
/*
* See if the job is owned by the requesting user...
*/
if (!validate_user(job, con, job->username, username, sizeof(username)))
{
send_http_error(con, con->username[0] ? HTTP_FORBIDDEN : HTTP_UNAUTHORIZED,
cupsdFindDest(job->dest));
return;
}
/*
* See what the user wants to change.
*/
cupsdLoadJob(job);
check_jobs = 0;
event = 0;
for (attr = con->request->attrs; attr; attr = attr->next)
{
if (attr->group_tag != IPP_TAG_JOB || !attr->name)
continue;
if (!strcmp(attr->name, "attributes-charset") ||
!strcmp(attr->name, "attributes-natural-language") ||
!strncmp(attr->name, "date-time-at-", 13) ||
!strncmp(attr->name, "document-compression", 20) ||
!strncmp(attr->name, "document-format", 15) ||
!strcmp(attr->name, "job-detailed-status-messages") ||
!strcmp(attr->name, "job-document-access-errors") ||
!strcmp(attr->name, "job-id") ||
!strcmp(attr->name, "job-impressions-completed") ||
!strcmp(attr->name, "job-k-octets-completed") ||
!strcmp(attr->name, "job-media-sheets-completed") ||
!strcmp(attr->name, "job-originating-host-name") ||
!strcmp(attr->name, "job-originating-user-name") ||
!strcmp(attr->name, "job-pages-completed") ||
!strcmp(attr->name, "job-printer-up-time") ||
!strcmp(attr->name, "job-printer-uri") ||
!strcmp(attr->name, "job-sheets") ||
!strcmp(attr->name, "job-state-message") ||
!strcmp(attr->name, "job-state-reasons") ||
!strcmp(attr->name, "job-uri") ||
!strcmp(attr->name, "number-of-documents") ||
!strcmp(attr->name, "number-of-intervening-jobs") ||
!strcmp(attr->name, "output-device-assigned") ||
!strncmp(attr->name, "time-at-", 8))
{
/*
* Read-only attrs!
*/
send_ipp_status(con, IPP_ATTRIBUTES_NOT_SETTABLE,
_("%s cannot be changed."), attr->name);
attr2 = ippCopyAttribute(con->response, attr, 0);
ippSetGroupTag(con->response, &attr2, IPP_TAG_UNSUPPORTED_GROUP);
continue;
}
if (!strcmp(attr->name, "job-priority"))
{
/*
* Change the job priority...
*/
if (attr->value_tag != IPP_TAG_INTEGER)
{
send_ipp_status(con, IPP_REQUEST_VALUE, _("Bad job-priority value."));
attr2 = ippCopyAttribute(con->response, attr, 0);
ippSetGroupTag(con->response, &attr2, IPP_TAG_UNSUPPORTED_GROUP);
}
else if (job->state_value >= IPP_JOB_PROCESSING)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job is completed and cannot be changed."));
return;
}
else if (con->response->request.status.status_code == IPP_OK)
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-priority to %d",
attr->values[0].integer);
cupsdSetJobPriority(job, attr->values[0].integer);
check_jobs = 1;
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED |
CUPSD_EVENT_PRINTER_QUEUE_ORDER_CHANGED;
}
}
else if (!strcmp(attr->name, "job-state"))
{
/*
* Change the job state...
*/
if (attr->value_tag != IPP_TAG_ENUM)
{
send_ipp_status(con, IPP_REQUEST_VALUE, _("Bad job-state value."));
attr2 = ippCopyAttribute(con->response, attr, 0);
ippSetGroupTag(con->response, &attr2, IPP_TAG_UNSUPPORTED_GROUP);
}
else
{
switch (attr->values[0].integer)
{
case IPP_JOB_PENDING :
case IPP_JOB_HELD :
if (job->state_value > IPP_JOB_HELD)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job state cannot be changed."));
return;
}
else if (con->response->request.status.status_code == IPP_OK)
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-state to %d",
attr->values[0].integer);
cupsdSetJobState(job, (ipp_jstate_t)attr->values[0].integer, CUPSD_JOB_DEFAULT, "Job state changed by \"%s\"", username);
check_jobs = 1;
}
break;
case IPP_JOB_PROCESSING :
case IPP_JOB_STOPPED :
if (job->state_value != attr->values[0].integer)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job state cannot be changed."));
return;
}
break;
case IPP_JOB_CANCELED :
case IPP_JOB_ABORTED :
case IPP_JOB_COMPLETED :
if (job->state_value > IPP_JOB_PROCESSING)
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Job state cannot be changed."));
return;
}
else if (con->response->request.status.status_code == IPP_OK)
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-state to %d",
attr->values[0].integer);
cupsdSetJobState(job, (ipp_jstate_t)attr->values[0].integer,
CUPSD_JOB_DEFAULT,
"Job state changed by \"%s\"", username);
check_jobs = 1;
}
break;
}
}
}
else if (con->response->request.status.status_code != IPP_OK)
continue;
else if ((attr2 = ippFindAttribute(job->attrs, attr->name,
IPP_TAG_ZERO)) != NULL)
{
/*
* Some other value; first free the old value...
*/
if (job->attrs->prev)
job->attrs->prev->next = attr2->next;
else
job->attrs->attrs = attr2->next;
if (job->attrs->last == attr2)
job->attrs->last = job->attrs->prev;
ippDeleteAttribute(NULL, attr2);
/*
* Then copy the attribute...
*/
ippCopyAttribute(job->attrs, attr, 0);
/*
* See if the job-name or job-hold-until is being changed.
*/
if (!strcmp(attr->name, "job-hold-until"))
{
cupsdLogJob(job, CUPSD_LOG_DEBUG, "Setting job-hold-until to %s",
attr->values[0].string.text);
cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0);
if (!strcmp(attr->values[0].string.text, "no-hold"))
{
cupsdReleaseJob(job);
check_jobs = 1;
}
else
cupsdSetJobState(job, IPP_JOB_HELD, CUPSD_JOB_DEFAULT,
"Job held by \"%s\".", username);
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED | CUPSD_EVENT_JOB_STATE;
}
}
else if (attr->value_tag == IPP_TAG_DELETEATTR)
{
/*
* Delete the attribute...
*/
if ((attr2 = ippFindAttribute(job->attrs, attr->name,
IPP_TAG_ZERO)) != NULL)
{
if (job->attrs->prev)
job->attrs->prev->next = attr2->next;
else
job->attrs->attrs = attr2->next;
if (attr2 == job->attrs->last)
job->attrs->last = job->attrs->prev;
ippDeleteAttribute(NULL, attr2);
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED;
}
}
else
{
/*
* Add new option by copying it...
*/
ippCopyAttribute(job->attrs, attr, 0);
event |= CUPSD_EVENT_JOB_CONFIG_CHANGED;
}
}
/*
* Save the job...
*/
job->dirty = 1;
cupsdMarkDirty(CUPSD_DIRTY_JOBS);
/*
* Send events as needed...
*/
if (event & CUPSD_EVENT_PRINTER_QUEUE_ORDER_CHANGED)
cupsdAddEvent(CUPSD_EVENT_PRINTER_QUEUE_ORDER_CHANGED,
cupsdFindDest(job->dest), job,
"Job priority changed by user.");
if (event & CUPSD_EVENT_JOB_STATE)
cupsdAddEvent(CUPSD_EVENT_JOB_STATE, cupsdFindDest(job->dest), job,
job->state_value == IPP_JOB_HELD ?
"Job held by user." : "Job restarted by user.");
if (event & CUPSD_EVENT_JOB_CONFIG_CHANGED)
cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, cupsdFindDest(job->dest), job,
"Job options changed by user.");
/*
* Start jobs if possible...
*/
if (check_jobs)
cupsdCheckJobs();
}
/*
* 'set_printer_attrs()' - Set printer attributes.
*/
static void
set_printer_attrs(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer/class */
ipp_attribute_t *attr; /* Printer attribute */
int changed = 0; /* Was anything changed? */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_printer_attrs(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Return a list of attributes that can be set via Set-Printer-Attributes.
*/
if ((attr = ippFindAttribute(con->request, "printer-location",
IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->location, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-geo-location", IPP_TAG_URI)) != NULL && !strncmp(attr->values[0].string.text, "geo:", 4))
{
cupsdSetString(&printer->geo_location, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-organization", IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->organization, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-organizational-unit", IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->organizational_unit, attr->values[0].string.text);
changed = 1;
}
if ((attr = ippFindAttribute(con->request, "printer-info",
IPP_TAG_TEXT)) != NULL)
{
cupsdSetString(&printer->info, attr->values[0].string.text);
changed = 1;
}
/*
* Update the printer attributes and return...
*/
if (changed)
{
printer->config_time = time(NULL);
cupsdSetPrinterAttrs(printer);
cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
cupsdAddEvent(CUPSD_EVENT_PRINTER_CONFIG, printer, NULL,
"Printer \"%s\" description or location changed by \"%s\".",
printer->name, get_username(con));
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer \"%s\" description or location changed by \"%s\".",
printer->name, get_username(con));
}
con->response->request.status.status_code = IPP_OK;
}
/*
* 'set_printer_defaults()' - Set printer default options from a request.
*/
static int /* O - 1 on success, 0 on failure */
set_printer_defaults(
cupsd_client_t *con, /* I - Client connection */
cupsd_printer_t *printer) /* I - Printer */
{
int i; /* Looping var */
ipp_attribute_t *attr; /* Current attribute */
size_t namelen; /* Length of attribute name */
char name[256], /* New attribute name */
value[256]; /* String version of integer attrs */
for (attr = con->request->attrs; attr; attr = attr->next)
{
/*
* Skip non-printer attributes...
*/
if (attr->group_tag != IPP_TAG_PRINTER || !attr->name)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_printer_defaults: %s", attr->name);
if (!strcmp(attr->name, "job-sheets-default"))
{
/*
* Only allow keywords and names...
*/
if (attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_KEYWORD)
continue;
/*
* Only allow job-sheets-default to be set when running without a
* system high classification level...
*/
if (Classification)
continue;
cupsdSetString(&printer->job_sheets[0], attr->values[0].string.text);
if (attr->num_values > 1)
cupsdSetString(&printer->job_sheets[1], attr->values[1].string.text);
else
cupsdSetString(&printer->job_sheets[1], "none");
}
else if (!strcmp(attr->name, "requesting-user-name-allowed"))
{
cupsdFreeStrings(&(printer->users));
printer->deny_users = 0;
if (attr->value_tag == IPP_TAG_NAME &&
(attr->num_values > 1 ||
strcmp(attr->values[0].string.text, "all")))
{
for (i = 0; i < attr->num_values; i ++)
cupsdAddString(&(printer->users), attr->values[i].string.text);
}
}
else if (!strcmp(attr->name, "requesting-user-name-denied"))
{
cupsdFreeStrings(&(printer->users));
printer->deny_users = 1;
if (attr->value_tag == IPP_TAG_NAME &&
(attr->num_values > 1 ||
strcmp(attr->values[0].string.text, "none")))
{
for (i = 0; i < attr->num_values; i ++)
cupsdAddString(&(printer->users), attr->values[i].string.text);
}
}
else if (!strcmp(attr->name, "job-quota-period"))
{
if (attr->value_tag != IPP_TAG_INTEGER)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG, "Setting job-quota-period to %d...",
attr->values[0].integer);
cupsdFreeQuotas(printer);
printer->quota_period = attr->values[0].integer;
}
else if (!strcmp(attr->name, "job-k-limit"))
{
if (attr->value_tag != IPP_TAG_INTEGER)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG, "Setting job-k-limit to %d...",
attr->values[0].integer);
cupsdFreeQuotas(printer);
printer->k_limit = attr->values[0].integer;
}
else if (!strcmp(attr->name, "job-page-limit"))
{
if (attr->value_tag != IPP_TAG_INTEGER)
continue;
cupsdLogMessage(CUPSD_LOG_DEBUG, "Setting job-page-limit to %d...",
attr->values[0].integer);
cupsdFreeQuotas(printer);
printer->page_limit = attr->values[0].integer;
}
else if (!strcmp(attr->name, "printer-op-policy"))
{
cupsd_policy_t *p; /* Policy */
if (attr->value_tag != IPP_TAG_NAME)
continue;
if ((p = cupsdFindPolicy(attr->values[0].string.text)) != NULL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting printer-op-policy to \"%s\"...",
attr->values[0].string.text);
cupsdSetString(&printer->op_policy, attr->values[0].string.text);
printer->op_policy_ptr = p;
}
else
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Unknown printer-op-policy \"%s\"."),
attr->values[0].string.text);
return (0);
}
}
else if (!strcmp(attr->name, "printer-error-policy"))
{
if (attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_KEYWORD)
continue;
if (strcmp(attr->values[0].string.text, "retry-current-job") &&
((printer->type & CUPS_PRINTER_CLASS) ||
(strcmp(attr->values[0].string.text, "abort-job") &&
strcmp(attr->values[0].string.text, "retry-job") &&
strcmp(attr->values[0].string.text, "stop-printer"))))
{
send_ipp_status(con, IPP_NOT_POSSIBLE,
_("Unknown printer-error-policy \"%s\"."),
attr->values[0].string.text);
return (0);
}
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting printer-error-policy to \"%s\"...",
attr->values[0].string.text);
cupsdSetString(&printer->error_policy, attr->values[0].string.text);
}
/*
* Skip any other non-default attributes...
*/
namelen = strlen(attr->name);
if (namelen < 9 || strcmp(attr->name + namelen - 8, "-default") ||
namelen > (sizeof(name) - 1) || attr->num_values != 1)
continue;
/*
* OK, anything else must be a user-defined default...
*/
strlcpy(name, attr->name, sizeof(name));
name[namelen - 8] = '\0'; /* Strip "-default" */
switch (attr->value_tag)
{
case IPP_TAG_DELETEATTR :
printer->num_options = cupsRemoveOption(name,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Deleting %s", attr->name);
break;
case IPP_TAG_NAME :
case IPP_TAG_TEXT :
case IPP_TAG_KEYWORD :
case IPP_TAG_URI :
printer->num_options = cupsAddOption(name,
attr->values[0].string.text,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to \"%s\"...", attr->name,
attr->values[0].string.text);
break;
case IPP_TAG_BOOLEAN :
printer->num_options = cupsAddOption(name,
attr->values[0].boolean ?
"true" : "false",
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name,
attr->values[0].boolean ? "true" : "false");
break;
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
sprintf(value, "%d", attr->values[0].integer);
printer->num_options = cupsAddOption(name, value,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name, value);
break;
case IPP_TAG_RANGE :
sprintf(value, "%d-%d", attr->values[0].range.lower,
attr->values[0].range.upper);
printer->num_options = cupsAddOption(name, value,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name, value);
break;
case IPP_TAG_RESOLUTION :
sprintf(value, "%dx%d%s", attr->values[0].resolution.xres,
attr->values[0].resolution.yres,
attr->values[0].resolution.units == IPP_RES_PER_INCH ?
"dpi" : "dpcm");
printer->num_options = cupsAddOption(name, value,
printer->num_options,
&(printer->options));
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Setting %s to %s...", attr->name, value);
break;
default :
/* Do nothing for other values */
break;
}
}
return (1);
}
/*
* 'start_printer()' - Start a printer.
*/
static void
start_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
int i; /* Temporary variable */
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "start_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Start the printer...
*/
printer->state_message[0] = '\0';
cupsdStartPrinter(printer, 1);
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" started by \"%s\".",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" started by \"%s\".",
printer->name, get_username(con));
cupsdCheckJobs();
/*
* Check quotas...
*/
if ((i = check_quotas(con, printer)) < 0)
{
send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached."));
return;
}
else if (i == 0)
{
send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print."));
return;
}
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'stop_printer()' - Stop a printer.
*/
static void
stop_printer(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
cups_ptype_t dtype; /* Destination type (printer/class) */
cupsd_printer_t *printer; /* Printer data */
ipp_attribute_t *attr; /* printer-state-message attribute */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "stop_printer(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
/*
* Stop the printer...
*/
if ((attr = ippFindAttribute(con->request, "printer-state-message",
IPP_TAG_TEXT)) == NULL)
strlcpy(printer->state_message, "Paused", sizeof(printer->state_message));
else
{
strlcpy(printer->state_message, attr->values[0].string.text,
sizeof(printer->state_message));
}
cupsdStopPrinter(printer, 1);
if (dtype & CUPS_PRINTER_CLASS)
cupsdLogMessage(CUPSD_LOG_INFO, "Class \"%s\" stopped by \"%s\".",
printer->name, get_username(con));
else
cupsdLogMessage(CUPSD_LOG_INFO, "Printer \"%s\" stopped by \"%s\".",
printer->name, get_username(con));
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'url_encode_attr()' - URL-encode a string attribute.
*/
static void
url_encode_attr(ipp_attribute_t *attr, /* I - Attribute */
char *buffer,/* I - String buffer */
size_t bufsize)/* I - Size of buffer */
{
int i; /* Looping var */
char *bufptr, /* Pointer into buffer */
*bufend; /* End of buffer */
strlcpy(buffer, attr->name, bufsize);
bufptr = buffer + strlen(buffer);
bufend = buffer + bufsize - 1;
for (i = 0; i < attr->num_values; i ++)
{
if (bufptr >= bufend)
break;
if (i)
*bufptr++ = ',';
else
*bufptr++ = '=';
if (bufptr >= bufend)
break;
*bufptr++ = '\'';
bufptr = url_encode_string(attr->values[i].string.text, bufptr, (size_t)(bufend - bufptr + 1));
if (bufptr >= bufend)
break;
*bufptr++ = '\'';
}
*bufptr = '\0';
}
/*
* 'url_encode_string()' - URL-encode a string.
*/
static char * /* O - End of string */
url_encode_string(const char *s, /* I - String */
char *buffer, /* I - String buffer */
size_t bufsize) /* I - Size of buffer */
{
char *bufptr, /* Pointer into buffer */
*bufend; /* End of buffer */
static const char *hex = "0123456789ABCDEF";
/* Hex digits */
bufptr = buffer;
bufend = buffer + bufsize - 1;
while (*s && bufptr < bufend)
{
if (*s == ' ' || *s == '%' || *s == '+')
{
if (bufptr >= (bufend - 2))
break;
*bufptr++ = '%';
*bufptr++ = hex[(*s >> 4) & 15];
*bufptr++ = hex[*s & 15];
s ++;
}
else if (*s == '\'' || *s == '\\')
{
if (bufptr >= (bufend - 1))
break;
*bufptr++ = '\\';
*bufptr++ = *s++;
}
else
*bufptr++ = *s++;
}
*bufptr = '\0';
return (bufptr);
}
/*
* 'user_allowed()' - See if a user is allowed to print to a queue.
*/
static int /* O - 0 if not allowed, 1 if allowed */
user_allowed(cupsd_printer_t *p, /* I - Printer or class */
const char *username) /* I - Username */
{
struct passwd *pw; /* User password data */
char baseuser[256], /* Base username */
*baseptr, /* Pointer to "@" in base username */
*name; /* Current user name */
if (cupsArrayCount(p->users) == 0)
return (1);
if (!strcmp(username, "root"))
return (1);
if (strchr(username, '@'))
{
/*
* Strip @REALM for username check...
*/
strlcpy(baseuser, username, sizeof(baseuser));
if ((baseptr = strchr(baseuser, '@')) != NULL)
*baseptr = '\0';
username = baseuser;
}
pw = getpwnam(username);
endpwent();
for (name = (char *)cupsArrayFirst(p->users);
name;
name = (char *)cupsArrayNext(p->users))
{
if (name[0] == '@')
{
/*
* Check group membership...
*/
if (cupsdCheckGroup(username, pw, name + 1))
break;
}
else if (name[0] == '#')
{
/*
* Check UUID...
*/
if (cupsdCheckGroup(username, pw, name))
break;
}
else if (!_cups_strcasecmp(username, name))
break;
}
return ((name != NULL) != p->deny_users);
}
/*
* 'validate_job()' - Validate printer options and destination.
*/
static void
validate_job(cupsd_client_t *con, /* I - Client connection */
ipp_attribute_t *uri) /* I - Printer URI */
{
http_status_t status; /* Policy status */
ipp_attribute_t *attr; /* Current attribute */
#ifdef HAVE_SSL
ipp_attribute_t *auth_info; /* auth-info attribute */
#endif /* HAVE_SSL */
ipp_attribute_t *format, /* Document-format attribute */
*name; /* Job-name attribute */
cups_ptype_t dtype; /* Destination type (printer/class) */
char super[MIME_MAX_SUPER],
/* Supertype of file */
type[MIME_MAX_TYPE];
/* Subtype of file */
cupsd_printer_t *printer; /* Printer */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "validate_job(%p[%d], %s)", con,
con->number, uri->values[0].string.text);
/*
* OK, see if the client is sending the document compressed - CUPS
* doesn't support compression yet...
*/
if ((attr = ippFindAttribute(con->request, "compression",
IPP_TAG_KEYWORD)) != NULL)
{
if (strcmp(attr->values[0].string.text, "none")
#ifdef HAVE_LIBZ
&& strcmp(attr->values[0].string.text, "gzip")
#endif /* HAVE_LIBZ */
)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Unsupported 'compression' value \"%s\"."),
attr->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_KEYWORD,
"compression", NULL, attr->values[0].string.text);
return;
}
}
/*
* Is it a format we support?
*/
if ((format = ippFindAttribute(con->request, "document-format",
IPP_TAG_MIMETYPE)) != NULL)
{
if (sscanf(format->values[0].string.text, "%15[^/]/%255[^;]",
super, type) != 2)
{
send_ipp_status(con, IPP_BAD_REQUEST,
_("Bad 'document-format' value \"%s\"."),
format->values[0].string.text);
return;
}
if ((strcmp(super, "application") || strcmp(type, "octet-stream")) &&
!mimeType(MimeDatabase, super, type))
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Do you have the raw file printing rules enabled?");
send_ipp_status(con, IPP_DOCUMENT_FORMAT,
_("Unsupported 'document-format' value \"%s\"."),
format->values[0].string.text);
ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE,
"document-format", NULL, format->values[0].string.text);
return;
}
}
/*
* Is the job-name valid?
*/
if ((name = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) != NULL)
{
int bad_name = 0; /* Is the job-name value bad? */
if ((name->value_tag != IPP_TAG_NAME && name->value_tag != IPP_TAG_NAMELANG) ||
name->num_values != 1)
{
bad_name = 1;
}
else
{
/*
* Validate that job-name conforms to RFC 5198 (Network Unicode) and
* IPP Everywhere requirements for "name" values...
*/
const unsigned char *nameptr; /* Pointer into "job-name" attribute */
for (nameptr = (unsigned char *)name->values[0].string.text;
*nameptr;
nameptr ++)
{
if (*nameptr < ' ' && *nameptr != '\t')
break;
else if (*nameptr == 0x7f)
break;
else if ((*nameptr & 0xe0) == 0xc0)
{
if ((nameptr[1] & 0xc0) != 0x80)
break;
nameptr ++;
}
else if ((*nameptr & 0xf0) == 0xe0)
{
if ((nameptr[1] & 0xc0) != 0x80 ||
(nameptr[2] & 0xc0) != 0x80)
break;
nameptr += 2;
}
else if ((*nameptr & 0xf8) == 0xf0)
{
if ((nameptr[1] & 0xc0) != 0x80 ||
(nameptr[2] & 0xc0) != 0x80 ||
(nameptr[3] & 0xc0) != 0x80)
break;
nameptr += 3;
}
else if (*nameptr & 0x80)
break;
}
if (*nameptr)
bad_name = 1;
}
if (bad_name)
{
if (StrictConformance)
{
send_ipp_status(con, IPP_ATTRIBUTES,
_("Unsupported 'job-name' value."));
ippCopyAttribute(con->response, name, 0);
return;
}
else
{
cupsdLogMessage(CUPSD_LOG_WARN,
"Unsupported 'job-name' value, deleting from request.");
ippDeleteAttribute(con->request, name);
}
}
}
/*
* Is the destination valid?
*/
if (!cupsdValidateDest(uri->values[0].string.text, &dtype, &printer))
{
/*
* Bad URI...
*/
send_ipp_status(con, IPP_NOT_FOUND,
_("The printer or class does not exist."));
return;
}
/*
* Check policy...
*/
#ifdef HAVE_SSL
auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT);
#endif /* HAVE_SSL */
if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK)
{
send_http_error(con, status, printer);
return;
}
else if (printer->num_auth_info_required == 1 &&
!strcmp(printer->auth_info_required[0], "negotiate") &&
!con->username[0])
{
send_http_error(con, HTTP_UNAUTHORIZED, printer);
return;
}
#ifdef HAVE_SSL
else if (auth_info && !con->http->tls &&
!httpAddrLocalhost(con->http->hostaddr))
{
/*
* Require encryption of auth-info over non-local connections...
*/
send_http_error(con, HTTP_UPGRADE_REQUIRED, printer);
return;
}
#endif /* HAVE_SSL */
/*
* Everything was ok, so return OK status...
*/
con->response->request.status.status_code = IPP_OK;
}
/*
* 'validate_name()' - Make sure the printer name only contains valid chars.
*/
static int /* O - 0 if name is no good, 1 if good */
validate_name(const char *name) /* I - Name to check */
{
const char *ptr; /* Pointer into name */
/*
* Scan the whole name...
*/
for (ptr = name; *ptr; ptr ++)
if ((*ptr > 0 && *ptr <= ' ') || *ptr == 127 || *ptr == '/' || *ptr == '#')
return (0);
/*
* All the characters are good; validate the length, too...
*/
return ((ptr - name) < 128);
}
/*
* 'validate_user()' - Validate the user for the request.
*/
static int /* O - 1 if permitted, 0 otherwise */
validate_user(cupsd_job_t *job, /* I - Job */
cupsd_client_t *con, /* I - Client connection */
const char *owner, /* I - Owner of job/resource */
char *username, /* O - Authenticated username */
size_t userlen) /* I - Length of username */
{
cupsd_printer_t *printer; /* Printer for job */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "validate_user(job=%d, con=%d, owner=\"%s\", username=%p, userlen=" CUPS_LLFMT ")", job->id, con ? con->number : 0, owner ? owner : "(null)", username, CUPS_LLCAST userlen);
/*
* Validate input...
*/
if (!con || !owner || !username || userlen <= 0)
return (0);
/*
* Get the best authenticated username that is available.
*/
strlcpy(username, get_username(con), userlen);
/*
* Check the username against the owner...
*/
printer = cupsdFindDest(job->dest);
return (cupsdCheckPolicy(printer ? printer->op_policy_ptr : DefaultPolicyPtr,
con, owner) == HTTP_OK);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3025_1 |
crossvul-cpp_data_good_727_0 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2016, Linaro Limited
* Copyright (c) 2014, STMicroelectronics International N.V.
*/
#include <arm.h>
#include <assert.h>
#include <kernel/panic.h>
#include <kernel/spinlock.h>
#include <kernel/tee_common.h>
#include <kernel/tee_misc.h>
#include <kernel/tlb_helpers.h>
#include <mm/core_memprot.h>
#include <mm/core_mmu.h>
#include <mm/mobj.h>
#include <mm/pgt_cache.h>
#include <mm/tee_mm.h>
#include <mm/tee_mmu.h>
#include <mm/tee_mmu_types.h>
#include <mm/tee_pager.h>
#include <sm/optee_smc.h>
#include <stdlib.h>
#include <tee_api_defines_extensions.h>
#include <tee_api_types.h>
#include <trace.h>
#include <types_ext.h>
#include <user_ta_header.h>
#include <util.h>
#ifdef CFG_PL310
#include <kernel/tee_l2cc_mutex.h>
#endif
#define TEE_MMU_UDATA_ATTR (TEE_MATTR_VALID_BLOCK | \
TEE_MATTR_PRW | TEE_MATTR_URW | \
TEE_MATTR_SECURE)
#define TEE_MMU_UCODE_ATTR (TEE_MATTR_VALID_BLOCK | \
TEE_MATTR_PRW | TEE_MATTR_URWX | \
TEE_MATTR_SECURE)
#define TEE_MMU_UCACHE_DEFAULT_ATTR (TEE_MATTR_CACHE_CACHED << \
TEE_MATTR_CACHE_SHIFT)
static vaddr_t select_va_in_range(vaddr_t prev_end, uint32_t prev_attr,
vaddr_t next_begin, uint32_t next_attr,
const struct vm_region *reg)
{
size_t granul;
const uint32_t a = TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT;
size_t pad;
vaddr_t begin_va;
vaddr_t end_va;
/*
* Insert an unmapped entry to separate regions with differing
* TEE_MATTR_EPHEMERAL TEE_MATTR_PERMANENT bits as they never are
* to be contiguous with another region.
*/
if (prev_attr && (prev_attr & a) != (reg->attr & a))
pad = SMALL_PAGE_SIZE;
else
pad = 0;
granul = SMALL_PAGE_SIZE;
#ifndef CFG_WITH_LPAE
if ((prev_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE))
granul = CORE_MMU_PGDIR_SIZE;
#endif
begin_va = ROUNDUP(prev_end + pad, granul);
if (reg->va) {
if (reg->va < begin_va)
return 0;
begin_va = reg->va;
}
if (next_attr && (next_attr & a) != (reg->attr & a))
pad = SMALL_PAGE_SIZE;
else
pad = 0;
granul = SMALL_PAGE_SIZE;
#ifndef CFG_WITH_LPAE
if ((next_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE))
granul = CORE_MMU_PGDIR_SIZE;
#endif
end_va = ROUNDUP(begin_va + reg->size + pad, granul);
if (end_va <= next_begin) {
assert(!reg->va || reg->va == begin_va);
return begin_va;
}
return 0;
}
static size_t get_num_req_pgts(struct user_ta_ctx *utc, vaddr_t *begin,
vaddr_t *end)
{
vaddr_t b;
vaddr_t e;
if (TAILQ_EMPTY(&utc->vm_info->regions)) {
core_mmu_get_user_va_range(&b, NULL);
e = b;
} else {
struct vm_region *r;
b = TAILQ_FIRST(&utc->vm_info->regions)->va;
r = TAILQ_LAST(&utc->vm_info->regions, vm_region_head);
e = r->va + r->size;
b = ROUNDDOWN(b, CORE_MMU_PGDIR_SIZE);
e = ROUNDUP(e, CORE_MMU_PGDIR_SIZE);
}
if (begin)
*begin = b;
if (end)
*end = e;
return (e - b) >> CORE_MMU_PGDIR_SHIFT;
}
static TEE_Result alloc_pgt(struct user_ta_ctx *utc)
{
struct thread_specific_data *tsd __maybe_unused;
vaddr_t b;
vaddr_t e;
size_t ntbl;
ntbl = get_num_req_pgts(utc, &b, &e);
if (!pgt_check_avail(ntbl)) {
EMSG("%zu page tables not available", ntbl);
return TEE_ERROR_OUT_OF_MEMORY;
}
#ifdef CFG_PAGED_USER_TA
tsd = thread_get_tsd();
if (&utc->ctx == tsd->ctx) {
/*
* The supplied utc is the current active utc, allocate the
* page tables too as the pager needs to use them soon.
*/
pgt_alloc(&tsd->pgt_cache, &utc->ctx, b, e - 1);
}
#endif
return TEE_SUCCESS;
}
static void free_pgt(struct user_ta_ctx *utc, vaddr_t base, size_t size)
{
struct thread_specific_data *tsd = thread_get_tsd();
struct pgt_cache *pgt_cache = NULL;
if (&utc->ctx == tsd->ctx)
pgt_cache = &tsd->pgt_cache;
pgt_flush_ctx_range(pgt_cache, &utc->ctx, base, base + size);
}
static TEE_Result umap_add_region(struct vm_info *vmi, struct vm_region *reg)
{
struct vm_region *r;
struct vm_region *prev_r;
vaddr_t va_range_base;
size_t va_range_size;
vaddr_t va;
core_mmu_get_user_va_range(&va_range_base, &va_range_size);
/* Check alignment, it has to be at least SMALL_PAGE based */
if ((reg->va | reg->size) & SMALL_PAGE_MASK)
return TEE_ERROR_ACCESS_CONFLICT;
/* Check that the mobj is defined for the entire range */
if ((reg->offset + reg->size) >
ROUNDUP(reg->mobj->size, SMALL_PAGE_SIZE))
return TEE_ERROR_BAD_PARAMETERS;
prev_r = NULL;
TAILQ_FOREACH(r, &vmi->regions, link) {
if (TAILQ_FIRST(&vmi->regions) == r) {
va = select_va_in_range(va_range_base, 0,
r->va, r->attr, reg);
if (va) {
reg->va = va;
TAILQ_INSERT_HEAD(&vmi->regions, reg, link);
return TEE_SUCCESS;
}
} else {
va = select_va_in_range(prev_r->va + prev_r->size,
prev_r->attr, r->va, r->attr,
reg);
if (va) {
reg->va = va;
TAILQ_INSERT_BEFORE(r, reg, link);
return TEE_SUCCESS;
}
}
prev_r = r;
}
r = TAILQ_LAST(&vmi->regions, vm_region_head);
if (r) {
va = select_va_in_range(r->va + r->size, r->attr,
va_range_base + va_range_size, 0, reg);
if (va) {
reg->va = va;
TAILQ_INSERT_TAIL(&vmi->regions, reg, link);
return TEE_SUCCESS;
}
} else {
va = select_va_in_range(va_range_base, 0,
va_range_base + va_range_size, 0, reg);
if (va) {
reg->va = va;
TAILQ_INSERT_HEAD(&vmi->regions, reg, link);
return TEE_SUCCESS;
}
}
return TEE_ERROR_ACCESS_CONFLICT;
}
TEE_Result vm_map(struct user_ta_ctx *utc, vaddr_t *va, size_t len,
uint32_t prot, struct mobj *mobj, size_t offs)
{
TEE_Result res;
struct vm_region *reg = calloc(1, sizeof(*reg));
uint32_t attr = 0;
const uint32_t prot_mask = TEE_MATTR_PROT_MASK | TEE_MATTR_PERMANENT |
TEE_MATTR_EPHEMERAL;
if (!reg)
return TEE_ERROR_OUT_OF_MEMORY;
if (prot & ~prot_mask) {
res = TEE_ERROR_BAD_PARAMETERS;
goto err_free_reg;
}
if (!mobj_is_paged(mobj)) {
uint32_t cattr;
res = mobj_get_cattr(mobj, &cattr);
if (res)
goto err_free_reg;
attr |= cattr << TEE_MATTR_CACHE_SHIFT;
}
attr |= TEE_MATTR_VALID_BLOCK;
if (mobj_is_secure(mobj))
attr |= TEE_MATTR_SECURE;
reg->mobj = mobj;
reg->offset = offs;
reg->va = *va;
reg->size = ROUNDUP(len, SMALL_PAGE_SIZE);
reg->attr = attr | prot;
res = umap_add_region(utc->vm_info, reg);
if (res)
goto err_free_reg;
res = alloc_pgt(utc);
if (res)
goto err_rem_reg;
if (!(reg->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) &&
mobj_is_paged(mobj)) {
if (!tee_pager_add_uta_area(utc, reg->va, reg->size)) {
res = TEE_ERROR_GENERIC;
goto err_rem_reg;
}
}
/*
* If the context currently is active set it again to update
* the mapping.
*/
if (thread_get_tsd()->ctx == &utc->ctx)
tee_mmu_set_ctx(&utc->ctx);
*va = reg->va;
return TEE_SUCCESS;
err_rem_reg:
TAILQ_REMOVE(&utc->vm_info->regions, reg, link);
err_free_reg:
free(reg);
return res;
}
TEE_Result vm_set_prot(struct user_ta_ctx *utc, vaddr_t va, size_t len,
uint32_t prot)
{
struct vm_region *r;
/*
* To keep thing simple: specified va and len has to match exactly
* with an already registered region.
*/
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (core_is_buffer_intersect(r->va, r->size, va, len)) {
if (r->va != va || r->size != len)
return TEE_ERROR_BAD_PARAMETERS;
if (mobj_is_paged(r->mobj)) {
if (!tee_pager_set_uta_area_attr(utc, va, len,
prot))
return TEE_ERROR_GENERIC;
} else if ((prot & TEE_MATTR_UX) &&
(r->attr & (TEE_MATTR_UW | TEE_MATTR_PW))) {
cache_op_inner(DCACHE_AREA_CLEAN,
(void *)va, len);
cache_op_inner(ICACHE_AREA_INVALIDATE,
(void *)va, len);
}
r->attr &= ~TEE_MATTR_PROT_MASK;
r->attr |= prot & TEE_MATTR_PROT_MASK;
return TEE_SUCCESS;
}
}
return TEE_ERROR_ITEM_NOT_FOUND;
}
static TEE_Result map_kinit(struct user_ta_ctx *utc __maybe_unused)
{
TEE_Result res;
struct mobj *mobj;
size_t offs;
vaddr_t va;
size_t sz;
thread_get_user_kcode(&mobj, &offs, &va, &sz);
if (sz) {
res = vm_map(utc, &va, sz, TEE_MATTR_PRX | TEE_MATTR_PERMANENT,
mobj, offs);
if (res)
return res;
}
thread_get_user_kdata(&mobj, &offs, &va, &sz);
if (sz)
return vm_map(utc, &va, sz, TEE_MATTR_PRW | TEE_MATTR_PERMANENT,
mobj, offs);
return TEE_SUCCESS;
}
TEE_Result vm_info_init(struct user_ta_ctx *utc)
{
TEE_Result res;
uint32_t asid = asid_alloc();
if (!asid) {
DMSG("Failed to allocate ASID");
return TEE_ERROR_GENERIC;
}
utc->vm_info = calloc(1, sizeof(*utc->vm_info));
if (!utc->vm_info) {
asid_free(asid);
return TEE_ERROR_OUT_OF_MEMORY;
}
TAILQ_INIT(&utc->vm_info->regions);
utc->vm_info->asid = asid;
res = map_kinit(utc);
if (res)
vm_info_final(utc);
return res;
}
static void umap_remove_region(struct vm_info *vmi, struct vm_region *reg)
{
TAILQ_REMOVE(&vmi->regions, reg, link);
free(reg);
}
static void clear_param_map(struct user_ta_ctx *utc)
{
struct vm_region *next_r;
struct vm_region *r;
TAILQ_FOREACH_SAFE(r, &utc->vm_info->regions, link, next_r)
if (r->attr & TEE_MATTR_EPHEMERAL)
umap_remove_region(utc->vm_info, r);
}
static TEE_Result param_mem_to_user_va(struct user_ta_ctx *utc,
struct param_mem *mem, void **user_va)
{
struct vm_region *region;
TAILQ_FOREACH(region, &utc->vm_info->regions, link) {
vaddr_t va;
size_t phys_offs;
if (!(region->attr & TEE_MATTR_EPHEMERAL))
continue;
if (mem->mobj != region->mobj)
continue;
if (mem->offs < region->offset)
continue;
if (mem->offs >= (region->offset + region->size))
continue;
phys_offs = mobj_get_phys_offs(mem->mobj,
CORE_MMU_USER_PARAM_SIZE);
va = region->va + mem->offs + phys_offs - region->offset;
*user_va = (void *)va;
return TEE_SUCCESS;
}
return TEE_ERROR_GENERIC;
}
static int cmp_param_mem(const void *a0, const void *a1)
{
const struct param_mem *m1 = a1;
const struct param_mem *m0 = a0;
int ret;
/* Make sure that invalid param_mem are placed last in the array */
if (!m0->size && !m1->size)
return 0;
if (!m0->size)
return 1;
if (!m1->size)
return -1;
ret = CMP_TRILEAN(mobj_is_secure(m0->mobj), mobj_is_secure(m1->mobj));
if (ret)
return ret;
ret = CMP_TRILEAN((vaddr_t)m0->mobj, (vaddr_t)m1->mobj);
if (ret)
return ret;
ret = CMP_TRILEAN(m0->offs, m1->offs);
if (ret)
return ret;
return CMP_TRILEAN(m0->size, m1->size);
}
TEE_Result tee_mmu_map_param(struct user_ta_ctx *utc,
struct tee_ta_param *param, void *param_va[TEE_NUM_PARAMS])
{
TEE_Result res = TEE_SUCCESS;
size_t n;
size_t m;
struct param_mem mem[TEE_NUM_PARAMS];
memset(mem, 0, sizeof(mem));
for (n = 0; n < TEE_NUM_PARAMS; n++) {
uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n);
size_t phys_offs;
if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_INOUT)
continue;
phys_offs = mobj_get_phys_offs(param->u[n].mem.mobj,
CORE_MMU_USER_PARAM_SIZE);
mem[n].mobj = param->u[n].mem.mobj;
mem[n].offs = ROUNDDOWN(phys_offs + param->u[n].mem.offs,
CORE_MMU_USER_PARAM_SIZE);
mem[n].size = ROUNDUP(phys_offs + param->u[n].mem.offs -
mem[n].offs + param->u[n].mem.size,
CORE_MMU_USER_PARAM_SIZE);
}
/*
* Sort arguments so size = 0 is last, secure mobjs first, then by
* mobj pointer value since those entries can't be merged either,
* finally by offset.
*
* This should result in a list where all mergeable entries are
* next to each other and unused/invalid entries are at the end.
*/
qsort(mem, TEE_NUM_PARAMS, sizeof(struct param_mem), cmp_param_mem);
for (n = 1, m = 0; n < TEE_NUM_PARAMS && mem[n].size; n++) {
if (mem[n].mobj == mem[m].mobj &&
(mem[n].offs == (mem[m].offs + mem[m].size) ||
core_is_buffer_intersect(mem[m].offs, mem[m].size,
mem[n].offs, mem[n].size))) {
mem[m].size = mem[n].offs + mem[n].size - mem[m].offs;
continue;
}
m++;
if (n != m)
mem[m] = mem[n];
}
/*
* We'd like 'm' to be the number of valid entries. Here 'm' is the
* index of the last valid entry if the first entry is valid, else
* 0.
*/
if (mem[0].size)
m++;
/* Clear all the param entries as they can hold old information */
clear_param_map(utc);
for (n = 0; n < m; n++) {
vaddr_t va = 0;
const uint32_t prot = TEE_MATTR_PRW | TEE_MATTR_URW |
TEE_MATTR_EPHEMERAL;
res = vm_map(utc, &va, mem[n].size, prot, mem[n].mobj,
mem[n].offs);
if (res)
return res;
}
for (n = 0; n < TEE_NUM_PARAMS; n++) {
uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n);
if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_INOUT)
continue;
if (param->u[n].mem.size == 0)
continue;
res = param_mem_to_user_va(utc, ¶m->u[n].mem, param_va + n);
if (res != TEE_SUCCESS)
return res;
}
return alloc_pgt(utc);
}
TEE_Result tee_mmu_add_rwmem(struct user_ta_ctx *utc, struct mobj *mobj,
vaddr_t *va)
{
TEE_Result res;
struct vm_region *reg = calloc(1, sizeof(*reg));
if (!reg)
return TEE_ERROR_OUT_OF_MEMORY;
reg->mobj = mobj;
reg->offset = 0;
reg->va = 0;
reg->size = ROUNDUP(mobj->size, SMALL_PAGE_SIZE);
if (mobj_is_secure(mobj))
reg->attr = TEE_MATTR_SECURE;
else
reg->attr = 0;
res = umap_add_region(utc->vm_info, reg);
if (res) {
free(reg);
return res;
}
res = alloc_pgt(utc);
if (res)
umap_remove_region(utc->vm_info, reg);
else
*va = reg->va;
return res;
}
void tee_mmu_rem_rwmem(struct user_ta_ctx *utc, struct mobj *mobj, vaddr_t va)
{
struct vm_region *reg;
TAILQ_FOREACH(reg, &utc->vm_info->regions, link) {
if (reg->mobj == mobj && reg->va == va) {
free_pgt(utc, reg->va, reg->size);
umap_remove_region(utc->vm_info, reg);
return;
}
}
}
void vm_info_final(struct user_ta_ctx *utc)
{
if (!utc->vm_info)
return;
/* clear MMU entries to avoid clash when asid is reused */
tlbi_asid(utc->vm_info->asid);
asid_free(utc->vm_info->asid);
while (!TAILQ_EMPTY(&utc->vm_info->regions))
umap_remove_region(utc->vm_info,
TAILQ_FIRST(&utc->vm_info->regions));
free(utc->vm_info);
utc->vm_info = NULL;
}
/* return true only if buffer fits inside TA private memory */
bool tee_mmu_is_vbuf_inside_ta_private(const struct user_ta_ctx *utc,
const void *va, size_t size)
{
struct vm_region *r;
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT))
continue;
if (core_is_buffer_inside(va, size, r->va, r->size))
return true;
}
return false;
}
/* return true only if buffer intersects TA private memory */
bool tee_mmu_is_vbuf_intersect_ta_private(const struct user_ta_ctx *utc,
const void *va, size_t size)
{
struct vm_region *r;
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT))
continue;
if (core_is_buffer_intersect(va, size, r->va, r->size))
return true;
}
return false;
}
TEE_Result tee_mmu_vbuf_to_mobj_offs(const struct user_ta_ctx *utc,
const void *va, size_t size,
struct mobj **mobj, size_t *offs)
{
struct vm_region *r;
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (!r->mobj)
continue;
if (core_is_buffer_inside(va, size, r->va, r->size)) {
size_t poffs;
poffs = mobj_get_phys_offs(r->mobj,
CORE_MMU_USER_PARAM_SIZE);
*mobj = r->mobj;
*offs = (vaddr_t)va - r->va + r->offset - poffs;
return TEE_SUCCESS;
}
}
return TEE_ERROR_BAD_PARAMETERS;
}
static TEE_Result tee_mmu_user_va2pa_attr(const struct user_ta_ctx *utc,
void *ua, paddr_t *pa, uint32_t *attr)
{
struct vm_region *region;
TAILQ_FOREACH(region, &utc->vm_info->regions, link) {
if (!core_is_buffer_inside(ua, 1, region->va, region->size))
continue;
if (pa) {
TEE_Result res;
paddr_t p;
size_t offset;
size_t granule;
/*
* mobj and input user address may each include
* a specific offset-in-granule position.
* Drop both to get target physical page base
* address then apply only user address
* offset-in-granule.
* Mapping lowest granule is the small page.
*/
granule = MAX(region->mobj->phys_granule,
(size_t)SMALL_PAGE_SIZE);
assert(!granule || IS_POWER_OF_TWO(granule));
offset = region->offset +
ROUNDDOWN((vaddr_t)ua - region->va, granule);
res = mobj_get_pa(region->mobj, offset, granule, &p);
if (res != TEE_SUCCESS)
return res;
*pa = p | ((vaddr_t)ua & (granule - 1));
}
if (attr)
*attr = region->attr;
return TEE_SUCCESS;
}
return TEE_ERROR_ACCESS_DENIED;
}
TEE_Result tee_mmu_user_va2pa_helper(const struct user_ta_ctx *utc, void *ua,
paddr_t *pa)
{
return tee_mmu_user_va2pa_attr(utc, ua, pa, NULL);
}
/* */
TEE_Result tee_mmu_user_pa2va_helper(const struct user_ta_ctx *utc,
paddr_t pa, void **va)
{
TEE_Result res;
paddr_t p;
struct vm_region *region;
TAILQ_FOREACH(region, &utc->vm_info->regions, link) {
size_t granule;
size_t size;
size_t ofs;
/* pa2va is expected only for memory tracked through mobj */
if (!region->mobj)
continue;
/* Physically granulated memory object must be scanned */
granule = region->mobj->phys_granule;
assert(!granule || IS_POWER_OF_TWO(granule));
for (ofs = region->offset; ofs < region->size; ofs += size) {
if (granule) {
/* From current offset to buffer/granule end */
size = granule - (ofs & (granule - 1));
if (size > (region->size - ofs))
size = region->size - ofs;
} else
size = region->size;
res = mobj_get_pa(region->mobj, ofs, granule, &p);
if (res != TEE_SUCCESS)
return res;
if (core_is_buffer_inside(pa, 1, p, size)) {
/* Remove region offset (mobj phys offset) */
ofs -= region->offset;
/* Get offset-in-granule */
p = pa - p;
*va = (void *)(region->va + ofs + (vaddr_t)p);
return TEE_SUCCESS;
}
}
}
return TEE_ERROR_ACCESS_DENIED;
}
TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc,
uint32_t flags, uaddr_t uaddr,
size_t len)
{
uaddr_t a;
uaddr_t end_addr = 0;
size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE,
CORE_MMU_USER_PARAM_SIZE);
if (ADD_OVERFLOW(uaddr, len, &end_addr))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_NONSECURE) &&
(flags & TEE_MEMORY_ACCESS_SECURE))
return TEE_ERROR_ACCESS_DENIED;
/*
* Rely on TA private memory test to check if address range is private
* to TA or not.
*/
if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) &&
!tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len))
return TEE_ERROR_ACCESS_DENIED;
for (a = ROUNDDOWN(uaddr, addr_incr); a < end_addr; a += addr_incr) {
uint32_t attr;
TEE_Result res;
res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr);
if (res != TEE_SUCCESS)
return res;
if ((flags & TEE_MEMORY_ACCESS_NONSECURE) &&
(attr & TEE_MATTR_SECURE))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_SECURE) &&
!(attr & TEE_MATTR_SECURE))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR))
return TEE_ERROR_ACCESS_DENIED;
}
return TEE_SUCCESS;
}
void tee_mmu_set_ctx(struct tee_ta_ctx *ctx)
{
struct thread_specific_data *tsd = thread_get_tsd();
core_mmu_set_user_map(NULL);
/*
* No matter what happens below, the current user TA will not be
* current any longer. Make sure pager is in sync with that.
* This function has to be called before there's a chance that
* pgt_free_unlocked() is called.
*
* Save translation tables in a cache if it's a user TA.
*/
pgt_free(&tsd->pgt_cache, tsd->ctx && is_user_ta_ctx(tsd->ctx));
if (ctx && is_user_ta_ctx(ctx)) {
struct core_mmu_user_map map;
struct user_ta_ctx *utc = to_user_ta_ctx(ctx);
core_mmu_create_user_map(utc, &map);
core_mmu_set_user_map(&map);
tee_pager_assign_uta_tables(utc);
}
tsd->ctx = ctx;
}
struct tee_ta_ctx *tee_mmu_get_ctx(void)
{
return thread_get_tsd()->ctx;
}
void teecore_init_ta_ram(void)
{
vaddr_t s;
vaddr_t e;
paddr_t ps;
paddr_t pe;
/* get virtual addr/size of RAM where TA are loaded/executedNSec
* shared mem allcated from teecore */
core_mmu_get_mem_by_type(MEM_AREA_TA_RAM, &s, &e);
ps = virt_to_phys((void *)s);
pe = virt_to_phys((void *)(e - 1)) + 1;
if (!ps || (ps & CORE_MMU_USER_CODE_MASK) ||
!pe || (pe & CORE_MMU_USER_CODE_MASK))
panic("invalid TA RAM");
/* extra check: we could rely on core_mmu_get_mem_by_type() */
if (!tee_pbuf_is_sec(ps, pe - ps))
panic("TA RAM is not secure");
if (!tee_mm_is_empty(&tee_mm_sec_ddr))
panic("TA RAM pool is not empty");
/* remove previous config and init TA ddr memory pool */
tee_mm_final(&tee_mm_sec_ddr);
tee_mm_init(&tee_mm_sec_ddr, ps, pe, CORE_MMU_USER_CODE_SHIFT,
TEE_MM_POOL_NO_FLAGS);
}
void teecore_init_pub_ram(void)
{
vaddr_t s;
vaddr_t e;
/* get virtual addr/size of NSec shared mem allcated from teecore */
core_mmu_get_mem_by_type(MEM_AREA_NSEC_SHM, &s, &e);
if (s >= e || s & SMALL_PAGE_MASK || e & SMALL_PAGE_MASK)
panic("invalid PUB RAM");
/* extra check: we could rely on core_mmu_get_mem_by_type() */
if (!tee_vbuf_is_non_sec(s, e - s))
panic("PUB RAM is not non-secure");
#ifdef CFG_PL310
/* Allocate statically the l2cc mutex */
tee_l2cc_store_mutex_boot_pa(virt_to_phys((void *)s));
s += sizeof(uint32_t); /* size of a pl310 mutex */
s = ROUNDUP(s, SMALL_PAGE_SIZE); /* keep required alignment */
#endif
default_nsec_shm_paddr = virt_to_phys((void *)s);
default_nsec_shm_size = e - s;
}
uint32_t tee_mmu_user_get_cache_attr(struct user_ta_ctx *utc, void *va)
{
uint32_t attr;
if (tee_mmu_user_va2pa_attr(utc, va, NULL, &attr) != TEE_SUCCESS)
panic("cannot get attr");
return (attr >> TEE_MATTR_CACHE_SHIFT) & TEE_MATTR_CACHE_MASK;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_727_0 |
crossvul-cpp_data_good_5115_1 | /*
* packet-ppi.c
* Routines for PPI Packet Header dissection
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 2007 Gerald Combs
*
* Copyright (c) 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
*
*
* Dustin Johnson - Dustin@Dustinj.us, Dustin.Johnson@cacetech.com
* May 7, 2008 - Added 'Aggregation Extension' and '802.3 Extension'
*/
#include "config.h"
#include <epan/packet.h>
#include <epan/exceptions.h>
#include <epan/ptvcursor.h>
#include <epan/prefs.h>
#include <epan/expert.h>
#include <epan/reassemble.h>
#include <wsutil/frequency-utils.h>
#include <wsutil/pint.h>
/* Needed for wtap_pcap_encap_to_wtap_encap(). */
#include <wiretap/pcap-encap.h>
#include "packet-frame.h"
#include "packet-eth.h"
#include "packet-ieee80211.h"
#include "packet-ppi.h"
/*
* Per-Packet Information (PPI) header.
* See the PPI Packet Header documentation at http://www.cacetech.com/documents
* for details.
*/
/*
* PPI headers have the following format:
*
* ,---------------------------------------------------------.
* | PPH | PFH 1 | Field data 1 | PFH 2 | Field data 2 | ... |
* `---------------------------------------------------------'
*
* The PPH struct has the following format:
*
* typedef struct ppi_packetheader {
* guint8 pph_version; // Version. Currently 0
* guint8 pph_flags; // Flags.
* guint16 pph_len; // Length of entire message, including this header and TLV payload.
* guint32 pph_dlt; // libpcap Data Link Type of the captured packet data.
* } ppi_packetheader_t;
*
* The PFH struct has the following format:
*
* typedef struct ppi_fieldheader {
* guint16 pfh_type; // Type
* guint16 pfh_datalen; // Length of data
* } ppi_fieldheader_t;
*
* Anyone looking to add their own PPI dissector would probably do well to imitate the GPS
* ones separation into a distinct file. Here is a step by step guide:
* 1) add the number you received to the enum ppi_field_type declaration.
* 2) Add a value string for your number into vs_ppi_field_type
* 3) declare a dissector handle by the ppi_gps_handle, and initialize it inside proto_reg_handoff
* 4) add case inside dissect_ppi to call your new handle.
* 5) Write your parser, and get it loaded.
* Following these steps will result in less churn inside the ppi proper parser, and avoid namespace issues.
*/
#define PPI_PADDED (1 << 0)
#define PPI_V0_HEADER_LEN 8
#define PPI_80211_COMMON_LEN 20
#define PPI_80211N_MAC_LEN 12
#define PPI_80211N_MAC_PHY_OFF 9
#define PPI_80211N_MAC_PHY_LEN 48
#define PPI_AGGREGATION_EXTENSION_LEN 4
#define PPI_8023_EXTENSION_LEN 8
#define PPI_FLAG_ALIGN 0x01
#define IS_PPI_FLAG_ALIGN(x) ((x) & PPI_FLAG_ALIGN)
#define DOT11_FLAG_HAVE_FCS 0x0001
#define DOT11_FLAG_TSF_TIMER_MS 0x0002
#define DOT11_FLAG_FCS_INVALID 0x0004
#define DOT11_FLAG_PHY_ERROR 0x0008
#define DOT11N_FLAG_GREENFIELD 0x0001
#define DOT11N_FLAG_HT40 0x0002
#define DOT11N_FLAG_SHORT_GI 0x0004
#define DOT11N_FLAG_DUPLICATE_RX 0x0008
#define DOT11N_FLAG_IS_AGGREGATE 0x0010
#define DOT11N_FLAG_MORE_AGGREGATES 0x0020
#define DOT11N_FLAG_AGG_CRC_ERROR 0x0040
#define DOT11N_IS_AGGREGATE(flags) (flags & DOT11N_FLAG_IS_AGGREGATE)
#define DOT11N_MORE_AGGREGATES(flags) ( \
(flags & DOT11N_FLAG_MORE_AGGREGATES) && \
!(flags & DOT11N_FLAG_AGG_CRC_ERROR))
#define AGGREGATE_MAX 65535
#define AMPDU_MAX 16383
/* XXX - Start - Copied from packet-radiotap.c */
/* Channel flags. */
#define IEEE80211_CHAN_TURBO 0x0010 /* Turbo channel */
#define IEEE80211_CHAN_CCK 0x0020 /* CCK channel */
#define IEEE80211_CHAN_OFDM 0x0040 /* OFDM channel */
#define IEEE80211_CHAN_2GHZ 0x0080 /* 2 GHz spectrum channel. */
#define IEEE80211_CHAN_5GHZ 0x0100 /* 5 GHz spectrum channel */
#define IEEE80211_CHAN_PASSIVE 0x0200 /* Only passive scan allowed */
#define IEEE80211_CHAN_DYN 0x0400 /* Dynamic CCK-OFDM channel */
#define IEEE80211_CHAN_GFSK 0x0800 /* GFSK channel (FHSS PHY) */
#define IEEE80211_CHAN_ALL \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_GFSK | \
IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_ALLTURBO \
(IEEE80211_CHAN_ALL | IEEE80211_CHAN_TURBO)
/*
* Useful combinations of channel characteristics.
*/
#define IEEE80211_CHAN_FHSS \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK)
#define IEEE80211_CHAN_DSSS \
(IEEE80211_CHAN_2GHZ)
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_PUREG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_108A \
(IEEE80211_CHAN_A | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_108G \
(IEEE80211_CHAN_G | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_108PUREG \
(IEEE80211_CHAN_PUREG | IEEE80211_CHAN_TURBO)
/* XXX - End - Copied from packet-radiotap.c */
void proto_register_ppi(void);
void proto_reg_handoff_ppi(void);
typedef enum {
/* 0 - 29999: Public types */
PPI_80211_COMMON = 2,
PPI_80211N_MAC = 3,
PPI_80211N_MAC_PHY = 4,
PPI_SPECTRUM_MAP = 5,
PPI_PROCESS_INFO = 6,
PPI_CAPTURE_INFO = 7,
PPI_AGGREGATION_EXTENSION = 8,
PPI_8023_EXTENSION = 9,
/* 11 - 29999: RESERVED */
/* 30000 - 65535: Private types */
INTEL_CORP_PRIVATE = 30000,
MOHAMED_THAGA_PRIVATE = 30001,
PPI_GPS_INFO = 30002, /* 30002 - 30005 described in PPI-GEOLOCATION specifcation */
PPI_VECTOR_INFO = 30003, /* currently available in draft from. jellch@harris.com */
PPI_SENSOR_INFO = 30004,
PPI_ANTENNA_INFO = 30005,
FNET_PRIVATE = 0xC017,
CACE_PRIVATE = 0xCACE
/* All others RESERVED. Contact the WinPcap team for an assignment */
} ppi_field_type;
/* Protocol */
static int proto_ppi = -1;
/* Packet header */
static int hf_ppi_head_version = -1;
static int hf_ppi_head_flags = -1;
static int hf_ppi_head_flag_alignment = -1;
static int hf_ppi_head_flag_reserved = -1;
static int hf_ppi_head_len = -1;
static int hf_ppi_head_dlt = -1;
/* Field header */
static int hf_ppi_field_type = -1;
static int hf_ppi_field_len = -1;
/* 802.11 Common */
static int hf_80211_common_tsft = -1;
static int hf_80211_common_flags = -1;
static int hf_80211_common_flags_fcs = -1;
static int hf_80211_common_flags_tsft = -1;
static int hf_80211_common_flags_fcs_valid = -1;
static int hf_80211_common_flags_phy_err = -1;
static int hf_80211_common_rate = -1;
static int hf_80211_common_chan_freq = -1;
static int hf_80211_common_chan_flags = -1;
static int hf_80211_common_chan_flags_turbo = -1;
static int hf_80211_common_chan_flags_cck = -1;
static int hf_80211_common_chan_flags_ofdm = -1;
static int hf_80211_common_chan_flags_2ghz = -1;
static int hf_80211_common_chan_flags_5ghz = -1;
static int hf_80211_common_chan_flags_passive = -1;
static int hf_80211_common_chan_flags_dynamic = -1;
static int hf_80211_common_chan_flags_gfsk = -1;
static int hf_80211_common_fhss_hopset = -1;
static int hf_80211_common_fhss_pattern = -1;
static int hf_80211_common_dbm_antsignal = -1;
static int hf_80211_common_dbm_antnoise = -1;
/* 802.11n MAC */
static int hf_80211n_mac_flags = -1;
static int hf_80211n_mac_flags_greenfield = -1;
static int hf_80211n_mac_flags_ht20_40 = -1;
static int hf_80211n_mac_flags_rx_guard_interval = -1;
static int hf_80211n_mac_flags_duplicate_rx = -1;
static int hf_80211n_mac_flags_more_aggregates = -1;
static int hf_80211n_mac_flags_aggregate = -1;
static int hf_80211n_mac_flags_delimiter_crc_after = -1;
static int hf_80211n_mac_ampdu_id = -1;
static int hf_80211n_mac_num_delimiters = -1;
static int hf_80211n_mac_reserved = -1;
/* 802.11n MAC+PHY */
static int hf_80211n_mac_phy_mcs = -1;
static int hf_80211n_mac_phy_num_streams = -1;
static int hf_80211n_mac_phy_rssi_combined = -1;
static int hf_80211n_mac_phy_rssi_ant0_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant1_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant2_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant3_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant0_ext = -1;
static int hf_80211n_mac_phy_rssi_ant1_ext = -1;
static int hf_80211n_mac_phy_rssi_ant2_ext = -1;
static int hf_80211n_mac_phy_rssi_ant3_ext = -1;
static int hf_80211n_mac_phy_ext_chan_freq = -1;
static int hf_80211n_mac_phy_ext_chan_flags = -1;
static int hf_80211n_mac_phy_ext_chan_flags_turbo = -1;
static int hf_80211n_mac_phy_ext_chan_flags_cck = -1;
static int hf_80211n_mac_phy_ext_chan_flags_ofdm = -1;
static int hf_80211n_mac_phy_ext_chan_flags_2ghz = -1;
static int hf_80211n_mac_phy_ext_chan_flags_5ghz = -1;
static int hf_80211n_mac_phy_ext_chan_flags_passive = -1;
static int hf_80211n_mac_phy_ext_chan_flags_dynamic = -1;
static int hf_80211n_mac_phy_ext_chan_flags_gfsk = -1;
static int hf_80211n_mac_phy_dbm_ant0signal = -1;
static int hf_80211n_mac_phy_dbm_ant0noise = -1;
static int hf_80211n_mac_phy_dbm_ant1signal = -1;
static int hf_80211n_mac_phy_dbm_ant1noise = -1;
static int hf_80211n_mac_phy_dbm_ant2signal = -1;
static int hf_80211n_mac_phy_dbm_ant2noise = -1;
static int hf_80211n_mac_phy_dbm_ant3signal = -1;
static int hf_80211n_mac_phy_dbm_ant3noise = -1;
static int hf_80211n_mac_phy_evm0 = -1;
static int hf_80211n_mac_phy_evm1 = -1;
static int hf_80211n_mac_phy_evm2 = -1;
static int hf_80211n_mac_phy_evm3 = -1;
/* 802.11n-Extensions A-MPDU fragments */
static int hf_ampdu_reassembled_in = -1;
/* static int hf_ampdu_segments = -1; */
static int hf_ampdu_segment = -1;
static int hf_ampdu_count = -1;
/* Spectrum-Map */
static int hf_spectrum_map = -1;
/* Process-Info */
static int hf_process_info = -1;
/* Capture-Info */
static int hf_capture_info = -1;
/* Aggregation Extension */
static int hf_aggregation_extension_interface_id = -1;
/* 802.3 Extension */
static int hf_8023_extension_flags = -1;
static int hf_8023_extension_flags_fcs_present = -1;
static int hf_8023_extension_errors = -1;
static int hf_8023_extension_errors_fcs = -1;
static int hf_8023_extension_errors_sequence = -1;
static int hf_8023_extension_errors_symbol = -1;
static int hf_8023_extension_errors_data = -1;
/* Generated from convert_proto_tree_add_text.pl */
static int hf_ppi_antenna = -1;
static int hf_ppi_harris = -1;
static int hf_ppi_reserved = -1;
static int hf_ppi_vector = -1;
static int hf_ppi_fnet = -1;
static int hf_ppi_gps = -1;
static gint ett_ppi_pph = -1;
static gint ett_ppi_flags = -1;
static gint ett_dot11_common = -1;
static gint ett_dot11_common_flags = -1;
static gint ett_dot11_common_channel_flags = -1;
static gint ett_dot11n_mac = -1;
static gint ett_dot11n_mac_flags = -1;
static gint ett_dot11n_mac_phy = -1;
static gint ett_dot11n_mac_phy_ext_channel_flags = -1;
static gint ett_ampdu_segments = -1;
static gint ett_ampdu = -1;
static gint ett_ampdu_segment = -1;
static gint ett_aggregation_extension = -1;
static gint ett_8023_extension = -1;
static gint ett_8023_extension_flags = -1;
static gint ett_8023_extension_errors = -1;
/* Generated from convert_proto_tree_add_text.pl */
static expert_field ei_ppi_invalid_length = EI_INIT;
static dissector_handle_t ppi_handle;
static dissector_handle_t data_handle;
static dissector_handle_t ieee80211_radio_handle;
static dissector_handle_t ppi_gps_handle, ppi_vector_handle, ppi_sensor_handle, ppi_antenna_handle;
static dissector_handle_t ppi_fnet_handle;
static const true_false_string tfs_ppi_head_flag_alignment = { "32-bit aligned", "Not aligned" };
static const true_false_string tfs_tsft_ms = { "milliseconds", "microseconds" };
static const true_false_string tfs_ht20_40 = { "HT40", "HT20" };
static const true_false_string tfs_phy_error = { "PHY error", "No errors"};
static const value_string vs_ppi_field_type[] = {
{PPI_80211_COMMON, "802.11-Common"},
{PPI_80211N_MAC, "802.11n MAC Extensions"},
{PPI_80211N_MAC_PHY, "802.11n MAC+PHY Extensions"},
{PPI_SPECTRUM_MAP, "Spectrum-Map"},
{PPI_PROCESS_INFO, "Process-Info"},
{PPI_CAPTURE_INFO, "Capture-Info"},
{PPI_AGGREGATION_EXTENSION, "Aggregation Extension"},
{PPI_8023_EXTENSION, "802.3 Extension"},
{INTEL_CORP_PRIVATE, "Intel Corporation (private)"},
{MOHAMED_THAGA_PRIVATE, "Mohamed Thaga (private)"},
{PPI_GPS_INFO, "GPS Tagging"},
{PPI_VECTOR_INFO, "Vector Tagging"},
{PPI_SENSOR_INFO, "Sensor tagging"},
{PPI_ANTENNA_INFO, "Antenna Tagging"},
{FNET_PRIVATE, "FlukeNetworks (private)"},
{CACE_PRIVATE, "CACE Technologies (private)"},
{0, NULL}
};
/* Table for A-MPDU reassembly */
static reassembly_table ampdu_reassembly_table;
/* Reassemble A-MPDUs? */
static gboolean ppi_ampdu_reassemble = TRUE;
void
capture_ppi(const guchar *pd, int len, packet_counts *ld)
{
guint32 dlt;
guint ppi_len;
ppi_len = pletoh16(pd+2);
if(ppi_len < PPI_V0_HEADER_LEN || !BYTES_ARE_IN_FRAME(0, len, ppi_len)) {
ld->other++;
return;
}
dlt = pletoh32(pd+4);
/* XXX - We should probably combine this with capture_info.c:capture_info_packet() */
switch(dlt) {
case 1: /* DLT_EN10MB */
capture_eth(pd, ppi_len, len, ld);
return;
case 105: /* DLT_DLT_IEEE802_11 */
capture_ieee80211(pd, ppi_len, len, ld);
return;
default:
break;
}
ld->other++;
}
static void
ptvcursor_add_invalid_check(ptvcursor_t *csr, int hf, gint len, guint64 invalid_val) {
proto_item *ti;
guint64 val = invalid_val;
switch (len) {
case 8:
val = tvb_get_letoh64(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
case 4:
val = tvb_get_letohl(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
case 2:
val = tvb_get_letohs(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
case 1:
val = tvb_get_guint8(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
default:
DISSECTOR_ASSERT_NOT_REACHED();
}
ti = ptvcursor_add(csr, hf, len, ENC_LITTLE_ENDIAN);
if (val == invalid_val)
proto_item_append_text(ti, " [invalid]");
}
static void
add_ppi_field_header(tvbuff_t *tvb, proto_tree *tree, int *offset)
{
ptvcursor_t *csr;
csr = ptvcursor_new(tree, tvb, *offset);
ptvcursor_add(csr, hf_ppi_field_type, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_ppi_field_len, 2, ENC_LITTLE_ENDIAN);
ptvcursor_free(csr);
*offset=ptvcursor_current_offset(csr);
}
/* XXX - The main dissection function in the 802.11 dissector has the same name. */
static void
dissect_80211_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, int data_len, struct ieee_802_11_phdr *phdr)
{
proto_tree *ftree;
proto_item *ti;
ptvcursor_t *csr;
guint64 tsft_raw;
guint rate_raw;
guint rate_kbps;
guint32 common_flags;
guint16 common_frequency;
guint16 chan_flags;
gint8 dbm_value;
gchar *chan_str;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11_common, NULL, "802.11-Common");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_80211_COMMON_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
common_flags = tvb_get_letohs(tvb, offset + 8);
if (common_flags & DOT11_FLAG_HAVE_FCS)
phdr->fcs_len = 4;
else
phdr->fcs_len = 0;
csr = ptvcursor_new(ftree, tvb, offset);
tsft_raw = tvb_get_letoh64(tvb, offset);
if (tsft_raw != 0) {
phdr->presence_flags |= PHDR_802_11_HAS_TSF_TIMESTAMP;
if (common_flags & DOT11_FLAG_TSF_TIMER_MS)
phdr->tsf_timestamp = tsft_raw * 1000;
else
phdr->tsf_timestamp = tsft_raw;
}
ptvcursor_add_invalid_check(csr, hf_80211_common_tsft, 8, 0);
ptvcursor_add_with_subtree(csr, hf_80211_common_flags, 2, ENC_LITTLE_ENDIAN,
ett_dot11_common_flags);
ptvcursor_add_no_advance(csr, hf_80211_common_flags_fcs, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_flags_tsft, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_flags_fcs_valid, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211_common_flags_phy_err, 2, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
rate_raw = tvb_get_letohs(tvb, ptvcursor_current_offset(csr));
if (rate_raw != 0) {
phdr->presence_flags |= PHDR_802_11_HAS_DATA_RATE;
phdr->data_rate = rate_raw;
}
rate_kbps = rate_raw * 500;
ti = proto_tree_add_uint_format(ftree, hf_80211_common_rate, tvb,
ptvcursor_current_offset(csr), 2, rate_kbps, "Rate: %.1f Mbps",
rate_kbps / 1000.0);
if (rate_kbps == 0)
proto_item_append_text(ti, " [invalid]");
col_add_fstr(pinfo->cinfo, COL_TX_RATE, "%.1f Mbps", rate_kbps / 1000.0);
ptvcursor_advance(csr, 2);
common_frequency = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
if (common_frequency != 0) {
gint calc_channel;
phdr->presence_flags |= PHDR_802_11_HAS_FREQUENCY;
phdr->frequency = common_frequency;
calc_channel = ieee80211_mhz_to_chan(common_frequency);
if (calc_channel != -1) {
phdr->presence_flags |= PHDR_802_11_HAS_CHANNEL;
phdr->channel = calc_channel;
}
}
chan_str = ieee80211_mhz_to_str(common_frequency);
proto_tree_add_uint_format_value(ptvcursor_tree(csr), hf_80211_common_chan_freq, ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr), 2, common_frequency, "%s", chan_str);
col_add_fstr(pinfo->cinfo, COL_FREQ_CHAN, "%s", chan_str);
g_free(chan_str);
ptvcursor_advance(csr, 2);
chan_flags = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
switch (chan_flags & IEEE80211_CHAN_ALLTURBO) {
case IEEE80211_CHAN_FHSS:
phdr->phy = PHDR_802_11_PHY_11_FHSS;
phdr->phy_info.info_11_fhss.presence_flags =
PHDR_802_11_FHSS_HAS_HOP_SET |
PHDR_802_11_FHSS_HAS_HOP_PATTERN;
break;
case IEEE80211_CHAN_DSSS:
phdr->phy = PHDR_802_11_PHY_11_DSSS;
break;
case IEEE80211_CHAN_A:
phdr->phy = PHDR_802_11_PHY_11A;
phdr->phy_info.info_11a.presence_flags = PHDR_802_11A_HAS_TURBO_TYPE;
phdr->phy_info.info_11a.turbo_type = PHDR_802_11A_TURBO_TYPE_NORMAL;
break;
case IEEE80211_CHAN_B:
phdr->phy = PHDR_802_11_PHY_11B;
phdr->phy_info.info_11b.presence_flags = 0;
break;
case IEEE80211_CHAN_PUREG:
phdr->phy = PHDR_802_11_PHY_11G;
phdr->phy_info.info_11g.presence_flags = PHDR_802_11G_HAS_MODE;
phdr->phy_info.info_11g.mode = PHDR_802_11G_MODE_NORMAL;
break;
case IEEE80211_CHAN_G:
phdr->phy = PHDR_802_11_PHY_11G;
phdr->phy_info.info_11g.presence_flags = PHDR_802_11G_HAS_MODE;
phdr->phy_info.info_11g.mode = PHDR_802_11G_MODE_NORMAL;
break;
case IEEE80211_CHAN_108A:
phdr->phy = PHDR_802_11_PHY_11A;
phdr->phy_info.info_11a.presence_flags = PHDR_802_11A_HAS_TURBO_TYPE;
/* We assume non-STURBO is dynamic turbo */
phdr->phy_info.info_11a.turbo_type = PHDR_802_11A_TURBO_TYPE_DYNAMIC_TURBO;
break;
case IEEE80211_CHAN_108PUREG:
phdr->phy = PHDR_802_11_PHY_11G;
phdr->phy_info.info_11g.presence_flags = PHDR_802_11G_HAS_MODE;
phdr->phy_info.info_11g.mode = PHDR_802_11G_MODE_SUPER_G;
break;
}
ptvcursor_add_with_subtree(csr, hf_80211_common_chan_flags, 2, ENC_LITTLE_ENDIAN,
ett_dot11_common_channel_flags);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_turbo, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_cck, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_ofdm, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_2ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_5ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_passive, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_dynamic, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211_common_chan_flags_gfsk, 2, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
if (phdr->phy == PHDR_802_11_PHY_11_FHSS)
phdr->phy_info.info_11_fhss.hop_set = tvb_get_guint8(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
ptvcursor_add(csr, hf_80211_common_fhss_hopset, 1, ENC_LITTLE_ENDIAN);
if (phdr->phy == PHDR_802_11_PHY_11_FHSS)
phdr->phy_info.info_11_fhss.hop_pattern = tvb_get_guint8(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
ptvcursor_add(csr, hf_80211_common_fhss_pattern, 1, ENC_LITTLE_ENDIAN);
dbm_value = (gint8) tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
if (dbm_value != -128 && dbm_value != 0) {
/*
* XXX - the spec says -128 is invalid, presumably meaning "use
* -128 if you don't have the signal strength", but some captures
* have 0 for noise, presumably meaning it's incorrectly being
* used for "don't have it", so we check for it as well.
*/
col_add_fstr(pinfo->cinfo, COL_RSSI, "%d dBm", dbm_value);
phdr->presence_flags |= PHDR_802_11_HAS_SIGNAL_DBM;
phdr->signal_dbm = dbm_value;
}
ptvcursor_add_invalid_check(csr, hf_80211_common_dbm_antsignal, 1, 0x80); /* -128 */
dbm_value = (gint8) tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
if (dbm_value != -128 && dbm_value != 0) {
/*
* XXX - the spec says -128 is invalid, presumably meaning "use
* -128 if you don't have the noise level", but some captures
* have 0, presumably meaning it's incorrectly being used for
* "don't have it", so we check for it as well.
*/
phdr->presence_flags |= PHDR_802_11_HAS_NOISE_DBM;
phdr->noise_dbm = dbm_value;
}
ptvcursor_add_invalid_check(csr, hf_80211_common_dbm_antnoise, 1, 0x80);
ptvcursor_free(csr);
}
static void
dissect_80211n_mac(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len, gboolean add_subtree, guint32 *n_mac_flags, guint32 *ampdu_id, struct ieee_802_11_phdr *phdr)
{
proto_tree *ftree = tree;
ptvcursor_t *csr;
int subtree_off = add_subtree ? 4 : 0;
guint32 flags;
phdr->phy = PHDR_802_11_PHY_11N;
*n_mac_flags = tvb_get_letohl(tvb, offset + subtree_off);
*ampdu_id = tvb_get_letohl(tvb, offset + 4 + subtree_off);
if (add_subtree) {
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11n_mac, NULL, "802.11n MAC");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
}
if (data_len != PPI_80211N_MAC_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
csr = ptvcursor_new(ftree, tvb, offset);
flags = tvb_get_letohl(tvb, ptvcursor_current_offset(csr));
phdr->phy_info.info_11n.presence_flags = PHDR_802_11N_HAS_SHORT_GI|PHDR_802_11N_HAS_GREENFIELD;
phdr->phy_info.info_11n.short_gi = ((flags & DOT11N_FLAG_SHORT_GI) != 0);
phdr->phy_info.info_11n.greenfield = ((flags & DOT11N_FLAG_GREENFIELD) != 0);
ptvcursor_add_with_subtree(csr, hf_80211n_mac_flags, 4, ENC_LITTLE_ENDIAN,
ett_dot11n_mac_flags);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_greenfield, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_ht20_40, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_rx_guard_interval, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_duplicate_rx, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_aggregate, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_more_aggregates, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211n_mac_flags_delimiter_crc_after, 4, ENC_LITTLE_ENDIAN); /* Last */
ptvcursor_pop_subtree(csr);
ptvcursor_add(csr, hf_80211n_mac_ampdu_id, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211n_mac_num_delimiters, 1, ENC_LITTLE_ENDIAN);
if (add_subtree) {
ptvcursor_add(csr, hf_80211n_mac_reserved, 3, ENC_LITTLE_ENDIAN);
}
ptvcursor_free(csr);
}
static void
dissect_80211n_mac_phy(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, int data_len, guint32 *n_mac_flags, guint32 *ampdu_id, struct ieee_802_11_phdr *phdr)
{
proto_tree *ftree;
proto_item *ti;
ptvcursor_t *csr;
guint8 mcs;
guint8 ness;
guint16 ext_frequency;
gchar *chan_str;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11n_mac_phy, NULL, "802.11n MAC+PHY");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_80211N_MAC_PHY_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
dissect_80211n_mac(tvb, pinfo, ftree, offset, PPI_80211N_MAC_LEN,
FALSE, n_mac_flags, ampdu_id, phdr);
offset += PPI_80211N_MAC_PHY_OFF;
csr = ptvcursor_new(ftree, tvb, offset);
mcs = tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
if (mcs != 255) {
phdr->phy_info.info_11n.presence_flags |= PHDR_802_11N_HAS_MCS_INDEX;
phdr->phy_info.info_11n.mcs_index = mcs;
}
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_mcs, 1, 255);
ness = tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
phdr->phy_info.info_11n.presence_flags |= PHDR_802_11N_HAS_NESS;
phdr->phy_info.info_11n.ness = ness;
ti = ptvcursor_add(csr, hf_80211n_mac_phy_num_streams, 1, ENC_LITTLE_ENDIAN);
if (tvb_get_guint8(tvb, ptvcursor_current_offset(csr) - 1) == 0)
proto_item_append_text(ti, " (unknown)");
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_combined, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant0_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant1_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant2_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant3_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant0_ext, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant1_ext, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant2_ext, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant3_ext, 1, 255);
ext_frequency = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
chan_str = ieee80211_mhz_to_str(ext_frequency);
proto_tree_add_uint_format(ptvcursor_tree(csr), hf_80211n_mac_phy_ext_chan_freq, ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr), 2, ext_frequency, "Ext. Channel frequency: %s", chan_str);
g_free(chan_str);
ptvcursor_advance(csr, 2);
ptvcursor_add_with_subtree(csr, hf_80211n_mac_phy_ext_chan_flags, 2, ENC_LITTLE_ENDIAN,
ett_dot11n_mac_phy_ext_channel_flags);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_turbo, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_cck, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_ofdm, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_2ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_5ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_passive, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_dynamic, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211n_mac_phy_ext_chan_flags_gfsk, 2, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant0signal, 1, 0x80); /* -128 */
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant0noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant1signal, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant1noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant2signal, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant2noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant3signal, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant3noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm0, 4, 0);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm1, 4, 0);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm2, 4, 0);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm3, 4, 0);
ptvcursor_free(csr);
}
static void
dissect_aggregation_extension(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len)
{
proto_tree *ftree;
ptvcursor_t *csr;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_aggregation_extension, NULL, "Aggregation Extension");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_AGGREGATION_EXTENSION_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
csr = ptvcursor_new(ftree, tvb, offset);
ptvcursor_add(csr, hf_aggregation_extension_interface_id, 4, ENC_LITTLE_ENDIAN); /* Last */
ptvcursor_free(csr);
}
static void
dissect_8023_extension(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len)
{
proto_tree *ftree;
ptvcursor_t *csr;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_8023_extension, NULL, "802.3 Extension");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_8023_EXTENSION_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
csr = ptvcursor_new(ftree, tvb, offset);
ptvcursor_add_with_subtree(csr, hf_8023_extension_flags, 4, ENC_LITTLE_ENDIAN, ett_8023_extension_flags);
ptvcursor_add(csr, hf_8023_extension_flags_fcs_present, 4, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
ptvcursor_add_with_subtree(csr, hf_8023_extension_errors, 4, ENC_LITTLE_ENDIAN, ett_8023_extension_errors);
ptvcursor_add_no_advance(csr, hf_8023_extension_errors_fcs, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_8023_extension_errors_sequence, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_8023_extension_errors_symbol, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_8023_extension_errors_data, 4, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
ptvcursor_free(csr);
}
#define PADDING4(x) ((((x + 3) >> 2) << 2) - x)
#define ADD_BASIC_TAG(hf_tag) \
if (tree) \
proto_tree_add_item(ppi_tree, hf_tag, tvb, offset, data_len, ENC_NA)
static void
dissect_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL;
proto_tree *agg_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint version, flags;
gint tot_len, data_len;
guint data_type;
guint32 dlt;
guint32 n_ext_flags = 0;
guint32 ampdu_id = 0;
fragment_head *fd_head = NULL;
fragment_item *ft_fdh = NULL;
gint mpdu_count = 0;
gchar *mpdu_str;
gboolean first_mpdu = TRUE;
guint last_frame = 0;
gint len_remain, /*pad_len = 0,*/ ampdu_len = 0;
struct ieee_802_11_phdr phdr;
int wtap_encap;
struct eth_phdr eth;
void *phdrp;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPI");
col_clear(pinfo->cinfo, COL_INFO);
version = tvb_get_guint8(tvb, offset);
flags = tvb_get_guint8(tvb, offset + 1);
tot_len = tvb_get_letohs(tvb, offset+2);
dlt = tvb_get_letohl(tvb, offset+4);
col_add_fstr(pinfo->cinfo, COL_INFO, "PPI version %u, %u bytes",
version, tot_len);
/* Dissect the packet */
if (tree) {
ti = proto_tree_add_protocol_format(tree, proto_ppi,
tvb, 0, tot_len, "PPI version %u, %u bytes", version, tot_len);
ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph);
proto_tree_add_item(ppi_tree, hf_ppi_head_version,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags);
proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_tree, hf_ppi_head_len,
tvb, offset + 2, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_tree, hf_ppi_head_dlt,
tvb, offset + 4, 4, ENC_LITTLE_ENDIAN);
}
tot_len -= PPI_V0_HEADER_LEN;
offset += 8;
/* We don't have any 802.11 metadata yet. */
memset(&phdr, 0, sizeof(phdr));
phdr.fcs_len = -1;
phdr.decrypted = FALSE;
phdr.datapad = FALSE;
phdr.phy = PHDR_802_11_PHY_UNKNOWN;
phdr.presence_flags = 0;
while (tot_len > 0) {
data_type = tvb_get_letohs(tvb, offset);
data_len = tvb_get_letohs(tvb, offset + 2) + 4;
tot_len -= data_len;
switch (data_type) {
case PPI_80211_COMMON:
dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr);
break;
case PPI_80211N_MAC:
dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len,
TRUE, &n_ext_flags, &du_id, &phdr);
break;
case PPI_80211N_MAC_PHY:
dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset,
data_len, &n_ext_flags, &du_id, &phdr);
break;
case PPI_SPECTRUM_MAP:
ADD_BASIC_TAG(hf_spectrum_map);
break;
case PPI_PROCESS_INFO:
ADD_BASIC_TAG(hf_process_info);
break;
case PPI_CAPTURE_INFO:
ADD_BASIC_TAG(hf_capture_info);
break;
case PPI_AGGREGATION_EXTENSION:
dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len);
break;
case PPI_8023_EXTENSION:
dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len);
break;
case PPI_GPS_INFO:
if (ppi_gps_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_VECTOR_INFO:
if (ppi_vector_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_SENSOR_INFO:
if (ppi_sensor_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_ANTENNA_INFO:
if (ppi_antenna_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree);
}
break;
case FNET_PRIVATE:
if (ppi_fnet_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree);
}
break;
default:
proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA);
}
offset += data_len;
if (IS_PPI_FLAG_ALIGN(flags)){
offset += PADDING4(offset);
}
}
if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) {
len_remain = tvb_captured_length_remaining(tvb, offset);
#if 0 /* XXX: pad_len never actually used ?? */
if (DOT11N_MORE_AGGREGATES(n_ext_flags)) {
pad_len = PADDING4(len_remain);
}
#endif
pinfo->fragmented = TRUE;
/* Make sure we aren't going to go past AGGREGATE_MAX
* and caclulate our full A-MPDU length */
fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);
while (fd_head) {
ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4;
fd_head = fd_head->next;
}
if (ampdu_len > AGGREGATE_MAX) {
if (tree) {
proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, "Aggregate length greater than maximum (%u)", AGGREGATE_MAX);
THROW(ReportedBoundsError);
} else {
return;
}
}
/*
* Note that we never actually reassemble our A-MPDUs. Doing
* so would require prepending each MPDU with an A-MPDU delimiter
* and appending it with padding, only to hand it off to some
* routine which would un-do the work we just did. We're using
* the reassembly code to track MPDU sizes and frame numbers.
*/
/*??fd_head = */fragment_add_seq_next(&du_reassembly_table,
tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE);
pinfo->fragmented = TRUE;
/* Do reassembly? */
fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);
/* Show our fragments */
if (fd_head && tree) {
ft_fdh = fd_head;
/* List our fragments */
seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1,
ett_ampdu_segments, &ti, "A-MPDU (%u bytes w/hdrs):", ampdu_len);
PROTO_ITEM_SET_GENERATED(ti);
while (ft_fdh) {
if (ft_fdh->tvb_data && ft_fdh->len) {
last_frame = ft_fdh->frame;
if (!first_mpdu)
proto_item_append_text(ti, ",");
first_mpdu = FALSE;
proto_item_append_text(ti, " #%u(%u)",
ft_fdh->frame, ft_fdh->len);
proto_tree_add_uint_format(seg_tree, hf_ampdu_segment,
tvb, 0, 0, last_frame,
"Frame: %u (%u byte%s)",
last_frame,
ft_fdh->len,
plurality(ft_fdh->len, "", "s"));
}
ft_fdh = ft_fdh->next;
}
if (last_frame && last_frame != pinfo->fd->num)
proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in,
tvb, 0, 0, last_frame);
}
if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) {
if (tree) {
ti = proto_tree_add_protocol_format(tree,
proto_get_id_by_filter_name("wlan_aggregate"),
tvb, 0, tot_len, "IEEE 802.11 Aggregate MPDU");
agg_tree = proto_item_add_subtree(ti, ett_ampdu);
}
while (fd_head) {
if (fd_head->tvb_data && fd_head->len) {
mpdu_count++;
mpdu_str = wmem_strdup_printf(wmem_packet_scope(), "MPDU #%d", mpdu_count);
next_tvb = tvb_new_chain(tvb, fd_head->tvb_data);
add_new_data_source(pinfo, next_tvb, mpdu_str);
ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str);
call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr);
}
fd_head = fd_head->next;
}
proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count);
pinfo->fragmented=FALSE;
} else {
next_tvb = tvb_new_subset_remaining(tvb, offset);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE 802.11n");
col_set_str(pinfo->cinfo, COL_INFO, "Unreassembled A-MPDU data");
call_dissector(data_handle, next_tvb, pinfo, tree);
}
return;
}
next_tvb = tvb_new_subset_remaining(tvb, offset);
/*
* You can't just call an arbitrary subdissector based on a
* LINKTYPE_ value, because they may expect a particular
* pseudo-header to be passed to them.
*
* So we look for LINKTYPE_IEEE802_11, which is 105, and, if
* that's what the LINKTYPE_ value is, pass it a pointer
* to a struct ieee_802_11_phdr; otherwise, we pass it
* a null pointer - if it actually matters, we need to
* construct the appropriate pseudo-header and pass that.
*/
if (dlt == 105) {
/* LINKTYPE_IEEE802_11 */
call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr);
} else {
/* Everything else. This will pass a NULL data argument. */
wtap_encap = wtap_pcap_encap_to_wtap_encap(dlt);
switch (wtap_encap) {
case WTAP_ENCAP_ETHERNET:
eth.fcs_len = -1; /* Unknown whether we have an FCS */
phdrp = ð
break;
default:
phdrp = NULL;
break;
}
dissector_try_uint_new(wtap_encap_dissector_table,
wtap_encap, next_tvb, pinfo, tree, TRUE, phdrp);
}
}
/* Establish our beachead */
static void
ampdu_reassemble_init(void)
{
reassembly_table_init(&du_reassembly_table,
&addresses_reassembly_table_functions);
}
static void
ampdu_reassemble_cleanup(void)
{
reassembly_table_destroy(&du_reassembly_table);
}
void
proto_register_ppi(void)
{
static hf_register_info hf[] = {
{ &hf_ppi_head_version,
{ "Version", "ppi.version",
FT_UINT8, BASE_DEC, NULL, 0x0,
"PPI header format version", HFILL } },
{ &hf_ppi_head_flags,
{ "Flags", "ppi.flags",
FT_UINT8, BASE_HEX, NULL, 0x0,
"PPI header flags", HFILL } },
{ &hf_ppi_head_flag_alignment,
{ "Alignment", "ppi.flags.alignment",
FT_BOOLEAN, 8, TFS(&tfs_ppi_head_flag_alignment), 0x01,
"PPI header flags - 32bit Alignment", HFILL } },
{ &hf_ppi_head_flag_reserved,
{ "Reserved", "ppi.flags.reserved",
FT_UINT8, BASE_HEX, NULL, 0xFE,
"PPI header flags - Reserved Flags", HFILL } },
{ &hf_ppi_head_len,
{ "Header length", "ppi.length",
FT_UINT16, BASE_DEC, NULL, 0x0,
"Length of header including payload", HFILL } },
{ &hf_ppi_head_dlt,
{ "DLT", "ppi.dlt",
FT_UINT32, BASE_DEC, NULL, 0x0, "libpcap Data Link Type (DLT) of the payload", HFILL } },
{ &hf_ppi_field_type,
{ "Field type", "ppi.field_type",
FT_UINT16, BASE_DEC, VALS(vs_ppi_field_type), 0x0, "PPI data field type", HFILL } },
{ &hf_ppi_field_len,
{ "Field length", "ppi.field_len",
FT_UINT16, BASE_DEC, NULL, 0x0, "PPI data field length", HFILL } },
{ &hf_80211_common_tsft,
{ "TSFT", "ppi.80211-common.tsft",
FT_UINT64, BASE_DEC, NULL, 0x0, "PPI 802.11-Common Timing Synchronization Function Timer (TSFT)", HFILL } },
{ &hf_80211_common_flags,
{ "Flags", "ppi.80211-common.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Flags", HFILL } },
{ &hf_80211_common_flags_fcs,
{ "FCS present flag", "ppi.80211-common.flags.fcs",
FT_BOOLEAN, 16, TFS(&tfs_present_absent), DOT11_FLAG_HAVE_FCS, "PPI 802.11-Common Frame Check Sequence (FCS) Present Flag", HFILL } },
{ &hf_80211_common_flags_tsft,
{ "TSFT flag", "ppi.80211-common.flags.tsft",
FT_BOOLEAN, 16, TFS(&tfs_tsft_ms), DOT11_FLAG_TSF_TIMER_MS, "PPI 802.11-Common Timing Synchronization Function Timer (TSFT) msec/usec flag", HFILL } },
{ &hf_80211_common_flags_fcs_valid,
{ "FCS validity", "ppi.80211-common.flags.fcs-invalid",
FT_BOOLEAN, 16, TFS(&tfs_invalid_valid), DOT11_FLAG_FCS_INVALID, "PPI 802.11-Common Frame Check Sequence (FCS) Validity flag", HFILL } },
{ &hf_80211_common_flags_phy_err,
{ "PHY error flag", "ppi.80211-common.flags.phy-err",
FT_BOOLEAN, 16, TFS(&tfs_phy_error), DOT11_FLAG_PHY_ERROR, "PPI 802.11-Common Physical level (PHY) Error", HFILL } },
{ &hf_80211_common_rate,
{ "Data rate", "ppi.80211-common.rate",
FT_UINT16, BASE_DEC, NULL, 0x0, "PPI 802.11-Common Data Rate (x 500 Kbps)", HFILL } },
{ &hf_80211_common_chan_freq,
{ "Channel frequency", "ppi.80211-common.chan.freq",
FT_UINT16, BASE_DEC, NULL, 0x0,
"PPI 802.11-Common Channel Frequency", HFILL } },
{ &hf_80211_common_chan_flags,
{ "Channel flags", "ppi.80211-common.chan.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Channel Flags", HFILL } },
{ &hf_80211_common_chan_flags_turbo,
{ "Turbo", "ppi.80211-common.chan.flags.turbo",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_TURBO, "PPI 802.11-Common Channel Flags Turbo", HFILL } },
{ &hf_80211_common_chan_flags_cck,
{ "Complementary Code Keying (CCK)", "ppi.80211-common.chan.flags.cck",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_CCK, "PPI 802.11-Common Channel Flags Complementary Code Keying (CCK) Modulation", HFILL } },
{ &hf_80211_common_chan_flags_ofdm,
{ "Orthogonal Frequency-Division Multiplexing (OFDM)", "ppi.80211-common.chan.flags.ofdm",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_OFDM, "PPI 802.11-Common Channel Flags Orthogonal Frequency-Division Multiplexing (OFDM)", HFILL } },
{ &hf_80211_common_chan_flags_2ghz,
{ "2 GHz spectrum", "ppi.80211-common.chan.flags.2ghz",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_2GHZ, "PPI 802.11-Common Channel Flags 2 GHz spectrum", HFILL } },
{ &hf_80211_common_chan_flags_5ghz,
{ "5 GHz spectrum", "ppi.80211-common.chan.flags.5ghz",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_5GHZ, "PPI 802.11-Common Channel Flags 5 GHz spectrum", HFILL } },
{ &hf_80211_common_chan_flags_passive,
{ "Passive", "ppi.80211-common.chan.flags.passive",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_PASSIVE, "PPI 802.11-Common Channel Flags Passive", HFILL } },
{ &hf_80211_common_chan_flags_dynamic,
{ "Dynamic CCK-OFDM", "ppi.80211-common.chan.flags.dynamic",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_DYN, "PPI 802.11-Common Channel Flags Dynamic CCK-OFDM Channel", HFILL } },
{ &hf_80211_common_chan_flags_gfsk,
{ "Gaussian Frequency Shift Keying (GFSK)", "ppi.80211-common.chan.flags.gfsk",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_GFSK, "PPI 802.11-Common Channel Flags Gaussian Frequency Shift Keying (GFSK) Modulation", HFILL } },
{ &hf_80211_common_fhss_hopset,
{ "FHSS hopset", "ppi.80211-common.fhss.hopset",
FT_UINT8, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Frequency-Hopping Spread Spectrum (FHSS) Hopset", HFILL } },
{ &hf_80211_common_fhss_pattern,
{ "FHSS pattern", "ppi.80211-common.fhss.pattern",
FT_UINT8, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Frequency-Hopping Spread Spectrum (FHSS) Pattern", HFILL } },
{ &hf_80211_common_dbm_antsignal,
{ "dBm antenna signal", "ppi.80211-common.dbm.antsignal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11-Common dBm Antenna Signal", HFILL } },
{ &hf_80211_common_dbm_antnoise,
{ "dBm antenna noise", "ppi.80211-common.dbm.antnoise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11-Common dBm Antenna Noise", HFILL } },
/* 802.11n MAC */
{ &hf_80211n_mac_flags,
{ "MAC flags", "ppi.80211n-mac.flags",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC flags", HFILL } },
{ &hf_80211n_mac_flags_greenfield,
{ "Greenfield flag", "ppi.80211n-mac.flags.greenfield",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_GREENFIELD, "PPI 802.11n MAC Greenfield Flag", HFILL } },
{ &hf_80211n_mac_flags_ht20_40,
{ "HT20/HT40 flag", "ppi.80211n-mac.flags.ht20_40",
FT_BOOLEAN, 32, TFS(&tfs_ht20_40), DOT11N_FLAG_HT40, "PPI 802.11n MAC HT20/HT40 Flag", HFILL } },
{ &hf_80211n_mac_flags_rx_guard_interval,
{ "RX Short Guard Interval (SGI) flag", "ppi.80211n-mac.flags.rx.short_guard_interval",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_SHORT_GI, "PPI 802.11n MAC RX Short Guard Interval (SGI) Flag", HFILL } },
{ &hf_80211n_mac_flags_duplicate_rx,
{ "Duplicate RX flag", "ppi.80211n-mac.flags.rx.duplicate",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_DUPLICATE_RX, "PPI 802.11n MAC Duplicate RX Flag", HFILL } },
{ &hf_80211n_mac_flags_aggregate,
{ "Aggregate flag", "ppi.80211n-mac.flags.agg",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_IS_AGGREGATE, "PPI 802.11 MAC Aggregate Flag", HFILL } },
{ &hf_80211n_mac_flags_more_aggregates,
{ "More aggregates flag", "ppi.80211n-mac.flags.more_agg",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_MORE_AGGREGATES, "PPI 802.11n MAC More Aggregates Flag", HFILL } },
{ &hf_80211n_mac_flags_delimiter_crc_after,
{ "A-MPDU Delimiter CRC error after this frame flag", "ppi.80211n-mac.flags.delim_crc_error_after",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_AGG_CRC_ERROR, "PPI 802.11n MAC A-MPDU Delimiter CRC Error After This Frame Flag", HFILL } },
{ &hf_80211n_mac_ampdu_id,
{ "AMPDU-ID", "ppi.80211n-mac.ampdu_id",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC AMPDU-ID", HFILL } },
{ &hf_80211n_mac_num_delimiters,
{ "Num-Delimiters", "ppi.80211n-mac.num_delimiters",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC number of zero-length pad delimiters", HFILL } },
{ &hf_80211n_mac_reserved,
{ "Reserved", "ppi.80211n-mac.reserved",
FT_UINT24, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC Reserved", HFILL } },
/* 802.11n MAC+PHY */
{ &hf_80211n_mac_phy_mcs,
{ "MCS", "ppi.80211n-mac-phy.mcs",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Modulation Coding Scheme (MCS)", HFILL } },
{ &hf_80211n_mac_phy_num_streams,
{ "Number of spatial streams", "ppi.80211n-mac-phy.num_streams",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY number of spatial streams", HFILL } },
{ &hf_80211n_mac_phy_rssi_combined,
{ "RSSI combined", "ppi.80211n-mac-phy.rssi.combined",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Received Signal Strength Indication (RSSI) Combined", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant0_ctl,
{ "Antenna 0 control RSSI", "ppi.80211n-mac-phy.rssi.ant0ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 0 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant1_ctl,
{ "Antenna 1 control RSSI", "ppi.80211n-mac-phy.rssi.ant1ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 1 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant2_ctl,
{ "Antenna 2 control RSSI", "ppi.80211n-mac-phy.rssi.ant2ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 2 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant3_ctl,
{ "Antenna 3 control RSSI", "ppi.80211n-mac-phy.rssi.ant3ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 3 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant0_ext,
{ "Antenna 0 extension RSSI", "ppi.80211n-mac-phy.rssi.ant0ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 0 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant1_ext,
{ "Antenna 1 extension RSSI", "ppi.80211n-mac-phy.rssi.ant1ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 1 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant2_ext,
{ "Antenna 2 extension RSSI", "ppi.80211n-mac-phy.rssi.ant2ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 2 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant3_ext,
{ "Antenna 3 extension RSSI", "ppi.80211n-mac-phy.rssi.ant3ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 3 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_freq,
{ "Extended channel frequency", "ppi.80211-mac-phy.ext-chan.freq",
FT_UINT16, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Extended Channel Frequency", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags,
{ "Channel flags", "ppi.80211-mac-phy.ext-chan.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC+PHY Channel Flags", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_turbo,
{ "Turbo", "ppi.80211-mac-phy.ext-chan.flags.turbo",
FT_BOOLEAN, 16, NULL, 0x0010, "PPI 802.11n MAC+PHY Channel Flags Turbo", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_cck,
{ "Complementary Code Keying (CCK)", "ppi.80211-mac-phy.ext-chan.flags.cck",
FT_BOOLEAN, 16, NULL, 0x0020, "PPI 802.11n MAC+PHY Channel Flags Complementary Code Keying (CCK) Modulation", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_ofdm,
{ "Orthogonal Frequency-Division Multiplexing (OFDM)", "ppi.80211-mac-phy.ext-chan.flags.ofdm",
FT_BOOLEAN, 16, NULL, 0x0040, "PPI 802.11n MAC+PHY Channel Flags Orthogonal Frequency-Division Multiplexing (OFDM)", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_2ghz,
{ "2 GHz spectrum", "ppi.80211-mac-phy.ext-chan.flags.2ghz",
FT_BOOLEAN, 16, NULL, 0x0080, "PPI 802.11n MAC+PHY Channel Flags 2 GHz spectrum", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_5ghz,
{ "5 GHz spectrum", "ppi.80211-mac-phy.ext-chan.flags.5ghz",
FT_BOOLEAN, 16, NULL, 0x0100, "PPI 802.11n MAC+PHY Channel Flags 5 GHz spectrum", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_passive,
{ "Passive", "ppi.80211-mac-phy.ext-chan.flags.passive",
FT_BOOLEAN, 16, NULL, 0x0200, "PPI 802.11n MAC+PHY Channel Flags Passive", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_dynamic,
{ "Dynamic CCK-OFDM", "ppi.80211-mac-phy.ext-chan.flags.dynamic",
FT_BOOLEAN, 16, NULL, 0x0400, "PPI 802.11n MAC+PHY Channel Flags Dynamic CCK-OFDM Channel", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_gfsk,
{ "Gaussian Frequency Shift Keying (GFSK)", "ppi.80211-mac-phy.ext-chan.flags.gfsk",
FT_BOOLEAN, 16, NULL, 0x0800, "PPI 802.11n MAC+PHY Channel Flags Gaussian Frequency Shift Keying (GFSK) Modulation", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant0signal,
{ "dBm antenna 0 signal", "ppi.80211n-mac-phy.dbmant0.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 0 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant0noise,
{ "dBm antenna 0 noise", "ppi.80211n-mac-phy.dbmant0.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 0 Noise", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant1signal,
{ "dBm antenna 1 signal", "ppi.80211n-mac-phy.dbmant1.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 1 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant1noise,
{ "dBm antenna 1 noise", "ppi.80211n-mac-phy.dbmant1.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 1 Noise", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant2signal,
{ "dBm antenna 2 signal", "ppi.80211n-mac-phy.dbmant2.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 2 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant2noise,
{ "dBm antenna 2 noise", "ppi.80211n-mac-phy.dbmant2.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 2 Noise", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant3signal,
{ "dBm antenna 3 signal", "ppi.80211n-mac-phy.dbmant3.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 3 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant3noise,
{ "dBm antenna 3 noise", "ppi.80211n-mac-phy.dbmant3.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 3 Noise", HFILL } },
{ &hf_80211n_mac_phy_evm0,
{ "EVM-0", "ppi.80211n-mac-phy.evm0",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 0", HFILL } },
{ &hf_80211n_mac_phy_evm1,
{ "EVM-1", "ppi.80211n-mac-phy.evm1",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 1", HFILL } },
{ &hf_80211n_mac_phy_evm2,
{ "EVM-2", "ppi.80211n-mac-phy.evm2",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 2", HFILL } },
{ &hf_80211n_mac_phy_evm3,
{ "EVM-3", "ppi.80211n-mac-phy.evm3",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 3", HFILL } },
{ &hf_ampdu_segment,
{ "A-MPDU", "ppi.80211n-mac.ampdu",
FT_FRAMENUM, BASE_NONE, NULL, 0x0, "802.11n Aggregated MAC Protocol Data Unit (A-MPDU)", HFILL }},
#if 0
{ &hf_ampdu_segments,
{ "Reassembled A-MPDU", "ppi.80211n-mac.ampdu.reassembled",
FT_NONE, BASE_NONE, NULL, 0x0, "Reassembled Aggregated MAC Protocol Data Unit (A-MPDU)", HFILL }},
#endif
{ &hf_ampdu_reassembled_in,
{ "Reassembled A-MPDU in frame", "ppi.80211n-mac.ampdu.reassembled_in",
FT_FRAMENUM, BASE_NONE, NULL, 0x0,
"The A-MPDU that doesn't end in this segment is reassembled in this frame",
HFILL }},
{ &hf_ampdu_count,
{ "MPDU count", "ppi.80211n-mac.ampdu.count",
FT_UINT16, BASE_DEC, NULL, 0x0, "The number of aggregated MAC Protocol Data Units (MPDUs)", HFILL }},
{ &hf_spectrum_map,
{ "Radio spectrum map", "ppi.spectrum-map",
FT_BYTES, BASE_NONE, NULL, 0x0, "PPI Radio spectrum map", HFILL } },
{ &hf_process_info,
{ "Process information", "ppi.proc-info",
FT_BYTES, BASE_NONE, NULL, 0x0, "PPI Process information", HFILL } },
{ &hf_capture_info,
{ "Capture information", "ppi.cap-info",
FT_BYTES, BASE_NONE, NULL, 0x0, "PPI Capture information", HFILL } },
/* Aggregtion Extension */
{ &hf_aggregation_extension_interface_id,
{ "Interface ID", "ppi.aggregation_extension.interface_id",
FT_UINT32, BASE_DEC, NULL, 0x0, "Zero-based index of the physical interface the packet was captured from", HFILL } },
/* 802.3 Extension */
{ &hf_8023_extension_flags,
{ "Flags", "ppi.8023_extension.flags",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.3 Extension Flags", HFILL } },
{ &hf_8023_extension_flags_fcs_present,
{ "FCS Present Flag", "ppi.8023_extension.flags.fcs_present",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0001, "FCS (4 bytes) is present at the end of the packet", HFILL } },
{ &hf_8023_extension_errors,
{ "Errors", "ppi.8023_extension.errors",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.3 Extension Errors", HFILL } },
{ &hf_8023_extension_errors_fcs,
{ "FCS Error", "ppi.8023_extension.errors.fcs",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0001,
"PPI 802.3 Extension FCS Error", HFILL } },
{ &hf_8023_extension_errors_sequence,
{ "Sequence Error", "ppi.8023_extension.errors.sequence",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0002,
"PPI 802.3 Extension Sequence Error", HFILL } },
{ &hf_8023_extension_errors_symbol,
{ "Symbol Error", "ppi.8023_extension.errors.symbol",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0004,
"PPI 802.3 Extension Symbol Error", HFILL } },
{ &hf_8023_extension_errors_data,
{ "Data Error", "ppi.8023_extension.errors.data",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0008,
"PPI 802.3 Extension Data Error", HFILL } },
/* Generated from convert_proto_tree_add_text.pl */
{ &hf_ppi_gps, { "GPS", "ppi.gps", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_vector, { "VECTOR", "ppi.vector", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_harris, { "HARRIS", "ppi.harris", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_antenna, { "ANTENNA", "ppi.antenna", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_fnet, { "FNET", "ppi.fnet", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_reserved, { "Reserved", "ppi.reserved", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
};
static gint *ett[] = {
&ett_ppi_pph,
&ett_ppi_flags,
&ett_dot11_common,
&ett_dot11_common_flags,
&ett_dot11_common_channel_flags,
&ett_dot11n_mac,
&ett_dot11n_mac_flags,
&ett_dot11n_mac_phy,
&ett_dot11n_mac_phy_ext_channel_flags,
&ett_ampdu_segments,
&ett_ampdu,
&ett_ampdu_segment,
&ett_aggregation_extension,
&ett_8023_extension,
&ett_8023_extension_flags,
&ett_8023_extension_errors
};
static ei_register_info ei[] = {
{ &ei_ppi_invalid_length, { "ppi.invalid_length", PI_MALFORMED, PI_ERROR, "Invalid length", EXPFILL }},
};
module_t *ppi_module;
expert_module_t* expert_ppi;
proto_ppi = proto_register_protocol("PPI Packet Header", "PPI", "ppi");
proto_register_field_array(proto_ppi, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_ppi = expert_register_protocol(proto_ppi);
expert_register_field_array(expert_ppi, ei, array_length(ei));
ppi_handle = register_dissector("ppi", dissect_ppi, proto_ppi);
register_init_routine(ampdu_reassemble_init);
register_cleanup_routine(ampdu_reassemble_cleanup);
/* Configuration options */
ppi_module = prefs_register_protocol(proto_ppi, NULL);
prefs_register_bool_preference(ppi_module, "reassemble",
"Reassemble fragmented 802.11 A-MPDUs",
"Whether fragmented 802.11 aggregated MPDUs should be reassembled",
&ppi_ampdu_reassemble);
}
void
proto_reg_handoff_ppi(void)
{
data_handle = find_dissector("data");
ieee80211_radio_handle = find_dissector("wlan_radio");
ppi_gps_handle = find_dissector("ppi_gps");
ppi_vector_handle = find_dissector("ppi_vector");
ppi_sensor_handle = find_dissector("ppi_sensor");
ppi_antenna_handle = find_dissector("ppi_antenna");
ppi_fnet_handle = find_dissector("ppi_fnet");
dissector_add_uint("wtap_encap", WTAP_ENCAP_PPI, ppi_handle);
}
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5115_1 |
crossvul-cpp_data_good_5718_0 | #include <linux/err.h>
#include <linux/igmp.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/if_ether.h>
#include <net/ip.h>
#include <net/netlink.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <net/ipv6.h>
#endif
#include "br_private.h"
static int br_rports_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_port *p;
struct nlattr *nest;
if (!br->multicast_router || hlist_empty(&br->router_list))
return 0;
nest = nla_nest_start(skb, MDBA_ROUTER);
if (nest == NULL)
return -EMSGSIZE;
hlist_for_each_entry_rcu(p, &br->router_list, rlist) {
if (p && nla_put_u32(skb, MDBA_ROUTER_PORT, p->dev->ifindex))
goto fail;
}
nla_nest_end(skb, nest);
return 0;
fail:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_mdb_htable *mdb;
struct nlattr *nest, *nest2;
int i, err = 0;
int idx = 0, s_idx = cb->args[1];
if (br->multicast_disabled)
return 0;
mdb = rcu_dereference(br->mdb);
if (!mdb)
return 0;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
return -EMSGSIZE;
for (i = 0; i < mdb->max; i++) {
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p, **pp;
struct net_bridge_port *port;
hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) {
if (idx < s_idx)
goto skip;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL) {
err = -EMSGSIZE;
goto out;
}
for (pp = &mp->ports;
(p = rcu_dereference(*pp)) != NULL;
pp = &p->next) {
port = p->port;
if (port) {
struct br_mdb_entry e;
memset(&e, 0, sizeof(e));
e.ifindex = port->dev->ifindex;
e.state = p->state;
if (p->addr.proto == htons(ETH_P_IP))
e.addr.u.ip4 = p->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
if (p->addr.proto == htons(ETH_P_IPV6))
e.addr.u.ip6 = p->addr.u.ip6;
#endif
e.addr.proto = p->addr.proto;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) {
nla_nest_cancel(skb, nest2);
err = -EMSGSIZE;
goto out;
}
}
}
nla_nest_end(skb, nest2);
skip:
idx++;
}
}
out:
cb->args[1] = idx;
nla_nest_end(skb, nest);
return err;
}
static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net_device *dev;
struct net *net = sock_net(skb->sk);
struct nlmsghdr *nlh = NULL;
int idx = 0, s_idx;
s_idx = cb->args[0];
rcu_read_lock();
/* In theory this could be wrapped to 0... */
cb->seq = net->dev_base_seq + br_mdb_rehash_seq;
for_each_netdev_rcu(net, dev) {
if (dev->priv_flags & IFF_EBRIDGE) {
struct br_port_msg *bpm;
if (idx < s_idx)
goto skip;
nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, RTM_GETMDB,
sizeof(*bpm), NLM_F_MULTI);
if (nlh == NULL)
break;
bpm = nlmsg_data(nlh);
memset(bpm, 0, sizeof(*bpm));
bpm->ifindex = dev->ifindex;
if (br_mdb_fill_info(skb, cb, dev) < 0)
goto out;
if (br_rports_fill_info(skb, cb, dev) < 0)
goto out;
cb->args[1] = 0;
nlmsg_end(skb, nlh);
skip:
idx++;
}
}
out:
if (nlh)
nlmsg_end(skb, nlh);
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
static int nlmsg_populate_mdb_fill(struct sk_buff *skb,
struct net_device *dev,
struct br_mdb_entry *entry, u32 pid,
u32 seq, int type, unsigned int flags)
{
struct nlmsghdr *nlh;
struct br_port_msg *bpm;
struct nlattr *nest, *nest2;
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI);
if (!nlh)
return -EMSGSIZE;
bpm = nlmsg_data(nlh);
memset(bpm, 0, sizeof(*bpm));
bpm->family = AF_BRIDGE;
bpm->ifindex = dev->ifindex;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
goto cancel;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL)
goto end;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry))
goto end;
nla_nest_end(skb, nest2);
nla_nest_end(skb, nest);
return nlmsg_end(skb, nlh);
end:
nla_nest_end(skb, nest);
cancel:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static inline size_t rtnl_mdb_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct br_port_msg))
+ nla_total_size(sizeof(struct br_mdb_entry));
}
static void __br_mdb_notify(struct net_device *dev, struct br_mdb_entry *entry,
int type)
{
struct net *net = dev_net(dev);
struct sk_buff *skb;
int err = -ENOBUFS;
skb = nlmsg_new(rtnl_mdb_nlmsg_size(), GFP_ATOMIC);
if (!skb)
goto errout;
err = nlmsg_populate_mdb_fill(skb, dev, entry, 0, 0, type, NTF_SELF);
if (err < 0) {
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_MDB, NULL, GFP_ATOMIC);
return;
errout:
rtnl_set_sk_err(net, RTNLGRP_MDB, err);
}
void br_mdb_notify(struct net_device *dev, struct net_bridge_port *port,
struct br_ip *group, int type)
{
struct br_mdb_entry entry;
memset(&entry, 0, sizeof(entry));
entry.ifindex = port->dev->ifindex;
entry.addr.proto = group->proto;
entry.addr.u.ip4 = group->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
entry.addr.u.ip6 = group->u.ip6;
#endif
__br_mdb_notify(dev, &entry, type);
}
static bool is_valid_mdb_entry(struct br_mdb_entry *entry)
{
if (entry->ifindex == 0)
return false;
if (entry->addr.proto == htons(ETH_P_IP)) {
if (!ipv4_is_multicast(entry->addr.u.ip4))
return false;
if (ipv4_is_local_multicast(entry->addr.u.ip4))
return false;
#if IS_ENABLED(CONFIG_IPV6)
} else if (entry->addr.proto == htons(ETH_P_IPV6)) {
if (!ipv6_is_transient_multicast(&entry->addr.u.ip6))
return false;
#endif
} else
return false;
if (entry->state != MDB_PERMANENT && entry->state != MDB_TEMPORARY)
return false;
return true;
}
static int br_mdb_parse(struct sk_buff *skb, struct nlmsghdr *nlh,
struct net_device **pdev, struct br_mdb_entry **pentry)
{
struct net *net = sock_net(skb->sk);
struct br_mdb_entry *entry;
struct br_port_msg *bpm;
struct nlattr *tb[MDBA_SET_ENTRY_MAX+1];
struct net_device *dev;
int err;
err = nlmsg_parse(nlh, sizeof(*bpm), tb, MDBA_SET_ENTRY, NULL);
if (err < 0)
return err;
bpm = nlmsg_data(nlh);
if (bpm->ifindex == 0) {
pr_info("PF_BRIDGE: br_mdb_parse() with invalid ifindex\n");
return -EINVAL;
}
dev = __dev_get_by_index(net, bpm->ifindex);
if (dev == NULL) {
pr_info("PF_BRIDGE: br_mdb_parse() with unknown ifindex\n");
return -ENODEV;
}
if (!(dev->priv_flags & IFF_EBRIDGE)) {
pr_info("PF_BRIDGE: br_mdb_parse() with non-bridge\n");
return -EOPNOTSUPP;
}
*pdev = dev;
if (!tb[MDBA_SET_ENTRY] ||
nla_len(tb[MDBA_SET_ENTRY]) != sizeof(struct br_mdb_entry)) {
pr_info("PF_BRIDGE: br_mdb_parse() with invalid attr\n");
return -EINVAL;
}
entry = nla_data(tb[MDBA_SET_ENTRY]);
if (!is_valid_mdb_entry(entry)) {
pr_info("PF_BRIDGE: br_mdb_parse() with invalid entry\n");
return -EINVAL;
}
*pentry = entry;
return 0;
}
static int br_mdb_add_group(struct net_bridge *br, struct net_bridge_port *port,
struct br_ip *group, unsigned char state)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
struct net_bridge_mdb_htable *mdb;
int err;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, group);
if (!mp) {
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
return err;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
return -EEXIST;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = br_multicast_new_port_group(port, group, *pp, state);
if (unlikely(!p))
return -ENOMEM;
rcu_assign_pointer(*pp, p);
br_mdb_notify(br->dev, port, group, RTM_NEWMDB);
return 0;
}
static int __br_mdb_add(struct net *net, struct net_bridge *br,
struct br_mdb_entry *entry)
{
struct br_ip ip;
struct net_device *dev;
struct net_bridge_port *p;
int ret;
if (!netif_running(br->dev) || br->multicast_disabled)
return -EINVAL;
dev = __dev_get_by_index(net, entry->ifindex);
if (!dev)
return -ENODEV;
p = br_port_get_rtnl(dev);
if (!p || p->br != br || p->state == BR_STATE_DISABLED)
return -EINVAL;
ip.proto = entry->addr.proto;
if (ip.proto == htons(ETH_P_IP))
ip.u.ip4 = entry->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
else
ip.u.ip6 = entry->addr.u.ip6;
#endif
spin_lock_bh(&br->multicast_lock);
ret = br_mdb_add_group(br, p, &ip, entry->state);
spin_unlock_bh(&br->multicast_lock);
return ret;
}
static int br_mdb_add(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct br_mdb_entry *entry;
struct net_device *dev;
struct net_bridge *br;
int err;
err = br_mdb_parse(skb, nlh, &dev, &entry);
if (err < 0)
return err;
br = netdev_priv(dev);
err = __br_mdb_add(net, br, entry);
if (!err)
__br_mdb_notify(dev, entry, RTM_NEWMDB);
return err;
}
static int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
struct br_ip ip;
int err = -EINVAL;
if (!netif_running(br->dev) || br->multicast_disabled)
return -EINVAL;
if (timer_pending(&br->multicast_querier_timer))
return -EBUSY;
ip.proto = entry->addr.proto;
if (ip.proto == htons(ETH_P_IP))
ip.u.ip4 = entry->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
else
ip.u.ip6 = entry->addr.u.ip6;
#endif
spin_lock_bh(&br->multicast_lock);
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &ip);
if (!mp)
goto unlock;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (!p->port || p->port->dev->ifindex != entry->ifindex)
continue;
if (p->port->state == BR_STATE_DISABLED)
goto unlock;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
err = 0;
if (!mp->ports && !mp->mglist && mp->timer_armed &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
break;
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
static int br_mdb_del(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net_device *dev;
struct br_mdb_entry *entry;
struct net_bridge *br;
int err;
err = br_mdb_parse(skb, nlh, &dev, &entry);
if (err < 0)
return err;
br = netdev_priv(dev);
err = __br_mdb_del(br, entry);
if (!err)
__br_mdb_notify(dev, entry, RTM_DELMDB);
return err;
}
void br_mdb_init(void)
{
rtnl_register(PF_BRIDGE, RTM_GETMDB, NULL, br_mdb_dump, NULL);
rtnl_register(PF_BRIDGE, RTM_NEWMDB, br_mdb_add, NULL, NULL);
rtnl_register(PF_BRIDGE, RTM_DELMDB, br_mdb_del, NULL, NULL);
}
void br_mdb_uninit(void)
{
rtnl_unregister(PF_BRIDGE, RTM_GETMDB);
rtnl_unregister(PF_BRIDGE, RTM_NEWMDB);
rtnl_unregister(PF_BRIDGE, RTM_DELMDB);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5718_0 |
crossvul-cpp_data_good_435_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, version 2 of the
* License.
*/
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/slab.h>
#include <linux/sched/signal.h>
#include <linux/user_namespace.h>
#include <linux/proc_ns.h>
#include <linux/highuid.h>
#include <linux/cred.h>
#include <linux/securebits.h>
#include <linux/keyctl.h>
#include <linux/key-type.h>
#include <keys/user-type.h>
#include <linux/seq_file.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/ctype.h>
#include <linux/projid.h>
#include <linux/fs_struct.h>
#include <linux/bsearch.h>
#include <linux/sort.h>
static struct kmem_cache *user_ns_cachep __read_mostly;
static DEFINE_MUTEX(userns_state_mutex);
static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *map);
static void free_user_ns(struct work_struct *work);
static struct ucounts *inc_user_namespaces(struct user_namespace *ns, kuid_t uid)
{
return inc_ucount(ns, uid, UCOUNT_USER_NAMESPACES);
}
static void dec_user_namespaces(struct ucounts *ucounts)
{
return dec_ucount(ucounts, UCOUNT_USER_NAMESPACES);
}
static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
{
/* Start with the same capabilities as init but useless for doing
* anything as the capabilities are bound to the new user namespace.
*/
cred->securebits = SECUREBITS_DEFAULT;
cred->cap_inheritable = CAP_EMPTY_SET;
cred->cap_permitted = CAP_FULL_SET;
cred->cap_effective = CAP_FULL_SET;
cred->cap_ambient = CAP_EMPTY_SET;
cred->cap_bset = CAP_FULL_SET;
#ifdef CONFIG_KEYS
key_put(cred->request_key_auth);
cred->request_key_auth = NULL;
#endif
/* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */
cred->user_ns = user_ns;
}
/*
* Create a new user namespace, deriving the creator from the user in the
* passed credentials, and replacing that user with the new root user for the
* new namespace.
*
* This is called by copy_creds(), which will finish setting the target task's
* credentials.
*/
int create_user_ns(struct cred *new)
{
struct user_namespace *ns, *parent_ns = new->user_ns;
kuid_t owner = new->euid;
kgid_t group = new->egid;
struct ucounts *ucounts;
int ret, i;
ret = -ENOSPC;
if (parent_ns->level > 32)
goto fail;
ucounts = inc_user_namespaces(parent_ns, owner);
if (!ucounts)
goto fail;
/*
* Verify that we can not violate the policy of which files
* may be accessed that is specified by the root directory,
* by verifing that the root directory is at the root of the
* mount namespace which allows all files to be accessed.
*/
ret = -EPERM;
if (current_chrooted())
goto fail_dec;
/* The creator needs a mapping in the parent user namespace
* or else we won't be able to reasonably tell userspace who
* created a user_namespace.
*/
ret = -EPERM;
if (!kuid_has_mapping(parent_ns, owner) ||
!kgid_has_mapping(parent_ns, group))
goto fail_dec;
ret = -ENOMEM;
ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL);
if (!ns)
goto fail_dec;
ret = ns_alloc_inum(&ns->ns);
if (ret)
goto fail_free;
ns->ns.ops = &userns_operations;
atomic_set(&ns->count, 1);
/* Leave the new->user_ns reference with the new user namespace. */
ns->parent = parent_ns;
ns->level = parent_ns->level + 1;
ns->owner = owner;
ns->group = group;
INIT_WORK(&ns->work, free_user_ns);
for (i = 0; i < UCOUNT_COUNTS; i++) {
ns->ucount_max[i] = INT_MAX;
}
ns->ucounts = ucounts;
/* Inherit USERNS_SETGROUPS_ALLOWED from our parent */
mutex_lock(&userns_state_mutex);
ns->flags = parent_ns->flags;
mutex_unlock(&userns_state_mutex);
#ifdef CONFIG_PERSISTENT_KEYRINGS
init_rwsem(&ns->persistent_keyring_register_sem);
#endif
ret = -ENOMEM;
if (!setup_userns_sysctls(ns))
goto fail_keyring;
set_cred_user_ns(new, ns);
return 0;
fail_keyring:
#ifdef CONFIG_PERSISTENT_KEYRINGS
key_put(ns->persistent_keyring_register);
#endif
ns_free_inum(&ns->ns);
fail_free:
kmem_cache_free(user_ns_cachep, ns);
fail_dec:
dec_user_namespaces(ucounts);
fail:
return ret;
}
int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)
{
struct cred *cred;
int err = -ENOMEM;
if (!(unshare_flags & CLONE_NEWUSER))
return 0;
cred = prepare_creds();
if (cred) {
err = create_user_ns(cred);
if (err)
put_cred(cred);
else
*new_cred = cred;
}
return err;
}
static void free_user_ns(struct work_struct *work)
{
struct user_namespace *parent, *ns =
container_of(work, struct user_namespace, work);
do {
struct ucounts *ucounts = ns->ucounts;
parent = ns->parent;
if (ns->gid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
kfree(ns->gid_map.forward);
kfree(ns->gid_map.reverse);
}
if (ns->uid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
kfree(ns->uid_map.forward);
kfree(ns->uid_map.reverse);
}
if (ns->projid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
kfree(ns->projid_map.forward);
kfree(ns->projid_map.reverse);
}
retire_userns_sysctls(ns);
#ifdef CONFIG_PERSISTENT_KEYRINGS
key_put(ns->persistent_keyring_register);
#endif
ns_free_inum(&ns->ns);
kmem_cache_free(user_ns_cachep, ns);
dec_user_namespaces(ucounts);
ns = parent;
} while (atomic_dec_and_test(&parent->count));
}
void __put_user_ns(struct user_namespace *ns)
{
schedule_work(&ns->work);
}
EXPORT_SYMBOL(__put_user_ns);
/**
* idmap_key struct holds the information necessary to find an idmapping in a
* sorted idmap array. It is passed to cmp_map_id() as first argument.
*/
struct idmap_key {
bool map_up; /* true -> id from kid; false -> kid from id */
u32 id; /* id to find */
u32 count; /* == 0 unless used with map_id_range_down() */
};
/**
* cmp_map_id - Function to be passed to bsearch() to find the requested
* idmapping. Expects struct idmap_key to be passed via @k.
*/
static int cmp_map_id(const void *k, const void *e)
{
u32 first, last, id2;
const struct idmap_key *key = k;
const struct uid_gid_extent *el = e;
id2 = key->id + key->count - 1;
/* handle map_id_{down,up}() */
if (key->map_up)
first = el->lower_first;
else
first = el->first;
last = first + el->count - 1;
if (key->id >= first && key->id <= last &&
(id2 >= first && id2 <= last))
return 0;
if (key->id < first || id2 < first)
return -1;
return 1;
}
/**
* map_id_range_down_max - Find idmap via binary search in ordered idmap array.
* Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
*/
static struct uid_gid_extent *
map_id_range_down_max(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
{
struct idmap_key key;
key.map_up = false;
key.count = count;
key.id = id;
return bsearch(&key, map->forward, extents,
sizeof(struct uid_gid_extent), cmp_map_id);
}
/**
* map_id_range_down_base - Find idmap via binary search in static extent array.
* Can only be called if number of mappings is equal or less than
* UID_GID_MAP_MAX_BASE_EXTENTS.
*/
static struct uid_gid_extent *
map_id_range_down_base(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
{
unsigned idx;
u32 first, last, id2;
id2 = id + count - 1;
/* Find the matching extent */
for (idx = 0; idx < extents; idx++) {
first = map->extent[idx].first;
last = first + map->extent[idx].count - 1;
if (id >= first && id <= last &&
(id2 >= first && id2 <= last))
return &map->extent[idx];
}
return NULL;
}
static u32 map_id_range_down(struct uid_gid_map *map, u32 id, u32 count)
{
struct uid_gid_extent *extent;
unsigned extents = map->nr_extents;
smp_rmb();
if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
extent = map_id_range_down_base(extents, map, id, count);
else
extent = map_id_range_down_max(extents, map, id, count);
/* Map the id or note failure */
if (extent)
id = (id - extent->first) + extent->lower_first;
else
id = (u32) -1;
return id;
}
static u32 map_id_down(struct uid_gid_map *map, u32 id)
{
return map_id_range_down(map, id, 1);
}
/**
* map_id_up_base - Find idmap via binary search in static extent array.
* Can only be called if number of mappings is equal or less than
* UID_GID_MAP_MAX_BASE_EXTENTS.
*/
static struct uid_gid_extent *
map_id_up_base(unsigned extents, struct uid_gid_map *map, u32 id)
{
unsigned idx;
u32 first, last;
/* Find the matching extent */
for (idx = 0; idx < extents; idx++) {
first = map->extent[idx].lower_first;
last = first + map->extent[idx].count - 1;
if (id >= first && id <= last)
return &map->extent[idx];
}
return NULL;
}
/**
* map_id_up_max - Find idmap via binary search in ordered idmap array.
* Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
*/
static struct uid_gid_extent *
map_id_up_max(unsigned extents, struct uid_gid_map *map, u32 id)
{
struct idmap_key key;
key.map_up = true;
key.count = 1;
key.id = id;
return bsearch(&key, map->reverse, extents,
sizeof(struct uid_gid_extent), cmp_map_id);
}
static u32 map_id_up(struct uid_gid_map *map, u32 id)
{
struct uid_gid_extent *extent;
unsigned extents = map->nr_extents;
smp_rmb();
if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
extent = map_id_up_base(extents, map, id);
else
extent = map_id_up_max(extents, map, id);
/* Map the id or note failure */
if (extent)
id = (id - extent->lower_first) + extent->first;
else
id = (u32) -1;
return id;
}
/**
* make_kuid - Map a user-namespace uid pair into a kuid.
* @ns: User namespace that the uid is in
* @uid: User identifier
*
* Maps a user-namespace uid pair into a kernel internal kuid,
* and returns that kuid.
*
* When there is no mapping defined for the user-namespace uid
* pair INVALID_UID is returned. Callers are expected to test
* for and handle INVALID_UID being returned. INVALID_UID
* may be tested for using uid_valid().
*/
kuid_t make_kuid(struct user_namespace *ns, uid_t uid)
{
/* Map the uid to a global kernel uid */
return KUIDT_INIT(map_id_down(&ns->uid_map, uid));
}
EXPORT_SYMBOL(make_kuid);
/**
* from_kuid - Create a uid from a kuid user-namespace pair.
* @targ: The user namespace we want a uid in.
* @kuid: The kernel internal uid to start with.
*
* Map @kuid into the user-namespace specified by @targ and
* return the resulting uid.
*
* There is always a mapping into the initial user_namespace.
*
* If @kuid has no mapping in @targ (uid_t)-1 is returned.
*/
uid_t from_kuid(struct user_namespace *targ, kuid_t kuid)
{
/* Map the uid from a global kernel uid */
return map_id_up(&targ->uid_map, __kuid_val(kuid));
}
EXPORT_SYMBOL(from_kuid);
/**
* from_kuid_munged - Create a uid from a kuid user-namespace pair.
* @targ: The user namespace we want a uid in.
* @kuid: The kernel internal uid to start with.
*
* Map @kuid into the user-namespace specified by @targ and
* return the resulting uid.
*
* There is always a mapping into the initial user_namespace.
*
* Unlike from_kuid from_kuid_munged never fails and always
* returns a valid uid. This makes from_kuid_munged appropriate
* for use in syscalls like stat and getuid where failing the
* system call and failing to provide a valid uid are not an
* options.
*
* If @kuid has no mapping in @targ overflowuid is returned.
*/
uid_t from_kuid_munged(struct user_namespace *targ, kuid_t kuid)
{
uid_t uid;
uid = from_kuid(targ, kuid);
if (uid == (uid_t) -1)
uid = overflowuid;
return uid;
}
EXPORT_SYMBOL(from_kuid_munged);
/**
* make_kgid - Map a user-namespace gid pair into a kgid.
* @ns: User namespace that the gid is in
* @gid: group identifier
*
* Maps a user-namespace gid pair into a kernel internal kgid,
* and returns that kgid.
*
* When there is no mapping defined for the user-namespace gid
* pair INVALID_GID is returned. Callers are expected to test
* for and handle INVALID_GID being returned. INVALID_GID may be
* tested for using gid_valid().
*/
kgid_t make_kgid(struct user_namespace *ns, gid_t gid)
{
/* Map the gid to a global kernel gid */
return KGIDT_INIT(map_id_down(&ns->gid_map, gid));
}
EXPORT_SYMBOL(make_kgid);
/**
* from_kgid - Create a gid from a kgid user-namespace pair.
* @targ: The user namespace we want a gid in.
* @kgid: The kernel internal gid to start with.
*
* Map @kgid into the user-namespace specified by @targ and
* return the resulting gid.
*
* There is always a mapping into the initial user_namespace.
*
* If @kgid has no mapping in @targ (gid_t)-1 is returned.
*/
gid_t from_kgid(struct user_namespace *targ, kgid_t kgid)
{
/* Map the gid from a global kernel gid */
return map_id_up(&targ->gid_map, __kgid_val(kgid));
}
EXPORT_SYMBOL(from_kgid);
/**
* from_kgid_munged - Create a gid from a kgid user-namespace pair.
* @targ: The user namespace we want a gid in.
* @kgid: The kernel internal gid to start with.
*
* Map @kgid into the user-namespace specified by @targ and
* return the resulting gid.
*
* There is always a mapping into the initial user_namespace.
*
* Unlike from_kgid from_kgid_munged never fails and always
* returns a valid gid. This makes from_kgid_munged appropriate
* for use in syscalls like stat and getgid where failing the
* system call and failing to provide a valid gid are not options.
*
* If @kgid has no mapping in @targ overflowgid is returned.
*/
gid_t from_kgid_munged(struct user_namespace *targ, kgid_t kgid)
{
gid_t gid;
gid = from_kgid(targ, kgid);
if (gid == (gid_t) -1)
gid = overflowgid;
return gid;
}
EXPORT_SYMBOL(from_kgid_munged);
/**
* make_kprojid - Map a user-namespace projid pair into a kprojid.
* @ns: User namespace that the projid is in
* @projid: Project identifier
*
* Maps a user-namespace uid pair into a kernel internal kuid,
* and returns that kuid.
*
* When there is no mapping defined for the user-namespace projid
* pair INVALID_PROJID is returned. Callers are expected to test
* for and handle handle INVALID_PROJID being returned. INVALID_PROJID
* may be tested for using projid_valid().
*/
kprojid_t make_kprojid(struct user_namespace *ns, projid_t projid)
{
/* Map the uid to a global kernel uid */
return KPROJIDT_INIT(map_id_down(&ns->projid_map, projid));
}
EXPORT_SYMBOL(make_kprojid);
/**
* from_kprojid - Create a projid from a kprojid user-namespace pair.
* @targ: The user namespace we want a projid in.
* @kprojid: The kernel internal project identifier to start with.
*
* Map @kprojid into the user-namespace specified by @targ and
* return the resulting projid.
*
* There is always a mapping into the initial user_namespace.
*
* If @kprojid has no mapping in @targ (projid_t)-1 is returned.
*/
projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid)
{
/* Map the uid from a global kernel uid */
return map_id_up(&targ->projid_map, __kprojid_val(kprojid));
}
EXPORT_SYMBOL(from_kprojid);
/**
* from_kprojid_munged - Create a projiid from a kprojid user-namespace pair.
* @targ: The user namespace we want a projid in.
* @kprojid: The kernel internal projid to start with.
*
* Map @kprojid into the user-namespace specified by @targ and
* return the resulting projid.
*
* There is always a mapping into the initial user_namespace.
*
* Unlike from_kprojid from_kprojid_munged never fails and always
* returns a valid projid. This makes from_kprojid_munged
* appropriate for use in syscalls like stat and where
* failing the system call and failing to provide a valid projid are
* not an options.
*
* If @kprojid has no mapping in @targ OVERFLOW_PROJID is returned.
*/
projid_t from_kprojid_munged(struct user_namespace *targ, kprojid_t kprojid)
{
projid_t projid;
projid = from_kprojid(targ, kprojid);
if (projid == (projid_t) -1)
projid = OVERFLOW_PROJID;
return projid;
}
EXPORT_SYMBOL(from_kprojid_munged);
static int uid_m_show(struct seq_file *seq, void *v)
{
struct user_namespace *ns = seq->private;
struct uid_gid_extent *extent = v;
struct user_namespace *lower_ns;
uid_t lower;
lower_ns = seq_user_ns(seq);
if ((lower_ns == ns) && lower_ns->parent)
lower_ns = lower_ns->parent;
lower = from_kuid(lower_ns, KUIDT_INIT(extent->lower_first));
seq_printf(seq, "%10u %10u %10u\n",
extent->first,
lower,
extent->count);
return 0;
}
static int gid_m_show(struct seq_file *seq, void *v)
{
struct user_namespace *ns = seq->private;
struct uid_gid_extent *extent = v;
struct user_namespace *lower_ns;
gid_t lower;
lower_ns = seq_user_ns(seq);
if ((lower_ns == ns) && lower_ns->parent)
lower_ns = lower_ns->parent;
lower = from_kgid(lower_ns, KGIDT_INIT(extent->lower_first));
seq_printf(seq, "%10u %10u %10u\n",
extent->first,
lower,
extent->count);
return 0;
}
static int projid_m_show(struct seq_file *seq, void *v)
{
struct user_namespace *ns = seq->private;
struct uid_gid_extent *extent = v;
struct user_namespace *lower_ns;
projid_t lower;
lower_ns = seq_user_ns(seq);
if ((lower_ns == ns) && lower_ns->parent)
lower_ns = lower_ns->parent;
lower = from_kprojid(lower_ns, KPROJIDT_INIT(extent->lower_first));
seq_printf(seq, "%10u %10u %10u\n",
extent->first,
lower,
extent->count);
return 0;
}
static void *m_start(struct seq_file *seq, loff_t *ppos,
struct uid_gid_map *map)
{
loff_t pos = *ppos;
unsigned extents = map->nr_extents;
smp_rmb();
if (pos >= extents)
return NULL;
if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
return &map->extent[pos];
return &map->forward[pos];
}
static void *uid_m_start(struct seq_file *seq, loff_t *ppos)
{
struct user_namespace *ns = seq->private;
return m_start(seq, ppos, &ns->uid_map);
}
static void *gid_m_start(struct seq_file *seq, loff_t *ppos)
{
struct user_namespace *ns = seq->private;
return m_start(seq, ppos, &ns->gid_map);
}
static void *projid_m_start(struct seq_file *seq, loff_t *ppos)
{
struct user_namespace *ns = seq->private;
return m_start(seq, ppos, &ns->projid_map);
}
static void *m_next(struct seq_file *seq, void *v, loff_t *pos)
{
(*pos)++;
return seq->op->start(seq, pos);
}
static void m_stop(struct seq_file *seq, void *v)
{
return;
}
const struct seq_operations proc_uid_seq_operations = {
.start = uid_m_start,
.stop = m_stop,
.next = m_next,
.show = uid_m_show,
};
const struct seq_operations proc_gid_seq_operations = {
.start = gid_m_start,
.stop = m_stop,
.next = m_next,
.show = gid_m_show,
};
const struct seq_operations proc_projid_seq_operations = {
.start = projid_m_start,
.stop = m_stop,
.next = m_next,
.show = projid_m_show,
};
static bool mappings_overlap(struct uid_gid_map *new_map,
struct uid_gid_extent *extent)
{
u32 upper_first, lower_first, upper_last, lower_last;
unsigned idx;
upper_first = extent->first;
lower_first = extent->lower_first;
upper_last = upper_first + extent->count - 1;
lower_last = lower_first + extent->count - 1;
for (idx = 0; idx < new_map->nr_extents; idx++) {
u32 prev_upper_first, prev_lower_first;
u32 prev_upper_last, prev_lower_last;
struct uid_gid_extent *prev;
if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
prev = &new_map->extent[idx];
else
prev = &new_map->forward[idx];
prev_upper_first = prev->first;
prev_lower_first = prev->lower_first;
prev_upper_last = prev_upper_first + prev->count - 1;
prev_lower_last = prev_lower_first + prev->count - 1;
/* Does the upper range intersect a previous extent? */
if ((prev_upper_first <= upper_last) &&
(prev_upper_last >= upper_first))
return true;
/* Does the lower range intersect a previous extent? */
if ((prev_lower_first <= lower_last) &&
(prev_lower_last >= lower_first))
return true;
}
return false;
}
/**
* insert_extent - Safely insert a new idmap extent into struct uid_gid_map.
* Takes care to allocate a 4K block of memory if the number of mappings exceeds
* UID_GID_MAP_MAX_BASE_EXTENTS.
*/
static int insert_extent(struct uid_gid_map *map, struct uid_gid_extent *extent)
{
struct uid_gid_extent *dest;
if (map->nr_extents == UID_GID_MAP_MAX_BASE_EXTENTS) {
struct uid_gid_extent *forward;
/* Allocate memory for 340 mappings. */
forward = kmalloc_array(UID_GID_MAP_MAX_EXTENTS,
sizeof(struct uid_gid_extent),
GFP_KERNEL);
if (!forward)
return -ENOMEM;
/* Copy over memory. Only set up memory for the forward pointer.
* Defer the memory setup for the reverse pointer.
*/
memcpy(forward, map->extent,
map->nr_extents * sizeof(map->extent[0]));
map->forward = forward;
map->reverse = NULL;
}
if (map->nr_extents < UID_GID_MAP_MAX_BASE_EXTENTS)
dest = &map->extent[map->nr_extents];
else
dest = &map->forward[map->nr_extents];
*dest = *extent;
map->nr_extents++;
return 0;
}
/* cmp function to sort() forward mappings */
static int cmp_extents_forward(const void *a, const void *b)
{
const struct uid_gid_extent *e1 = a;
const struct uid_gid_extent *e2 = b;
if (e1->first < e2->first)
return -1;
if (e1->first > e2->first)
return 1;
return 0;
}
/* cmp function to sort() reverse mappings */
static int cmp_extents_reverse(const void *a, const void *b)
{
const struct uid_gid_extent *e1 = a;
const struct uid_gid_extent *e2 = b;
if (e1->lower_first < e2->lower_first)
return -1;
if (e1->lower_first > e2->lower_first)
return 1;
return 0;
}
/**
* sort_idmaps - Sorts an array of idmap entries.
* Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
*/
static int sort_idmaps(struct uid_gid_map *map)
{
if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
return 0;
/* Sort forward array. */
sort(map->forward, map->nr_extents, sizeof(struct uid_gid_extent),
cmp_extents_forward, NULL);
/* Only copy the memory from forward we actually need. */
map->reverse = kmemdup(map->forward,
map->nr_extents * sizeof(struct uid_gid_extent),
GFP_KERNEL);
if (!map->reverse)
return -ENOMEM;
/* Sort reverse array. */
sort(map->reverse, map->nr_extents, sizeof(struct uid_gid_extent),
cmp_extents_reverse, NULL);
return 0;
}
static ssize_t map_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos,
int cap_setid,
struct uid_gid_map *map,
struct uid_gid_map *parent_map)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct uid_gid_map new_map;
unsigned idx;
struct uid_gid_extent extent;
char *kbuf = NULL, *pos, *next_line;
ssize_t ret;
/* Only allow < page size writes at the beginning of the file */
if ((*ppos != 0) || (count >= PAGE_SIZE))
return -EINVAL;
/* Slurp in the user data */
kbuf = memdup_user_nul(buf, count);
if (IS_ERR(kbuf))
return PTR_ERR(kbuf);
/*
* The userns_state_mutex serializes all writes to any given map.
*
* Any map is only ever written once.
*
* An id map fits within 1 cache line on most architectures.
*
* On read nothing needs to be done unless you are on an
* architecture with a crazy cache coherency model like alpha.
*
* There is a one time data dependency between reading the
* count of the extents and the values of the extents. The
* desired behavior is to see the values of the extents that
* were written before the count of the extents.
*
* To achieve this smp_wmb() is used on guarantee the write
* order and smp_rmb() is guaranteed that we don't have crazy
* architectures returning stale data.
*/
mutex_lock(&userns_state_mutex);
memset(&new_map, 0, sizeof(struct uid_gid_map));
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
goto out;
/*
* Adjusting namespace settings requires capabilities on the target.
*/
if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN))
goto out;
/* Parse the user data */
ret = -EINVAL;
pos = kbuf;
for (; pos; pos = next_line) {
/* Find the end of line and ensure I don't look past it */
next_line = strchr(pos, '\n');
if (next_line) {
*next_line = '\0';
next_line++;
if (*next_line == '\0')
next_line = NULL;
}
pos = skip_spaces(pos);
extent.first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent.lower_first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent.count = simple_strtoul(pos, &pos, 10);
if (*pos && !isspace(*pos))
goto out;
/* Verify there is not trailing junk on the line */
pos = skip_spaces(pos);
if (*pos != '\0')
goto out;
/* Verify we have been given valid starting values */
if ((extent.first == (u32) -1) ||
(extent.lower_first == (u32) -1))
goto out;
/* Verify count is not zero and does not cause the
* extent to wrap
*/
if ((extent.first + extent.count) <= extent.first)
goto out;
if ((extent.lower_first + extent.count) <=
extent.lower_first)
goto out;
/* Do the ranges in extent overlap any previous extents? */
if (mappings_overlap(&new_map, &extent))
goto out;
if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
(next_line != NULL))
goto out;
ret = insert_extent(&new_map, &extent);
if (ret < 0)
goto out;
ret = -EINVAL;
}
/* Be very certaint the new map actually exists */
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
/* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
goto out;
ret = -EPERM;
/* Map the lower ids from the parent user namespace to the
* kernel global id space.
*/
for (idx = 0; idx < new_map.nr_extents; idx++) {
struct uid_gid_extent *e;
u32 lower_first;
if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
e = &new_map.extent[idx];
else
e = &new_map.forward[idx];
lower_first = map_id_range_down(parent_map,
e->lower_first,
e->count);
/* Fail if we can not map the specified extent to
* the kernel global id space.
*/
if (lower_first == (u32) -1)
goto out;
e->lower_first = lower_first;
}
/*
* If we want to use binary search for lookup, this clones the extent
* array and sorts both copies.
*/
ret = sort_idmaps(&new_map);
if (ret < 0)
goto out;
/* Install the map */
if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
memcpy(map->extent, new_map.extent,
new_map.nr_extents * sizeof(new_map.extent[0]));
} else {
map->forward = new_map.forward;
map->reverse = new_map.reverse;
}
smp_wmb();
map->nr_extents = new_map.nr_extents;
*ppos = count;
ret = count;
out:
if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
kfree(new_map.forward);
kfree(new_map.reverse);
map->forward = NULL;
map->reverse = NULL;
map->nr_extents = 0;
}
mutex_unlock(&userns_state_mutex);
kfree(kbuf);
return ret;
}
ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
size_t size, loff_t *ppos)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct user_namespace *seq_ns = seq_user_ns(seq);
if (!ns->parent)
return -EPERM;
if ((seq_ns != ns) && (seq_ns != ns->parent))
return -EPERM;
return map_write(file, buf, size, ppos, CAP_SETUID,
&ns->uid_map, &ns->parent->uid_map);
}
ssize_t proc_gid_map_write(struct file *file, const char __user *buf,
size_t size, loff_t *ppos)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct user_namespace *seq_ns = seq_user_ns(seq);
if (!ns->parent)
return -EPERM;
if ((seq_ns != ns) && (seq_ns != ns->parent))
return -EPERM;
return map_write(file, buf, size, ppos, CAP_SETGID,
&ns->gid_map, &ns->parent->gid_map);
}
ssize_t proc_projid_map_write(struct file *file, const char __user *buf,
size_t size, loff_t *ppos)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct user_namespace *seq_ns = seq_user_ns(seq);
if (!ns->parent)
return -EPERM;
if ((seq_ns != ns) && (seq_ns != ns->parent))
return -EPERM;
/* Anyone can set any valid project id no capability needed */
return map_write(file, buf, size, ppos, -1,
&ns->projid_map, &ns->parent->projid_map);
}
static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
const struct cred *cred = file->f_cred;
/* Don't allow mappings that would allow anything that wouldn't
* be allowed without the establishment of unprivileged mappings.
*/
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) &&
uid_eq(ns->owner, cred->euid)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, cred->euid))
return true;
} else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
gid_eq(gid, cred->egid))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
int proc_setgroups_show(struct seq_file *seq, void *v)
{
struct user_namespace *ns = seq->private;
unsigned long userns_flags = READ_ONCE(ns->flags);
seq_printf(seq, "%s\n",
(userns_flags & USERNS_SETGROUPS_ALLOWED) ?
"allow" : "deny");
return 0;
}
ssize_t proc_setgroups_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
char kbuf[8], *pos;
bool setgroups_allowed;
ssize_t ret;
/* Only allow a very narrow range of strings to be written */
ret = -EINVAL;
if ((*ppos != 0) || (count >= sizeof(kbuf)))
goto out;
/* What was written? */
ret = -EFAULT;
if (copy_from_user(kbuf, buf, count))
goto out;
kbuf[count] = '\0';
pos = kbuf;
/* What is being requested? */
ret = -EINVAL;
if (strncmp(pos, "allow", 5) == 0) {
pos += 5;
setgroups_allowed = true;
}
else if (strncmp(pos, "deny", 4) == 0) {
pos += 4;
setgroups_allowed = false;
}
else
goto out;
/* Verify there is not trailing junk on the line */
pos = skip_spaces(pos);
if (*pos != '\0')
goto out;
ret = -EPERM;
mutex_lock(&userns_state_mutex);
if (setgroups_allowed) {
/* Enabling setgroups after setgroups has been disabled
* is not allowed.
*/
if (!(ns->flags & USERNS_SETGROUPS_ALLOWED))
goto out_unlock;
} else {
/* Permanently disabling setgroups after setgroups has
* been enabled by writing the gid_map is not allowed.
*/
if (ns->gid_map.nr_extents != 0)
goto out_unlock;
ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
}
mutex_unlock(&userns_state_mutex);
/* Report a successful write */
*ppos = count;
ret = count;
out:
return ret;
out_unlock:
mutex_unlock(&userns_state_mutex);
goto out;
}
bool userns_may_setgroups(const struct user_namespace *ns)
{
bool allowed;
mutex_lock(&userns_state_mutex);
/* It is not safe to use setgroups until a gid mapping in
* the user namespace has been established.
*/
allowed = ns->gid_map.nr_extents != 0;
/* Is setgroups allowed? */
allowed = allowed && (ns->flags & USERNS_SETGROUPS_ALLOWED);
mutex_unlock(&userns_state_mutex);
return allowed;
}
/*
* Returns true if @child is the same namespace or a descendant of
* @ancestor.
*/
bool in_userns(const struct user_namespace *ancestor,
const struct user_namespace *child)
{
const struct user_namespace *ns;
for (ns = child; ns->level > ancestor->level; ns = ns->parent)
;
return (ns == ancestor);
}
bool current_in_userns(const struct user_namespace *target_ns)
{
return in_userns(target_ns, current_user_ns());
}
EXPORT_SYMBOL(current_in_userns);
static inline struct user_namespace *to_user_ns(struct ns_common *ns)
{
return container_of(ns, struct user_namespace, ns);
}
static struct ns_common *userns_get(struct task_struct *task)
{
struct user_namespace *user_ns;
rcu_read_lock();
user_ns = get_user_ns(__task_cred(task)->user_ns);
rcu_read_unlock();
return user_ns ? &user_ns->ns : NULL;
}
static void userns_put(struct ns_common *ns)
{
put_user_ns(to_user_ns(ns));
}
static int userns_install(struct nsproxy *nsproxy, struct ns_common *ns)
{
struct user_namespace *user_ns = to_user_ns(ns);
struct cred *cred;
/* Don't allow gaining capabilities by reentering
* the same user namespace.
*/
if (user_ns == current_user_ns())
return -EINVAL;
/* Tasks that share a thread group must share a user namespace */
if (!thread_group_empty(current))
return -EINVAL;
if (current->fs->users != 1)
return -EINVAL;
if (!ns_capable(user_ns, CAP_SYS_ADMIN))
return -EPERM;
cred = prepare_creds();
if (!cred)
return -ENOMEM;
put_user_ns(cred->user_ns);
set_cred_user_ns(cred, get_user_ns(user_ns));
return commit_creds(cred);
}
struct ns_common *ns_get_owner(struct ns_common *ns)
{
struct user_namespace *my_user_ns = current_user_ns();
struct user_namespace *owner, *p;
/* See if the owner is in the current user namespace */
owner = p = ns->ops->owner(ns);
for (;;) {
if (!p)
return ERR_PTR(-EPERM);
if (p == my_user_ns)
break;
p = p->parent;
}
return &get_user_ns(owner)->ns;
}
static struct user_namespace *userns_owner(struct ns_common *ns)
{
return to_user_ns(ns)->parent;
}
const struct proc_ns_operations userns_operations = {
.name = "user",
.type = CLONE_NEWUSER,
.get = userns_get,
.put = userns_put,
.install = userns_install,
.owner = userns_owner,
.get_parent = ns_get_owner,
};
static __init int user_namespaces_init(void)
{
user_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC);
return 0;
}
subsys_initcall(user_namespaces_init);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_435_0 |
crossvul-cpp_data_bad_76_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;
TASKS_RCU(int tasks_rcu_i);
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_unlock_wait(&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);
TASKS_RCU(preempt_disable());
TASKS_RCU(tasks_rcu_i = __srcu_read_lock(&tasks_rcu_exit_srcu));
TASKS_RCU(preempt_enable());
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();
TASKS_RCU(__srcu_read_unlock(&tasks_rcu_exit_srcu, tasks_rcu_i));
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(¤t->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(¤t->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(¤t->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(¤t->signal->wait_chldexit, &wo->child_wait);
return retval;
}
static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
int options, struct rusage *ru)
{
struct wait_opts wo;
struct pid *pid = NULL;
enum pid_type type;
long ret;
if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED|
__WNOTHREAD|__WCLONE|__WALL))
return -EINVAL;
if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
return -EINVAL;
switch (which) {
case P_ALL:
type = PIDTYPE_MAX;
break;
case P_PID:
type = PIDTYPE_PID;
if (upid <= 0)
return -EINVAL;
break;
case P_PGID:
type = PIDTYPE_PGID;
if (upid <= 0)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (type < PIDTYPE_MAX)
pid = find_get_pid(upid);
wo.wo_type = type;
wo.wo_pid = pid;
wo.wo_flags = options;
wo.wo_info = infop;
wo.wo_rusage = ru;
ret = do_wait(&wo);
put_pid(pid);
return ret;
}
SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
infop, int, options, struct rusage __user *, ru)
{
struct rusage r;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
}
if (!err) {
if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
return -EFAULT;
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user((short)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;
if (upid == -1)
type = PIDTYPE_MAX;
else if (upid < 0) {
type = PIDTYPE_PGID;
pid = find_get_pid(-upid);
} else if (upid == 0) {
type = PIDTYPE_PGID;
pid = get_task_pid(current, PIDTYPE_PGID);
} else /* upid > 0 */ {
type = PIDTYPE_PID;
pid = find_get_pid(upid);
}
wo.wo_type = type;
wo.wo_pid = pid;
wo.wo_flags = options | WEXITED;
wo.wo_info = NULL;
wo.wo_stat = 0;
wo.wo_rusage = ru;
ret = do_wait(&wo);
put_pid(pid);
if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
ret = -EFAULT;
return ret;
}
SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
int, options, struct rusage __user *, ru)
{
struct rusage r;
long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL);
if (err > 0) {
if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
return -EFAULT;
}
return err;
}
#ifdef __ARCH_WANT_SYS_WAITPID
/*
* sys_waitpid() remains for compatibility. waitpid() should be
* implemented by calling sys_wait4() from libc.a.
*/
SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options)
{
return sys_wait4(pid, stat_addr, options, NULL);
}
#endif
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(wait4,
compat_pid_t, pid,
compat_uint_t __user *, stat_addr,
int, options,
struct compat_rusage __user *, ru)
{
struct rusage r;
long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL);
if (err > 0) {
if (ru && put_compat_rusage(&r, ru))
return -EFAULT;
}
return err;
}
COMPAT_SYSCALL_DEFINE5(waitid,
int, which, compat_pid_t, pid,
struct compat_siginfo __user *, infop, int, options,
struct compat_rusage __user *, uru)
{
struct rusage ru;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
}
if (!err && uru) {
/* kernel_waitid() overwrites everything in ru */
if (COMPAT_USE_64BIT_TIME)
err = copy_to_user(uru, &ru, sizeof(ru));
else
err = put_compat_rusage(&ru, uru);
if (err)
return -EFAULT;
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user((short)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-20/c/bad_76_0 |
crossvul-cpp_data_good_2891_9 | /* Manage a process's keyrings
*
* Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/sched/user.h>
#include <linux/keyctl.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/security.h>
#include <linux/user_namespace.h>
#include <linux/uaccess.h>
#include "internal.h"
/* Session keyring create vs join semaphore */
static DEFINE_MUTEX(key_session_mutex);
/* User keyring creation semaphore */
static DEFINE_MUTEX(key_user_keyring_mutex);
/* The root user's tracking struct */
struct key_user root_key_user = {
.usage = REFCOUNT_INIT(3),
.cons_lock = __MUTEX_INITIALIZER(root_key_user.cons_lock),
.lock = __SPIN_LOCK_UNLOCKED(root_key_user.lock),
.nkeys = ATOMIC_INIT(2),
.nikeys = ATOMIC_INIT(2),
.uid = GLOBAL_ROOT_UID,
};
/*
* Install the user and user session keyrings for the current process's UID.
*/
int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
/*
* Install a thread keyring to the given credentials struct if it didn't have
* one already. This is allowed to overrun the quota.
*
* Return: 0 if a thread keyring is now present; -errno on failure.
*/
int install_thread_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->thread_keyring)
return 0;
keyring = keyring_alloc("_tid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->thread_keyring = keyring;
return 0;
}
/*
* Install a thread keyring to the current task if it didn't have one already.
*
* Return: 0 if a thread keyring is now present; -errno on failure.
*/
static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Install a process keyring to the given credentials struct if it didn't have
* one already. This is allowed to overrun the quota.
*
* Return: 0 if a process keyring is now present; -errno on failure.
*/
int install_process_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->process_keyring)
return 0;
keyring = keyring_alloc("_pid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->process_keyring = keyring;
return 0;
}
/*
* Install a process keyring to the current task if it didn't have one already.
*
* Return: 0 if a process keyring is now present; -errno on failure.
*/
static int install_process_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_process_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Install the given keyring as the session keyring of the given credentials
* struct, replacing the existing one if any. If the given keyring is NULL,
* then install a new anonymous session keyring.
*
* Return: 0 on success; -errno on failure.
*/
int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
{
unsigned long flags;
struct key *old;
might_sleep();
/* create an empty session keyring */
if (!keyring) {
flags = KEY_ALLOC_QUOTA_OVERRUN;
if (cred->session_keyring)
flags = KEY_ALLOC_IN_QUOTA;
keyring = keyring_alloc("_ses", cred->uid, cred->gid, cred,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
flags, NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
} else {
__key_get(keyring);
}
/* install the keyring */
old = cred->session_keyring;
rcu_assign_pointer(cred->session_keyring, keyring);
if (old)
key_put(old);
return 0;
}
/*
* Install the given keyring as the session keyring of the current task,
* replacing the existing one if any. If the given keyring is NULL, then
* install a new anonymous session keyring.
*
* Return: 0 on success; -errno on failure.
*/
static int install_session_keyring(struct key *keyring)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Handle the fsuid changing.
*/
void key_fsuid_changed(struct task_struct *tsk)
{
/* update the ownership of the thread keyring */
BUG_ON(!tsk->cred);
if (tsk->cred->thread_keyring) {
down_write(&tsk->cred->thread_keyring->sem);
tsk->cred->thread_keyring->uid = tsk->cred->fsuid;
up_write(&tsk->cred->thread_keyring->sem);
}
}
/*
* Handle the fsgid changing.
*/
void key_fsgid_changed(struct task_struct *tsk)
{
/* update the ownership of the thread keyring */
BUG_ON(!tsk->cred);
if (tsk->cred->thread_keyring) {
down_write(&tsk->cred->thread_keyring->sem);
tsk->cred->thread_keyring->gid = tsk->cred->fsgid;
up_write(&tsk->cred->thread_keyring->sem);
}
}
/*
* Search the process keyrings attached to the supplied cred for the first
* matching key.
*
* The search criteria are the type and the match function. The description is
* given to the match function as a parameter, but doesn't otherwise influence
* the search. Typically the match function will compare the description
* parameter to the key's description.
*
* This can only search keyrings that grant Search permission to the supplied
* credentials. Keyrings linked to searched keyrings will also be searched if
* they grant Search permission too. Keys can only be found if they grant
* Search permission to the credentials.
*
* Returns a pointer to the key with the key usage count incremented if
* successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only
* matched negative keys.
*
* In the case of a successful return, the possession attribute is set on the
* returned key reference.
*/
key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx)
{
key_ref_t key_ref, ret, err;
/* we want to return -EAGAIN or -ENOKEY if any of the keyrings were
* searchable, but we failed to find a key or we found a negative key;
* otherwise we want to return a sample error (probably -EACCES) if
* none of the keyrings were searchable
*
* in terms of priority: success > -ENOKEY > -EAGAIN > other error
*/
key_ref = NULL;
ret = NULL;
err = ERR_PTR(-EAGAIN);
/* search the thread keyring first */
if (ctx->cred->thread_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->thread_keyring, 1), ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* search the process keyring second */
if (ctx->cred->process_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->process_keyring, 1), ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* search the session keyring */
if (ctx->cred->session_keyring) {
rcu_read_lock();
key_ref = keyring_search_aux(
make_key_ref(rcu_dereference(ctx->cred->session_keyring), 1),
ctx);
rcu_read_unlock();
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* or search the user-session keyring */
else if (ctx->cred->user->session_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->user->session_keyring, 1),
ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* no key - decide on the error we're going to go for */
key_ref = ret ? ret : err;
found:
return key_ref;
}
/*
* Search the process keyrings attached to the supplied cred for the first
* matching key in the manner of search_my_process_keyrings(), but also search
* the keys attached to the assumed authorisation key using its credentials if
* one is available.
*
* Return same as search_my_process_keyrings().
*/
key_ref_t search_process_keyrings(struct keyring_search_context *ctx)
{
struct request_key_auth *rka;
key_ref_t key_ref, ret = ERR_PTR(-EACCES), err;
might_sleep();
key_ref = search_my_process_keyrings(ctx);
if (!IS_ERR(key_ref))
goto found;
err = key_ref;
/* if this process has an instantiation authorisation key, then we also
* search the keyrings of the process mentioned there
* - we don't permit access to request_key auth keys via this method
*/
if (ctx->cred->request_key_auth &&
ctx->cred == current_cred() &&
ctx->index_key.type != &key_type_request_key_auth
) {
const struct cred *cred = ctx->cred;
/* defend against the auth key being revoked */
down_read(&cred->request_key_auth->sem);
if (key_validate(ctx->cred->request_key_auth) == 0) {
rka = ctx->cred->request_key_auth->payload.data[0];
ctx->cred = rka->cred;
key_ref = search_process_keyrings(ctx);
ctx->cred = cred;
up_read(&cred->request_key_auth->sem);
if (!IS_ERR(key_ref))
goto found;
ret = key_ref;
} else {
up_read(&cred->request_key_auth->sem);
}
}
/* no key - decide on the error we're going to go for */
if (err == ERR_PTR(-ENOKEY) || ret == ERR_PTR(-ENOKEY))
key_ref = ERR_PTR(-ENOKEY);
else if (err == ERR_PTR(-EACCES))
key_ref = ret;
else
key_ref = err;
found:
return key_ref;
}
/*
* See if the key we're looking at is the target key.
*/
bool lookup_user_key_possessed(const struct key *key,
const struct key_match_data *match_data)
{
return key == match_data->raw_data;
}
/*
* Look up a key ID given us by userspace with a given permissions mask to get
* the key it refers to.
*
* Flags can be passed to request that special keyrings be created if referred
* to directly, to permit partially constructed keys to be found and to skip
* validity and permission checks on the found key.
*
* Returns a pointer to the key with an incremented usage count if successful;
* -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond
* to a key or the best found key was a negative key; -EKEYREVOKED or
* -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the
* found key doesn't grant the requested permit or the LSM denied access to it;
* or -ENOMEM if a special keyring couldn't be created.
*
* In the case of a successful return, the possession attribute is set on the
* returned key reference.
*/
key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
key_perm_t perm)
{
struct keyring_search_context ctx = {
.match_data.cmp = lookup_user_key_possessed,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
struct request_key_auth *rka;
struct key *key;
key_ref_t key_ref, skey_ref;
int ret;
try_again:
ctx.cred = get_current_cred();
key_ref = ERR_PTR(-ENOKEY);
switch (id) {
case KEY_SPEC_THREAD_KEYRING:
if (!ctx.cred->thread_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_thread_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->thread_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_PROCESS_KEYRING:
if (!ctx.cred->process_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_process_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->process_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_SESSION_KEYRING:
if (!ctx.cred->session_keyring) {
/* always install a session keyring upon access if one
* doesn't exist yet */
ret = install_user_keyrings();
if (ret < 0)
goto error;
if (lflags & KEY_LOOKUP_CREATE)
ret = join_session_keyring(NULL);
else
ret = install_session_keyring(
ctx.cred->user->session_keyring);
if (ret < 0)
goto error;
goto reget_creds;
} else if (ctx.cred->session_keyring ==
ctx.cred->user->session_keyring &&
lflags & KEY_LOOKUP_CREATE) {
ret = join_session_keyring(NULL);
if (ret < 0)
goto error;
goto reget_creds;
}
rcu_read_lock();
key = rcu_dereference(ctx.cred->session_keyring);
__key_get(key);
rcu_read_unlock();
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_KEYRING:
if (!ctx.cred->user->uid_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->uid_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_SESSION_KEYRING:
if (!ctx.cred->user->session_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->session_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_GROUP_KEYRING:
/* group keyrings are not yet supported */
key_ref = ERR_PTR(-EINVAL);
goto error;
case KEY_SPEC_REQKEY_AUTH_KEY:
key = ctx.cred->request_key_auth;
if (!key)
goto error;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_REQUESTOR_KEYRING:
if (!ctx.cred->request_key_auth)
goto error;
down_read(&ctx.cred->request_key_auth->sem);
if (test_bit(KEY_FLAG_REVOKED,
&ctx.cred->request_key_auth->flags)) {
key_ref = ERR_PTR(-EKEYREVOKED);
key = NULL;
} else {
rka = ctx.cred->request_key_auth->payload.data[0];
key = rka->dest_keyring;
__key_get(key);
}
up_read(&ctx.cred->request_key_auth->sem);
if (!key)
goto error;
key_ref = make_key_ref(key, 1);
break;
default:
key_ref = ERR_PTR(-EINVAL);
if (id < 1)
goto error;
key = key_lookup(id);
if (IS_ERR(key)) {
key_ref = ERR_CAST(key);
goto error;
}
key_ref = make_key_ref(key, 0);
/* check to see if we possess the key */
ctx.index_key.type = key->type;
ctx.index_key.description = key->description;
ctx.index_key.desc_len = strlen(key->description);
ctx.match_data.raw_data = key;
kdebug("check possessed");
skey_ref = search_process_keyrings(&ctx);
kdebug("possessed=%p", skey_ref);
if (!IS_ERR(skey_ref)) {
key_put(key);
key_ref = skey_ref;
}
break;
}
/* unlink does not use the nominated key in any way, so can skip all
* the permission checks as it is only concerned with the keyring */
if (lflags & KEY_LOOKUP_FOR_UNLINK) {
ret = 0;
goto error;
}
if (!(lflags & KEY_LOOKUP_PARTIAL)) {
ret = wait_for_key_construction(key, true);
switch (ret) {
case -ERESTARTSYS:
goto invalid_key;
default:
if (perm)
goto invalid_key;
case 0:
break;
}
} else if (perm) {
ret = key_validate(key);
if (ret < 0)
goto invalid_key;
}
ret = -EIO;
if (!(lflags & KEY_LOOKUP_PARTIAL) &&
key_read_state(key) == KEY_IS_UNINSTANTIATED)
goto invalid_key;
/* check the permissions */
ret = key_task_permission(key_ref, ctx.cred, perm);
if (ret < 0)
goto invalid_key;
key->last_used_at = current_kernel_time().tv_sec;
error:
put_cred(ctx.cred);
return key_ref;
invalid_key:
key_ref_put(key_ref);
key_ref = ERR_PTR(ret);
goto error;
/* if we attempted to install a keyring, then it may have caused new
* creds to be installed */
reget_creds:
put_cred(ctx.cred);
goto try_again;
}
/*
* Join the named keyring as the session keyring if possible else attempt to
* create a new one of that name and join that.
*
* If the name is NULL, an empty anonymous keyring will be installed as the
* session keyring.
*
* Named session keyrings are joined with a semaphore held to prevent the
* keyrings from going away whilst the attempt is made to going them and also
* to prevent a race in creating compatible session keyrings.
*/
long join_session_keyring(const char *name)
{
const struct cred *old;
struct cred *new;
struct key *keyring;
long ret, serial;
new = prepare_creds();
if (!new)
return -ENOMEM;
old = current_cred();
/* if no name is provided, install an anonymous keyring */
if (!name) {
ret = install_session_keyring_to_cred(new, NULL);
if (ret < 0)
goto error;
serial = new->session_keyring->serial;
ret = commit_creds(new);
if (ret == 0)
ret = serial;
goto okay;
}
/* allow the user to join or create a named keyring */
mutex_lock(&key_session_mutex);
/* look for an existing keyring of this name */
keyring = find_keyring_by_name(name, false);
if (PTR_ERR(keyring) == -ENOKEY) {
/* not found - try and create a new one */
keyring = keyring_alloc(
name, old->uid, old->gid, old,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
KEY_ALLOC_IN_QUOTA, NULL, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
}
} else if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
} else if (keyring == new->session_keyring) {
ret = 0;
goto error3;
}
/* we've got a keyring - now to install it */
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0)
goto error3;
commit_creds(new);
mutex_unlock(&key_session_mutex);
ret = keyring->serial;
key_put(keyring);
okay:
return ret;
error3:
key_put(keyring);
error2:
mutex_unlock(&key_session_mutex);
error:
abort_creds(new);
return ret;
}
/*
* Replace a process's session keyring on behalf of one of its children when
* the target process is about to resume userspace execution.
*/
void key_change_session_keyring(struct callback_head *twork)
{
const struct cred *old = current_cred();
struct cred *new = container_of(twork, struct cred, rcu);
if (unlikely(current->flags & PF_EXITING)) {
put_cred(new);
return;
}
new-> uid = old-> uid;
new-> euid = old-> euid;
new-> suid = old-> suid;
new->fsuid = old->fsuid;
new-> gid = old-> gid;
new-> egid = old-> egid;
new-> sgid = old-> sgid;
new->fsgid = old->fsgid;
new->user = get_uid(old->user);
new->user_ns = get_user_ns(old->user_ns);
new->group_info = get_group_info(old->group_info);
new->securebits = old->securebits;
new->cap_inheritable = old->cap_inheritable;
new->cap_permitted = old->cap_permitted;
new->cap_effective = old->cap_effective;
new->cap_ambient = old->cap_ambient;
new->cap_bset = old->cap_bset;
new->jit_keyring = old->jit_keyring;
new->thread_keyring = key_get(old->thread_keyring);
new->process_keyring = key_get(old->process_keyring);
security_transfer_creds(new, old);
commit_creds(new);
}
/*
* Make sure that root's user and user-session keyrings exist.
*/
static int __init init_root_keyring(void)
{
return install_user_keyrings();
}
late_initcall(init_root_keyring);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_9 |
crossvul-cpp_data_bad_3019_0 | /*
* linux/mm/mlock.c
*
* (C) Copyright 1995 Linus Torvalds
* (C) Copyright 2002 Christoph Hellwig
*/
#include <linux/capability.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/sched/user.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/pagemap.h>
#include <linux/pagevec.h>
#include <linux/mempolicy.h>
#include <linux/syscalls.h>
#include <linux/sched.h>
#include <linux/export.h>
#include <linux/rmap.h>
#include <linux/mmzone.h>
#include <linux/hugetlb.h>
#include <linux/memcontrol.h>
#include <linux/mm_inline.h>
#include "internal.h"
bool can_do_mlock(void)
{
if (rlimit(RLIMIT_MEMLOCK) != 0)
return true;
if (capable(CAP_IPC_LOCK))
return true;
return false;
}
EXPORT_SYMBOL(can_do_mlock);
/*
* Mlocked pages are marked with PageMlocked() flag for efficient testing
* in vmscan and, possibly, the fault path; and to support semi-accurate
* statistics.
*
* An mlocked page [PageMlocked(page)] is unevictable. As such, it will
* be placed on the LRU "unevictable" list, rather than the [in]active lists.
* The unevictable list is an LRU sibling list to the [in]active lists.
* PageUnevictable is set to indicate the unevictable state.
*
* When lazy mlocking via vmscan, it is important to ensure that the
* vma's VM_LOCKED status is not concurrently being modified, otherwise we
* may have mlocked a page that is being munlocked. So lazy mlock must take
* the mmap_sem for read, and verify that the vma really is locked
* (see mm/rmap.c).
*/
/*
* LRU accounting for clear_page_mlock()
*/
void clear_page_mlock(struct page *page)
{
if (!TestClearPageMlocked(page))
return;
mod_zone_page_state(page_zone(page), NR_MLOCK,
-hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGCLEARED);
if (!isolate_lru_page(page)) {
putback_lru_page(page);
} else {
/*
* We lost the race. the page already moved to evictable list.
*/
if (PageUnevictable(page))
count_vm_event(UNEVICTABLE_PGSTRANDED);
}
}
/*
* Mark page as mlocked if not already.
* If page on LRU, isolate and putback to move to unevictable list.
*/
void mlock_vma_page(struct page *page)
{
/* Serialize with page migration */
BUG_ON(!PageLocked(page));
VM_BUG_ON_PAGE(PageTail(page), page);
VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
if (!TestSetPageMlocked(page)) {
mod_zone_page_state(page_zone(page), NR_MLOCK,
hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGMLOCKED);
if (!isolate_lru_page(page))
putback_lru_page(page);
}
}
/*
* Isolate a page from LRU with optional get_page() pin.
* Assumes lru_lock already held and page already pinned.
*/
static bool __munlock_isolate_lru_page(struct page *page, bool getpage)
{
if (PageLRU(page)) {
struct lruvec *lruvec;
lruvec = mem_cgroup_page_lruvec(page, page_pgdat(page));
if (getpage)
get_page(page);
ClearPageLRU(page);
del_page_from_lru_list(page, lruvec, page_lru(page));
return true;
}
return false;
}
/*
* Finish munlock after successful page isolation
*
* Page must be locked. This is a wrapper for try_to_munlock()
* and putback_lru_page() with munlock accounting.
*/
static void __munlock_isolated_page(struct page *page)
{
/*
* Optimization: if the page was mapped just once, that's our mapping
* and we don't need to check all the other vmas.
*/
if (page_mapcount(page) > 1)
try_to_munlock(page);
/* Did try_to_unlock() succeed or punt? */
if (!PageMlocked(page))
count_vm_event(UNEVICTABLE_PGMUNLOCKED);
putback_lru_page(page);
}
/*
* Accounting for page isolation fail during munlock
*
* Performs accounting when page isolation fails in munlock. There is nothing
* else to do because it means some other task has already removed the page
* from the LRU. putback_lru_page() will take care of removing the page from
* the unevictable list, if necessary. vmscan [page_referenced()] will move
* the page back to the unevictable list if some other vma has it mlocked.
*/
static void __munlock_isolation_failed(struct page *page)
{
if (PageUnevictable(page))
__count_vm_event(UNEVICTABLE_PGSTRANDED);
else
__count_vm_event(UNEVICTABLE_PGMUNLOCKED);
}
/**
* munlock_vma_page - munlock a vma page
* @page - page to be unlocked, either a normal page or THP page head
*
* returns the size of the page as a page mask (0 for normal page,
* HPAGE_PMD_NR - 1 for THP head page)
*
* called from munlock()/munmap() path with page supposedly on the LRU.
* When we munlock a page, because the vma where we found the page is being
* munlock()ed or munmap()ed, we want to check whether other vmas hold the
* page locked so that we can leave it on the unevictable lru list and not
* bother vmscan with it. However, to walk the page's rmap list in
* try_to_munlock() we must isolate the page from the LRU. If some other
* task has removed the page from the LRU, we won't be able to do that.
* So we clear the PageMlocked as we might not get another chance. If we
* can't isolate the page, we leave it for putback_lru_page() and vmscan
* [page_referenced()/try_to_unmap()] to deal with.
*/
unsigned int munlock_vma_page(struct page *page)
{
int nr_pages;
struct zone *zone = page_zone(page);
/* For try_to_munlock() and to serialize with page migration */
BUG_ON(!PageLocked(page));
VM_BUG_ON_PAGE(PageTail(page), page);
/*
* Serialize with any parallel __split_huge_page_refcount() which
* might otherwise copy PageMlocked to part of the tail pages before
* we clear it in the head page. It also stabilizes hpage_nr_pages().
*/
spin_lock_irq(zone_lru_lock(zone));
if (!TestClearPageMlocked(page)) {
/* Potentially, PTE-mapped THP: do not skip the rest PTEs */
nr_pages = 1;
goto unlock_out;
}
nr_pages = hpage_nr_pages(page);
__mod_zone_page_state(zone, NR_MLOCK, -nr_pages);
if (__munlock_isolate_lru_page(page, true)) {
spin_unlock_irq(zone_lru_lock(zone));
__munlock_isolated_page(page);
goto out;
}
__munlock_isolation_failed(page);
unlock_out:
spin_unlock_irq(zone_lru_lock(zone));
out:
return nr_pages - 1;
}
/*
* convert get_user_pages() return value to posix mlock() error
*/
static int __mlock_posix_error_return(long retval)
{
if (retval == -EFAULT)
retval = -ENOMEM;
else if (retval == -ENOMEM)
retval = -EAGAIN;
return retval;
}
/*
* Prepare page for fast batched LRU putback via putback_lru_evictable_pagevec()
*
* The fast path is available only for evictable pages with single mapping.
* Then we can bypass the per-cpu pvec and get better performance.
* when mapcount > 1 we need try_to_munlock() which can fail.
* when !page_evictable(), we need the full redo logic of putback_lru_page to
* avoid leaving evictable page in unevictable list.
*
* In case of success, @page is added to @pvec and @pgrescued is incremented
* in case that the page was previously unevictable. @page is also unlocked.
*/
static bool __putback_lru_fast_prepare(struct page *page, struct pagevec *pvec,
int *pgrescued)
{
VM_BUG_ON_PAGE(PageLRU(page), page);
VM_BUG_ON_PAGE(!PageLocked(page), page);
if (page_mapcount(page) <= 1 && page_evictable(page)) {
pagevec_add(pvec, page);
if (TestClearPageUnevictable(page))
(*pgrescued)++;
unlock_page(page);
return true;
}
return false;
}
/*
* Putback multiple evictable pages to the LRU
*
* Batched putback of evictable pages that bypasses the per-cpu pvec. Some of
* the pages might have meanwhile become unevictable but that is OK.
*/
static void __putback_lru_fast(struct pagevec *pvec, int pgrescued)
{
count_vm_events(UNEVICTABLE_PGMUNLOCKED, pagevec_count(pvec));
/*
*__pagevec_lru_add() calls release_pages() so we don't call
* put_page() explicitly
*/
__pagevec_lru_add(pvec);
count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
}
/*
* Munlock a batch of pages from the same zone
*
* The work is split to two main phases. First phase clears the Mlocked flag
* and attempts to isolate the pages, all under a single zone lru lock.
* The second phase finishes the munlock only for pages where isolation
* succeeded.
*
* Note that the pagevec may be modified during the process.
*/
static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)
{
int i;
int nr = pagevec_count(pvec);
int delta_munlocked;
struct pagevec pvec_putback;
int pgrescued = 0;
pagevec_init(&pvec_putback, 0);
/* Phase 1: page isolation */
spin_lock_irq(zone_lru_lock(zone));
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (TestClearPageMlocked(page)) {
/*
* We already have pin from follow_page_mask()
* so we can spare the get_page() here.
*/
if (__munlock_isolate_lru_page(page, false))
continue;
else
__munlock_isolation_failed(page);
}
/*
* We won't be munlocking this page in the next phase
* but we still need to release the follow_page_mask()
* pin. We cannot do it under lru_lock however. If it's
* the last pin, __page_cache_release() would deadlock.
*/
pagevec_add(&pvec_putback, pvec->pages[i]);
pvec->pages[i] = NULL;
}
delta_munlocked = -nr + pagevec_count(&pvec_putback);
__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);
spin_unlock_irq(zone_lru_lock(zone));
/* Now we can release pins of pages that we are not munlocking */
pagevec_release(&pvec_putback);
/* Phase 2: page munlock */
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (page) {
lock_page(page);
if (!__putback_lru_fast_prepare(page, &pvec_putback,
&pgrescued)) {
/*
* Slow path. We don't want to lose the last
* pin before unlock_page()
*/
get_page(page); /* for putback_lru_page() */
__munlock_isolated_page(page);
unlock_page(page);
put_page(page); /* from follow_page_mask() */
}
}
}
/*
* Phase 3: page putback for pages that qualified for the fast path
* This will also call put_page() to return pin from follow_page_mask()
*/
if (pagevec_count(&pvec_putback))
__putback_lru_fast(&pvec_putback, pgrescued);
}
/*
* Fill up pagevec for __munlock_pagevec using pte walk
*
* The function expects that the struct page corresponding to @start address is
* a non-TPH page already pinned and in the @pvec, and that it belongs to @zone.
*
* The rest of @pvec is filled by subsequent pages within the same pmd and same
* zone, as long as the pte's are present and vm_normal_page() succeeds. These
* pages also get pinned.
*
* Returns the address of the next page that should be scanned. This equals
* @start + PAGE_SIZE when no page could be added by the pte walk.
*/
static unsigned long __munlock_pagevec_fill(struct pagevec *pvec,
struct vm_area_struct *vma, int zoneid, unsigned long start,
unsigned long end)
{
pte_t *pte;
spinlock_t *ptl;
/*
* Initialize pte walk starting at the already pinned page where we
* are sure that there is a pte, as it was pinned under the same
* mmap_sem write op.
*/
pte = get_locked_pte(vma->vm_mm, start, &ptl);
/* Make sure we do not cross the page table boundary */
end = pgd_addr_end(start, end);
end = p4d_addr_end(start, end);
end = pud_addr_end(start, end);
end = pmd_addr_end(start, end);
/* The page next to the pinned page is the first we will try to get */
start += PAGE_SIZE;
while (start < end) {
struct page *page = NULL;
pte++;
if (pte_present(*pte))
page = vm_normal_page(vma, start, *pte);
/*
* Break if page could not be obtained or the page's node+zone does not
* match
*/
if (!page || page_zone_id(page) != zoneid)
break;
/*
* Do not use pagevec for PTE-mapped THP,
* munlock_vma_pages_range() will handle them.
*/
if (PageTransCompound(page))
break;
get_page(page);
/*
* Increase the address that will be returned *before* the
* eventual break due to pvec becoming full by adding the page
*/
start += PAGE_SIZE;
if (pagevec_add(pvec, page) == 0)
break;
}
pte_unmap_unlock(pte, ptl);
return start;
}
/*
* munlock_vma_pages_range() - munlock all pages in the vma range.'
* @vma - vma containing range to be munlock()ed.
* @start - start address in @vma of the range
* @end - end of range in @vma.
*
* For mremap(), munmap() and exit().
*
* Called with @vma VM_LOCKED.
*
* Returns with VM_LOCKED cleared. Callers must be prepared to
* deal with this.
*
* We don't save and restore VM_LOCKED here because pages are
* still on lru. In unmap path, pages might be scanned by reclaim
* and re-mlocked by try_to_{munlock|unmap} before we unmap and
* free them. This will result in freeing mlocked pages.
*/
void munlock_vma_pages_range(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
while (start < end) {
struct page *page;
unsigned int page_mask = 0;
unsigned long page_increm;
struct pagevec pvec;
struct zone *zone;
int zoneid;
pagevec_init(&pvec, 0);
/*
* Although FOLL_DUMP is intended for get_dump_page(),
* it just so happens that its special treatment of the
* ZERO_PAGE (returning an error instead of doing get_page)
* suits munlock very well (and if somehow an abnormal page
* has sneaked into the range, we won't oops here: great).
*/
page = follow_page(vma, start, FOLL_GET | FOLL_DUMP);
if (page && !IS_ERR(page)) {
if (PageTransTail(page)) {
VM_BUG_ON_PAGE(PageMlocked(page), page);
put_page(page); /* follow_page_mask() */
} else if (PageTransHuge(page)) {
lock_page(page);
/*
* Any THP page found by follow_page_mask() may
* have gotten split before reaching
* munlock_vma_page(), so we need to compute
* the page_mask here instead.
*/
page_mask = munlock_vma_page(page);
unlock_page(page);
put_page(page); /* follow_page_mask() */
} else {
/*
* Non-huge pages are handled in batches via
* pagevec. The pin from follow_page_mask()
* prevents them from collapsing by THP.
*/
pagevec_add(&pvec, page);
zone = page_zone(page);
zoneid = page_zone_id(page);
/*
* Try to fill the rest of pagevec using fast
* pte walk. This will also update start to
* the next page to process. Then munlock the
* pagevec.
*/
start = __munlock_pagevec_fill(&pvec, vma,
zoneid, start, end);
__munlock_pagevec(&pvec, zone);
goto next;
}
}
page_increm = 1 + page_mask;
start += page_increm * PAGE_SIZE;
next:
cond_resched();
}
}
/*
* mlock_fixup - handle mlock[all]/munlock[all] requests.
*
* Filters out "special" vmas -- VM_LOCKED never gets set for these, and
* munlock is a no-op. However, for some special vmas, we go ahead and
* populate the ptes.
*
* For vmas that pass the filters, merge/split as appropriate.
*/
static int mlock_fixup(struct vm_area_struct *vma, struct vm_area_struct **prev,
unsigned long start, unsigned long end, vm_flags_t newflags)
{
struct mm_struct *mm = vma->vm_mm;
pgoff_t pgoff;
int nr_pages;
int ret = 0;
int lock = !!(newflags & VM_LOCKED);
vm_flags_t old_flags = vma->vm_flags;
if (newflags == vma->vm_flags || (vma->vm_flags & VM_SPECIAL) ||
is_vm_hugetlb_page(vma) || vma == get_gate_vma(current->mm))
/* don't set VM_LOCKED or VM_LOCKONFAULT and don't count */
goto out;
pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
*prev = vma_merge(mm, *prev, start, end, newflags, vma->anon_vma,
vma->vm_file, pgoff, vma_policy(vma),
vma->vm_userfaultfd_ctx);
if (*prev) {
vma = *prev;
goto success;
}
if (start != vma->vm_start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
goto out;
}
if (end != vma->vm_end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
goto out;
}
success:
/*
* Keep track of amount of locked VM.
*/
nr_pages = (end - start) >> PAGE_SHIFT;
if (!lock)
nr_pages = -nr_pages;
else if (old_flags & VM_LOCKED)
nr_pages = 0;
mm->locked_vm += nr_pages;
/*
* vm_flags is protected by the mmap_sem held in write mode.
* It's okay if try_to_unmap_one unmaps a page just after we
* set VM_LOCKED, populate_vma_page_range will bring it back.
*/
if (lock)
vma->vm_flags = newflags;
else
munlock_vma_pages_range(vma, start, end);
out:
*prev = vma;
return ret;
}
static int apply_vma_lock_flags(unsigned long start, size_t len,
vm_flags_t flags)
{
unsigned long nstart, end, tmp;
struct vm_area_struct * vma, * prev;
int error;
VM_BUG_ON(offset_in_page(start));
VM_BUG_ON(len != PAGE_ALIGN(len));
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
vma = find_vma(current->mm, start);
if (!vma || vma->vm_start > start)
return -ENOMEM;
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (nstart = start ; ; ) {
vm_flags_t newflags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
newflags |= flags;
/* Here we know that vma->vm_start <= nstart < vma->vm_end. */
tmp = vma->vm_end;
if (tmp > end)
tmp = end;
error = mlock_fixup(vma, &prev, nstart, tmp, newflags);
if (error)
break;
nstart = tmp;
if (nstart < prev->vm_end)
nstart = prev->vm_end;
if (nstart >= end)
break;
vma = prev->vm_next;
if (!vma || vma->vm_start != nstart) {
error = -ENOMEM;
break;
}
}
return error;
}
/*
* Go through vma areas and sum size of mlocked
* vma pages, as return value.
* Note deferred memory locking case(mlock2(,,MLOCK_ONFAULT)
* is also counted.
* Return value: previously mlocked page counts
*/
static int count_mm_mlocked_page_nr(struct mm_struct *mm,
unsigned long start, size_t len)
{
struct vm_area_struct *vma;
int count = 0;
if (mm == NULL)
mm = current->mm;
vma = find_vma(mm, start);
if (vma == NULL)
vma = mm->mmap;
for (; vma ; vma = vma->vm_next) {
if (start >= vma->vm_end)
continue;
if (start + len <= vma->vm_start)
break;
if (vma->vm_flags & VM_LOCKED) {
if (start > vma->vm_start)
count -= (start - vma->vm_start);
if (start + len < vma->vm_end) {
count += start + len - vma->vm_start;
break;
}
count += vma->vm_end - vma->vm_start;
}
}
return count >> PAGE_SHIFT;
}
static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t flags)
{
unsigned long locked;
unsigned long lock_limit;
int error = -ENOMEM;
if (!can_do_mlock())
return -EPERM;
lru_add_drain_all(); /* flush pagevec */
len = PAGE_ALIGN(len + (offset_in_page(start)));
start &= PAGE_MASK;
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
locked = len >> PAGE_SHIFT;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
locked += current->mm->locked_vm;
if ((locked > lock_limit) && (!capable(CAP_IPC_LOCK))) {
/*
* It is possible that the regions requested intersect with
* previously mlocked areas, that part area in "mm->locked_vm"
* should not be counted to new mlock increment count. So check
* and adjust locked count if necessary.
*/
locked -= count_mm_mlocked_page_nr(current->mm,
start, len);
}
/* check against resource limits */
if ((locked <= lock_limit) || capable(CAP_IPC_LOCK))
error = apply_vma_lock_flags(start, len, flags);
up_write(¤t->mm->mmap_sem);
if (error)
return error;
error = __mm_populate(start, len, 0);
if (error)
return __mlock_posix_error_return(error);
return 0;
}
SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len)
{
return do_mlock(start, len, VM_LOCKED);
}
SYSCALL_DEFINE3(mlock2, unsigned long, start, size_t, len, int, flags)
{
vm_flags_t vm_flags = VM_LOCKED;
if (flags & ~MLOCK_ONFAULT)
return -EINVAL;
if (flags & MLOCK_ONFAULT)
vm_flags |= VM_LOCKONFAULT;
return do_mlock(start, len, vm_flags);
}
SYSCALL_DEFINE2(munlock, unsigned long, start, size_t, len)
{
int ret;
len = PAGE_ALIGN(len + (offset_in_page(start)));
start &= PAGE_MASK;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
ret = apply_vma_lock_flags(start, len, 0);
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Take the MCL_* flags passed into mlockall (or 0 if called from munlockall)
* and translate into the appropriate modifications to mm->def_flags and/or the
* flags for all current VMAs.
*
* There are a couple of subtleties with this. If mlockall() is called multiple
* times with different flags, the values do not necessarily stack. If mlockall
* is called once including the MCL_FUTURE flag and then a second time without
* it, VM_LOCKED and VM_LOCKONFAULT will be cleared from mm->def_flags.
*/
static int apply_mlockall_flags(int flags)
{
struct vm_area_struct * vma, * prev = NULL;
vm_flags_t to_add = 0;
current->mm->def_flags &= VM_LOCKED_CLEAR_MASK;
if (flags & MCL_FUTURE) {
current->mm->def_flags |= VM_LOCKED;
if (flags & MCL_ONFAULT)
current->mm->def_flags |= VM_LOCKONFAULT;
if (!(flags & MCL_CURRENT))
goto out;
}
if (flags & MCL_CURRENT) {
to_add |= VM_LOCKED;
if (flags & MCL_ONFAULT)
to_add |= VM_LOCKONFAULT;
}
for (vma = current->mm->mmap; vma ; vma = prev->vm_next) {
vm_flags_t newflags;
newflags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
newflags |= to_add;
/* Ignore errors */
mlock_fixup(vma, &prev, vma->vm_start, vma->vm_end, newflags);
cond_resched_rcu_qs();
}
out:
return 0;
}
SYSCALL_DEFINE1(mlockall, int, flags)
{
unsigned long lock_limit;
int ret;
if (!flags || (flags & ~(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT)))
return -EINVAL;
if (!can_do_mlock())
return -EPERM;
if (flags & MCL_CURRENT)
lru_add_drain_all(); /* flush pagevec */
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
ret = -ENOMEM;
if (!(flags & MCL_CURRENT) || (current->mm->total_vm <= lock_limit) ||
capable(CAP_IPC_LOCK))
ret = apply_mlockall_flags(flags);
up_write(¤t->mm->mmap_sem);
if (!ret && (flags & MCL_CURRENT))
mm_populate(0, TASK_SIZE);
return ret;
}
SYSCALL_DEFINE0(munlockall)
{
int ret;
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
ret = apply_mlockall_flags(0);
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Objects with different lifetime than processes (SHM_LOCK and SHM_HUGETLB
* shm segments) get accounted against the user_struct instead.
*/
static DEFINE_SPINLOCK(shmlock_user_lock);
int user_shm_lock(size_t size, struct user_struct *user)
{
unsigned long lock_limit, locked;
int allowed = 0;
locked = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
lock_limit = rlimit(RLIMIT_MEMLOCK);
if (lock_limit == RLIM_INFINITY)
allowed = 1;
lock_limit >>= PAGE_SHIFT;
spin_lock(&shmlock_user_lock);
if (!allowed &&
locked + user->locked_shm > lock_limit && !capable(CAP_IPC_LOCK))
goto out;
get_uid(user);
user->locked_shm += locked;
allowed = 1;
out:
spin_unlock(&shmlock_user_lock);
return allowed;
}
void user_shm_unlock(size_t size, struct user_struct *user)
{
spin_lock(&shmlock_user_lock);
user->locked_shm -= (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
spin_unlock(&shmlock_user_lock);
free_uid(user);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3019_0 |
crossvul-cpp_data_good_2513_0 | /*
* Copyright 2014, Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* A daemon that supports a simplified interface for writing TCMU
* handlers.
*/
#define _GNU_SOURCE
#define _BITS_UIO_H
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <assert.h>
#include <dlfcn.h>
#include <pthread.h>
#include <signal.h>
#include <glib.h>
#include <glib-unix.h>
#include <gio/gio.h>
#include <getopt.h>
#include <poll.h>
#include <scsi/scsi.h>
#include <libkmod.h>
#include <sys/utsname.h>
#include "target_core_user_local.h"
#include "darray.h"
#include "tcmu-runner.h"
#include "tcmur_aio.h"
#include "tcmur_device.h"
#include "tcmur_cmd_handler.h"
#include "libtcmu.h"
#include "tcmuhandler-generated.h"
#include "version.h"
#include "libtcmu_config.h"
#include "libtcmu_log.h"
static char *handler_path = DEFAULT_HANDLER_PATH;
/* tcmu log dir path */
extern char *tcmu_log_dir;
static struct tcmu_config *tcmu_cfg;
darray(struct tcmur_handler *) g_runner_handlers = darray_new();
static struct tcmur_handler *find_handler_by_subtype(gchar *subtype)
{
struct tcmur_handler **handler;
darray_foreach(handler, g_runner_handlers) {
if (strcmp((*handler)->subtype, subtype) == 0)
return *handler;
}
return NULL;
}
int tcmur_register_handler(struct tcmur_handler *handler)
{
struct tcmur_handler *h;
int i;
for (i = 0; i < darray_size(g_runner_handlers); i++) {
h = darray_item(g_runner_handlers, i);
if (!strcmp(h->subtype, handler->subtype)) {
tcmu_err("Handler %s has already been registered\n",
handler->subtype);
return -1;
}
}
darray_append(g_runner_handlers, handler);
return 0;
}
bool tcmur_unregister_handler(struct tcmur_handler *handler)
{
int i;
for (i = 0; i < darray_size(g_runner_handlers); i++) {
if (darray_item(g_runner_handlers, i) == handler) {
darray_remove(g_runner_handlers, i);
return true;
}
}
return false;
}
static int is_handler(const struct dirent *dirent)
{
if (strncmp(dirent->d_name, "handler_", 8))
return 0;
return 1;
}
static int open_handlers(void)
{
struct dirent **dirent_list;
int num_handlers;
int num_good = 0;
int i;
num_handlers = scandir(handler_path, &dirent_list, is_handler, alphasort);
if (num_handlers == -1)
return -1;
for (i = 0; i < num_handlers; i++) {
char *path;
void *handle;
int (*handler_init)(void);
int ret;
ret = asprintf(&path, "%s/%s", handler_path, dirent_list[i]->d_name);
if (ret == -1) {
tcmu_err("ENOMEM\n");
continue;
}
handle = dlopen(path, RTLD_NOW|RTLD_LOCAL);
if (!handle) {
tcmu_err("Could not open handler at %s: %s\n", path, dlerror());
free(path);
continue;
}
handler_init = dlsym(handle, "handler_init");
if (!handler_init) {
tcmu_err("dlsym failure on %s\n", path);
free(path);
continue;
}
ret = handler_init();
free(path);
if (ret == 0)
num_good++;
}
for (i = 0; i < num_handlers; i++)
free(dirent_list[i]);
free(dirent_list);
return num_good;
}
static gboolean sighandler(gpointer user_data)
{
tcmulib_cleanup_all_cmdproc_threads();
tcmu_cancel_log_thread();
tcmu_cancel_config_thread(tcmu_cfg);
g_main_loop_quit((GMainLoop*)user_data);
return G_SOURCE_CONTINUE;
}
gboolean tcmulib_callback(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
struct tcmulib_context *ctx = data;
tcmulib_master_fd_ready(ctx);
return TRUE;
}
static GDBusObjectManagerServer *manager = NULL;
static gboolean
on_check_config(TCMUService1 *interface,
GDBusMethodInvocation *invocation,
gchar *cfgstring,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
char *reason = NULL;
bool str_ok = true;
if (handler->check_config)
str_ok = handler->check_config(cfgstring, &reason);
if (str_ok)
reason = "success";
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", str_ok, reason ? : "unknown"));
if (!str_ok)
free(reason);
return TRUE;
}
static void
dbus_export_handler(struct tcmur_handler *handler, GCallback check_config)
{
GDBusObjectSkeleton *object;
char obj_name[128];
TCMUService1 *interface;
snprintf(obj_name, sizeof(obj_name), "/org/kernel/TCMUService1/%s",
handler->subtype);
object = g_dbus_object_skeleton_new(obj_name);
interface = tcmuservice1_skeleton_new();
g_dbus_object_skeleton_add_interface(object, G_DBUS_INTERFACE_SKELETON(interface));
g_signal_connect(interface,
"handle-check-config",
check_config,
handler); /* user_data */
tcmuservice1_set_config_desc(interface, handler->cfg_desc);
g_dbus_object_manager_server_export(manager, G_DBUS_OBJECT_SKELETON(object));
g_object_unref(object);
}
static bool
dbus_unexport_handler(struct tcmur_handler *handler)
{
char obj_name[128];
snprintf(obj_name, sizeof(obj_name), "/org/kernel/TCMUService1/%s",
handler->subtype);
return g_dbus_object_manager_server_unexport(manager, obj_name) == TRUE;
}
struct dbus_info {
guint watcher_id;
/* The RegisterHandler invocation on
* org.kernel.TCMUService1.HandlerManager1 interface. */
GDBusMethodInvocation *register_invocation;
/* Connection to the handler's bus_name. */
GDBusConnection *connection;
};
static int dbus_handler_open(struct tcmu_device *dev)
{
return -1;
}
static void dbus_handler_close(struct tcmu_device *dev)
{
/* nop */
}
static int dbus_handler_handle_cmd(struct tcmu_device *dev,
struct tcmulib_cmd *cmd)
{
abort();
}
static gboolean
on_dbus_check_config(TCMUService1 *interface,
GDBusMethodInvocation *invocation,
gchar *cfgstring,
gpointer user_data)
{
char *bus_name, *obj_name;
struct tcmur_handler *handler = user_data;
GDBusConnection *connection;
GError *error = NULL;
GVariant *result;
bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
obj_name = g_strdup_printf("/org/kernel/TCMUService1/HandlerManager1/%s",
handler->subtype);
connection = g_dbus_method_invocation_get_connection(invocation);
result = g_dbus_connection_call_sync(connection,
bus_name,
obj_name,
"org.kernel.TCMUService1",
"CheckConfig",
g_variant_new("(s)", cfgstring),
NULL, G_DBUS_CALL_FLAGS_NONE, -1,
NULL, &error);
if (result)
g_dbus_method_invocation_return_value(invocation, result);
else
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE, error->message));
g_free(bus_name);
g_free(obj_name);
return TRUE;
}
static void
on_handler_appeared(GDBusConnection *connection,
const gchar *name,
const gchar *name_owner,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
info->connection = connection;
tcmur_register_handler(handler);
dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config));
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
info->register_invocation = NULL;
}
}
static void
on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_handler(handler);
dbus_unexport_handler(handler);
}
static gboolean
on_register_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gchar *cfg_desc,
gpointer user_data)
{
struct tcmur_handler *handler;
struct dbus_info *info;
char *bus_name;
bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s",
subtype);
handler = g_new0(struct tcmur_handler, 1);
handler->subtype = g_strdup(subtype);
handler->cfg_desc = g_strdup(cfg_desc);
handler->open = dbus_handler_open;
handler->close = dbus_handler_close;
handler->handle_cmd = dbus_handler_handle_cmd;
info = g_new0(struct dbus_info, 1);
info->register_invocation = invocation;
info->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM,
bus_name,
G_BUS_NAME_WATCHER_FLAGS_NONE,
on_handler_appeared,
on_handler_vanished,
handler,
NULL);
g_free(bus_name);
handler->opaque = info;
return TRUE;
}
static gboolean
on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
void dbus_handler_manager1_init(GDBusConnection *connection)
{
GError *error = NULL;
TCMUService1HandlerManager1 *interface;
gboolean ret;
interface = tcmuservice1_handler_manager1_skeleton_new();
ret = g_dbus_interface_skeleton_export(
G_DBUS_INTERFACE_SKELETON(interface),
connection,
"/org/kernel/TCMUService1/HandlerManager1",
&error);
g_signal_connect(interface,
"handle-register-handler",
G_CALLBACK (on_register_handler),
NULL);
g_signal_connect(interface,
"handle-unregister-handler",
G_CALLBACK (on_unregister_handler),
NULL);
if (!ret)
tcmu_err("Handler manager export failed: %s\n",
error ? error->message : "unknown error");
if (error)
g_error_free(error);
}
static void dbus_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler **handler;
tcmu_dbg("bus %s acquired\n", name);
manager = g_dbus_object_manager_server_new("/org/kernel/TCMUService1");
darray_foreach(handler, g_runner_handlers) {
dbus_export_handler(*handler, G_CALLBACK(on_check_config));
}
dbus_handler_manager1_init(connection);
g_dbus_object_manager_server_set_connection(manager, connection);
}
static void dbus_name_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
tcmu_dbg("name %s acquired\n", name);
}
static void dbus_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
tcmu_dbg("name lost\n");
}
static int load_our_module(void)
{
struct kmod_list *list = NULL, *itr;
struct kmod_ctx *ctx;
struct stat sb;
struct utsname u;
int ret;
ctx = kmod_new(NULL, NULL);
if (!ctx) {
tcmu_err("kmod_new() failed: %m\n");
return -1;
}
ret = kmod_module_new_from_lookup(ctx, "target_core_user", &list);
if (ret < 0) {
/* In some environments like containers, /lib/modules/`uname -r`
* will not exist, in such cases the load module job be taken
* care by admin, either by manual load or makesure it's builtin
*/
if (ENOENT == errno) {
if (uname(&u) < 0) {
tcmu_err("uname() failed: %m\n");
} else {
tcmu_info("no modules directory '/lib/modules/%s', checking module target_core_user entry in '/sys/modules/'\n",
u.release);
ret = stat("/sys/module/target_core_user", &sb);
if (!ret) {
tcmu_dbg("Module target_core_user already loaded\n");
} else {
tcmu_err("stat() on '/sys/module/target_core_user' failed: %m\n");
}
}
} else {
tcmu_err("kmod_module_new_from_lookup() failed to lookup alias target_core_use %m\n");
}
kmod_unref(ctx);
return ret;
}
if (!list) {
tcmu_err("kmod_module_new_from_lookup() failed to find module target_core_user\n");
kmod_unref(ctx);
return -ENOENT;
}
kmod_list_foreach(itr, list) {
int state, err;
struct kmod_module *mod = kmod_module_get_module(itr);
state = kmod_module_get_initstate(mod);
switch (state) {
case KMOD_MODULE_BUILTIN:
tcmu_info("Module '%s' is builtin\n",
kmod_module_get_name(mod));
break;
case KMOD_MODULE_LIVE:
tcmu_dbg("Module '%s' is already loaded\n",
kmod_module_get_name(mod));
break;
default:
err = kmod_module_probe_insert_module(mod,
KMOD_PROBE_APPLY_BLACKLIST,
NULL, NULL, NULL, NULL);
if (err == 0) {
tcmu_info("Inserted module '%s'\n",
kmod_module_get_name(mod));
} else if (err == KMOD_PROBE_APPLY_BLACKLIST) {
tcmu_err("Module '%s' is blacklisted\n",
kmod_module_get_name(mod));
} else {
tcmu_err("Failed to insert '%s'\n",
kmod_module_get_name(mod));
}
ret = err;
}
kmod_module_unref(mod);
}
kmod_module_unref_list(list);
kmod_unref(ctx);
return ret;
}
static void cmdproc_thread_cleanup(void *arg)
{
struct tcmu_device *dev = arg;
struct tcmur_handler *rhandler = tcmu_get_runner_handler(dev);
rhandler->close(dev);
}
static void *tcmur_cmdproc_thread(void *arg)
{
struct tcmu_device *dev = arg;
struct tcmur_handler *rhandler = tcmu_get_runner_handler(dev);
struct pollfd pfd;
int ret;
pthread_cleanup_push(cmdproc_thread_cleanup, dev);
while (1) {
int completed = 0;
struct tcmulib_cmd *cmd;
tcmulib_processing_start(dev);
while ((cmd = tcmulib_get_next_command(dev)) != NULL) {
if (tcmu_get_log_level() == TCMU_LOG_DEBUG_SCSI_CMD)
tcmu_cdb_debug_info(cmd);
if (tcmur_handler_is_passthrough_only(rhandler))
ret = tcmur_cmd_passthrough_handler(dev, cmd);
else
ret = tcmur_generic_handle_cmd(dev, cmd);
if (ret == TCMU_NOT_HANDLED)
tcmu_warn("Command 0x%x not supported\n", cmd->cdb[0]);
/*
* command (processing) completion is called in the following
* scenarios:
* - handle_cmd: synchronous handlers
* - generic_handle_cmd: non tcmur handler calls (see generic_cmd())
* and on errors when calling tcmur handler.
*/
if (ret != TCMU_ASYNC_HANDLED) {
completed = 1;
tcmur_command_complete(dev, cmd, ret);
}
}
if (completed)
tcmulib_processing_complete(dev);
pfd.fd = tcmu_get_dev_fd(dev);
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, -1);
if (pfd.revents != POLLIN) {
tcmu_err("poll received unexpected revent: 0x%x\n", pfd.revents);
break;
}
}
tcmu_err("thread terminating, should never happen\n");
pthread_cleanup_pop(1);
return NULL;
}
static int dev_added(struct tcmu_device *dev)
{
struct tcmur_handler *rhandler = tcmu_get_runner_handler(dev);
struct tcmur_device *rdev;
int32_t block_size, max_sectors;
int64_t dev_size;
int ret;
rdev = calloc(1, sizeof(*rdev));
if (!rdev)
return -ENOMEM;
tcmu_set_daemon_dev_private(dev, rdev);
ret = -EINVAL;
block_size = tcmu_get_attribute(dev, "hw_block_size");
if (block_size <= 0) {
tcmu_dev_err(dev, "Could not get hw_block_size\n");
goto free_rdev;
}
tcmu_set_dev_block_size(dev, block_size);
dev_size = tcmu_get_device_size(dev);
if (dev_size < 0) {
tcmu_dev_err(dev, "Could not get device size\n");
goto free_rdev;
}
tcmu_set_dev_num_lbas(dev, dev_size / block_size);
max_sectors = tcmu_get_attribute(dev, "hw_max_sectors");
if (max_sectors < 0)
goto free_rdev;
tcmu_set_dev_max_xfer_len(dev, max_sectors);
tcmu_dev_dbg(dev, "Got block_size %ld, size in bytes %lld\n",
block_size, dev_size);
ret = pthread_spin_init(&rdev->lock, 0);
if (ret != 0)
goto free_rdev;
ret = pthread_mutex_init(&rdev->caw_lock, NULL);
if (ret != 0)
goto cleanup_dev_lock;
ret = pthread_mutex_init(&rdev->format_lock, NULL);
if (ret != 0)
goto cleanup_caw_lock;
ret = setup_io_work_queue(dev);
if (ret < 0)
goto cleanup_format_lock;
ret = setup_aio_tracking(rdev);
if (ret < 0)
goto cleanup_io_work_queue;
ret = rhandler->open(dev);
if (ret)
goto cleanup_aio_tracking;
ret = tcmulib_start_cmdproc_thread(dev, tcmur_cmdproc_thread);
if (ret < 0)
goto close_dev;
return 0;
close_dev:
rhandler->close(dev);
cleanup_aio_tracking:
cleanup_aio_tracking(rdev);
cleanup_io_work_queue:
cleanup_io_work_queue(dev, true);
cleanup_format_lock:
pthread_mutex_destroy(&rdev->format_lock);
cleanup_caw_lock:
pthread_mutex_destroy(&rdev->caw_lock);
cleanup_dev_lock:
pthread_spin_destroy(&rdev->lock);
free_rdev:
free(rdev);
return ret;
}
static void dev_removed(struct tcmu_device *dev)
{
struct tcmur_device *rdev = tcmu_get_daemon_dev_private(dev);
int ret;
/*
* The order of cleaning up worker threads and calling ->removed()
* is important: for sync handlers, the worker thread needs to be
* terminated before removing the handler (i.e., calling handlers
* ->close() callout) in order to ensure that no handler callouts
* are getting invoked when shutting down the handler.
*/
cleanup_io_work_queue_threads(dev);
tcmulib_cleanup_cmdproc_thread(dev);
cleanup_io_work_queue(dev, false);
cleanup_aio_tracking(rdev);
ret = pthread_mutex_destroy(&rdev->format_lock);
if (ret != 0)
tcmu_err("could not cleanup format lock %d\n", ret);
ret = pthread_mutex_destroy(&rdev->caw_lock);
if (ret != 0)
tcmu_err("could not cleanup caw lock %d\n", ret);
ret = pthread_spin_destroy(&rdev->lock);
if (ret != 0)
tcmu_err("could not cleanup mailbox lock %d\n", ret);
free(rdev);
}
static bool tcmu_logdir_create(const char *path)
{
DIR* dir = opendir(path);
if (dir) {
closedir(dir);
} else if (errno == ENOENT) {
if (mkdir(path, 0755) == -1) {
tcmu_err("mkdir(%s) failed: %m\n", path);
return FALSE;
}
} else {
tcmu_err("opendir(%s) failed: %m\n", path);
return FALSE;
}
return TRUE;
}
static void usage(void) {
printf("\nusage:\n");
printf("\ttcmu-runner [options]\n");
printf("\noptions:\n");
printf("\t-h, --help: print this message and exit\n");
printf("\t-V, --version: print version and exit\n");
printf("\t-d, --debug: enable debug messages\n");
printf("\t--handler-path: set path to search for handler modules\n");
printf("\t\tdefault is %s\n", DEFAULT_HANDLER_PATH);
printf("\t-l, --tcmu-log-dir: tcmu log dir\n");
printf("\t\tdefault is %s\n", TCMU_LOG_DIR_DEFAULT);
printf("\n");
}
static struct option long_options[] = {
{"debug", no_argument, 0, 'd'},
{"handler-path", required_argument, 0, 0},
{"tcmu-log-dir", required_argument, 0, 'l'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{0, 0, 0, 0},
};
int main(int argc, char **argv)
{
darray(struct tcmulib_handler) handlers = darray_new();
struct tcmulib_context *tcmulib_context;
struct tcmur_handler **tmp_r_handler;
GMainLoop *loop;
GIOChannel *libtcmu_gio;
guint reg_id;
int ret;
tcmu_cfg = tcmu_config_new();
if (!tcmu_cfg)
exit(1);
ret = tcmu_load_config(tcmu_cfg, NULL);
if (ret == -1)
goto err_out;
while (1) {
int option_index = 0;
int c;
c = getopt_long(argc, argv, "dhlV",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
if (option_index == 1)
handler_path = strdup(optarg);
break;
case 'l':
if (strlen(optarg) > PATH_MAX - TCMU_LOG_FILENAME_MAX) {
tcmu_err("--tcmu-log-dir='%s' cannot exceed %d characters\n",
optarg, PATH_MAX - TCMU_LOG_FILENAME_MAX);
}
if (!tcmu_logdir_create(optarg)) {
goto err_out;
}
tcmu_log_dir = strdup(optarg);
break;
case 'd':
tcmu_set_log_level(TCMU_CONF_LOG_DEBUG_SCSI_CMD);
break;
case 'V':
printf("tcmu-runner %s\n", TCMUR_VERSION);
goto err_out;
default:
case 'h':
usage();
goto err_out;
}
}
tcmu_dbg("handler path: %s\n", handler_path);
ret = load_our_module();
if (ret < 0) {
tcmu_err("couldn't load module\n");
goto err_out;
}
ret = open_handlers();
if (ret < 0) {
tcmu_err("couldn't open handlers\n");
goto err_out;
}
tcmu_dbg("%d runner handlers found\n", ret);
/*
* Convert from tcmu-runner's handler struct to libtcmu's
* handler struct, an array of which we pass in, below.
*/
darray_foreach(tmp_r_handler, g_runner_handlers) {
struct tcmulib_handler tmp_handler;
tmp_handler.name = (*tmp_r_handler)->name;
tmp_handler.subtype = (*tmp_r_handler)->subtype;
tmp_handler.cfg_desc = (*tmp_r_handler)->cfg_desc;
tmp_handler.check_config = (*tmp_r_handler)->check_config;
tmp_handler.reconfig = (*tmp_r_handler)->reconfig;
tmp_handler.added = dev_added;
tmp_handler.removed = dev_removed;
/*
* Can hand out a ref to an internal pointer to the
* darray b/c handlers will never be added or removed
* once open_handlers() is done.
*/
tmp_handler.hm_private = *tmp_r_handler;
darray_append(handlers, tmp_handler);
}
tcmulib_context = tcmulib_initialize(handlers.item, handlers.size);
if (!tcmulib_context) {
tcmu_err("tcmulib_initialize failed\n");
goto err_out;
}
loop = g_main_loop_new(NULL, FALSE);
if (g_unix_signal_add(SIGINT, sighandler, loop) <= 0 ||
g_unix_signal_add(SIGTERM, sighandler, loop) <= 0) {
tcmu_err("couldn't setup signal handlers\n");
goto err_tcmulib_close;
}
/* Set up event for libtcmu */
libtcmu_gio = g_io_channel_unix_new(tcmulib_get_master_fd(tcmulib_context));
g_io_add_watch(libtcmu_gio, G_IO_IN, tcmulib_callback, tcmulib_context);
/* Set up DBus name, see callback */
reg_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
"org.kernel.TCMUService1",
G_BUS_NAME_OWNER_FLAGS_NONE,
dbus_bus_acquired,
dbus_name_acquired, // name acquired
dbus_name_lost, // name lost
NULL, // user data
NULL // user date free func
);
g_main_loop_run(loop);
tcmu_dbg("Exiting...\n");
g_bus_unown_name(reg_id);
g_main_loop_unref(loop);
tcmulib_close(tcmulib_context);
tcmu_config_destroy(tcmu_cfg);
return 0;
err_tcmulib_close:
tcmulib_close(tcmulib_context);
err_out:
tcmu_config_destroy(tcmu_cfg);
exit(1);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2513_0 |
crossvul-cpp_data_bad_2221_0 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* This module provides the abstraction for an SCTP association.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation 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 GNU CC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <linux-sctp@vger.kernel.org>
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Jon Grimm <jgrimm@us.ibm.com>
* Xingang Guo <xingang.guo@intel.com>
* Hui Huang <hui.huang@nokia.com>
* Sridhar Samudrala <sri@us.ibm.com>
* Daisy Chang <daisyc@us.ibm.com>
* Ryan Layer <rmlayer@us.ibm.com>
* Kevin Gao <kevin.gao@intel.com>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <net/ipv6.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal functions. */
static void sctp_select_active_and_retran_path(struct sctp_association *asoc);
static void sctp_assoc_bh_rcv(struct work_struct *work);
static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc);
static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc);
/* 1st Level Abstractions. */
/* Initialize a new association from provided memory. */
static struct sctp_association *sctp_association_init(struct sctp_association *asoc,
const struct sctp_endpoint *ep,
const struct sock *sk,
sctp_scope_t scope,
gfp_t gfp)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
int i;
sctp_paramhdr_t *p;
int err;
/* Retrieve the SCTP per socket area. */
sp = sctp_sk((struct sock *)sk);
/* Discarding const is appropriate here. */
asoc->ep = (struct sctp_endpoint *)ep;
asoc->base.sk = (struct sock *)sk;
sctp_endpoint_hold(asoc->ep);
sock_hold(asoc->base.sk);
/* Initialize the common base substructure. */
asoc->base.type = SCTP_EP_TYPE_ASSOCIATION;
/* Initialize the object handling fields. */
atomic_set(&asoc->base.refcnt, 1);
/* Initialize the bind addr area. */
sctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port);
asoc->state = SCTP_STATE_CLOSED;
asoc->cookie_life = ms_to_ktime(sp->assocparams.sasoc_cookie_life);
asoc->user_frag = sp->user_frag;
/* Set the association max_retrans and RTO values from the
* socket values.
*/
asoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt;
asoc->pf_retrans = net->sctp.pf_retrans;
asoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial);
asoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max);
asoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min);
/* Initialize the association's heartbeat interval based on the
* sock configured value.
*/
asoc->hbinterval = msecs_to_jiffies(sp->hbinterval);
/* Initialize path max retrans value. */
asoc->pathmaxrxt = sp->pathmaxrxt;
/* Initialize default path MTU. */
asoc->pathmtu = sp->pathmtu;
/* Set association default SACK delay */
asoc->sackdelay = msecs_to_jiffies(sp->sackdelay);
asoc->sackfreq = sp->sackfreq;
/* Set the association default flags controlling
* Heartbeat, SACK delay, and Path MTU Discovery.
*/
asoc->param_flags = sp->param_flags;
/* Initialize the maximum number of new data packets that can be sent
* in a burst.
*/
asoc->max_burst = sp->max_burst;
/* initialize association timers */
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial;
/* sctpimpguide Section 2.12.2
* If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the
* recommended value of 5 times 'RTO.Max'.
*/
asoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]
= 5 * asoc->rto_max;
asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay;
asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = sp->autoclose * HZ;
/* Initializes the timers */
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i)
setup_timer(&asoc->timers[i], sctp_timer_events[i],
(unsigned long)asoc);
/* Pull default initialization values from the sock options.
* Note: This assumes that the values have already been
* validated in the sock.
*/
asoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams;
asoc->c.sinit_num_ostreams = sp->initmsg.sinit_num_ostreams;
asoc->max_init_attempts = sp->initmsg.sinit_max_attempts;
asoc->max_init_timeo =
msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo);
/* Set the local window size for receive.
* This is also the rcvbuf space per association.
* RFC 6 - A SCTP receiver MUST be able to receive a minimum of
* 1500 bytes in one SCTP packet.
*/
if ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW)
asoc->rwnd = SCTP_DEFAULT_MINWINDOW;
else
asoc->rwnd = sk->sk_rcvbuf/2;
asoc->a_rwnd = asoc->rwnd;
/* Use my own max window until I learn something better. */
asoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW;
/* Initialize the receive memory counter */
atomic_set(&asoc->rmem_alloc, 0);
init_waitqueue_head(&asoc->wait);
asoc->c.my_vtag = sctp_generate_tag(ep);
asoc->c.my_port = ep->base.bind_addr.port;
asoc->c.initial_tsn = sctp_generate_tsn(ep);
asoc->next_tsn = asoc->c.initial_tsn;
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
asoc->highest_sacked = asoc->ctsn_ack_point;
asoc->last_cwr_tsn = asoc->ctsn_ack_point;
/* ADDIP Section 4.1 Asconf Chunk Procedures
*
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do the following:
* ...
* A2) a serial number should be assigned to the chunk. The serial
* number SHOULD be a monotonically increasing number. The serial
* numbers SHOULD be initialized at the start of the
* association to the same value as the initial TSN.
*/
asoc->addip_serial = asoc->c.initial_tsn;
INIT_LIST_HEAD(&asoc->addip_chunk_list);
INIT_LIST_HEAD(&asoc->asconf_ack_list);
/* Make an empty list of remote transport addresses. */
INIT_LIST_HEAD(&asoc->peer.transport_addr_list);
/* RFC 2960 5.1 Normal Establishment of an Association
*
* After the reception of the first data chunk in an
* association the endpoint must immediately respond with a
* sack to acknowledge the data chunk. Subsequent
* acknowledgements should be done as described in Section
* 6.2.
*
* [We implement this by telling a new association that it
* already received one packet.]
*/
asoc->peer.sack_needed = 1;
asoc->peer.sack_generation = 1;
/* Assume that the peer will tell us if he recognizes ASCONF
* as part of INIT exchange.
* The sctp_addip_noauth option is there for backward compatibility
* and will revert old behavior.
*/
if (net->sctp.addip_noauth)
asoc->peer.asconf_capable = 1;
/* Create an input queue. */
sctp_inq_init(&asoc->base.inqueue);
sctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv);
/* Create an output queue. */
sctp_outq_init(asoc, &asoc->outqueue);
if (!sctp_ulpq_init(&asoc->ulpq, asoc))
goto fail_init;
/* Assume that peer would support both address types unless we are
* told otherwise.
*/
asoc->peer.ipv4_address = 1;
if (asoc->base.sk->sk_family == PF_INET6)
asoc->peer.ipv6_address = 1;
INIT_LIST_HEAD(&asoc->asocs);
asoc->default_stream = sp->default_stream;
asoc->default_ppid = sp->default_ppid;
asoc->default_flags = sp->default_flags;
asoc->default_context = sp->default_context;
asoc->default_timetolive = sp->default_timetolive;
asoc->default_rcv_context = sp->default_rcv_context;
/* AUTH related initializations */
INIT_LIST_HEAD(&asoc->endpoint_shared_keys);
err = sctp_auth_asoc_copy_shkeys(ep, asoc, gfp);
if (err)
goto fail_init;
asoc->active_key_id = ep->active_key_id;
/* Save the hmacs and chunks list into this association */
if (ep->auth_hmacs_list)
memcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list,
ntohs(ep->auth_hmacs_list->param_hdr.length));
if (ep->auth_chunk_list)
memcpy(asoc->c.auth_chunks, ep->auth_chunk_list,
ntohs(ep->auth_chunk_list->param_hdr.length));
/* Get the AUTH random number for this association */
p = (sctp_paramhdr_t *)asoc->c.auth_random;
p->type = SCTP_PARAM_RANDOM;
p->length = htons(sizeof(sctp_paramhdr_t) + SCTP_AUTH_RANDOM_LENGTH);
get_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH);
return asoc;
fail_init:
sock_put(asoc->base.sk);
sctp_endpoint_put(asoc->ep);
return NULL;
}
/* Allocate and initialize a new association */
struct sctp_association *sctp_association_new(const struct sctp_endpoint *ep,
const struct sock *sk,
sctp_scope_t scope,
gfp_t gfp)
{
struct sctp_association *asoc;
asoc = kzalloc(sizeof(*asoc), gfp);
if (!asoc)
goto fail;
if (!sctp_association_init(asoc, ep, sk, scope, gfp))
goto fail_init;
SCTP_DBG_OBJCNT_INC(assoc);
pr_debug("Created asoc %p\n", asoc);
return asoc;
fail_init:
kfree(asoc);
fail:
return NULL;
}
/* Free this association if possible. There may still be users, so
* the actual deallocation may be delayed.
*/
void sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!asoc->temp) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk->sk_ack_backlog--;
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = true;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free ssnmap storage. */
sctp_ssnmap_free(asoc->ssnmap);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
if (asoc->asconf_addr_del_pending != NULL)
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
/* Cleanup and free up an association. */
static void sctp_association_destroy(struct sctp_association *asoc)
{
if (unlikely(!asoc->base.dead)) {
WARN(1, "Attempt to destroy undead association %p!\n", asoc);
return;
}
sctp_endpoint_put(asoc->ep);
sock_put(asoc->base.sk);
if (asoc->assoc_id != 0) {
spin_lock_bh(&sctp_assocs_id_lock);
idr_remove(&sctp_assocs_id, asoc->assoc_id);
spin_unlock_bh(&sctp_assocs_id_lock);
}
WARN_ON(atomic_read(&asoc->rmem_alloc));
kfree(asoc);
SCTP_DBG_OBJCNT_DEC(assoc);
}
/* Change the primary destination address for the peer. */
void sctp_assoc_set_primary(struct sctp_association *asoc,
struct sctp_transport *transport)
{
int changeover = 0;
/* it's a changeover only if we already have a primary path
* that we are changing
*/
if (asoc->peer.primary_path != NULL &&
asoc->peer.primary_path != transport)
changeover = 1 ;
asoc->peer.primary_path = transport;
/* Set a default msg_name for events. */
memcpy(&asoc->peer.primary_addr, &transport->ipaddr,
sizeof(union sctp_addr));
/* If the primary path is changing, assume that the
* user wants to use this new path.
*/
if ((transport->state == SCTP_ACTIVE) ||
(transport->state == SCTP_UNKNOWN))
asoc->peer.active_path = transport;
/*
* SFR-CACC algorithm:
* Upon the receipt of a request to change the primary
* destination address, on the data structure for the new
* primary destination, the sender MUST do the following:
*
* 1) If CHANGEOVER_ACTIVE is set, then there was a switch
* to this destination address earlier. The sender MUST set
* CYCLING_CHANGEOVER to indicate that this switch is a
* double switch to the same destination address.
*
* Really, only bother is we have data queued or outstanding on
* the association.
*/
if (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen)
return;
if (transport->cacc.changeover_active)
transport->cacc.cycling_changeover = changeover;
/* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that
* a changeover has occurred.
*/
transport->cacc.changeover_active = changeover;
/* 3) The sender MUST store the next TSN to be sent in
* next_tsn_at_change.
*/
transport->cacc.next_tsn_at_change = asoc->next_tsn;
}
/* Remove a transport from an association. */
void sctp_assoc_rm_peer(struct sctp_association *asoc,
struct sctp_transport *peer)
{
struct list_head *pos;
struct sctp_transport *transport;
pr_debug("%s: association:%p addr:%pISpc\n",
__func__, asoc, &peer->ipaddr.sa);
/* If we are to remove the current retran_path, update it
* to the next peer before removing this peer from the list.
*/
if (asoc->peer.retran_path == peer)
sctp_assoc_update_retran_path(asoc);
/* Remove this peer from the list. */
list_del_rcu(&peer->transports);
/* Get the first transport of asoc. */
pos = asoc->peer.transport_addr_list.next;
transport = list_entry(pos, struct sctp_transport, transports);
/* Update any entries that match the peer to be deleted. */
if (asoc->peer.primary_path == peer)
sctp_assoc_set_primary(asoc, transport);
if (asoc->peer.active_path == peer)
asoc->peer.active_path = transport;
if (asoc->peer.retran_path == peer)
asoc->peer.retran_path = transport;
if (asoc->peer.last_data_from == peer)
asoc->peer.last_data_from = transport;
/* If we remove the transport an INIT was last sent to, set it to
* NULL. Combined with the update of the retran path above, this
* will cause the next INIT to be sent to the next available
* transport, maintaining the cycle.
*/
if (asoc->init_last_sent_to == peer)
asoc->init_last_sent_to = NULL;
/* If we remove the transport an SHUTDOWN was last sent to, set it
* to NULL. Combined with the update of the retran path above, this
* will cause the next SHUTDOWN to be sent to the next available
* transport, maintaining the cycle.
*/
if (asoc->shutdown_last_sent_to == peer)
asoc->shutdown_last_sent_to = NULL;
/* If we remove the transport an ASCONF was last sent to, set it to
* NULL.
*/
if (asoc->addip_last_asconf &&
asoc->addip_last_asconf->transport == peer)
asoc->addip_last_asconf->transport = NULL;
/* If we have something on the transmitted list, we have to
* save it off. The best place is the active path.
*/
if (!list_empty(&peer->transmitted)) {
struct sctp_transport *active = asoc->peer.active_path;
struct sctp_chunk *ch;
/* Reset the transport of each chunk on this list */
list_for_each_entry(ch, &peer->transmitted,
transmitted_list) {
ch->transport = NULL;
ch->rtt_in_progress = 0;
}
list_splice_tail_init(&peer->transmitted,
&active->transmitted);
/* Start a T3 timer here in case it wasn't running so
* that these migrated packets have a chance to get
* retransmitted.
*/
if (!timer_pending(&active->T3_rtx_timer))
if (!mod_timer(&active->T3_rtx_timer,
jiffies + active->rto))
sctp_transport_hold(active);
}
asoc->peer.transport_count--;
sctp_transport_free(peer);
}
/* Add a transport address to an association. */
struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc,
const union sctp_addr *addr,
const gfp_t gfp,
const int peer_state)
{
struct net *net = sock_net(asoc->base.sk);
struct sctp_transport *peer;
struct sctp_sock *sp;
unsigned short port;
sp = sctp_sk(asoc->base.sk);
/* AF_INET and AF_INET6 share common port field. */
port = ntohs(addr->v4.sin_port);
pr_debug("%s: association:%p addr:%pISpc state:%d\n", __func__,
asoc, &addr->sa, peer_state);
/* Set the port if it has not been set yet. */
if (0 == asoc->peer.port)
asoc->peer.port = port;
/* Check to see if this is a duplicate. */
peer = sctp_assoc_lookup_paddr(asoc, addr);
if (peer) {
/* An UNKNOWN state is only set on transports added by
* user in sctp_connectx() call. Such transports should be
* considered CONFIRMED per RFC 4960, Section 5.4.
*/
if (peer->state == SCTP_UNKNOWN) {
peer->state = SCTP_ACTIVE;
}
return peer;
}
peer = sctp_transport_new(net, addr, gfp);
if (!peer)
return NULL;
sctp_transport_set_owner(peer, asoc);
/* Initialize the peer's heartbeat interval based on the
* association configured value.
*/
peer->hbinterval = asoc->hbinterval;
/* Set the path max_retrans. */
peer->pathmaxrxt = asoc->pathmaxrxt;
/* And the partial failure retrans threshold */
peer->pf_retrans = asoc->pf_retrans;
/* Initialize the peer's SACK delay timeout based on the
* association configured value.
*/
peer->sackdelay = asoc->sackdelay;
peer->sackfreq = asoc->sackfreq;
/* Enable/disable heartbeat, SACK delay, and path MTU discovery
* based on association setting.
*/
peer->param_flags = asoc->param_flags;
sctp_transport_route(peer, NULL, sp);
/* Initialize the pmtu of the transport. */
if (peer->param_flags & SPP_PMTUD_DISABLE) {
if (asoc->pathmtu)
peer->pathmtu = asoc->pathmtu;
else
peer->pathmtu = SCTP_DEFAULT_MAXSEGMENT;
}
/* If this is the first transport addr on this association,
* initialize the association PMTU to the peer's PMTU.
* If not and the current association PMTU is higher than the new
* peer's PMTU, reset the association PMTU to the new peer's PMTU.
*/
if (asoc->pathmtu)
asoc->pathmtu = min_t(int, peer->pathmtu, asoc->pathmtu);
else
asoc->pathmtu = peer->pathmtu;
pr_debug("%s: association:%p PMTU set to %d\n", __func__, asoc,
asoc->pathmtu);
peer->pmtu_pending = 0;
asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
/* The asoc->peer.port might not be meaningful yet, but
* initialize the packet structure anyway.
*/
sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port,
asoc->peer.port);
/* 7.2.1 Slow-Start
*
* o The initial cwnd before DATA transmission or after a sufficiently
* long idle period MUST be set to
* min(4*MTU, max(2*MTU, 4380 bytes))
*
* o The initial value of ssthresh MAY be arbitrarily high
* (for example, implementations MAY use the size of the
* receiver advertised window).
*/
peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380));
/* At this point, we may not have the receiver's advertised window,
* so initialize ssthresh to the default value and it will be set
* later when we process the INIT.
*/
peer->ssthresh = SCTP_DEFAULT_MAXWINDOW;
peer->partial_bytes_acked = 0;
peer->flight_size = 0;
peer->burst_limited = 0;
/* Set the transport's RTO.initial value */
peer->rto = asoc->rto_initial;
sctp_max_rto(asoc, peer);
/* Set the peer's active state. */
peer->state = peer_state;
/* Attach the remote transport to our asoc. */
list_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list);
asoc->peer.transport_count++;
/* If we do not yet have a primary path, set one. */
if (!asoc->peer.primary_path) {
sctp_assoc_set_primary(asoc, peer);
asoc->peer.retran_path = peer;
}
if (asoc->peer.active_path == asoc->peer.retran_path &&
peer->state != SCTP_UNCONFIRMED) {
asoc->peer.retran_path = peer;
}
return peer;
}
/* Delete a transport address from an association. */
void sctp_assoc_del_peer(struct sctp_association *asoc,
const union sctp_addr *addr)
{
struct list_head *pos;
struct list_head *temp;
struct sctp_transport *transport;
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (sctp_cmp_addr_exact(addr, &transport->ipaddr)) {
/* Do book keeping for removing the peer and free it. */
sctp_assoc_rm_peer(asoc, transport);
break;
}
}
}
/* Lookup a transport by address. */
struct sctp_transport *sctp_assoc_lookup_paddr(
const struct sctp_association *asoc,
const union sctp_addr *address)
{
struct sctp_transport *t;
/* Cycle through all transports searching for a peer address. */
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (sctp_cmp_addr_exact(address, &t->ipaddr))
return t;
}
return NULL;
}
/* Remove all transports except a give one */
void sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc,
struct sctp_transport *primary)
{
struct sctp_transport *temp;
struct sctp_transport *t;
list_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list,
transports) {
/* if the current transport is not the primary one, delete it */
if (t != primary)
sctp_assoc_rm_peer(asoc, t);
}
}
/* Engage in transport control operations.
* Mark the transport up or down and send a notification to the user.
* Select and update the new active and retran paths.
*/
void sctp_assoc_control_transport(struct sctp_association *asoc,
struct sctp_transport *transport,
sctp_transport_cmd_t command,
sctp_sn_error_t error)
{
struct sctp_ulpevent *event;
struct sockaddr_storage addr;
int spc_state = 0;
bool ulp_notify = true;
/* Record the transition on the transport. */
switch (command) {
case SCTP_TRANSPORT_UP:
/* If we are moving from UNCONFIRMED state due
* to heartbeat success, report the SCTP_ADDR_CONFIRMED
* state to the user, otherwise report SCTP_ADDR_AVAILABLE.
*/
if (SCTP_UNCONFIRMED == transport->state &&
SCTP_HEARTBEAT_SUCCESS == error)
spc_state = SCTP_ADDR_CONFIRMED;
else
spc_state = SCTP_ADDR_AVAILABLE;
/* Don't inform ULP about transition from PF to
* active state and set cwnd to 1 MTU, see SCTP
* Quick failover draft section 5.1, point 5
*/
if (transport->state == SCTP_PF) {
ulp_notify = false;
transport->cwnd = asoc->pathmtu;
}
transport->state = SCTP_ACTIVE;
break;
case SCTP_TRANSPORT_DOWN:
/* If the transport was never confirmed, do not transition it
* to inactive state. Also, release the cached route since
* there may be a better route next time.
*/
if (transport->state != SCTP_UNCONFIRMED)
transport->state = SCTP_INACTIVE;
else {
dst_release(transport->dst);
transport->dst = NULL;
}
spc_state = SCTP_ADDR_UNREACHABLE;
break;
case SCTP_TRANSPORT_PF:
transport->state = SCTP_PF;
ulp_notify = false;
break;
default:
return;
}
/* Generate and send a SCTP_PEER_ADDR_CHANGE notification
* to the user.
*/
if (ulp_notify) {
memset(&addr, 0, sizeof(struct sockaddr_storage));
memcpy(&addr, &transport->ipaddr,
transport->af_specific->sockaddr_len);
event = sctp_ulpevent_make_peer_addr_change(asoc, &addr,
0, spc_state, error, GFP_ATOMIC);
if (event)
sctp_ulpq_tail_event(&asoc->ulpq, event);
}
/* Select new active and retran paths. */
sctp_select_active_and_retran_path(asoc);
}
/* Hold a reference to an association. */
void sctp_association_hold(struct sctp_association *asoc)
{
atomic_inc(&asoc->base.refcnt);
}
/* Release a reference to an association and cleanup
* if there are no more references.
*/
void sctp_association_put(struct sctp_association *asoc)
{
if (atomic_dec_and_test(&asoc->base.refcnt))
sctp_association_destroy(asoc);
}
/* Allocate the next TSN, Transmission Sequence Number, for the given
* association.
*/
__u32 sctp_association_get_next_tsn(struct sctp_association *asoc)
{
/* From Section 1.6 Serial Number Arithmetic:
* Transmission Sequence Numbers wrap around when they reach
* 2**32 - 1. That is, the next TSN a DATA chunk MUST use
* after transmitting TSN = 2*32 - 1 is TSN = 0.
*/
__u32 retval = asoc->next_tsn;
asoc->next_tsn++;
asoc->unack_data++;
return retval;
}
/* Compare two addresses to see if they match. Wildcard addresses
* only match themselves.
*/
int sctp_cmp_addr_exact(const union sctp_addr *ss1,
const union sctp_addr *ss2)
{
struct sctp_af *af;
af = sctp_get_af_specific(ss1->sa.sa_family);
if (unlikely(!af))
return 0;
return af->cmp_addr(ss1, ss2);
}
/* Return an ecne chunk to get prepended to a packet.
* Note: We are sly and return a shared, prealloced chunk. FIXME:
* No we don't, but we could/should.
*/
struct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc)
{
if (!asoc->need_ecne)
return NULL;
/* Send ECNE if needed.
* Not being able to allocate a chunk here is not deadly.
*/
return sctp_make_ecne(asoc, asoc->last_ecne_tsn);
}
/*
* Find which transport this TSN was sent on.
*/
struct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc,
__u32 tsn)
{
struct sctp_transport *active;
struct sctp_transport *match;
struct sctp_transport *transport;
struct sctp_chunk *chunk;
__be32 key = htonl(tsn);
match = NULL;
/*
* FIXME: In general, find a more efficient data structure for
* searching.
*/
/*
* The general strategy is to search each transport's transmitted
* list. Return which transport this TSN lives on.
*
* Let's be hopeful and check the active_path first.
* Another optimization would be to know if there is only one
* outbound path and not have to look for the TSN at all.
*
*/
active = asoc->peer.active_path;
list_for_each_entry(chunk, &active->transmitted,
transmitted_list) {
if (key == chunk->subh.data_hdr->tsn) {
match = active;
goto out;
}
}
/* If not found, go search all the other transports. */
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
if (transport == active)
continue;
list_for_each_entry(chunk, &transport->transmitted,
transmitted_list) {
if (key == chunk->subh.data_hdr->tsn) {
match = transport;
goto out;
}
}
}
out:
return match;
}
/* Is this the association we are looking for? */
struct sctp_transport *sctp_assoc_is_match(struct sctp_association *asoc,
struct net *net,
const union sctp_addr *laddr,
const union sctp_addr *paddr)
{
struct sctp_transport *transport;
if ((htons(asoc->base.bind_addr.port) == laddr->v4.sin_port) &&
(htons(asoc->peer.port) == paddr->v4.sin_port) &&
net_eq(sock_net(asoc->base.sk), net)) {
transport = sctp_assoc_lookup_paddr(asoc, paddr);
if (!transport)
goto out;
if (sctp_bind_addr_match(&asoc->base.bind_addr, laddr,
sctp_sk(asoc->base.sk)))
goto out;
}
transport = NULL;
out:
return transport;
}
/* Do delayed input processing. This is scheduled by sctp_rcv(). */
static void sctp_assoc_bh_rcv(struct work_struct *work)
{
struct sctp_association *asoc =
container_of(work, struct sctp_association,
base.inqueue.immediate);
struct net *net = sock_net(asoc->base.sk);
struct sctp_endpoint *ep;
struct sctp_chunk *chunk;
struct sctp_inq *inqueue;
int state;
sctp_subtype_t subtype;
int error = 0;
/* The association should be held so we should be safe. */
ep = asoc->ep;
inqueue = &asoc->base.inqueue;
sctp_association_hold(asoc);
while (NULL != (chunk = sctp_inq_pop(inqueue))) {
state = asoc->state;
subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type);
/* SCTP-AUTH, Section 6.3:
* The receiver has a list of chunk types which it expects
* to be received only after an AUTH-chunk. This list has
* been sent to the peer during the association setup. It
* MUST silently discard these chunks if they are not placed
* after an AUTH chunk in the packet.
*/
if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth)
continue;
/* Remember where the last DATA chunk came from so we
* know where to send the SACK.
*/
if (sctp_chunk_is_data(chunk))
asoc->peer.last_data_from = chunk->transport;
else {
SCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS);
asoc->stats.ictrlchunks++;
if (chunk->chunk_hdr->type == SCTP_CID_SACK)
asoc->stats.isacks++;
}
if (chunk->transport)
chunk->transport->last_time_heard = ktime_get();
/* Run through the state machine. */
error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype,
state, ep, asoc, chunk, GFP_ATOMIC);
/* Check to see if the association is freed in response to
* the incoming chunk. If so, get out of the while loop.
*/
if (asoc->base.dead)
break;
/* If there is an error on chunk, discard this packet. */
if (error && chunk)
chunk->pdiscard = 1;
}
sctp_association_put(asoc);
}
/* This routine moves an association from its old sk to a new sk. */
void sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk)
{
struct sctp_sock *newsp = sctp_sk(newsk);
struct sock *oldsk = assoc->base.sk;
/* Delete the association from the old endpoint's list of
* associations.
*/
list_del_init(&assoc->asocs);
/* Decrement the backlog value for a TCP-style socket. */
if (sctp_style(oldsk, TCP))
oldsk->sk_ack_backlog--;
/* Release references to the old endpoint and the sock. */
sctp_endpoint_put(assoc->ep);
sock_put(assoc->base.sk);
/* Get a reference to the new endpoint. */
assoc->ep = newsp->ep;
sctp_endpoint_hold(assoc->ep);
/* Get a reference to the new sock. */
assoc->base.sk = newsk;
sock_hold(assoc->base.sk);
/* Add the association to the new endpoint's list of associations. */
sctp_endpoint_add_asoc(newsp->ep, assoc);
}
/* Update an association (possibly from unexpected COOKIE-ECHO processing). */
void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
/* Update the retran path for sending a retransmitted packet.
* See also RFC4960, 6.4. Multi-Homed SCTP Endpoints:
*
* When there is outbound data to send and the primary path
* becomes inactive (e.g., due to failures), or where the
* SCTP user explicitly requests to send data to an
* inactive destination transport address, before reporting
* an error to its ULP, the SCTP endpoint should try to send
* the data to an alternate active destination transport
* address if one exists.
*
* When retransmitting data that timed out, if the endpoint
* is multihomed, it should consider each source-destination
* address pair in its retransmission selection policy.
* When retransmitting timed-out data, the endpoint should
* attempt to pick the most divergent source-destination
* pair from the original source-destination pair to which
* the packet was transmitted.
*
* Note: Rules for picking the most divergent source-destination
* pair are an implementation decision and are not specified
* within this document.
*
* Our basic strategy is to round-robin transports in priorities
* according to sctp_state_prio_map[] e.g., if no such
* transport with state SCTP_ACTIVE exists, round-robin through
* SCTP_UNKNOWN, etc. You get the picture.
*/
static const u8 sctp_trans_state_to_prio_map[] = {
[SCTP_ACTIVE] = 3, /* best case */
[SCTP_UNKNOWN] = 2,
[SCTP_PF] = 1,
[SCTP_INACTIVE] = 0, /* worst case */
};
static u8 sctp_trans_score(const struct sctp_transport *trans)
{
return sctp_trans_state_to_prio_map[trans->state];
}
static struct sctp_transport *sctp_trans_elect_tie(struct sctp_transport *trans1,
struct sctp_transport *trans2)
{
if (trans1->error_count > trans2->error_count) {
return trans2;
} else if (trans1->error_count == trans2->error_count &&
ktime_after(trans2->last_time_heard,
trans1->last_time_heard)) {
return trans2;
} else {
return trans1;
}
}
static struct sctp_transport *sctp_trans_elect_best(struct sctp_transport *curr,
struct sctp_transport *best)
{
u8 score_curr, score_best;
if (best == NULL)
return curr;
score_curr = sctp_trans_score(curr);
score_best = sctp_trans_score(best);
/* First, try a score-based selection if both transport states
* differ. If we're in a tie, lets try to make a more clever
* decision here based on error counts and last time heard.
*/
if (score_curr > score_best)
return curr;
else if (score_curr == score_best)
return sctp_trans_elect_tie(curr, best);
else
return best;
}
void sctp_assoc_update_retran_path(struct sctp_association *asoc)
{
struct sctp_transport *trans = asoc->peer.retran_path;
struct sctp_transport *trans_next = NULL;
/* We're done as we only have the one and only path. */
if (asoc->peer.transport_count == 1)
return;
/* If active_path and retran_path are the same and active,
* then this is the only active path. Use it.
*/
if (asoc->peer.active_path == asoc->peer.retran_path &&
asoc->peer.active_path->state == SCTP_ACTIVE)
return;
/* Iterate from retran_path's successor back to retran_path. */
for (trans = list_next_entry(trans, transports); 1;
trans = list_next_entry(trans, transports)) {
/* Manually skip the head element. */
if (&trans->transports == &asoc->peer.transport_addr_list)
continue;
if (trans->state == SCTP_UNCONFIRMED)
continue;
trans_next = sctp_trans_elect_best(trans, trans_next);
/* Active is good enough for immediate return. */
if (trans_next->state == SCTP_ACTIVE)
break;
/* We've reached the end, time to update path. */
if (trans == asoc->peer.retran_path)
break;
}
asoc->peer.retran_path = trans_next;
pr_debug("%s: association:%p updated new path to addr:%pISpc\n",
__func__, asoc, &asoc->peer.retran_path->ipaddr.sa);
}
static void sctp_select_active_and_retran_path(struct sctp_association *asoc)
{
struct sctp_transport *trans, *trans_pri = NULL, *trans_sec = NULL;
struct sctp_transport *trans_pf = NULL;
/* Look for the two most recently used active transports. */
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
/* Skip uninteresting transports. */
if (trans->state == SCTP_INACTIVE ||
trans->state == SCTP_UNCONFIRMED)
continue;
/* Keep track of the best PF transport from our
* list in case we don't find an active one.
*/
if (trans->state == SCTP_PF) {
trans_pf = sctp_trans_elect_best(trans, trans_pf);
continue;
}
/* For active transports, pick the most recent ones. */
if (trans_pri == NULL ||
ktime_after(trans->last_time_heard,
trans_pri->last_time_heard)) {
trans_sec = trans_pri;
trans_pri = trans;
} else if (trans_sec == NULL ||
ktime_after(trans->last_time_heard,
trans_sec->last_time_heard)) {
trans_sec = trans;
}
}
/* RFC 2960 6.4 Multi-Homed SCTP Endpoints
*
* By default, an endpoint should always transmit to the primary
* path, unless the SCTP user explicitly specifies the
* destination transport address (and possibly source transport
* address) to use. [If the primary is active but not most recent,
* bump the most recently used transport.]
*/
if ((asoc->peer.primary_path->state == SCTP_ACTIVE ||
asoc->peer.primary_path->state == SCTP_UNKNOWN) &&
asoc->peer.primary_path != trans_pri) {
trans_sec = trans_pri;
trans_pri = asoc->peer.primary_path;
}
/* We did not find anything useful for a possible retransmission
* path; either primary path that we found is the the same as
* the current one, or we didn't generally find an active one.
*/
if (trans_sec == NULL)
trans_sec = trans_pri;
/* If we failed to find a usable transport, just camp on the
* primary or retran, even if they are inactive, if possible
* pick a PF iff it's the better choice.
*/
if (trans_pri == NULL) {
trans_pri = sctp_trans_elect_best(asoc->peer.primary_path,
asoc->peer.retran_path);
trans_pri = sctp_trans_elect_best(trans_pri, trans_pf);
trans_sec = asoc->peer.primary_path;
}
/* Set the active and retran transports. */
asoc->peer.active_path = trans_pri;
asoc->peer.retran_path = trans_sec;
}
struct sctp_transport *
sctp_assoc_choose_alter_transport(struct sctp_association *asoc,
struct sctp_transport *last_sent_to)
{
/* If this is the first time packet is sent, use the active path,
* else use the retran path. If the last packet was sent over the
* retran path, update the retran path and use it.
*/
if (last_sent_to == NULL) {
return asoc->peer.active_path;
} else {
if (last_sent_to == asoc->peer.retran_path)
sctp_assoc_update_retran_path(asoc);
return asoc->peer.retran_path;
}
}
/* Update the association's pmtu and frag_point by going through all the
* transports. This routine is called when a transport's PMTU has changed.
*/
void sctp_assoc_sync_pmtu(struct sock *sk, struct sctp_association *asoc)
{
struct sctp_transport *t;
__u32 pmtu = 0;
if (!asoc)
return;
/* Get the lowest pmtu of all the transports. */
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (t->pmtu_pending && t->dst) {
sctp_transport_update_pmtu(sk, t, dst_mtu(t->dst));
t->pmtu_pending = 0;
}
if (!pmtu || (t->pathmtu < pmtu))
pmtu = t->pathmtu;
}
if (pmtu) {
asoc->pathmtu = pmtu;
asoc->frag_point = sctp_frag_point(asoc, pmtu);
}
pr_debug("%s: asoc:%p, pmtu:%d, frag_point:%d\n", __func__, asoc,
asoc->pathmtu, asoc->frag_point);
}
/* Should we send a SACK to update our peer? */
static inline bool sctp_peer_needs_update(struct sctp_association *asoc)
{
struct net *net = sock_net(asoc->base.sk);
switch (asoc->state) {
case SCTP_STATE_ESTABLISHED:
case SCTP_STATE_SHUTDOWN_PENDING:
case SCTP_STATE_SHUTDOWN_RECEIVED:
case SCTP_STATE_SHUTDOWN_SENT:
if ((asoc->rwnd > asoc->a_rwnd) &&
((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32,
(asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift),
asoc->pathmtu)))
return true;
break;
default:
break;
}
return false;
}
/* Increase asoc's rwnd by len and send any window update SACK if needed. */
void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len)
{
struct sctp_chunk *sack;
struct timer_list *timer;
if (asoc->rwnd_over) {
if (asoc->rwnd_over >= len) {
asoc->rwnd_over -= len;
} else {
asoc->rwnd += (len - asoc->rwnd_over);
asoc->rwnd_over = 0;
}
} else {
asoc->rwnd += len;
}
/* If we had window pressure, start recovering it
* once our rwnd had reached the accumulated pressure
* threshold. The idea is to recover slowly, but up
* to the initial advertised window.
*/
if (asoc->rwnd_press && asoc->rwnd >= asoc->rwnd_press) {
int change = min(asoc->pathmtu, asoc->rwnd_press);
asoc->rwnd += change;
asoc->rwnd_press -= change;
}
pr_debug("%s: asoc:%p rwnd increased by %d to (%u, %u) - %u\n",
__func__, asoc, len, asoc->rwnd, asoc->rwnd_over,
asoc->a_rwnd);
/* Send a window update SACK if the rwnd has increased by at least the
* minimum of the association's PMTU and half of the receive buffer.
* The algorithm used is similar to the one described in
* Section 4.2.3.3 of RFC 1122.
*/
if (sctp_peer_needs_update(asoc)) {
asoc->a_rwnd = asoc->rwnd;
pr_debug("%s: sending window update SACK- asoc:%p rwnd:%u "
"a_rwnd:%u\n", __func__, asoc, asoc->rwnd,
asoc->a_rwnd);
sack = sctp_make_sack(asoc);
if (!sack)
return;
asoc->peer.sack_needed = 0;
sctp_outq_tail(&asoc->outqueue, sack);
/* Stop the SACK timer. */
timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];
if (del_timer(timer))
sctp_association_put(asoc);
}
}
/* Decrease asoc's rwnd by len. */
void sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len)
{
int rx_count;
int over = 0;
if (unlikely(!asoc->rwnd || asoc->rwnd_over))
pr_debug("%s: association:%p has asoc->rwnd:%u, "
"asoc->rwnd_over:%u!\n", __func__, asoc,
asoc->rwnd, asoc->rwnd_over);
if (asoc->ep->rcvbuf_policy)
rx_count = atomic_read(&asoc->rmem_alloc);
else
rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc);
/* If we've reached or overflowed our receive buffer, announce
* a 0 rwnd if rwnd would still be positive. Store the
* the potential pressure overflow so that the window can be restored
* back to original value.
*/
if (rx_count >= asoc->base.sk->sk_rcvbuf)
over = 1;
if (asoc->rwnd >= len) {
asoc->rwnd -= len;
if (over) {
asoc->rwnd_press += asoc->rwnd;
asoc->rwnd = 0;
}
} else {
asoc->rwnd_over = len - asoc->rwnd;
asoc->rwnd = 0;
}
pr_debug("%s: asoc:%p rwnd decreased by %d to (%u, %u, %u)\n",
__func__, asoc, len, asoc->rwnd, asoc->rwnd_over,
asoc->rwnd_press);
}
/* Build the bind address list for the association based on info from the
* local endpoint and the remote peer.
*/
int sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc,
sctp_scope_t scope, gfp_t gfp)
{
int flags;
/* Use scoping rules to determine the subset of addresses from
* the endpoint.
*/
flags = (PF_INET6 == asoc->base.sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0;
if (asoc->peer.ipv4_address)
flags |= SCTP_ADDR4_PEERSUPP;
if (asoc->peer.ipv6_address)
flags |= SCTP_ADDR6_PEERSUPP;
return sctp_bind_addr_copy(sock_net(asoc->base.sk),
&asoc->base.bind_addr,
&asoc->ep->base.bind_addr,
scope, gfp, flags);
}
/* Build the association's bind address list from the cookie. */
int sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc,
struct sctp_cookie *cookie,
gfp_t gfp)
{
int var_size2 = ntohs(cookie->peer_init->chunk_hdr.length);
int var_size3 = cookie->raw_addr_list_len;
__u8 *raw = (__u8 *)cookie->peer_init + var_size2;
return sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3,
asoc->ep->base.bind_addr.port, gfp);
}
/* Lookup laddr in the bind address list of an association. */
int sctp_assoc_lookup_laddr(struct sctp_association *asoc,
const union sctp_addr *laddr)
{
int found = 0;
if ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) &&
sctp_bind_addr_match(&asoc->base.bind_addr, laddr,
sctp_sk(asoc->base.sk)))
found = 1;
return found;
}
/* Set an association id for a given association */
int sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp)
{
bool preload = !!(gfp & __GFP_WAIT);
int ret;
/* If the id is already assigned, keep it. */
if (asoc->assoc_id)
return 0;
if (preload)
idr_preload(gfp);
spin_lock_bh(&sctp_assocs_id_lock);
/* 0 is not a valid assoc_id, must be >= 1 */
ret = idr_alloc_cyclic(&sctp_assocs_id, asoc, 1, 0, GFP_NOWAIT);
spin_unlock_bh(&sctp_assocs_id_lock);
if (preload)
idr_preload_end();
if (ret < 0)
return ret;
asoc->assoc_id = (sctp_assoc_t)ret;
return 0;
}
/* Free the ASCONF queue */
static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc)
{
struct sctp_chunk *asconf;
struct sctp_chunk *tmp;
list_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) {
list_del_init(&asconf->list);
sctp_chunk_free(asconf);
}
}
/* Free asconf_ack cache */
static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc)
{
struct sctp_chunk *ack;
struct sctp_chunk *tmp;
list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
transmitted_list) {
list_del_init(&ack->transmitted_list);
sctp_chunk_free(ack);
}
}
/* Clean up the ASCONF_ACK queue */
void sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc)
{
struct sctp_chunk *ack;
struct sctp_chunk *tmp;
/* We can remove all the entries from the queue up to
* the "Peer-Sequence-Number".
*/
list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
transmitted_list) {
if (ack->subh.addip_hdr->serial ==
htonl(asoc->peer.addip_serial))
break;
list_del_init(&ack->transmitted_list);
sctp_chunk_free(ack);
}
}
/* Find the ASCONF_ACK whose serial number matches ASCONF */
struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
const struct sctp_association *asoc,
__be32 serial)
{
struct sctp_chunk *ack;
/* Walk through the list of cached ASCONF-ACKs and find the
* ack chunk whose serial number matches that of the request.
*/
list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
if (ack->subh.addip_hdr->serial == serial) {
sctp_chunk_hold(ack);
return ack;
}
}
return NULL;
}
void sctp_asconf_queue_teardown(struct sctp_association *asoc)
{
/* Free any cached ASCONF_ACK chunk. */
sctp_assoc_free_asconf_acks(asoc);
/* Free the ASCONF queue. */
sctp_assoc_free_asconf_queue(asoc);
/* Free any cached ASCONF chunk. */
if (asoc->addip_last_asconf)
sctp_chunk_free(asoc->addip_last_asconf);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2221_0 |
crossvul-cpp_data_bad_2138_0 | /*-
* Copyright (c) 2008 Christos Zoulas
* 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*
* Parse Composite Document Files, the format used in Microsoft Office
* document files before they switched to zipped XML.
* Info from: http://sc.openoffice.org/compdocfileformat.pdf
*
* N.B. This is the "Composite Document File" format, and not the
* "Compound Document Format", nor the "Channel Definition Format".
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: cdf.c,v 1.61 2014/06/04 17:23:19 christos Exp $")
#endif
#include <assert.h>
#ifdef CDF_DEBUG
#include <err.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifndef EFTYPE
#define EFTYPE EINVAL
#endif
#include "cdf.h"
#ifdef CDF_DEBUG
#define DPRINTF(a) printf a, fflush(stdout)
#else
#define DPRINTF(a)
#endif
static union {
char s[4];
uint32_t u;
} cdf_bo;
#define NEED_SWAP (cdf_bo.u == (uint32_t)0x01020304)
#define CDF_TOLE8(x) ((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x)))
#define CDF_TOLE4(x) ((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x)))
#define CDF_TOLE2(x) ((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x)))
#define CDF_GETUINT32(x, y) cdf_getuint32(x, y)
/*
* swap a short
*/
static uint16_t
_cdf_tole2(uint16_t sv)
{
uint16_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[1];
d[1] = s[0];
return rv;
}
/*
* swap an int
*/
static uint32_t
_cdf_tole4(uint32_t sv)
{
uint32_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[3];
d[1] = s[2];
d[2] = s[1];
d[3] = s[0];
return rv;
}
/*
* swap a quad
*/
static uint64_t
_cdf_tole8(uint64_t sv)
{
uint64_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[7];
d[1] = s[6];
d[2] = s[5];
d[3] = s[4];
d[4] = s[3];
d[5] = s[2];
d[6] = s[1];
d[7] = s[0];
return rv;
}
/*
* grab a uint32_t from a possibly unaligned address, and return it in
* the native host order.
*/
static uint32_t
cdf_getuint32(const uint8_t *p, size_t offs)
{
uint32_t rv;
(void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv));
return CDF_TOLE4(rv);
}
#define CDF_UNPACK(a) \
(void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a)
#define CDF_UNPACKA(a) \
(void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a)
uint16_t
cdf_tole2(uint16_t sv)
{
return CDF_TOLE2(sv);
}
uint32_t
cdf_tole4(uint32_t sv)
{
return CDF_TOLE4(sv);
}
uint64_t
cdf_tole8(uint64_t sv)
{
return CDF_TOLE8(sv);
}
void
cdf_swap_header(cdf_header_t *h)
{
size_t i;
h->h_magic = CDF_TOLE8(h->h_magic);
h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]);
h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]);
h->h_revision = CDF_TOLE2(h->h_revision);
h->h_version = CDF_TOLE2(h->h_version);
h->h_byte_order = CDF_TOLE2(h->h_byte_order);
h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2);
h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2);
h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat);
h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory);
h->h_min_size_standard_stream =
CDF_TOLE4(h->h_min_size_standard_stream);
h->h_secid_first_sector_in_short_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat);
h->h_num_sectors_in_short_sat =
CDF_TOLE4(h->h_num_sectors_in_short_sat);
h->h_secid_first_sector_in_master_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat);
h->h_num_sectors_in_master_sat =
CDF_TOLE4(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]);
}
void
cdf_unpack_header(cdf_header_t *h, char *buf)
{
size_t i;
size_t len = 0;
CDF_UNPACK(h->h_magic);
CDF_UNPACKA(h->h_uuid);
CDF_UNPACK(h->h_revision);
CDF_UNPACK(h->h_version);
CDF_UNPACK(h->h_byte_order);
CDF_UNPACK(h->h_sec_size_p2);
CDF_UNPACK(h->h_short_sec_size_p2);
CDF_UNPACKA(h->h_unused0);
CDF_UNPACK(h->h_num_sectors_in_sat);
CDF_UNPACK(h->h_secid_first_directory);
CDF_UNPACKA(h->h_unused1);
CDF_UNPACK(h->h_min_size_standard_stream);
CDF_UNPACK(h->h_secid_first_sector_in_short_sat);
CDF_UNPACK(h->h_num_sectors_in_short_sat);
CDF_UNPACK(h->h_secid_first_sector_in_master_sat);
CDF_UNPACK(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
CDF_UNPACK(h->h_master_sat[i]);
}
void
cdf_swap_dir(cdf_directory_t *d)
{
d->d_namelen = CDF_TOLE2(d->d_namelen);
d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child);
d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child);
d->d_storage = CDF_TOLE4((uint32_t)d->d_storage);
d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]);
d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]);
d->d_flags = CDF_TOLE4(d->d_flags);
d->d_created = CDF_TOLE8((uint64_t)d->d_created);
d->d_modified = CDF_TOLE8((uint64_t)d->d_modified);
d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector);
d->d_size = CDF_TOLE4(d->d_size);
}
void
cdf_swap_class(cdf_classid_t *d)
{
d->cl_dword = CDF_TOLE4(d->cl_dword);
d->cl_word[0] = CDF_TOLE2(d->cl_word[0]);
d->cl_word[1] = CDF_TOLE2(d->cl_word[1]);
}
void
cdf_unpack_dir(cdf_directory_t *d, char *buf)
{
size_t len = 0;
CDF_UNPACKA(d->d_name);
CDF_UNPACK(d->d_namelen);
CDF_UNPACK(d->d_type);
CDF_UNPACK(d->d_color);
CDF_UNPACK(d->d_left_child);
CDF_UNPACK(d->d_right_child);
CDF_UNPACK(d->d_storage);
CDF_UNPACKA(d->d_storage_uuid);
CDF_UNPACK(d->d_flags);
CDF_UNPACK(d->d_created);
CDF_UNPACK(d->d_modified);
CDF_UNPACK(d->d_stream_first_sector);
CDF_UNPACK(d->d_size);
CDF_UNPACK(d->d_unused0);
}
static int
cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
(void)&line;
if (e >= b && (size_t)(e - b) <= ss * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
ss * sst->sst_len, ss, sst->sst_len));
errno = EFTYPE;
return -1;
}
static ssize_t
cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len)
{
size_t siz = (size_t)off + len;
if ((off_t)(off + len) != (off_t)siz) {
errno = EINVAL;
return -1;
}
if (info->i_buf != NULL && info->i_len >= siz) {
(void)memcpy(buf, &info->i_buf[off], len);
return (ssize_t)len;
}
if (info->i_fd == -1)
return -1;
if (pread(info->i_fd, buf, len, off) != (ssize_t)len)
return -1;
return (ssize_t)len;
}
int
cdf_read_header(const cdf_info_t *info, cdf_header_t *h)
{
char buf[512];
(void)memcpy(cdf_bo.s, "\01\02\03\04", 4);
if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1)
return -1;
cdf_unpack_header(h, buf);
cdf_swap_header(h);
if (h->h_magic != CDF_MAGIC) {
DPRINTF(("Bad magic 0x%" INT64_T_FORMAT "x != 0x%"
INT64_T_FORMAT "x\n",
(unsigned long long)h->h_magic,
(unsigned long long)CDF_MAGIC));
goto out;
}
if (h->h_sec_size_p2 > 20) {
DPRINTF(("Bad sector size 0x%u\n", h->h_sec_size_p2));
goto out;
}
if (h->h_short_sec_size_p2 > 20) {
DPRINTF(("Bad short sector size 0x%u\n",
h->h_short_sec_size_p2));
goto out;
}
return 0;
out:
errno = EFTYPE;
return -1;
}
ssize_t
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SEC_SIZE(h);
size_t pos = CDF_SEC_POS(h, id);
assert(ss == len);
return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len);
}
ssize_t
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
size_t len, const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SHORT_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos + len, CDF_SEC_SIZE(h) * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
/*
* Read the sector allocation table.
*/
int
cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat)
{
size_t i, j, k;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t *msa, mid, sec;
size_t nsatpersec = (ss / sizeof(mid)) - 1;
for (i = 0; i < __arraycount(h->h_master_sat); i++)
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
#define CDF_SEC_LIMIT (UINT32_MAX / (4 * ss))
if ((nsatpersec > 0 &&
h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) ||
i > CDF_SEC_LIMIT) {
DPRINTF(("Number of sectors in master SAT too big %u %"
SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i));
errno = EFTYPE;
return -1;
}
sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i;
DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n",
sat->sat_len, ss));
if ((sat->sat_tab = CAST(cdf_secid_t *, calloc(sat->sat_len, ss)))
== NULL)
return -1;
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] < 0)
break;
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
h->h_master_sat[i]) != (ssize_t)ss) {
DPRINTF(("Reading sector %d", h->h_master_sat[i]));
goto out1;
}
}
if ((msa = CAST(cdf_secid_t *, calloc(1, ss))) == NULL)
goto out1;
mid = h->h_secid_first_sector_in_master_sat;
for (j = 0; j < h->h_num_sectors_in_master_sat; j++) {
if (mid < 0)
goto out;
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Reading master sector loop limit"));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) {
DPRINTF(("Reading master sector %d", mid));
goto out2;
}
for (k = 0; k < nsatpersec; k++, i++) {
sec = CDF_TOLE4((uint32_t)msa[k]);
if (sec < 0)
goto out;
if (i >= sat->sat_len) {
DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT
"u >= %" SIZE_T_FORMAT "u", i, sat->sat_len));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
sec) != (ssize_t)ss) {
DPRINTF(("Reading sector %d",
CDF_TOLE4(msa[k])));
goto out2;
}
}
mid = CDF_TOLE4((uint32_t)msa[nsatpersec]);
}
out:
sat->sat_len = i;
free(msa);
return 0;
out2:
free(msa);
out1:
free(sat->sat_tab);
return -1;
}
size_t
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
{
size_t i, j;
cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size)
/ sizeof(maxsector));
DPRINTF(("Chain:"));
for (j = i = 0; sid >= 0; i++, j++) {
DPRINTF((" %d", sid));
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Counting chain loop limit"));
errno = EFTYPE;
return (size_t)-1;
}
if (sid >= maxsector) {
DPRINTF(("Sector %d >= %d\n", sid, maxsector));
errno = EFTYPE;
return (size_t)-1;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (i == 0) {
DPRINTF((" none, sid: %d\n", sid));
return (size_t)-1;
}
DPRINTF(("\n"));
return i;
}
int
cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
ssize_t nr;
scn->sst_len = cdf_count_chain(sat, sid, ss);
scn->sst_dirlen = len;
if (scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read long sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading long sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
scn->sst_len));
errno = EFTYPE;
goto out;
}
if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h,
sid)) != (ssize_t)ss) {
if (i == scn->sst_len - 1 && nr > 0) {
/* Last sector might be truncated */
return 0;
}
DPRINTF(("Reading long sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL)
return cdf_read_short_sector_chain(h, ssat, sst, sid, len,
scn);
else
return cdf_read_long_sector_chain(info, h, sat, sid, len, scn);
}
int
cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_dir_t *dir)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h), ns, nd;
char *buf;
cdf_secid_t sid = h->h_secid_first_directory;
ns = cdf_count_chain(sat, sid, ss);
if (ns == (size_t)-1)
return -1;
nd = ss / CDF_DIRECTORY_SIZE;
dir->dir_len = ns * nd;
dir->dir_tab = CAST(cdf_directory_t *,
calloc(dir->dir_len, sizeof(dir->dir_tab[0])));
if (dir->dir_tab == NULL)
return -1;
if ((buf = CAST(char *, malloc(ss))) == NULL) {
free(dir->dir_tab);
return -1;
}
for (j = i = 0; i < ns; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read dir loop limit"));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) {
DPRINTF(("Reading directory sector %d", sid));
goto out;
}
for (j = 0; j < nd; j++) {
cdf_unpack_dir(&dir->dir_tab[i * nd + j],
&buf[j * CDF_DIRECTORY_SIZE]);
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (NEED_SWAP)
for (i = 0; i < dir->dir_len; i++)
cdf_swap_dir(&dir->dir_tab[i]);
free(buf);
return 0;
out:
free(dir->dir_tab);
free(buf);
return -1;
}
int
cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_sat_t *ssat)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t sid = h->h_secid_first_sector_in_short_sat;
ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h));
if (ssat->sat_len == (size_t)-1)
return -1;
ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss));
if (ssat->sat_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sat sector loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= ssat->sat_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
ssat->sat_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) !=
(ssize_t)ss) {
DPRINTF(("Reading short sat sector %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(ssat->sat_tab);
return -1;
}
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
*root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
/* If the it is not there, just fake it; some docs don't have it */
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
*root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0)
goto out;
return cdf_read_long_sector_chain(info, h, sat,
d->d_stream_first_sector, d->d_size, scn);
out:
scn->sst_tab = NULL;
scn->sst_len = 0;
scn->sst_dirlen = 0;
return 0;
}
static int
cdf_namecmp(const char *d, const uint16_t *s, size_t l)
{
for (; l--; d++, s++)
if (*d != CDF_TOLE2(*s))
return (unsigned char)*d - CDF_TOLE2(*s);
return 0;
}
int
cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, cdf_stream_t *scn)
{
return cdf_read_user_stream(info, h, sat, ssat, sst, dir,
"\05SummaryInformation", scn);
}
int
cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, const char *name, cdf_stream_t *scn)
{
size_t i;
const cdf_directory_t *d;
size_t name_len = strlen(name) + 1;
for (i = dir->dir_len; i > 0; i--)
if (dir->dir_tab[i - 1].d_type == CDF_DIR_TYPE_USER_STREAM &&
cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len)
== 0)
break;
if (i == 0) {
DPRINTF(("Cannot find user stream `%s'\n", name));
errno = ESRCH;
return -1;
}
d = &dir->dir_tab[i - 1];
return cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, scn);
}
int
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
int
cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
{
size_t maxcount;
const cdf_summary_info_header_t *si =
CAST(const cdf_summary_info_header_t *, sst->sst_tab);
const cdf_section_declaration_t *sd =
CAST(const cdf_section_declaration_t *, (const void *)
((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
return -1;
ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
ssi->si_os_version = CDF_TOLE2(si->si_os_version);
ssi->si_os = CDF_TOLE2(si->si_os);
ssi->si_class = si->si_class;
cdf_swap_class(&ssi->si_class);
ssi->si_count = CDF_TOLE4(si->si_count);
*count = 0;
maxcount = 0;
*info = NULL;
if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,
count, &maxcount) == -1)
return -1;
return 0;
}
int
cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id)
{
return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-"
"%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0],
id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0],
id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4],
id->cl_six[5]);
}
static const struct {
uint32_t v;
const char *n;
} vn[] = {
{ CDF_PROPERTY_CODE_PAGE, "Code page" },
{ CDF_PROPERTY_TITLE, "Title" },
{ CDF_PROPERTY_SUBJECT, "Subject" },
{ CDF_PROPERTY_AUTHOR, "Author" },
{ CDF_PROPERTY_KEYWORDS, "Keywords" },
{ CDF_PROPERTY_COMMENTS, "Comments" },
{ CDF_PROPERTY_TEMPLATE, "Template" },
{ CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" },
{ CDF_PROPERTY_REVISION_NUMBER, "Revision Number" },
{ CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" },
{ CDF_PROPERTY_LAST_PRINTED, "Last Printed" },
{ CDF_PROPERTY_CREATE_TIME, "Create Time/Date" },
{ CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" },
{ CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" },
{ CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" },
{ CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" },
{ CDF_PROPERTY_THUMBNAIL, "Thumbnail" },
{ CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" },
{ CDF_PROPERTY_SECURITY, "Security" },
{ CDF_PROPERTY_LOCALE_ID, "Locale ID" },
};
int
cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p)
{
size_t i;
for (i = 0; i < __arraycount(vn); i++)
if (vn[i].v == p)
return snprintf(buf, bufsiz, "%s", vn[i].n);
return snprintf(buf, bufsiz, "0x%x", p);
}
int
cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts)
{
int len = 0;
int days, hours, mins, secs;
ts /= CDF_TIME_PREC;
secs = (int)(ts % 60);
ts /= 60;
mins = (int)(ts % 60);
ts /= 60;
hours = (int)(ts % 24);
ts /= 24;
days = (int)ts;
if (days) {
len += snprintf(buf + len, bufsiz - len, "%dd+", days);
if ((size_t)len >= bufsiz)
return len;
}
if (days || hours) {
len += snprintf(buf + len, bufsiz - len, "%.2d:", hours);
if ((size_t)len >= bufsiz)
return len;
}
len += snprintf(buf + len, bufsiz - len, "%.2d:", mins);
if ((size_t)len >= bufsiz)
return len;
len += snprintf(buf + len, bufsiz - len, "%.2d", secs);
return len;
}
#ifdef CDF_DEBUG
void
cdf_dump_header(const cdf_header_t *h)
{
size_t i;
#define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b)
#define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \
h->h_ ## b, 1 << h->h_ ## b)
DUMP("%d", revision);
DUMP("%d", version);
DUMP("0x%x", byte_order);
DUMP2("%d", sec_size_p2);
DUMP2("%d", short_sec_size_p2);
DUMP("%d", num_sectors_in_sat);
DUMP("%d", secid_first_directory);
DUMP("%d", min_size_standard_stream);
DUMP("%d", secid_first_sector_in_short_sat);
DUMP("%d", num_sectors_in_short_sat);
DUMP("%d", secid_first_sector_in_master_sat);
DUMP("%d", num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
(void)fprintf(stderr, "%35.35s[%.3zu] = %d\n",
"master_sat", i, h->h_master_sat[i]);
}
}
void
cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size)
{
size_t i, j, s = size / sizeof(cdf_secid_t);
for (i = 0; i < sat->sat_len; i++) {
(void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6"
SIZE_T_FORMAT "u: ", prefix, i, i * s);
for (j = 0; j < s; j++) {
(void)fprintf(stderr, "%5d, ",
CDF_TOLE4(sat->sat_tab[s * i + j]));
if ((j + 1) % 10 == 0)
(void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT
"u: ", i * s + j + 1);
}
(void)fprintf(stderr, "\n");
}
}
void
cdf_dump(void *v, size_t len)
{
size_t i, j;
unsigned char *p = v;
char abuf[16];
(void)fprintf(stderr, "%.4x: ", 0);
for (i = 0, j = 0; i < len; i++, p++) {
(void)fprintf(stderr, "%.2x ", *p);
abuf[j++] = isprint(*p) ? *p : '.';
if (j == 16) {
j = 0;
abuf[15] = '\0';
(void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ",
abuf, i + 1);
}
}
(void)fprintf(stderr, "\n");
}
void
cdf_dump_stream(const cdf_header_t *h, const cdf_stream_t *sst)
{
size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
cdf_dump(sst->sst_tab, ss * sst->sst_len);
}
void
cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir)
{
size_t i, j;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
cdf_stream_t scn;
struct timespec ts;
static const char *types[] = { "empty", "user storage",
"user stream", "lockbytes", "property", "root storage" };
for (i = 0; i < dir->dir_len; i++) {
char buf[26];
d = &dir->dir_tab[i];
for (j = 0; j < sizeof(name); j++)
name[j] = (char)CDF_TOLE2(d->d_name[j]);
(void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n",
i, name);
if (d->d_type < __arraycount(types))
(void)fprintf(stderr, "Type: %s\n", types[d->d_type]);
else
(void)fprintf(stderr, "Type: %d\n", d->d_type);
(void)fprintf(stderr, "Color: %s\n",
d->d_color ? "black" : "red");
(void)fprintf(stderr, "Left child: %d\n", d->d_left_child);
(void)fprintf(stderr, "Right child: %d\n", d->d_right_child);
(void)fprintf(stderr, "Flags: 0x%x\n", d->d_flags);
cdf_timestamp_to_timespec(&ts, d->d_created);
(void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf));
cdf_timestamp_to_timespec(&ts, d->d_modified);
(void)fprintf(stderr, "Modified %s",
cdf_ctime(&ts.tv_sec, buf));
(void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector);
(void)fprintf(stderr, "Size %d\n", d->d_size);
switch (d->d_type) {
case CDF_DIR_TYPE_USER_STORAGE:
(void)fprintf(stderr, "Storage: %d\n", d->d_storage);
break;
case CDF_DIR_TYPE_USER_STREAM:
if (sst == NULL)
break;
if (cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, &scn) == -1) {
warn("Can't read stream for %s at %d len %d",
name, d->d_stream_first_sector, d->d_size);
break;
}
cdf_dump_stream(h, &scn);
free(scn.sst_tab);
break;
default:
break;
}
}
}
void
cdf_dump_property_info(const cdf_property_info_t *info, size_t count)
{
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
size_t i, j;
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
(void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
(void)fprintf(stderr, "signed 16 [%hd]\n",
info[i].pi_s16);
break;
case CDF_SIGNED32:
(void)fprintf(stderr, "signed 32 [%d]\n",
info[i].pi_s32);
break;
case CDF_UNSIGNED32:
(void)fprintf(stderr, "unsigned 32 [%u]\n",
info[i].pi_u32);
break;
case CDF_FLOAT:
(void)fprintf(stderr, "float [%g]\n",
info[i].pi_f);
break;
case CDF_DOUBLE:
(void)fprintf(stderr, "double [%g]\n",
info[i].pi_d);
break;
case CDF_LENGTH32_STRING:
(void)fprintf(stderr, "string %u [%.*s]\n",
info[i].pi_str.s_len,
info[i].pi_str.s_len, info[i].pi_str.s_buf);
break;
case CDF_LENGTH32_WSTRING:
(void)fprintf(stderr, "string %u [",
info[i].pi_str.s_len);
for (j = 0; j < info[i].pi_str.s_len - 1; j++)
(void)fputc(info[i].pi_str.s_buf[j << 1], stderr);
(void)fprintf(stderr, "]\n");
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(buf, sizeof(buf), tp);
(void)fprintf(stderr, "timestamp %s\n", buf);
} else {
char buf[26];
cdf_timestamp_to_timespec(&ts, tp);
(void)fprintf(stderr, "timestamp %s",
cdf_ctime(&ts.tv_sec, buf));
}
break;
case CDF_CLIPBOARD:
(void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32);
break;
default:
DPRINTF(("Don't know how to deal with %x\n",
info[i].pi_type));
break;
}
}
}
void
cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst)
{
char buf[128];
cdf_summary_info_header_t ssi;
cdf_property_info_t *info;
size_t count;
(void)&h;
if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1)
return;
(void)fprintf(stderr, "Endian: %x\n", ssi.si_byte_order);
(void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff,
ssi.si_os_version >> 8);
(void)fprintf(stderr, "Os %d\n", ssi.si_os);
cdf_print_classid(buf, sizeof(buf), &ssi.si_class);
(void)fprintf(stderr, "Class %s\n", buf);
(void)fprintf(stderr, "Count %d\n", ssi.si_count);
cdf_dump_property_info(info, count);
free(info);
}
#endif
#ifdef TEST
int
main(int argc, char *argv[])
{
int i;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
cdf_info_t info;
if (argc < 2) {
(void)fprintf(stderr, "Usage: %s <filename>\n", getprogname());
return -1;
}
info.i_buf = NULL;
info.i_len = 0;
for (i = 1; i < argc; i++) {
if ((info.i_fd = open(argv[1], O_RDONLY)) == -1)
err(1, "Cannot open `%s'", argv[1]);
if (cdf_read_header(&info, &h) == -1)
err(1, "Cannot read header");
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if (cdf_read_sat(&info, &h, &sat) == -1)
err(1, "Cannot read sat");
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1)
err(1, "Cannot read ssat");
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if (cdf_read_dir(&info, &h, &sat, &dir) == -1)
err(1, "Cannot read dir");
if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst) == -1)
err(1, "Cannot read short stream");
#ifdef CDF_DEBUG
cdf_dump_stream(&h, &sst);
#endif
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn) == -1)
err(1, "Cannot read summary info");
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
(void)close(info.i_fd);
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2138_0 |
crossvul-cpp_data_bad_2976_0 | /*
* Glue code for optimized assembly version of Salsa20.
*
* Copyright (c) 2007 Tan Swee Heng <thesweeheng@gmail.com>
*
* The assembly codes are public domain assembly codes written by Daniel. J.
* Bernstein <djb@cr.yp.to>. The codes are modified to include indentation
* and to remove extraneous comments and functions that are not needed.
* - i586 version, renamed as salsa20-i586-asm_32.S
* available from <http://cr.yp.to/snuffle/salsa20/x86-pm/salsa20.s>
* - x86-64 version, renamed as salsa20-x86_64-asm_64.S
* available from <http://cr.yp.to/snuffle/salsa20/amd64-3/salsa20.s>
*
* 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/algapi.h>
#include <linux/module.h>
#include <linux/crypto.h>
#define SALSA20_IV_SIZE 8U
#define SALSA20_MIN_KEY_SIZE 16U
#define SALSA20_MAX_KEY_SIZE 32U
struct salsa20_ctx
{
u32 input[16];
};
asmlinkage void salsa20_keysetup(struct salsa20_ctx *ctx, const u8 *k,
u32 keysize, u32 ivsize);
asmlinkage void salsa20_ivsetup(struct salsa20_ctx *ctx, const u8 *iv);
asmlinkage void salsa20_encrypt_bytes(struct salsa20_ctx *ctx,
const u8 *src, u8 *dst, u32 bytes);
static int setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keysize)
{
struct salsa20_ctx *ctx = crypto_tfm_ctx(tfm);
salsa20_keysetup(ctx, key, keysize*8, SALSA20_IV_SIZE*8);
return 0;
}
static int encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, 64);
salsa20_ivsetup(ctx, walk.iv);
if (likely(walk.nbytes == nbytes))
{
salsa20_encrypt_bytes(ctx, walk.src.virt.addr,
walk.dst.virt.addr, nbytes);
return blkcipher_walk_done(desc, &walk, 0);
}
while (walk.nbytes >= 64) {
salsa20_encrypt_bytes(ctx, walk.src.virt.addr,
walk.dst.virt.addr,
walk.nbytes - (walk.nbytes % 64));
err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);
}
if (walk.nbytes) {
salsa20_encrypt_bytes(ctx, walk.src.virt.addr,
walk.dst.virt.addr, walk.nbytes);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
static struct crypto_alg alg = {
.cra_name = "salsa20",
.cra_driver_name = "salsa20-asm",
.cra_priority = 200,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_type = &crypto_blkcipher_type,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct salsa20_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_u = {
.blkcipher = {
.setkey = setkey,
.encrypt = encrypt,
.decrypt = encrypt,
.min_keysize = SALSA20_MIN_KEY_SIZE,
.max_keysize = SALSA20_MAX_KEY_SIZE,
.ivsize = SALSA20_IV_SIZE,
}
}
};
static int __init init(void)
{
return crypto_register_alg(&alg);
}
static void __exit fini(void)
{
crypto_unregister_alg(&alg);
}
module_init(init);
module_exit(fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION ("Salsa20 stream cipher algorithm (optimized assembly version)");
MODULE_ALIAS_CRYPTO("salsa20");
MODULE_ALIAS_CRYPTO("salsa20-asm");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2976_0 |
crossvul-cpp_data_good_406_0 | /*
* Copyright (C) 2012,2013 - ARM Ltd
* Author: Marc Zyngier <marc.zyngier@arm.com>
*
* Derived from arch/arm/kvm/guest.c:
* Copyright (C) 2012 - Virtual Open Systems and Columbia University
* Author: Christoffer Dall <c.dall@virtualopensystems.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/kvm_host.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <kvm/arm_psci.h>
#include <asm/cputype.h>
#include <linux/uaccess.h>
#include <asm/kvm.h>
#include <asm/kvm_emulate.h>
#include <asm/kvm_coproc.h>
#include "trace.h"
#define VM_STAT(x) { #x, offsetof(struct kvm, stat.x), KVM_STAT_VM }
#define VCPU_STAT(x) { #x, offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU }
struct kvm_stats_debugfs_item debugfs_entries[] = {
VCPU_STAT(hvc_exit_stat),
VCPU_STAT(wfe_exit_stat),
VCPU_STAT(wfi_exit_stat),
VCPU_STAT(mmio_exit_user),
VCPU_STAT(mmio_exit_kernel),
VCPU_STAT(exits),
{ NULL }
};
int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
{
return 0;
}
static u64 core_reg_offset_from_id(u64 id)
{
return id & ~(KVM_REG_ARCH_MASK | KVM_REG_SIZE_MASK | KVM_REG_ARM_CORE);
}
static int validate_core_offset(const struct kvm_one_reg *reg)
{
u64 off = core_reg_offset_from_id(reg->id);
int size;
switch (off) {
case KVM_REG_ARM_CORE_REG(regs.regs[0]) ...
KVM_REG_ARM_CORE_REG(regs.regs[30]):
case KVM_REG_ARM_CORE_REG(regs.sp):
case KVM_REG_ARM_CORE_REG(regs.pc):
case KVM_REG_ARM_CORE_REG(regs.pstate):
case KVM_REG_ARM_CORE_REG(sp_el1):
case KVM_REG_ARM_CORE_REG(elr_el1):
case KVM_REG_ARM_CORE_REG(spsr[0]) ...
KVM_REG_ARM_CORE_REG(spsr[KVM_NR_SPSR - 1]):
size = sizeof(__u64);
break;
case KVM_REG_ARM_CORE_REG(fp_regs.vregs[0]) ...
KVM_REG_ARM_CORE_REG(fp_regs.vregs[31]):
size = sizeof(__uint128_t);
break;
case KVM_REG_ARM_CORE_REG(fp_regs.fpsr):
case KVM_REG_ARM_CORE_REG(fp_regs.fpcr):
size = sizeof(__u32);
break;
default:
return -EINVAL;
}
if (KVM_REG_SIZE(reg->id) == size &&
IS_ALIGNED(off, size / sizeof(__u32)))
return 0;
return -EINVAL;
}
static int get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/*
* Because the kvm_regs structure is a mix of 32, 64 and
* 128bit fields, we index it as if it was a 32bit
* array. Hence below, nr_regs is the number of entries, and
* off the index in the "array".
*/
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
u32 off;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id)))
return -EFAULT;
return 0;
}
static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
return -EINVAL;
}
static unsigned long num_core_regs(void)
{
return sizeof(struct kvm_regs) / sizeof(__u32);
}
/**
* ARM64 versions of the TIMER registers, always available on arm64
*/
#define NUM_TIMER_REGS 3
static bool is_timer_reg(u64 index)
{
switch (index) {
case KVM_REG_ARM_TIMER_CTL:
case KVM_REG_ARM_TIMER_CNT:
case KVM_REG_ARM_TIMER_CVAL:
return true;
}
return false;
}
static int copy_timer_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
{
if (put_user(KVM_REG_ARM_TIMER_CTL, uindices))
return -EFAULT;
uindices++;
if (put_user(KVM_REG_ARM_TIMER_CNT, uindices))
return -EFAULT;
uindices++;
if (put_user(KVM_REG_ARM_TIMER_CVAL, uindices))
return -EFAULT;
return 0;
}
static int set_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
void __user *uaddr = (void __user *)(long)reg->addr;
u64 val;
int ret;
ret = copy_from_user(&val, uaddr, KVM_REG_SIZE(reg->id));
if (ret != 0)
return -EFAULT;
return kvm_arm_timer_set_reg(vcpu, reg->id, val);
}
static int get_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
void __user *uaddr = (void __user *)(long)reg->addr;
u64 val;
val = kvm_arm_timer_get_reg(vcpu, reg->id);
return copy_to_user(uaddr, &val, KVM_REG_SIZE(reg->id)) ? -EFAULT : 0;
}
/**
* kvm_arm_num_regs - how many registers do we present via KVM_GET_ONE_REG
*
* This is for all registers.
*/
unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu)
{
return num_core_regs() + kvm_arm_num_sys_reg_descs(vcpu)
+ kvm_arm_get_fw_num_regs(vcpu) + NUM_TIMER_REGS;
}
/**
* kvm_arm_copy_reg_indices - get indices of all registers.
*
* We do core registers right here, then we append system regs.
*/
int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices)
{
unsigned int i;
const u64 core_reg = KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM_CORE;
int ret;
for (i = 0; i < sizeof(struct kvm_regs) / sizeof(__u32); i++) {
if (put_user(core_reg | i, uindices))
return -EFAULT;
uindices++;
}
ret = kvm_arm_copy_fw_reg_indices(vcpu, uindices);
if (ret)
return ret;
uindices += kvm_arm_get_fw_num_regs(vcpu);
ret = copy_timer_indices(vcpu, uindices);
if (ret)
return ret;
uindices += NUM_TIMER_REGS;
return kvm_arm_copy_sys_reg_indices(vcpu, uindices);
}
int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/* We currently use nothing arch-specific in upper 32 bits */
if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
return -EINVAL;
/* Register group 16 means we want a core register. */
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE)
return get_core_reg(vcpu, reg);
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW)
return kvm_arm_get_fw_reg(vcpu, reg);
if (is_timer_reg(reg->id))
return get_timer_reg(vcpu, reg);
return kvm_arm_sys_reg_get_reg(vcpu, reg);
}
int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
/* We currently use nothing arch-specific in upper 32 bits */
if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32)
return -EINVAL;
/* Register group 16 means we set a core register. */
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE)
return set_core_reg(vcpu, reg);
if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW)
return kvm_arm_set_fw_reg(vcpu, reg);
if (is_timer_reg(reg->id))
return set_timer_reg(vcpu, reg);
return kvm_arm_sys_reg_set_reg(vcpu, reg);
}
int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
return -EINVAL;
}
int __kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
events->exception.serror_pending = !!(vcpu->arch.hcr_el2 & HCR_VSE);
events->exception.serror_has_esr = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
if (events->exception.serror_pending && events->exception.serror_has_esr)
events->exception.serror_esr = vcpu_get_vsesr(vcpu);
return 0;
}
int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
bool serror_pending = events->exception.serror_pending;
bool has_esr = events->exception.serror_has_esr;
if (serror_pending && has_esr) {
if (!cpus_have_const_cap(ARM64_HAS_RAS_EXTN))
return -EINVAL;
if (!((events->exception.serror_esr) & ~ESR_ELx_ISS_MASK))
kvm_set_sei_esr(vcpu, events->exception.serror_esr);
else
return -EINVAL;
} else if (serror_pending) {
kvm_inject_vabt(vcpu);
}
return 0;
}
int __attribute_const__ kvm_target_cpu(void)
{
unsigned long implementor = read_cpuid_implementor();
unsigned long part_number = read_cpuid_part_number();
switch (implementor) {
case ARM_CPU_IMP_ARM:
switch (part_number) {
case ARM_CPU_PART_AEM_V8:
return KVM_ARM_TARGET_AEM_V8;
case ARM_CPU_PART_FOUNDATION:
return KVM_ARM_TARGET_FOUNDATION_V8;
case ARM_CPU_PART_CORTEX_A53:
return KVM_ARM_TARGET_CORTEX_A53;
case ARM_CPU_PART_CORTEX_A57:
return KVM_ARM_TARGET_CORTEX_A57;
};
break;
case ARM_CPU_IMP_APM:
switch (part_number) {
case APM_CPU_PART_POTENZA:
return KVM_ARM_TARGET_XGENE_POTENZA;
};
break;
};
/* Return a default generic target */
return KVM_ARM_TARGET_GENERIC_V8;
}
int kvm_vcpu_preferred_target(struct kvm_vcpu_init *init)
{
int target = kvm_target_cpu();
if (target < 0)
return -ENODEV;
memset(init, 0, sizeof(*init));
/*
* For now, we don't return any features.
* In future, we might use features to return target
* specific features available for the preferred
* target type.
*/
init->target = (__u32)target;
return 0;
}
int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
return -EINVAL;
}
#define KVM_GUESTDBG_VALID_MASK (KVM_GUESTDBG_ENABLE | \
KVM_GUESTDBG_USE_SW_BP | \
KVM_GUESTDBG_USE_HW | \
KVM_GUESTDBG_SINGLESTEP)
/**
* kvm_arch_vcpu_ioctl_set_guest_debug - set up guest debugging
* @kvm: pointer to the KVM struct
* @kvm_guest_debug: the ioctl data buffer
*
* This sets up and enables the VM for guest debugging. Userspace
* passes in a control flag to enable different debug types and
* potentially other architecture specific information in the rest of
* the structure.
*/
int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
int ret = 0;
trace_kvm_set_guest_debug(vcpu, dbg->control);
if (dbg->control & ~KVM_GUESTDBG_VALID_MASK) {
ret = -EINVAL;
goto out;
}
if (dbg->control & KVM_GUESTDBG_ENABLE) {
vcpu->guest_debug = dbg->control;
/* Hardware assisted Break and Watch points */
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW) {
vcpu->arch.external_debug_state = dbg->arch;
}
} else {
/* If not enabled clear all flags */
vcpu->guest_debug = 0;
}
out:
return ret;
}
int kvm_arm_vcpu_arch_set_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_set_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_set_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_get_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_get_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
struct kvm_device_attr *attr)
{
int ret;
switch (attr->group) {
case KVM_ARM_VCPU_PMU_V3_CTRL:
ret = kvm_arm_pmu_v3_has_attr(vcpu, attr);
break;
case KVM_ARM_VCPU_TIMER_CTRL:
ret = kvm_arm_timer_has_attr(vcpu, attr);
break;
default:
ret = -ENXIO;
break;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_406_0 |
crossvul-cpp_data_good_2314_0 | /*
* Copyright (c) 2007, 2008, Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* OS dependent API for using card via network.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/select.h>
#include <errno.h>
#include "osdep.h"
#include "network.h"
#define QUEUE_MAX 666
struct queue {
unsigned char q_buf[2048];
int q_len;
struct queue *q_next;
struct queue *q_prev;
};
struct priv_net {
int pn_s;
struct queue pn_queue;
struct queue pn_queue_free;
int pn_queue_len;
};
int net_send(int s, int command, void *arg, int len)
{
struct net_hdr *pnh;
char *pktbuf;
size_t pktlen;
pktlen = sizeof(struct net_hdr) + len;
pktbuf = (char*)calloc(sizeof(char), pktlen);
if (pktbuf == NULL) {
perror("calloc");
goto net_send_error;
}
pnh = (struct net_hdr*)pktbuf;
pnh->nh_type = command;
pnh->nh_len = htonl(len);
memcpy(pktbuf + sizeof(struct net_hdr), arg, len);
for (;;) {
ssize_t rc = send(s, pktbuf, pktlen, 0);
if ((size_t)rc == pktlen)
break;
if (rc == EAGAIN || rc == EWOULDBLOCK || rc == EINTR)
continue;
if (rc == ECONNRESET)
printf("Connection reset while sending packet!\n");
goto net_send_error;
}
free(pktbuf);
return 0;
net_send_error:
free(pktbuf);
return -1;
}
int net_read_exact(int s, void *arg, int len)
{
ssize_t rc;
int rlen = 0;
char *buf = (char*)arg;
while (rlen < len) {
rc = recv(s, buf, (len - rlen), 0);
if (rc < 1) {
if (rc == -1 && (errno == EAGAIN || errno == EINTR)) {
usleep(100);
continue;
}
return -1;
}
buf += rc;
rlen += rc;
}
return 0;
}
int net_get(int s, void *arg, int *len)
{
struct net_hdr nh;
int plen;
if (net_read_exact(s, &nh, sizeof(nh)) == -1)
{
return -1;
}
plen = ntohl(nh.nh_len);
if (!(plen <= *len))
printf("PLEN %d type %d len %d\n",
plen, nh.nh_type, *len);
assert(plen <= *len && plen > 0); /* XXX */
*len = plen;
if ((*len) && (net_read_exact(s, arg, *len) == -1))
{
return -1;
}
return nh.nh_type;
}
static void queue_del(struct queue *q)
{
q->q_prev->q_next = q->q_next;
q->q_next->q_prev = q->q_prev;
}
static void queue_add(struct queue *head, struct queue *q)
{
struct queue *pos = head->q_prev;
q->q_prev = pos;
q->q_next = pos->q_next;
q->q_next->q_prev = q;
pos->q_next = q;
}
#if 0
static int queue_len(struct queue *head)
{
struct queue *q = head->q_next;
int i = 0;
while (q != head) {
i++;
q = q->q_next;
}
return i;
}
#endif
static struct queue *queue_get_slot(struct priv_net *pn)
{
struct queue *q = pn->pn_queue_free.q_next;
if (q != &pn->pn_queue_free) {
queue_del(q);
return q;
}
if (pn->pn_queue_len++ > QUEUE_MAX)
return NULL;
return malloc(sizeof(*q));
}
static void net_enque(struct priv_net *pn, void *buf, int len)
{
struct queue *q;
q = queue_get_slot(pn);
if (!q)
return;
q->q_len = len;
assert((int) sizeof(q->q_buf) >= q->q_len);
memcpy(q->q_buf, buf, q->q_len);
queue_add(&pn->pn_queue, q);
}
static int net_get_nopacket(struct priv_net *pn, void *arg, int *len)
{
unsigned char buf[2048];
int l = sizeof(buf);
int c;
while (1) {
l = sizeof(buf);
c = net_get(pn->pn_s, buf, &l);
if (c != NET_PACKET && c > 0)
break;
if(c > 0)
net_enque(pn, buf, l);
}
assert(l <= *len);
memcpy(arg, buf, l);
*len = l;
return c;
}
static int net_cmd(struct priv_net *pn, int command, void *arg, int alen)
{
uint32_t rc;
int len;
int cmd;
if (net_send(pn->pn_s, command, arg, alen) == -1)
{
return -1;
}
len = sizeof(rc);
cmd = net_get_nopacket(pn, &rc, &len);
if (cmd == -1)
{
return -1;
}
assert(cmd == NET_RC);
assert(len == sizeof(rc));
return ntohl(rc);
}
static int queue_get(struct priv_net *pn, void *buf, int len)
{
struct queue *head = &pn->pn_queue;
struct queue *q = head->q_next;
if (q == head)
return 0;
assert(q->q_len <= len);
memcpy(buf, q->q_buf, q->q_len);
queue_del(q);
queue_add(&pn->pn_queue_free, q);
return q->q_len;
}
static int net_read(struct wif *wi, unsigned char *h80211, int len,
struct rx_info *ri)
{
struct priv_net *pn = wi_priv(wi);
uint32_t buf[512]; // 512 * 4 = 2048
unsigned char *bufc = (unsigned char*)buf;
int cmd;
int sz = sizeof(*ri);
int l;
int ret;
/* try queue */
l = queue_get(pn, buf, sizeof(buf));
if (!l) {
/* try reading form net */
l = sizeof(buf);
cmd = net_get(pn->pn_s, buf, &l);
if (cmd == -1)
return -1;
if (cmd == NET_RC)
{
ret = ntohl((buf[0]));
return ret;
}
assert(cmd == NET_PACKET);
}
/* XXX */
if (ri) {
// re-assemble 64-bit integer
ri->ri_mactime = __be64_to_cpu(((uint64_t)buf[0] << 32 || buf[1] ));
ri->ri_power = __be32_to_cpu(buf[2]);
ri->ri_noise = __be32_to_cpu(buf[3]);
ri->ri_channel = __be32_to_cpu(buf[4]);
ri->ri_rate = __be32_to_cpu(buf[5]);
ri->ri_antenna = __be32_to_cpu(buf[6]);
}
l -= sz;
assert(l > 0);
if (l > len)
l = len;
memcpy(h80211, &bufc[sz], l);
return l;
}
static int net_get_mac(struct wif *wi, unsigned char *mac)
{
struct priv_net *pn = wi_priv(wi);
uint32_t buf[2]; // only need 6 bytes, this provides 8
int cmd;
int sz = 6;
if (net_send(pn->pn_s, NET_GET_MAC, NULL, 0) == -1)
return -1;
cmd = net_get_nopacket(pn, buf, &sz);
if (cmd == -1)
return -1;
if (cmd == NET_RC)
return ntohl(buf[0]);
assert(cmd == NET_MAC);
assert(sz == 6);
memcpy(mac, buf, 6);
return 0;
}
static int net_write(struct wif *wi, unsigned char *h80211, int len,
struct tx_info *ti)
{
struct priv_net *pn = wi_priv(wi);
int sz = sizeof(*ti);
unsigned char buf[2048];
unsigned char *ptr = buf;
/* XXX */
if (ti)
memcpy(ptr, ti, sz);
else
memset(ptr, 0, sizeof(*ti));
ptr += sz;
memcpy(ptr, h80211, len);
sz += len;
return net_cmd(pn, NET_WRITE, buf, sz);
}
static int net_set_channel(struct wif *wi, int chan)
{
uint32_t c = htonl(chan);
return net_cmd(wi_priv(wi), NET_SET_CHAN, &c, sizeof(c));
}
static int net_get_channel(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
return net_cmd(pn, NET_GET_CHAN, NULL, 0);
}
static int net_set_rate(struct wif *wi, int rate)
{
uint32_t c = htonl(rate);
return net_cmd(wi_priv(wi), NET_SET_RATE, &c, sizeof(c));
}
static int net_get_rate(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
return net_cmd(pn, NET_GET_RATE, NULL, 0);
}
static int net_get_monitor(struct wif *wi)
{
return net_cmd(wi_priv(wi), NET_GET_MONITOR, NULL, 0);
}
static void do_net_free(struct wif *wi)
{
assert(wi->wi_priv);
free(wi->wi_priv);
wi->wi_priv = 0;
free(wi);
}
static void net_close(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
close(pn->pn_s);
do_net_free(wi);
}
static int get_ip_port(char *iface, char *ip, const int ipsize)
{
char *host;
char *ptr;
int port = -1;
struct in_addr addr;
host = strdup(iface);
if (!host)
return -1;
ptr = strchr(host, ':');
if (!ptr)
goto out;
*ptr++ = 0;
if (!inet_aton(host, &addr))
goto out; /* XXX resolve hostname */
assert(strlen(host) <= 15);
strncpy(ip, host, ipsize);
port = atoi(ptr);
out:
free(host);
return port;
}
static int handshake(int s)
{
if (s) {} /* XXX unused */
/* XXX do a handshake */
return 0;
}
static int do_net_open(char *iface)
{
int s, port;
char ip[16];
struct sockaddr_in s_in;
port = get_ip_port(iface, ip, sizeof(ip)-1);
if (port == -1)
return -1;
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
if (!inet_aton(ip, &s_in.sin_addr))
return -1;
if ((s = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
printf("Connecting to %s port %d...\n", ip, port);
if (connect(s, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) {
close(s);
printf("Failed to connect\n");
return -1;
}
if (handshake(s) == -1) {
close(s);
printf("Failed to connect - handshake failed\n");
return -1;
}
printf("Connection successful\n");
return s;
}
static int net_fd(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
return pn->pn_s;
}
struct wif *net_open(char *iface)
{
struct wif *wi;
struct priv_net *pn;
int s;
/* setup wi struct */
wi = wi_alloc(sizeof(*pn));
if (!wi)
return NULL;
wi->wi_read = net_read;
wi->wi_write = net_write;
wi->wi_set_channel = net_set_channel;
wi->wi_get_channel = net_get_channel;
wi->wi_set_rate = net_set_rate;
wi->wi_get_rate = net_get_rate;
wi->wi_close = net_close;
wi->wi_fd = net_fd;
wi->wi_get_mac = net_get_mac;
wi->wi_get_monitor = net_get_monitor;
/* setup iface */
s = do_net_open(iface);
if (s == -1) {
do_net_free(wi);
return NULL;
}
/* setup private state */
pn = wi_priv(wi);
pn->pn_s = s;
pn->pn_queue.q_next = pn->pn_queue.q_prev = &pn->pn_queue;
pn->pn_queue_free.q_next = pn->pn_queue_free.q_prev
= &pn->pn_queue_free;
return wi;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2314_0 |
crossvul-cpp_data_good_5844_7 | /*
* File: datagram.c
*
* Datagram (ISI) Phonet sockets
*
* Copyright (C) 2008 Nokia Corporation.
*
* Authors: Sakari Ailus <sakari.ailus@nokia.com>
* Rémi Denis-Courmont
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <asm/ioctls.h>
#include <net/sock.h>
#include <linux/phonet.h>
#include <linux/export.h>
#include <net/phonet/phonet.h>
static int pn_backlog_rcv(struct sock *sk, struct sk_buff *skb);
/* associated socket ceases to exist */
static void pn_sock_close(struct sock *sk, long timeout)
{
sk_common_release(sk);
}
static int pn_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
struct sk_buff *skb;
int answ;
switch (cmd) {
case SIOCINQ:
lock_sock(sk);
skb = skb_peek(&sk->sk_receive_queue);
answ = skb ? skb->len : 0;
release_sock(sk);
return put_user(answ, (int __user *)arg);
case SIOCPNADDRESOURCE:
case SIOCPNDELRESOURCE: {
u32 res;
if (get_user(res, (u32 __user *)arg))
return -EFAULT;
if (res >= 256)
return -EINVAL;
if (cmd == SIOCPNADDRESOURCE)
return pn_sock_bind_res(sk, res);
else
return pn_sock_unbind_res(sk, res);
}
}
return -ENOIOCTLCMD;
}
/* Destroy socket. All references are gone. */
static void pn_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_receive_queue);
}
static int pn_init(struct sock *sk)
{
sk->sk_destruct = pn_destruct;
return 0;
}
static int pn_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len)
{
struct sockaddr_pn *target;
struct sk_buff *skb;
int err;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_NOSIGNAL|
MSG_CMSG_COMPAT))
return -EOPNOTSUPP;
if (msg->msg_name == NULL)
return -EDESTADDRREQ;
if (msg->msg_namelen < sizeof(struct sockaddr_pn))
return -EINVAL;
target = (struct sockaddr_pn *)msg->msg_name;
if (target->spn_family != AF_PHONET)
return -EAFNOSUPPORT;
skb = sock_alloc_send_skb(sk, MAX_PHONET_HEADER + len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
return err;
skb_reserve(skb, MAX_PHONET_HEADER);
err = memcpy_fromiovec((void *)skb_put(skb, len), msg->msg_iov, len);
if (err < 0) {
kfree_skb(skb);
return err;
}
/*
* Fill in the Phonet header and
* finally pass the packet forwards.
*/
err = pn_skb_send(sk, skb, target);
/* If ok, return len. */
return (err >= 0) ? len : err;
}
static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct sk_buff *skb = NULL;
struct sockaddr_pn sa;
int rval = -EOPNOTSUPP;
int copylen;
if (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|
MSG_CMSG_COMPAT))
goto out_nofree;
skb = skb_recv_datagram(sk, flags, noblock, &rval);
if (skb == NULL)
goto out_nofree;
pn_skb_get_src_sockaddr(skb, &sa);
copylen = skb->len;
if (len < copylen) {
msg->msg_flags |= MSG_TRUNC;
copylen = len;
}
rval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);
if (rval) {
rval = -EFAULT;
goto out;
}
rval = (flags & MSG_TRUNC) ? skb->len : copylen;
if (msg->msg_name != NULL) {
memcpy(msg->msg_name, &sa, sizeof(sa));
*addr_len = sizeof(sa);
}
out:
skb_free_datagram(sk, skb);
out_nofree:
return rval;
}
/* Queue an skb for a sock. */
static int pn_backlog_rcv(struct sock *sk, struct sk_buff *skb)
{
int err = sock_queue_rcv_skb(sk, skb);
if (err < 0)
kfree_skb(skb);
return err ? NET_RX_DROP : NET_RX_SUCCESS;
}
/* Module registration */
static struct proto pn_proto = {
.close = pn_sock_close,
.ioctl = pn_ioctl,
.init = pn_init,
.sendmsg = pn_sendmsg,
.recvmsg = pn_recvmsg,
.backlog_rcv = pn_backlog_rcv,
.hash = pn_sock_hash,
.unhash = pn_sock_unhash,
.get_port = pn_sock_get_port,
.obj_size = sizeof(struct pn_sock),
.owner = THIS_MODULE,
.name = "PHONET",
};
static struct phonet_protocol pn_dgram_proto = {
.ops = &phonet_dgram_ops,
.prot = &pn_proto,
.sock_type = SOCK_DGRAM,
};
int __init isi_register(void)
{
return phonet_proto_register(PN_PROTO_PHONET, &pn_dgram_proto);
}
void __exit isi_unregister(void)
{
phonet_proto_unregister(PN_PROTO_PHONET, &pn_dgram_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5844_7 |
crossvul-cpp_data_good_5844_6 | /*
* L2TPv3 IP encapsulation support
*
* Copyright (c) 2008,2009,2010 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 <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 "l2tp_core.h"
struct l2tp_ip_sock {
/* inet_sock has to be the first member of l2tp_ip_sock */
struct inet_sock inet;
u32 conn_id;
u32 peer_conn_id;
};
static DEFINE_RWLOCK(l2tp_ip_lock);
static struct hlist_head l2tp_ip_table;
static struct hlist_head l2tp_ip_bind_table;
static inline struct l2tp_ip_sock *l2tp_ip_sk(const struct sock *sk)
{
return (struct l2tp_ip_sock *)sk;
}
static struct sock *__l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id)
{
struct sock *sk;
sk_for_each_bound(sk, &l2tp_ip_bind_table) {
struct inet_sock *inet = inet_sk(sk);
struct l2tp_ip_sock *l2tp = l2tp_ip_sk(sk);
if (l2tp == NULL)
continue;
if ((l2tp->conn_id == tunnel_id) &&
net_eq(sock_net(sk), net) &&
!(inet->inet_rcv_saddr && inet->inet_rcv_saddr != laddr) &&
!(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
goto found;
}
sk = NULL;
found:
return sk;
}
static inline struct sock *l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id)
{
struct sock *sk = __l2tp_ip_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_ip_recv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
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(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(net, tunnel_id);
if (tunnel != NULL)
sk = tunnel->sock;
else {
struct iphdr *iph = (struct iphdr *) skb_network_header(skb);
read_lock_bh(&l2tp_ip_lock);
sk = __l2tp_ip_bind_lookup(net, iph->daddr, 0, tunnel_id);
read_unlock_bh(&l2tp_ip_lock);
}
if (sk == NULL)
goto discard;
sock_hold(sk);
if (!xfrm4_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_ip_open(struct sock *sk)
{
/* Prevent autobind. We don't have ports. */
inet_sk(sk)->inet_num = IPPROTO_L2TP;
write_lock_bh(&l2tp_ip_lock);
sk_add_node(sk, &l2tp_ip_table);
write_unlock_bh(&l2tp_ip_lock);
return 0;
}
static void l2tp_ip_close(struct sock *sk, long timeout)
{
write_lock_bh(&l2tp_ip_lock);
hlist_del_init(&sk->sk_bind_node);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
sk_common_release(sk);
}
static void l2tp_ip_destroy_sock(struct sock *sk)
{
struct sk_buff *skb;
struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk);
while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL)
kfree_skb(skb);
if (tunnel) {
l2tp_tunnel_closeall(tunnel);
sock_put(sk);
}
sk_refcnt_debug_dec(sk);
}
static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr;
struct net *net = sock_net(sk);
int ret;
int chk_addr_ret;
if (!sock_flag(sk, SOCK_ZAPPED))
return -EINVAL;
if (addr_len < sizeof(struct sockaddr_l2tpip))
return -EINVAL;
if (addr->l2tp_family != AF_INET)
return -EINVAL;
ret = -EADDRINUSE;
read_lock_bh(&l2tp_ip_lock);
if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr,
sk->sk_bound_dev_if, addr->l2tp_conn_id))
goto out_in_use;
read_unlock_bh(&l2tp_ip_lock);
lock_sock(sk);
if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip))
goto out;
chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr);
ret = -EADDRNOTAVAIL;
if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST)
goto out;
if (addr->l2tp_addr.s_addr)
inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr;
if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
inet->inet_saddr = 0; /* Use device */
sk_dst_reset(sk);
l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id;
write_lock_bh(&l2tp_ip_lock);
sk_add_bind_node(sk, &l2tp_ip_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
ret = 0;
sock_reset_flag(sk, SOCK_ZAPPED);
out:
release_sock(sk);
return ret;
out_in_use:
read_unlock_bh(&l2tp_ip_lock);
return ret;
}
static int l2tp_ip_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *) uaddr;
int rc;
if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */
return -EINVAL;
if (addr_len < sizeof(*lsa))
return -EINVAL;
if (ipv4_is_multicast(lsa->l2tp_addr.s_addr))
return -EINVAL;
rc = ip4_datagram_connect(sk, uaddr, addr_len);
if (rc < 0)
return rc;
lock_sock(sk);
l2tp_ip_sk(sk)->peer_conn_id = lsa->l2tp_conn_id;
write_lock_bh(&l2tp_ip_lock);
hlist_del_init(&sk->sk_bind_node);
sk_add_bind_node(sk, &l2tp_ip_bind_table);
write_unlock_bh(&l2tp_ip_lock);
release_sock(sk);
return rc;
}
static int l2tp_ip_disconnect(struct sock *sk, int flags)
{
if (sock_flag(sk, SOCK_ZAPPED))
return 0;
return udp_disconnect(sk, flags);
}
static int l2tp_ip_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct l2tp_ip_sock *lsk = l2tp_ip_sk(sk);
struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr;
memset(lsa, 0, sizeof(*lsa));
lsa->l2tp_family = AF_INET;
if (peer) {
if (!inet->inet_dport)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr.s_addr = inet->inet_daddr;
} else {
__be32 addr = inet->inet_rcv_saddr;
if (!addr)
addr = inet->inet_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
lsa->l2tp_addr.s_addr = addr;
}
*uaddr_len = sizeof(*lsa);
return 0;
}
static int l2tp_ip_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(sock_net(sk), IPSTATS_MIB_INDISCARDS);
kfree_skb(skb);
return -1;
}
/* Userspace will call sendmsg() on the tunnel socket to send L2TP
* control frames.
*/
static int l2tp_ip_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len)
{
struct sk_buff *skb;
int rc;
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = NULL;
struct flowi4 *fl4;
int connected = 0;
__be32 daddr;
lock_sock(sk);
rc = -ENOTCONN;
if (sock_flag(sk, SOCK_DEAD))
goto out;
/* Get and verify the address. */
if (msg->msg_name) {
struct sockaddr_l2tpip *lip = (struct sockaddr_l2tpip *) msg->msg_name;
rc = -EINVAL;
if (msg->msg_namelen < sizeof(*lip))
goto out;
if (lip->l2tp_family != AF_INET) {
rc = -EAFNOSUPPORT;
if (lip->l2tp_family != AF_UNSPEC)
goto out;
}
daddr = lip->l2tp_addr.s_addr;
} else {
rc = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
connected = 1;
}
/* Allocate a socket buffer */
rc = -ENOMEM;
skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) +
4 + len, 0, GFP_KERNEL);
if (!skb)
goto error;
/* Reserve space for headers, putting IP header on 4-byte boundary. */
skb_reserve(skb, 2 + NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
/* Insert 0 session_id */
*((__be32 *) skb_put(skb, 4)) = 0;
/* Copy user data into skb */
rc = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
if (rc < 0) {
kfree_skb(skb);
goto error;
}
fl4 = &inet->cork.fl.u.ip4;
if (connected)
rt = (struct rtable *) __sk_dst_check(sk, 0);
rcu_read_lock();
if (rt == NULL) {
const struct ip_options_rcu *inet_opt;
inet_opt = rcu_dereference(inet->inet_opt);
/* Use correct destination address if we have options. */
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times
* itself out.
*/
rt = ip_route_output_ports(sock_net(sk), fl4, sk,
daddr, inet->inet_saddr,
inet->inet_dport, inet->inet_sport,
sk->sk_protocol, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (IS_ERR(rt))
goto no_route;
if (connected) {
sk_setup_caps(sk, &rt->dst);
} else {
skb_dst_set(skb, &rt->dst);
goto xmit;
}
}
/* We dont need to clone dst here, it is guaranteed to not disappear.
* __dev_xmit_skb() might force a refcount if needed.
*/
skb_dst_set_noref(skb, &rt->dst);
xmit:
/* Queue the packet to IP for output */
rc = ip_queue_xmit(skb, &inet->cork.fl);
rcu_read_unlock();
error:
if (rc >= 0)
rc = len;
out:
release_sock(sk);
return rc;
no_route:
rcu_read_unlock();
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
rc = -EHOSTUNREACH;
goto out;
}
static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
if (flags & MSG_OOB)
goto out;
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 (sin) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
sin->sin_port = 0;
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
return err ? err : copied;
}
static struct proto l2tp_ip_prot = {
.name = "L2TP/IP",
.owner = THIS_MODULE,
.init = l2tp_ip_open,
.close = l2tp_ip_close,
.bind = l2tp_ip_bind,
.connect = l2tp_ip_connect,
.disconnect = l2tp_ip_disconnect,
.ioctl = udp_ioctl,
.destroy = l2tp_ip_destroy_sock,
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.sendmsg = l2tp_ip_sendmsg,
.recvmsg = l2tp_ip_recvmsg,
.backlog_rcv = l2tp_ip_backlog_recv,
.hash = inet_hash,
.unhash = inet_unhash,
.obj_size = sizeof(struct l2tp_ip_sock),
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_ip_setsockopt,
.compat_getsockopt = compat_ip_getsockopt,
#endif
};
static const struct proto_ops l2tp_ip_ops = {
.family = PF_INET,
.owner = THIS_MODULE,
.release = inet_release,
.bind = inet_bind,
.connect = inet_dgram_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = l2tp_ip_getname,
.poll = datagram_poll,
.ioctl = inet_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_ip_protosw = {
.type = SOCK_DGRAM,
.protocol = IPPROTO_L2TP,
.prot = &l2tp_ip_prot,
.ops = &l2tp_ip_ops,
.no_check = 0,
};
static struct net_protocol l2tp_ip_protocol __read_mostly = {
.handler = l2tp_ip_recv,
.netns_ok = 1,
};
static int __init l2tp_ip_init(void)
{
int err;
pr_info("L2TP IP encapsulation support (L2TPv3)\n");
err = proto_register(&l2tp_ip_prot, 1);
if (err != 0)
goto out;
err = inet_add_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
if (err)
goto out1;
inet_register_protosw(&l2tp_ip_protosw);
return 0;
out1:
proto_unregister(&l2tp_ip_prot);
out:
return err;
}
static void __exit l2tp_ip_exit(void)
{
inet_unregister_protosw(&l2tp_ip_protosw);
inet_del_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
proto_unregister(&l2tp_ip_prot);
}
module_init(l2tp_ip_init);
module_exit(l2tp_ip_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
MODULE_DESCRIPTION("L2TP over IP");
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_INET, 2, IPPROTO_L2TP);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5844_6 |
crossvul-cpp_data_bad_4700_0 | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.danga.com/memcached/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <mellon@pobox.com>
* Brad Fitzpatrick <brad@danga.com>
*/
#include "memcached.h"
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sysexits.h>
#include <stddef.h>
/* FreeBSD 4.x doesn't have IOV_MAX exposed. */
#ifndef IOV_MAX
#if defined(__FreeBSD__) || defined(__APPLE__)
# define IOV_MAX 1024
#endif
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static int try_read_command(conn *c);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occured (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static void conn_set_state(conn *c, enum conn_states state);
/* stats */
static void stats_init(void);
static void server_stats(ADD_STAT add_stats, conn *c);
static void process_stat_settings(ADD_STAT add_stats, void *c);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void process_command(conn *c, char *command);
static void write_and_free(conn *c, char *buf, int bytes);
static int ensure_iov_space(conn *c);
static int add_iov(conn *c, const void *buf, int len);
static int add_msghdr(conn *c);
/* time handling */
static void set_current_time(void); /* update the global variable holding
global 32-bit seconds-since-start time
(to avoid 64 bit time_t) */
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct settings settings;
time_t process_started; /* when the process was started */
/** file scope variables **/
static conn *listen_conn = NULL;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
static enum transmit_result transmit(conn *c);
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
static rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
stats.curr_items = stats.total_items = stats.curr_conns = stats.total_conns = stats.conn_structs = 0;
stats.get_cmds = stats.set_cmds = stats.get_hits = stats.get_misses = stats.evictions = 0;
stats.curr_bytes = stats.listen_disabled_num = 0;
stats.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - 2;
stats_prefix_init();
}
static void stats_reset(void) {
STATS_LOCK();
stats.total_items = stats.total_conns = 0;
stats.evictions = 0;
stats.listen_disabled_num = 0;
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 11211;
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_msghdr(conn *c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (! msg)
return -1;
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
if (c->request_addr_size > 0) {
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
}
c->msgbytes = 0;
c->msgused++;
if (IS_UDP(c->transport)) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE);
}
return 0;
}
/*
* Free list management for connections.
*/
static conn **freeconns;
static int freetotal;
static int freecurr;
/* Lock for connection freelist */
static pthread_mutex_t conn_lock = PTHREAD_MUTEX_INITIALIZER;
static void conn_init(void) {
freetotal = 200;
freecurr = 0;
if ((freeconns = calloc(freetotal, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
}
return;
}
/*
* Returns a connection from the freelist, if any.
*/
conn *conn_from_freelist() {
conn *c;
pthread_mutex_lock(&conn_lock);
if (freecurr > 0) {
c = freeconns[--freecurr];
} else {
c = NULL;
}
pthread_mutex_unlock(&conn_lock);
return c;
}
/*
* Adds a connection to the freelist. 0 = success.
*/
bool conn_add_to_freelist(conn *c) {
bool ret = true;
pthread_mutex_lock(&conn_lock);
if (freecurr < freetotal) {
freeconns[freecurr++] = c;
ret = false;
} else {
/* try to enlarge free connections array */
size_t newsize = freetotal * 2;
conn **new_freeconns = realloc(freeconns, sizeof(conn *) * newsize);
if (new_freeconns) {
freetotal = newsize;
freeconns = new_freeconns;
freeconns[freecurr++] = c;
ret = false;
}
}
pthread_mutex_unlock(&conn_lock);
return ret;
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
}
return rv;
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base) {
conn *c = conn_from_freelist();
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
fprintf(stderr, "calloc()\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->rbuf = c->wbuf = 0;
c->ilist = 0;
c->suffixlist = 0;
c->iov = 0;
c->msglist = 0;
c->hdrbuf = 0;
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->suffixsize = SUFFIX_LIST_INITIAL;
c->iovsize = IOV_LIST_INITIAL;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize);
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 ||
c->msglist == 0 || c->suffixlist == 0) {
conn_free(c);
fprintf(stderr, "malloc()\n");
return NULL;
}
STATS_LOCK();
stats.conn_structs++;
STATS_UNLOCK();
}
c->transport = transport;
c->protocol = settings.binding_protocol;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
c->sfd = sfd;
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = c->wbytes = 0;
c->wcurr = c->wbuf;
c->rcurr = c->rbuf;
c->ritem = 0;
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
c->ileft = 0;
c->suffixleft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->write_and_go = init_state;
c->write_and_free = 0;
c->item = 0;
c->noreply = false;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
if (conn_add_to_freelist(c)) {
conn_free(c);
}
perror("event_add");
return NULL;
}
STATS_LOCK();
stats.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
if (c->item) {
item_remove(c->item);
c->item = 0;
}
if (c->ileft != 0) {
for (; c->ileft > 0; c->ileft--,c->icurr++) {
item_remove(*(c->icurr));
}
}
if (c->suffixleft != 0) {
for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) {
cache_free(c->thread->suffix_cache, *(c->suffixcurr));
}
}
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
MEMCACHED_CONN_DESTROY(c);
if (c->hdrbuf)
free(c->hdrbuf);
if (c->msglist)
free(c->msglist);
if (c->rbuf)
free(c->rbuf);
if (c->wbuf)
free(c->wbuf);
if (c->ilist)
free(c->ilist);
if (c->suffixlist)
free(c->suffixlist);
if (c->iov)
free(c->iov);
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
MEMCACHED_CONN_RELEASE(c->sfd);
close(c->sfd);
accept_new_conns(true);
conn_cleanup(c);
/* if the connection has big buffers, just free it */
if (c->rsize > READ_BUFFER_HIGHWAT || conn_add_to_freelist(c)) {
conn_free(c);
}
STATS_LOCK();
stats.curr_conns--;
STATS_UNLOCK();
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
static void conn_shrink(conn *c) {
assert(c != NULL);
if (IS_UDP(c->transport))
return;
if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) {
char *newbuf;
if (c->rcurr != c->rbuf)
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
if (newbuf) {
c->rbuf = newbuf;
c->rsize = DATA_BUFFER_SIZE;
}
/* TODO check other branch... */
c->rcurr = c->rbuf;
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]));
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0]));
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->iovsize > IOV_LIST_HIGHWAT) {
struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0]));
if (newbuf) {
c->iov = newbuf;
c->iovsize = IOV_LIST_INITIAL;
}
/* TODO check return value */
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);
if (state != c->state) {
if (settings.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state),
state_text(state));
}
c->state = state;
if (state == conn_write || state == conn_mwrite) {
MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes);
}
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov = (struct iovec *)realloc(c->iov,
(c->iovsize * 2) * sizeof(struct iovec));
if (! new_iov)
return -1;
c->iov = new_iov;
c->iovsize *= 2;
/* Point all the msghdr structures at the new list. */
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_iov(conn *c, const void *buf, int len) {
struct msghdr *m;
int leftover;
bool limit_to_mtu;
assert(c != NULL);
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets, and the first payloads of TCP replies, to
* UDP_MAX_PAYLOAD_SIZE bytes.
*/
limit_to_mtu = IS_UDP(c->transport) || (1 == c->msgused);
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(limit_to_mtu && c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (limit_to_mtu && len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
static int build_udp_headers(conn *c) {
int i;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf)
new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE);
else
new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE);
if (! new_hdrbuf)
return -1;
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = (void*)hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = 0;
*hdr++ = 0;
assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn *c, const char *str) {
size_t len;
assert(c != NULL);
if (c->noreply) {
if (settings.verbose > 1)
fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str);
c->noreply = false;
conn_set_state(c, conn_new_cmd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
return;
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->cmd, and the item is ready in c->item.
*/
static void complete_nread_ascii(conn *c) {
assert(c != NULL);
item *it = c->item;
int comm = c->cmd;
enum store_item_type ret;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) != 0) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
ret = store_item(it, comm, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_CAS:
MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes,
cas);
break;
}
#endif
switch (ret) {
case STORED:
out_string(c, "STORED");
break;
case EXISTS:
out_string(c, "EXISTS");
break;
case NOT_FOUND:
out_string(c, "NOT_FOUND");
break;
case NOT_STORED:
out_string(c, "NOT_STORED");
break;
default:
out_string(c, "SERVER_ERROR Unhandled storage type.");
}
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
/**
* get a pointer to the start of the request struct for the current command
*/
static void* binary_get_request(conn *c) {
char *ret = c->rcurr;
ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen +
c->binary_header.request.extlen);
assert(ret >= c->rbuf);
return ret;
}
/**
* get a pointer to the key in this request
*/
static char* binary_get_key(conn *c) {
return c->rcurr - (c->binary_header.request.keylen);
}
static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) {
protocol_binary_response_header* header;
assert(c);
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
/* XXX: out_string is inappropriate here */
out_string(c, "SERVER_ERROR out of memory");
return;
}
header = (protocol_binary_response_header *)c->wbuf;
header->response.magic = (uint8_t)PROTOCOL_BINARY_RES;
header->response.opcode = c->binary_header.request.opcode;
header->response.keylen = (uint16_t)htons(key_len);
header->response.extlen = (uint8_t)hdr_len;
header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
header->response.status = (uint16_t)htons(err);
header->response.bodylen = htonl(body_len);
header->response.opaque = c->opaque;
header->response.cas = htonll(c->cas);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d Writing bin response:", c->sfd);
for (ii = 0; ii < sizeof(header->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n>%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", header->bytes[ii]);
}
fprintf(stderr, "\n");
}
add_iov(c, c->wbuf, sizeof(header->response));
}
static void write_bin_error(conn *c, protocol_binary_response_status err, int swallow) {
const char *errstr = "Unknown error";
size_t len;
switch (err) {
case PROTOCOL_BINARY_RESPONSE_ENOMEM:
errstr = "Out of memory";
break;
case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
errstr = "Unknown command";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
errstr = "Not found";
break;
case PROTOCOL_BINARY_RESPONSE_EINVAL:
errstr = "Invalid arguments";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
errstr = "Data exists for key.";
break;
case PROTOCOL_BINARY_RESPONSE_E2BIG:
errstr = "Too large.";
break;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL:
errstr = "Non-numeric server-side value for incr or decr";
break;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
errstr = "Not stored.";
break;
case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR:
errstr = "Auth failure.";
break;
default:
assert(false);
errstr = "UNHANDLED ERROR";
fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err);
}
if (settings.verbose > 1) {
fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr);
}
len = strlen(errstr);
add_bin_header(c, err, 0, 0, len);
if (len > 0) {
add_iov(c, errstr, len);
}
conn_set_state(c, conn_mwrite);
if(swallow > 0) {
c->sbytes = swallow;
c->write_and_go = conn_swallow;
} else {
c->write_and_go = conn_new_cmd;
}
}
/* Form and send a response to a command over the binary protocol */
static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) {
if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET ||
c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_bin_header(c, 0, hlen, keylen, dlen);
if(dlen > 0) {
add_iov(c, d, dlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
conn_set_state(c, conn_new_cmd);
}
}
static void complete_incr_bin(conn *c) {
item *it;
char *key;
size_t nkey;
protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf;
protocol_binary_request_incr* req = binary_get_request(c);
assert(c != NULL);
assert(c->wsize >= sizeof(*rsp));
/* fix byteorder in the request */
req->message.body.delta = ntohll(req->message.body.delta);
req->message.body.initial = ntohll(req->message.body.initial);
req->message.body.expiration = ntohl(req->message.body.expiration);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int i;
fprintf(stderr, "incr ");
for (i = 0; i < nkey; i++) {
fprintf(stderr, "%c", key[i]);
}
fprintf(stderr, " %lld, %llu, %d\n",
(long long)req->message.body.delta,
(long long)req->message.body.initial,
req->message.body.expiration);
}
it = item_get(key, nkey);
if (it && (c->binary_header.request.cas == 0 ||
c->binary_header.request.cas == ITEM_get_cas(it))) {
/* Weird magic in add_delta forces me to pad here */
char tmpbuf[INCR_MAX_STORAGE_LEN];
protocol_binary_response_status st = PROTOCOL_BINARY_RESPONSE_SUCCESS;
switch(add_delta(c, it, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT,
req->message.body.delta, tmpbuf)) {
case OK:
break;
case NON_NUMERIC:
st = PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL;
break;
case EOM:
st = PROTOCOL_BINARY_RESPONSE_ENOMEM;
break;
}
if (st != PROTOCOL_BINARY_RESPONSE_SUCCESS) {
write_bin_error(c, st, 0);
} else {
rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10));
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0,
sizeof(rsp->message.body.value));
}
item_remove(it); /* release our reference */
} else if (!it && req->message.body.expiration != 0xffffffff) {
/* Save some room for the response */
rsp->message.body.value = htonll(req->message.body.initial);
it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration),
INCR_MAX_STORAGE_LEN);
if (it != NULL) {
snprintf(ITEM_data(it), INCR_MAX_STORAGE_LEN, "%llu",
(unsigned long long)req->message.body.initial);
if (store_item(it, NREAD_SET, c)) {
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value));
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
}
} else if (it) {
/* incorrect CAS */
item_remove(it); /* release our reference */
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
static void complete_update_bin(conn *c) {
protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL;
enum store_item_type ret = NOT_STORED;
assert(c != NULL);
item *it = c->item;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We don't actually receive the trailing two characters in the bin
* protocol, so we're going to just set them here */
*(ITEM_data(it) + it->nbytes - 2) = '\r';
*(ITEM_data(it) + it->nbytes - 1) = '\n';
ret = store_item(it, c->cmd, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
}
#endif
switch (ret) {
case STORED:
/* Stored */
write_bin_response(c, NULL, 0, 0, 0);
break;
case EXISTS:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
break;
case NOT_FOUND:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
break;
case NOT_STORED:
if (c->cmd == NREAD_ADD) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;
} else if(c->cmd == NREAD_REPLACE) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED;
}
write_bin_error(c, eno, 0);
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
static void process_bin_get(conn *c) {
item *it;
protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf;
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d GET ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
it = item_get(key, nkey);
if (it) {
/* the length has two unnecessary bytes ("\r\n") */
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_cmds++;
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
bodylen += nkey;
keylen = nkey;
}
add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen);
rsp->message.header.response.cas = htonll(ITEM_get_cas(it));
// add the flags
rsp->message.body.flags = htonl(strtoul(ITEM_suffix(it), NULL, 10));
add_iov(c, &rsp->message.body, sizeof(rsp->message.body));
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_iov(c, ITEM_key(it), nkey);
}
/* Add the data minus the CRLF */
add_iov(c, ITEM_data(it), it->nbytes - 2);
conn_set_state(c, conn_mwrite);
/* Remember this command so we can garbage collect it later */
c->item = it;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_cmds++;
c->thread->stats.get_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
if (c->noreply) {
conn_set_state(c, conn_new_cmd);
} else {
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
char *ofs = c->wbuf + sizeof(protocol_binary_response_header);
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, nkey, nkey);
memcpy(ofs, key, nkey);
add_iov(c, ofs, nkey);
conn_set_state(c, conn_mwrite);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
}
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
}
static void append_bin_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *buf = c->stats.buffer + c->stats.offset;
uint32_t bodylen = klen + vlen;
protocol_binary_response_header header = {
.response.magic = (uint8_t)PROTOCOL_BINARY_RES,
.response.opcode = PROTOCOL_BINARY_CMD_STAT,
.response.keylen = (uint16_t)htons(klen),
.response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES,
.response.bodylen = htonl(bodylen),
.response.opaque = c->opaque
};
memcpy(buf, header.bytes, sizeof(header.response));
buf += sizeof(header.response);
if (klen > 0) {
memcpy(buf, key, klen);
buf += klen;
if (vlen > 0) {
memcpy(buf, val, vlen);
}
}
c->stats.offset += sizeof(header.response) + bodylen;
}
static void append_ascii_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *pos = c->stats.buffer + c->stats.offset;
uint32_t nbytes = 0;
int remaining = c->stats.size - c->stats.offset;
int room = remaining - 1;
if (klen == 0 && vlen == 0) {
nbytes = snprintf(pos, room, "END\r\n");
} else if (vlen == 0) {
nbytes = snprintf(pos, room, "STAT %s\r\n", key);
} else {
nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val);
}
c->stats.offset += nbytes;
}
static bool grow_stats_buf(conn *c, size_t needed) {
size_t nsize = c->stats.size;
size_t available = nsize - c->stats.offset;
bool rv = true;
/* Special case: No buffer -- need to allocate fresh */
if (c->stats.buffer == NULL) {
nsize = 1024;
available = c->stats.size = c->stats.offset = 0;
}
while (needed > available) {
assert(nsize > 0);
nsize = nsize << 1;
available = nsize - c->stats.offset;
}
if (nsize != c->stats.size) {
char *ptr = realloc(c->stats.buffer, nsize);
if (ptr) {
c->stats.buffer = ptr;
c->stats.size = nsize;
} else {
rv = false;
}
}
return rv;
}
static void append_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
const void *cookie)
{
/* value without a key is invalid */
if (klen == 0 && vlen > 0) {
return ;
}
conn *c = (conn*)cookie;
if (c->protocol == binary_prot) {
size_t needed = vlen + klen + sizeof(protocol_binary_response_header);
if (!grow_stats_buf(c, needed)) {
return ;
}
append_bin_stats(key, klen, val, vlen, c);
} else {
size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n"
if (!grow_stats_buf(c, needed)) {
return ;
}
append_ascii_stats(key, klen, val, vlen, c);
}
assert(c->stats.offset <= c->stats.size);
}
static void process_bin_stat(conn *c) {
char *subcommand = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d STATS ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", subcommand[ii]);
}
fprintf(stderr, "\n");
}
if (nkey == 0) {
/* request all statistics */
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strncmp(subcommand, "reset", 5) == 0) {
stats_reset();
} else if (strncmp(subcommand, "settings", 8) == 0) {
process_stat_settings(&append_stats, c);
} else if (strncmp(subcommand, "detail", 6) == 0) {
char *subcmd_pos = subcommand + 6;
if (strncmp(subcmd_pos, " dump", 5) == 0) {
int len;
char *dump_buf = stats_prefix_dump(&len);
if (dump_buf == NULL || len <= 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
return ;
} else {
append_stats("detailed", strlen("detailed"), dump_buf, len, c);
free(dump_buf);
}
} else if (strncmp(subcmd_pos, " on", 3) == 0) {
settings.detail_enabled = 1;
} else if (strncmp(subcmd_pos, " off", 4) == 0) {
settings.detail_enabled = 0;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
return;
}
} else {
if (get_stats(subcommand, nkey, &append_stats, c)) {
if (c->stats.buffer == NULL) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
return;
}
/* Append termination package and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) {
assert(c);
c->substate = next_substate;
c->rlbytes = c->keylen + extra;
/* Ok... do we have room for the extras and the key in the input buffer? */
ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf;
if (c->rlbytes > c->rsize - offset) {
size_t nsize = c->rsize;
size_t size = c->rlbytes + sizeof(protocol_binary_request_header);
while (size > nsize) {
nsize *= 2;
}
if (nsize != c->rsize) {
if (settings.verbose > 1) {
fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n",
c->sfd, (unsigned long)c->rsize, (unsigned long)nsize);
}
char *newm = realloc(c->rbuf, nsize);
if (newm == NULL) {
if (settings.verbose) {
fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n",
c->sfd);
}
conn_set_state(c, conn_closing);
return;
}
c->rbuf= newm;
/* rcurr should point to the same offset in the packet */
c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header);
c->rsize = nsize;
}
if (c->rbuf != c->rcurr) {
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Repack input buffer\n", c->sfd);
}
}
}
/* preserve the header in the buffer.. */
c->ritem = c->rcurr + sizeof(protocol_binary_request_header);
conn_set_state(c, conn_nread);
}
/* Just write an error message and disconnect the client */
static void handle_binary_protocol_error(conn *c) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, 0);
if (settings.verbose) {
fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n",
c->binary_header.request.opcode, c->sfd);
}
c->write_and_go = conn_closing;
}
static void init_sasl_conn(conn *c) {
assert(c);
/* should something else be returned? */
if (!settings.sasl)
return;
if (!c->sasl_conn) {
int result=sasl_server_new("memcached",
NULL, NULL, NULL, NULL,
NULL, 0, &c->sasl_conn);
if (result != SASL_OK) {
if (settings.verbose) {
fprintf(stderr, "Failed to initialize SASL conn.\n");
}
c->sasl_conn = NULL;
}
}
}
static void bin_list_sasl_mechs(conn *c) {
// Guard against a disabled SASL.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
init_sasl_conn(c);
const char *result_string = NULL;
unsigned int string_length = 0;
int result=sasl_listmech(c->sasl_conn, NULL,
"", /* What to prepend the string with */
" ", /* What to separate mechanisms with */
"", /* What to append to the string */
&result_string, &string_length,
NULL);
if (result != SASL_OK) {
/* Perhaps there's a better error for this... */
if (settings.verbose) {
fprintf(stderr, "Failed to list SASL mechanisms.\n");
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
return;
}
write_bin_response(c, (char*)result_string, 0, 0, string_length);
}
static void process_bin_sasl_auth(conn *c) {
// Guard for handling disabled SASL on the server.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
assert(c->binary_header.request.extlen == 0);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > MAX_SASL_MECH_LEN) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, vlen);
c->write_and_go = conn_swallow;
return;
}
char *key = binary_get_key(c);
assert(key);
item *it = item_alloc(key, nkey, 0, 0, vlen);
if (it == 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
c->write_and_go = conn_swallow;
return;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_reading_sasl_auth_data;
}
static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
}
}
static bool authenticated(conn *c) {
assert(settings.sasl);
bool rv = false;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */
rv = true;
break;
default:
if (c->sasl_conn) {
const void *uname = NULL;
sasl_getprop(c->sasl_conn, SASL_USERNAME, &uname);
rv = uname != NULL;
}
}
if (settings.verbose > 1) {
fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n",
c->cmd, rv ? "true" : "false");
}
return rv;
}
static void dispatch_bin_command(conn *c) {
int protocol_error = 0;
int extlen = c->binary_header.request.extlen;
int keylen = c->binary_header.request.keylen;
uint32_t bodylen = c->binary_header.request.bodylen;
if (settings.sasl && !authenticated(c)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
c->write_and_go = conn_closing;
return;
}
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
c->noreply = true;
/* binprot supports 16bit keys, but internals are still 8bit */
if (keylen > KEY_MAX_LENGTH) {
handle_binary_protocol_error(c);
return;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SETQ:
c->cmd = PROTOCOL_BINARY_CMD_SET;
break;
case PROTOCOL_BINARY_CMD_ADDQ:
c->cmd = PROTOCOL_BINARY_CMD_ADD;
break;
case PROTOCOL_BINARY_CMD_REPLACEQ:
c->cmd = PROTOCOL_BINARY_CMD_REPLACE;
break;
case PROTOCOL_BINARY_CMD_DELETEQ:
c->cmd = PROTOCOL_BINARY_CMD_DELETE;
break;
case PROTOCOL_BINARY_CMD_INCREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_INCREMENT;
break;
case PROTOCOL_BINARY_CMD_DECREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_DECREMENT;
break;
case PROTOCOL_BINARY_CMD_QUITQ:
c->cmd = PROTOCOL_BINARY_CMD_QUIT;
break;
case PROTOCOL_BINARY_CMD_FLUSHQ:
c->cmd = PROTOCOL_BINARY_CMD_FLUSH;
break;
case PROTOCOL_BINARY_CMD_APPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_PREPEND;
break;
case PROTOCOL_BINARY_CMD_GETQ:
c->cmd = PROTOCOL_BINARY_CMD_GET;
break;
case PROTOCOL_BINARY_CMD_GETKQ:
c->cmd = PROTOCOL_BINARY_CMD_GETK;
break;
default:
c->noreply = false;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_VERSION:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, VERSION, 0, 0, strlen(VERSION));
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_FLUSH:
if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) {
bin_read_key(c, bin_read_flush_exptime, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_NOOP:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_REPLACE:
if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) {
bin_read_key(c, bin_reading_set_header, 8);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETK:
if (extlen == 0 && bodylen == keylen && keylen > 0) {
bin_read_key(c, bin_reading_get_key, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_DELETE:
if (keylen > 0 && extlen == 0 && bodylen == keylen) {
bin_read_key(c, bin_reading_del_header, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_INCREMENT:
case PROTOCOL_BINARY_CMD_DECREMENT:
if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) {
bin_read_key(c, bin_reading_incr_header, 20);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_APPEND:
case PROTOCOL_BINARY_CMD_PREPEND:
if (keylen > 0 && extlen == 0) {
bin_read_key(c, bin_reading_set_header, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_STAT:
if (extlen == 0) {
bin_read_key(c, bin_reading_stat, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_QUIT:
if (keylen == 0 && extlen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
c->write_and_go = conn_closing;
if (c->noreply) {
conn_set_state(c, conn_closing);
}
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
bin_list_sasl_mechs(c);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_AUTH:
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (extlen == 0 && keylen != 0) {
bin_read_key(c, bin_reading_sasl_auth, 0);
} else {
protocol_error = 1;
}
break;
default:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, bodylen);
}
if (protocol_error)
handle_binary_protocol_error(c);
}
static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, vlen);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
}
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey);
if (it) {
item_unlink(it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_append_prepend(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
vlen = c->binary_header.request.bodylen - nkey;
if (settings.verbose > 1) {
fprintf(stderr, "Value len is %d\n", vlen);
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, 0, 0, vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, 0, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, vlen);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_APPEND:
c->cmd = NREAD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPEND:
c->cmd = NREAD_PREPEND;
break;
default:
assert(0);
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_flush(conn *c) {
time_t exptime = 0;
protocol_binary_request_flush* req = binary_get_request(c);
if (c->binary_header.request.extlen == sizeof(req->message.body)) {
exptime = ntohl(req->message.body.expiration);
}
set_current_time();
if (exptime > 0) {
settings.oldest_live = realtime(exptime) - 1;
} else {
settings.oldest_live = current_time - 1;
}
item_flush_expired();
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_response(c, NULL, 0, 0, 0);
}
static void process_bin_delete(conn *c) {
item *it;
protocol_binary_request_delete* req = binary_get_request(c);
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
assert(c != NULL);
if (settings.verbose > 1) {
fprintf(stderr, "Deleting %s\n", key);
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey);
if (it) {
uint64_t cas = ntohll(req->message.header.request.cas);
if (cas == 0 || cas == ITEM_get_cas(it)) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
item_unlink(it);
write_bin_response(c, NULL, 0, 0, 0);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
static void complete_nread_binary(conn *c) {
assert(c != NULL);
assert(c->cmd >= 0);
switch(c->substate) {
case bin_reading_set_header:
if (c->cmd == PROTOCOL_BINARY_CMD_APPEND ||
c->cmd == PROTOCOL_BINARY_CMD_PREPEND) {
process_bin_append_prepend(c);
} else {
process_bin_update(c);
}
break;
case bin_read_set_value:
complete_update_bin(c);
break;
case bin_reading_get_key:
process_bin_get(c);
break;
case bin_reading_stat:
process_bin_stat(c);
break;
case bin_reading_del_header:
process_bin_delete(c);
break;
case bin_reading_incr_header:
complete_incr_bin(c);
break;
case bin_read_flush_exptime:
process_bin_flush(c);
break;
case bin_reading_sasl_auth:
process_bin_sasl_auth(c);
break;
case bin_reading_sasl_auth_data:
process_bin_complete_sasl_auth(c);
break;
default:
fprintf(stderr, "Not handling substate %d\n", c->substate);
assert(0);
}
}
static void reset_cmd_handler(conn *c) {
c->cmd = -1;
c->substate = bin_no_state;
if(c->item != NULL) {
item_remove(c->item);
c->item = NULL;
}
conn_shrink(c);
if (c->rbytes > 0) {
conn_set_state(c, conn_parse_cmd);
} else {
conn_set_state(c, conn_waiting);
}
}
static void complete_nread(conn *c) {
assert(c != NULL);
assert(c->protocol == ascii_prot
|| c->protocol == binary_prot);
if (c->protocol == ascii_prot) {
complete_nread_ascii(c);
} else if (c->protocol == binary_prot) {
complete_nread_binary(c);
}
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns the state of storage.
*/
enum store_item_type do_store_item(item *it, int comm, conn *c) {
char *key = ITEM_key(it);
item *old_it = do_item_get(key, it->nkey);
enum store_item_type stored = NOT_STORED;
item *new_it = NULL;
int flags;
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && (comm == NREAD_REPLACE
|| comm == NREAD_APPEND || comm == NREAD_PREPEND))
{
/* replace only replaces an existing value; don't store */
} else if (comm == NREAD_CAS) {
/* validate cas operation */
if(old_it == NULL) {
// LRU expired
stored = NOT_FOUND;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.cas_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) {
// cas validates
// it and old_it may belong to different classes.
// I'm updating the stats for the one that's getting pushed out
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[old_it->slabs_clsid].cas_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_replace(old_it, it);
stored = STORED;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[old_it->slabs_clsid].cas_badval++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(settings.verbose > 1) {
fprintf(stderr, "CAS: failure: expected %llu, got %llu\n",
(unsigned long long)ITEM_get_cas(old_it),
(unsigned long long)ITEM_get_cas(it));
}
stored = EXISTS;
}
} else {
/*
* Append - combine new and old record into single one. Here it's
* atomic and thread-safe.
*/
if (comm == NREAD_APPEND || comm == NREAD_PREPEND) {
/*
* Validate CAS
*/
if (ITEM_get_cas(it) != 0) {
// CAS much be equal
if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) {
stored = EXISTS;
}
}
if (stored == NOT_STORED) {
/* we have it and old_it here - alloc memory to hold both */
/* flags was already lost - so recover them from ITEM_suffix(it) */
flags = (int) strtol(ITEM_suffix(old_it), (char **) NULL, 10);
new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */);
if (new_it == NULL) {
/* SERVER_ERROR out of memory */
if (old_it != NULL)
do_item_remove(old_it);
return NOT_STORED;
}
/* copy data from it and old_it to new_it */
if (comm == NREAD_APPEND) {
memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes);
memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(it), it->nbytes);
} else {
/* NREAD_PREPEND */
memcpy(ITEM_data(new_it), ITEM_data(it), it->nbytes);
memcpy(ITEM_data(new_it) + it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes);
}
it = new_it;
}
}
if (stored == NOT_STORED) {
if (old_it != NULL)
item_replace(old_it, it);
else
do_item_link(it);
c->cas = ITEM_get_cas(it);
stored = STORED;
}
}
if (old_it != NULL)
do_item_remove(old_it); /* release our reference */
if (new_it != NULL)
do_item_remove(new_it);
if (stored == STORED) {
c->cas = ITEM_get_cas(it);
}
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 8
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
for (s = e = command; ntokens < max_tokens - 1; ++e) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
}
s = e + 1;
}
else if (*e == '\0') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
break; /* string end */
}
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
/* set up a connection to write a buffer then free it, used for stats */
static void write_and_free(conn *c, char *buf, int bytes) {
if (buf) {
c->write_and_free = buf;
c->wcurr = buf;
c->wbytes = bytes;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
} else {
out_string(c, "SERVER_ERROR out of memory writing stats");
}
}
static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens)
{
int noreply_index = ntokens - 2;
/*
NOTE: this function is not the first place where we are going to
send the reply. We could send it instead from process_command()
if the request line has wrong number of tokens. However parsing
malformed line for "noreply" option is not reliable anyway, so
it can't be helped.
*/
if (tokens[noreply_index].value
&& strcmp(tokens[noreply_index].value, "noreply") == 0) {
c->noreply = true;
}
return c->noreply;
}
void append_stat(const char *name, ADD_STAT add_stats, conn *c,
const char *fmt, ...) {
char val_str[STAT_VAL_LEN];
int vlen;
va_list ap;
assert(name);
assert(add_stats);
assert(c);
assert(fmt);
va_start(ap, fmt);
vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap);
va_end(ap);
add_stats(name, strlen(name), val_str, vlen, c);
}
inline static void process_stats_detail(conn *c, const char *command) {
assert(c != NULL);
if (strcmp(command, "on") == 0) {
settings.detail_enabled = 1;
out_string(c, "OK");
}
else if (strcmp(command, "off") == 0) {
settings.detail_enabled = 0;
out_string(c, "OK");
}
else if (strcmp(command, "dump") == 0) {
int len;
char *stats = stats_prefix_dump(&len);
write_and_free(c, stats, len);
}
else {
out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump");
}
}
/* return server specific stats only */
static void server_stats(ADD_STAT add_stats, conn *c) {
pid_t pid = getpid();
rel_time_t now = current_time;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(&thread_stats);
struct slab_stats slab_stats;
slab_stats_aggregate(&thread_stats, &slab_stats);
#ifndef WIN32
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
#endif /* !WIN32 */
STATS_LOCK();
APPEND_STAT("pid", "%lu", (long)pid);
APPEND_STAT("uptime", "%u", now);
APPEND_STAT("time", "%ld", now + (long)process_started);
APPEND_STAT("version", "%s", VERSION);
APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *)));
#ifndef WIN32
append_stat("rusage_user", add_stats, c, "%ld.%06ld",
(long)usage.ru_utime.tv_sec,
(long)usage.ru_utime.tv_usec);
append_stat("rusage_system", add_stats, c, "%ld.%06ld",
(long)usage.ru_stime.tv_sec,
(long)usage.ru_stime.tv_usec);
#endif /* !WIN32 */
APPEND_STAT("curr_connections", "%u", stats.curr_conns - 1);
APPEND_STAT("total_connections", "%u", stats.total_conns);
APPEND_STAT("connection_structures", "%u", stats.conn_structs);
APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds);
APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds);
APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds);
APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits);
APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses);
APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses);
APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits);
APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses);
APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits);
APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses);
APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits);
APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses);
APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits);
APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval);
APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read);
APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written);
APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("accepting_conns", "%u", stats.accepting_conns);
APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num);
APPEND_STAT("threads", "%d", settings.num_threads);
APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields);
STATS_UNLOCK();
}
static void process_stat_settings(ADD_STAT add_stats, void *c) {
assert(add_stats);
APPEND_STAT("maxbytes", "%u", (unsigned int)settings.maxbytes);
APPEND_STAT("maxconns", "%d", settings.maxconns);
APPEND_STAT("tcpport", "%d", settings.port);
APPEND_STAT("udpport", "%d", settings.udpport);
APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL");
APPEND_STAT("verbosity", "%d", settings.verbose);
APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live);
APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off");
APPEND_STAT("domain_socket", "%s",
settings.socketpath ? settings.socketpath : "NULL");
APPEND_STAT("umask", "%o", settings.access);
APPEND_STAT("growth_factor", "%.2f", settings.factor);
APPEND_STAT("chunk_size", "%d", settings.chunk_size);
APPEND_STAT("num_threads", "%d", settings.num_threads);
APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter);
APPEND_STAT("detail_enabled", "%s",
settings.detail_enabled ? "yes" : "no");
APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event);
APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no");
APPEND_STAT("tcp_backlog", "%d", settings.backlog);
APPEND_STAT("binding_protocol", "%s",
prot_text(settings.binding_protocol));
APPEND_STAT("item_size_max", "%d", settings.item_size_max);
}
static void process_stat(conn *c, token_t *tokens, const size_t ntokens) {
const char *subcommand = tokens[SUBCOMMAND_TOKEN].value;
assert(c != NULL);
if (ntokens < 2) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (ntokens == 2) {
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strcmp(subcommand, "reset") == 0) {
stats_reset();
out_string(c, "RESET");
return ;
} else if (strcmp(subcommand, "detail") == 0) {
/* NOTE: how to tackle detail with binary? */
if (ntokens < 4)
process_stats_detail(c, ""); /* outputs the error message */
else
process_stats_detail(c, tokens[2].value);
/* Output already generated */
return ;
} else if (strcmp(subcommand, "settings") == 0) {
process_stat_settings(&append_stats, c);
} else if (strcmp(subcommand, "cachedump") == 0) {
char *buf;
unsigned int bytes, id, limit = 0;
if (ntokens < 5) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (!safe_strtoul(tokens[2].value, &id) ||
!safe_strtoul(tokens[3].value, &limit)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (id >= POWER_LARGEST) {
out_string(c, "CLIENT_ERROR Illegal slab id");
return;
}
buf = item_cachedump(id, limit, &bytes);
write_and_free(c, buf, bytes);
return ;
} else {
/* getting here means that the subcommand is either engine specific or
is invalid. query the engine and see. */
if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_string(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
out_string(c, "ERROR");
}
return ;
}
/* append terminator and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_string(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
/* ntokens is overwritten here... shrug.. */
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) {
char *key;
size_t nkey;
int i = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
assert(c != NULL);
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
it = item_get(key, nkey);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
item_remove(it);
break;
}
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
item_remove(it);
break;
}
}
suffix = cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
out_string(c, "SERVER_ERROR out of memory making CAS suffix");
item_remove(it);
return;
}
*(c->suffixlist + i) = suffix;
int suffix_len = snprintf(suffix, SUFFIX_SIZE,
" %llu\r\n",
(unsigned long long)ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0 ||
add_iov(c, suffix, suffix_len) != 0 ||
add_iov(c, ITEM_data(it), it->nbytes) != 0)
{
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
}
if (settings.verbose > 1)
fprintf(stderr, ">%d sending key %s\n", c->sfd, ITEM_key(it));
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_update(it);
*(c->ilist + i) = it;
i++;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_misses++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas) {
c->suffixcurr = c->suffixlist;
c->suffixleft = i;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_string(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
return;
}
static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
// does cas value exist?
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
vlen += 2;
if (vlen < 0 || vlen - 2 < 0) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
if (! item_size_ok(nkey, flags, vlen))
out_string(c, "SERVER_ERROR object too large for cache");
else
out_string(c, "SERVER_ERROR out of memory storing object");
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey);
if (it) {
item_unlink(it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) {
char temp[INCR_MAX_STORAGE_LEN];
item *it;
uint64_t delta;
char *key;
size_t nkey;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtoull(tokens[2].value, &delta)) {
out_string(c, "CLIENT_ERROR invalid numeric delta argument");
return;
}
it = item_get(key, nkey);
if (!it) {
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
return;
}
switch(add_delta(c, it, incr, delta, temp)) {
case OK:
out_string(c, temp);
break;
case NON_NUMERIC:
out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value");
break;
case EOM:
out_string(c, "SERVER_ERROR out of memory");
break;
}
item_remove(it); /* release our reference */
}
/*
* adds a delta value to a numeric item.
*
* c connection requesting the operation
* it item to adjust
* incr true to increment value, false to decrement
* delta amount to adjust value by
* buf buffer for response string
*
* returns a response string to send back to the client.
*/
enum delta_result_type do_add_delta(conn *c, item *it, const bool incr,
const int64_t delta, char *buf) {
char *ptr;
uint64_t value;
int res;
ptr = ITEM_data(it);
if (!safe_strtoull(ptr, &value)) {
return NON_NUMERIC;
}
if (incr) {
value += delta;
MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value);
} else {
if(delta > value) {
value = 0;
} else {
value -= delta;
}
MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value);
}
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.slab_stats[it->slabs_clsid].incr_hits++;
} else {
c->thread->stats.slab_stats[it->slabs_clsid].decr_hits++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value);
res = strlen(buf);
if (res + 2 > it->nbytes) { /* need to realloc */
item *new_it;
new_it = do_item_alloc(ITEM_key(it), it->nkey, atoi(ITEM_suffix(it) + 1), it->exptime, res + 2 );
if (new_it == 0) {
return EOM;
}
memcpy(ITEM_data(new_it), buf, res);
memcpy(ITEM_data(new_it) + res, "\r\n", 2);
item_replace(it, new_it);
do_item_remove(new_it); /* release our reference */
} else { /* replace in-place */
/* When changing the value without replacing the item, we
need to update the CAS on the existing item. */
ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
memcpy(ITEM_data(it), buf, res);
memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2);
}
return OK;
}
static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
item *it;
assert(c != NULL);
if (ntokens == 4) {
if (!set_noreply_maybe(c, tokens, ntokens)) {
out_string(c, "CLIENT_ERROR bad command line format. "
"Usage: delete <key> [noreply]");
return;
}
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey);
if (it) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
item_remove(it); /* release our reference */
out_string(c, "DELETED");
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
level = strtoul(tokens[1].value, NULL, 10);
settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level;
out_string(c, "OK");
return;
}
static void process_command(conn *c, char *command) {
token_t tokens[MAX_TOKENS];
size_t ntokens;
int comm;
assert(c != NULL);
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
if (settings.verbose > 1)
fprintf(stderr, "<%d %s\n", c->sfd, command);
/*
* for commands set/add/replace, we build an item and read the data
* directly into it, then continue in nread_complete().
*/
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory preparing response");
return;
}
ntokens = tokenize_command(command, tokens, MAX_TOKENS);
if (ntokens >= 3 &&
((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) ||
(strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) {
process_get_command(c, tokens, ntokens, false);
} else if ((ntokens == 6 || ntokens == 7) &&
((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) {
process_update_command(c, tokens, ntokens, comm, false);
} else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) {
process_update_command(c, tokens, ntokens, comm, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 1);
} else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) {
process_get_command(c, tokens, ntokens, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 0);
} else if (ntokens >= 3 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) {
process_delete_command(c, tokens, ntokens);
} else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) {
process_stat(c, tokens, ntokens);
} else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) {
time_t exptime = 0;
set_current_time();
set_noreply_maybe(c, tokens, ntokens);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(ntokens == (c->noreply ? 3 : 2)) {
settings.oldest_live = current_time - 1;
item_flush_expired();
out_string(c, "OK");
return;
}
exptime = strtol(tokens[1].value, NULL, 10);
if(errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/*
If exptime is zero realtime() would return zero too, and
realtime(exptime) - 1 would overflow to the max unsigned
value. So we process exptime == 0 the same way we do when
no delay is given at all.
*/
if (exptime > 0)
settings.oldest_live = realtime(exptime) - 1;
else /* exptime == 0 */
settings.oldest_live = current_time - 1;
item_flush_expired();
out_string(c, "OK");
return;
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) {
out_string(c, "VERSION " VERSION);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) {
conn_set_state(c, conn_closing);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) {
process_verbosity_command(c, tokens, ntokens);
} else {
out_string(c, "ERROR");
}
return;
}
/*
* if we have a complete line in the buffer, process it.
*/
static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
/*
* read a UDP request.
*/
static enum try_read_result try_read_udp(conn *c) {
int res;
assert(c != NULL);
c->request_addr_size = sizeof(c->request_addr);
res = recvfrom(c->sfd, c->rbuf, c->rsize,
0, &c->request_addr, &c->request_addr_size);
if (res > 8) {
unsigned char *buf = (unsigned char *)c->rbuf;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* Beginning of UDP packet is the request ID; save it. */
c->request_id = buf[0] * 256 + buf[1];
/* If this is a multi-packet request, drop it. */
if (buf[4] != 0 || buf[5] != 1) {
out_string(c, "SERVER_ERROR multi-packet request not supported");
return READ_NO_DATA_RECEIVED;
}
/* Don't care about any of the rest of the header. */
res -= 8;
memmove(c->rbuf, c->rbuf + 8, res);
c->rbytes += res;
c->rcurr = c->rbuf;
return READ_DATA_RECEIVED;
}
return READ_NO_DATA_RECEIVED;
}
/*
* read from network as much as we can, handle buffer overflow and connection
* close.
* before reading, move the remaining incomplete fragment of a command
* (if any) to the beginning of the buffer.
*
* To protect us from someone flooding a connection with bogus data causing
* the connection to eat up all available memory, break out and start looking
* at the data I've got after a number of reallocs...
*
* @return enum try_read_result
*/
static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
int num_allocs = 0;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
if (num_allocs == 4) {
return gotdata;
}
++num_allocs;
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't realloc input buffer\n");
c->rbytes = 0; /* ignore what we read */
out_string(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = read(c->sfd, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
static bool update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags)
return true;
if (event_del(&c->event) == -1) return false;
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) return false;
return true;
}
/*
* Sets whether we are listening for new connections or not.
*/
void do_accept_new_conns(const bool do_accept) {
conn *next;
for (next = listen_conn; next; next = next->next) {
if (do_accept) {
update_event(next, EV_READ | EV_PERSIST);
if (listen(next->sfd, settings.backlog) != 0) {
perror("listen");
}
}
else {
update_event(next, 0);
if (listen(next->sfd, 0) != 0) {
perror("listen");
}
}
}
if (do_accept) {
STATS_LOCK();
stats.accepting_conns = true;
STATS_UNLOCK();
} else {
STATS_LOCK();
stats.accepting_conns = false;
stats.listen_disabled_num++;
STATS_UNLOCK();
}
}
/*
* Transmit the next chunk of data from our list of msgbuf structures.
*
* Returns:
* TRANSMIT_COMPLETE All done writing.
* TRANSMIT_INCOMPLETE More data remaining to write.
* TRANSMIT_SOFT_ERROR Can't write any more right now.
* TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
*/
static enum transmit_result transmit(conn *c) {
assert(c != NULL);
if (c->msgcurr < c->msgused &&
c->msglist[c->msgcurr].msg_iovlen == 0) {
/* Finished writing the current msg; advance to the next. */
c->msgcurr++;
}
if (c->msgcurr < c->msgused) {
ssize_t res;
struct msghdr *m = &c->msglist[c->msgcurr];
res = sendmsg(c->sfd, m, 0);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_written += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We've written some of the data. Remove the completed
iovec entries from the list of pending writes. */
while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) {
res -= m->msg_iov->iov_len;
m->msg_iovlen--;
m->msg_iov++;
}
/* Might have written just part of the last iovec entry;
adjust it so the next write will do the rest. */
if (res > 0) {
m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res;
m->msg_iov->iov_len -= res;
}
return TRANSMIT_INCOMPLETE;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
}
return TRANSMIT_SOFT_ERROR;
}
/* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK,
we have a real error, on which we close the connection */
if (settings.verbose > 0)
perror("Failed to write, and not due to blocking");
if (IS_UDP(c->transport))
conn_set_state(c, conn_read);
else
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
} else {
return TRANSMIT_COMPLETE;
}
}
static void drive_machine(conn *c) {
bool stop = false;
int sfd, flags = 1;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, tcp_transport);
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = read(c->sfd, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes == 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
while (c->suffixleft > 0) {
char *suffix = *(c->suffixcurr);
cache_free(c->thread->suffix_cache, suffix);
c->suffixcurr++;
c->suffixleft--;
}
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
}
void event_handler(const int fd, const short which, void *arg) {
conn *c;
c = (conn *)arg;
assert(c != NULL);
c->which = which;
/* sanity */
if (fd != c->sfd) {
if (settings.verbose > 0)
fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n");
conn_close(c);
return;
}
drive_machine(c);
/* wait for next event */
return;
}
static int new_socket(struct addrinfo *ai) {
int sfd;
int flags;
if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
/*
* Sets a socket's send buffer size to the maximum allowed by the system.
*/
static void maximize_sndbuf(const int sfd) {
socklen_t intsize = sizeof(int);
int last_good = 0;
int min, max, avg;
int old_size;
/* Start with the default size. */
if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) {
if (settings.verbose > 0)
perror("getsockopt(SO_SNDBUF)");
return;
}
/* Binary-search for the real maximum. */
min = old_size;
max = MAX_SENDBUF_SIZE;
while (min <= max) {
avg = ((unsigned int)(min + max)) / 2;
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) {
last_good = avg;
min = avg + 1;
} else {
max = avg - 1;
}
}
if (settings.verbose > 1)
fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good);
}
/**
* Create a socket and bind it to a specific port number
* @param port the port number to bind to
* @param transport the transport protocol (TCP / UDP)
* @param portnumber_file A filepointer to write the port numbers to
* when they are successfully added to the list of ports we
* listen on.
*/
static int server_socket(int port, enum network_transport transport,
FILE *portnumber_file) {
int sfd;
struct linger ling = {0, 0};
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = { .ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC };
char port_buf[NI_MAXSERV];
int error;
int success = 0;
int flags =1;
hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM;
if (port == -1) {
port = 0;
}
snprintf(port_buf, sizeof(port_buf), "%d", port);
error= getaddrinfo(settings.inter, port_buf, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM)
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
else
perror("getaddrinfo()");
return 1;
}
for (next= ai; next; next= next->ai_next) {
conn *listen_conn_add;
if ((sfd = new_socket(next)) == -1) {
/* getaddrinfo can return "junk" addresses,
* we make sure at least one works before erroring.
*/
continue;
}
#ifdef IPV6_V6ONLY
if (next->ai_family == AF_INET6) {
error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags));
if (error != 0) {
perror("setsockopt");
close(sfd);
continue;
}
}
#endif
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
if (IS_UDP(transport)) {
maximize_sndbuf(sfd);
} else {
error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
}
if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
if (errno != EADDRINUSE) {
perror("bind()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
close(sfd);
continue;
} else {
success++;
if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
if (portnumber_file != NULL &&
(next->ai_addr->sa_family == AF_INET ||
next->ai_addr->sa_family == AF_INET6)) {
union {
struct sockaddr_in in;
struct sockaddr_in6 in6;
} my_sockaddr;
socklen_t len = sizeof(my_sockaddr);
if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
if (next->ai_addr->sa_family == AF_INET) {
fprintf(portnumber_file, "%s INET: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in.sin_port));
} else {
fprintf(portnumber_file, "%s INET6: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in6.sin6_port));
}
}
}
}
if (IS_UDP(transport)) {
int c;
for (c = 0; c < settings.num_threads; c++) {
/* this is guaranteed to hit all threads because we round-robin */
dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,
UDP_READ_BUFFER_SIZE, transport);
}
} else {
if (!(listen_conn_add = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
listen_conn_add->next = listen_conn;
listen_conn = listen_conn_add;
}
}
freeaddrinfo(ai);
/* Return zero iff we detected no errors in starting up connections */
return success == 0;
}
static int new_socket_unix(void) {
int sfd;
int flags;
if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket()");
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
static int server_socket_unix(const char *path, int access_mask) {
int sfd;
struct linger ling = {0, 0};
struct sockaddr_un addr;
struct stat tstat;
int flags =1;
int old_umask;
if (!path) {
return 1;
}
if ((sfd = new_socket_unix()) == -1) {
return 1;
}
/*
* Clean up a previous socket file if we left it around
*/
if (lstat(path, &tstat) == 0) {
if (S_ISSOCK(tstat.st_mode))
unlink(path);
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/*
* the memset call clears nonstandard fields in some impementations
* that otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
assert(strcmp(addr.sun_path, path) == 0);
old_umask = umask( ~(access_mask&0777));
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind()");
close(sfd);
umask(old_umask);
return 1;
}
umask(old_umask);
if (listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
return 1;
}
if (!(listen_conn = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
local_transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*
* We keep the current time of day in a global variable that's updated by a
* timer event. This saves us a bunch of time() system calls (we really only
* need to get the time once a second, whereas there can be tens of thousands
* of requests a second) and allows us to use server-start-relative timestamps
* rather than absolute UNIX timestamps, a space savings on systems where
* sizeof(time_t) > sizeof(unsigned int).
*/
volatile rel_time_t current_time;
static struct event clockevent;
/* time-sensitive callers can call it by hand with this, outside the normal ever-1-second timer */
static void set_current_time(void) {
struct timeval timer;
gettimeofday(&timer, NULL);
current_time = (rel_time_t) (timer.tv_sec - process_started);
}
static void clock_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
static bool initialized = false;
if (initialized) {
/* only delete the event if it's actually there. */
evtimer_del(&clockevent);
} else {
initialized = true;
}
evtimer_set(&clockevent, clock_handler, 0);
event_base_set(main_base, &clockevent);
evtimer_add(&clockevent, &t);
set_current_time();
}
static void usage(void) {
printf(PACKAGE " " VERSION "\n");
printf("-p <num> TCP port number to listen on (default: 11211)\n"
"-U <num> UDP port number to listen on (default: 11211, 0 is off)\n"
"-s <file> UNIX socket path to listen on (disables network support)\n"
"-a <mask> access mask for UNIX socket, in octal (default: 0700)\n"
"-l <ip_addr> interface to listen on (default: INADDR_ANY, all addresses)\n"
"-d run as a daemon\n"
"-r maximize core file limit\n"
"-u <username> assume identity of <username> (only when run as root)\n"
"-m <num> max memory to use for items in megabytes (default: 64 MB)\n"
"-M return error on memory exhausted (rather than removing items)\n"
"-c <num> max simultaneous connections (default: 1024)\n"
"-k lock down all paged memory. Note that there is a\n"
" limit on how much memory you may lock. Trying to\n"
" allocate more than that would fail, so be sure you\n"
" set the limit correctly for the user you started\n"
" the daemon with (not for -u <username> user;\n"
" under sh this is done with 'ulimit -S -l NUM_KB').\n"
"-v verbose (print errors/warnings while in event loop)\n"
"-vv very verbose (also print client commands/reponses)\n"
"-vvv extremely verbose (also print internal state transitions)\n"
"-h print this help and exit\n"
"-i print memcached and libevent license\n"
"-P <file> save PID in <file>, only used with -d option\n"
"-f <factor> chunk size growth factor (default: 1.25)\n"
"-n <bytes> minimum space allocated for key+value+flags (default: 48)\n");
printf("-L Try to use large memory pages (if available). Increasing\n"
" the memory page size could reduce the number of TLB misses\n"
" and improve the performance. In order to get large pages\n"
" from the OS, memcached will allocate the total item-cache\n"
" in one large chunk.\n");
printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n"
" This is used for per-prefix stats reporting. The default is\n"
" \":\" (colon). If this option is specified, stats collection\n"
" is turned on automatically; if not, then it may be turned on\n"
" by sending the \"stats detail on\" command to the server.\n");
printf("-t <num> number of threads to use (default: 4)\n");
printf("-R Maximum number of requests per event, limits the number of\n"
" requests process for a given connection to prevent \n"
" starvation (default: 20)\n");
printf("-C Disable use of CAS\n");
printf("-b Set the backlog queue limit (default: 1024)\n");
printf("-B Binding protocol - one of ascii, binary, or auto (default)\n");
printf("-I Override the size of each slab page. Adjusts max item size\n"
" (default: 1mb, min: 1k, max: 128m)\n");
#ifdef ENABLE_SASL
printf("-S Turn on Sasl authentication\n");
#endif
return;
}
static void usage_license(void) {
printf(PACKAGE " " VERSION "\n\n");
printf(
"Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are\n"
"met:\n"
"\n"
" * Redistributions of source code must retain the above copyright\n"
"notice, this list of conditions and the following disclaimer.\n"
"\n"
" * Redistributions in binary form must reproduce the above\n"
"copyright notice, this list of conditions and the following disclaimer\n"
"in the documentation and/or other materials provided with the\n"
"distribution.\n"
"\n"
" * Neither the name of the Danga Interactive nor the names of its\n"
"contributors may be used to endorse or promote products derived from\n"
"this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"\n"
"\n"
"This product includes software developed by Niels Provos.\n"
"\n"
"[ libevent ]\n"
"\n"
"Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions\n"
"are met:\n"
"1. Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
"3. All advertising materials mentioning features or use of this software\n"
" must display the following acknowledgement:\n"
" This product includes software developed by Niels Provos.\n"
"4. The name of the author may not be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n"
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
);
return;
}
static void save_pid(const pid_t pid, const char *pid_file) {
FILE *fp;
if (pid_file == NULL)
return;
if ((fp = fopen(pid_file, "w")) == NULL) {
fprintf(stderr, "Could not open the pid file %s for writing\n", pid_file);
return;
}
fprintf(fp,"%ld\n", (long)pid);
if (fclose(fp) == -1) {
fprintf(stderr, "Could not close the pid file %s.\n", pid_file);
return;
}
}
static void remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
fprintf(stderr, "Could not remove the pid file %s.\n", pid_file);
}
}
static void sig_handler(const int sig) {
printf("SIGINT handled.\n");
exit(EXIT_SUCCESS);
}
#ifndef HAVE_SIGIGNORE
static int sigignore(int sig) {
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 };
if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) {
return -1;
}
return 0;
}
#endif
/*
* On systems that supports multiple page sizes we may reduce the
* number of TLB-misses by using the biggest available page size
*/
static int enable_large_pages(void) {
#if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL)
int ret = -1;
size_t sizes[32];
int avail = getpagesizes(sizes, 32);
if (avail != -1) {
size_t max = sizes[0];
struct memcntl_mha arg = {0};
int ii;
for (ii = 1; ii < avail; ++ii) {
if (max < sizes[ii]) {
max = sizes[ii];
}
}
arg.mha_flags = 0;
arg.mha_pagesize = max;
arg.mha_cmd = MHA_MAPSIZE_BSSBRK;
if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) {
fprintf(stderr, "Failed to set large pages: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
} else {
ret = 0;
}
} else {
fprintf(stderr, "Failed to get supported pagesizes: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
}
return ret;
#else
return 0;
#endif
}
int main (int argc, char **argv) {
int c;
bool lock_memory = false;
bool do_daemonize = false;
bool preallocate = false;
int maxcore = 0;
char *username = NULL;
char *pid_file = NULL;
struct passwd *pw;
struct rlimit rlim;
char unit = '\0';
int size_max = 0;
/* listening sockets */
static int *l_socket = NULL;
/* udp socket */
static int *u_socket = NULL;
bool protocol_specified = false;
bool tcp_specified = false;
bool udp_specified = false;
/* handle SIGINT */
signal(SIGINT, sig_handler);
/* init settings */
settings_init();
/* set stderr non-buffering (for running under, say, daemontools) */
setbuf(stderr, NULL);
/* process arguments */
while (-1 != (c = getopt(argc, argv,
"a:" /* access mask for unix socket */
"p:" /* TCP port number to listen on */
"s:" /* unix socket path to listen on */
"U:" /* UDP port number to listen on */
"m:" /* max memory to use for items in megabytes */
"M" /* return error on memory exhausted */
"c:" /* max simultaneous connections */
"k" /* lock down all paged memory */
"hi" /* help, licence info */
"r" /* maximize core file limit */
"v" /* verbose */
"d" /* daemon mode */
"l:" /* interface to listen on */
"u:" /* user identity to run as */
"P:" /* save PID in file */
"f:" /* factor? */
"n:" /* minimum space allocated for key+value+flags */
"t:" /* threads */
"D:" /* prefix delimiter? */
"L" /* Large memory pages */
"R:" /* max requests per event */
"C" /* Disable use of CAS */
"b:" /* backlog queue limit */
"B:" /* Binding protocol */
"I:" /* Max item size */
"S" /* Sasl ON */
))) {
switch (c) {
case 'a':
/* access for unix domain socket, as octal mask (like chmod)*/
settings.access= strtol(optarg,NULL,8);
break;
case 'U':
settings.udpport = atoi(optarg);
udp_specified = true;
break;
case 'p':
settings.port = atoi(optarg);
tcp_specified = true;
break;
case 's':
settings.socketpath = optarg;
break;
case 'm':
settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
break;
case 'M':
settings.evict_to_free = 0;
break;
case 'c':
settings.maxconns = atoi(optarg);
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'i':
usage_license();
exit(EXIT_SUCCESS);
case 'k':
lock_memory = true;
break;
case 'v':
settings.verbose++;
break;
case 'l':
settings.inter= strdup(optarg);
break;
case 'd':
do_daemonize = true;
break;
case 'r':
maxcore = 1;
break;
case 'R':
settings.reqs_per_event = atoi(optarg);
if (settings.reqs_per_event == 0) {
fprintf(stderr, "Number of requests per event must be greater than 0\n");
return 1;
}
break;
case 'u':
username = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'f':
settings.factor = atof(optarg);
if (settings.factor <= 1.0) {
fprintf(stderr, "Factor must be greater than 1\n");
return 1;
}
break;
case 'n':
settings.chunk_size = atoi(optarg);
if (settings.chunk_size == 0) {
fprintf(stderr, "Chunk size must be greater than 0\n");
return 1;
}
break;
case 't':
settings.num_threads = atoi(optarg);
if (settings.num_threads <= 0) {
fprintf(stderr, "Number of threads must be greater than 0\n");
return 1;
}
/* There're other problems when you get above 64 threads.
* In the future we should portably detect # of cores for the
* default.
*/
if (settings.num_threads > 64) {
fprintf(stderr, "WARNING: Setting a high number of worker"
"threads is not recommended.\n"
" Set this value to the number of cores in"
" your machine or less.\n");
}
break;
case 'D':
if (! optarg || ! optarg[0]) {
fprintf(stderr, "No delimiter specified\n");
return 1;
}
settings.prefix_delimiter = optarg[0];
settings.detail_enabled = 1;
break;
case 'L' :
if (enable_large_pages() == 0) {
preallocate = true;
}
break;
case 'C' :
settings.use_cas = false;
break;
case 'b' :
settings.backlog = atoi(optarg);
break;
case 'B':
protocol_specified = true;
if (strcmp(optarg, "auto") == 0) {
settings.binding_protocol = negotiating_prot;
} else if (strcmp(optarg, "binary") == 0) {
settings.binding_protocol = binary_prot;
} else if (strcmp(optarg, "ascii") == 0) {
settings.binding_protocol = ascii_prot;
} else {
fprintf(stderr, "Invalid value for binding protocol: %s\n"
" -- should be one of auto, binary, or ascii\n", optarg);
exit(EX_USAGE);
}
break;
case 'I':
unit = optarg[strlen(optarg)-1];
if (unit == 'k' || unit == 'm' ||
unit == 'K' || unit == 'M') {
optarg[strlen(optarg)-1] = '\0';
size_max = atoi(optarg);
if (unit == 'k' || unit == 'K')
size_max *= 1024;
if (unit == 'm' || unit == 'M')
size_max *= 1024 * 1024;
settings.item_size_max = size_max;
} else {
settings.item_size_max = atoi(optarg);
}
if (settings.item_size_max < 1024) {
fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n");
return 1;
}
if (settings.item_size_max > 1024 * 1024 * 128) {
fprintf(stderr, "Cannot set item size limit higher than 128 mb.\n");
return 1;
}
if (settings.item_size_max > 1024 * 1024) {
fprintf(stderr, "WARNING: Setting item max size above 1MB is not"
" recommended!\n"
" Raising this limit increases the minimum memory requirements\n"
" and will decrease your memory efficiency.\n"
);
}
break;
case 'S': /* set Sasl authentication to true. Default is false */
#ifndef ENABLE_SASL
fprintf(stderr, "This server is not built with SASL support.\n");
exit(EX_USAGE);
#endif
settings.sasl = true;
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
return 1;
}
}
if (settings.sasl) {
if (!protocol_specified) {
settings.binding_protocol = binary_prot;
} else {
if (settings.binding_protocol != binary_prot) {
fprintf(stderr, "WARNING: You shouldn't allow the ASCII protocol while using SASL\n");
exit(EX_USAGE);
}
}
}
if (tcp_specified && !udp_specified) {
settings.udpport = settings.port;
} else if (udp_specified && !tcp_specified) {
settings.port = settings.udpport;
}
if (maxcore != 0) {
struct rlimit rlim_new;
/*
* First try raising to infinity; if that fails, try bringing
* the soft limit to the hard.
*/
if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) {
/* failed. try raising just to the old max */
rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
(void)setrlimit(RLIMIT_CORE, &rlim_new);
}
}
/*
* getrlimit again to see what we ended up with. Only fail if
* the soft limit ends up 0, because then no core files will be
* created at all.
*/
if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) {
fprintf(stderr, "failed to ensure corefile creation\n");
exit(EX_OSERR);
}
}
/*
* If needed, increase rlimits to allow as many connections
* as needed.
*/
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to getrlimit number of files\n");
exit(EX_OSERR);
} else {
int maxfiles = settings.maxconns;
if (rlim.rlim_cur < maxfiles)
rlim.rlim_cur = maxfiles;
if (rlim.rlim_max < rlim.rlim_cur)
rlim.rlim_max = rlim.rlim_cur;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to set rlimit for open files. Try running as root or requesting smaller maxconns value.\n");
exit(EX_OSERR);
}
}
/* lose root privileges if we have them */
if (getuid() == 0 || geteuid() == 0) {
if (username == 0 || *username == '\0') {
fprintf(stderr, "can't run as root without the -u switch\n");
exit(EX_USAGE);
}
if ((pw = getpwnam(username)) == 0) {
fprintf(stderr, "can't find the user %s to switch to\n", username);
exit(EX_NOUSER);
}
if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
fprintf(stderr, "failed to assume identity of user %s\n", username);
exit(EX_OSERR);
}
}
/* Initialize Sasl if -S was specified */
if (settings.sasl) {
init_sasl();
}
/* daemonize if requested */
/* if we want to ensure our ability to dump core, don't chdir to / */
if (do_daemonize) {
if (sigignore(SIGHUP) == -1) {
perror("Failed to ignore SIGHUP");
}
if (daemonize(maxcore, settings.verbose) == -1) {
fprintf(stderr, "failed to daemon() in order to daemonize\n");
exit(EXIT_FAILURE);
}
}
/* lock paged memory if needed */
if (lock_memory) {
#ifdef HAVE_MLOCKALL
int res = mlockall(MCL_CURRENT | MCL_FUTURE);
if (res != 0) {
fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n",
strerror(errno));
}
#else
fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n");
#endif
}
/* initialize main thread libevent instance */
main_base = event_init();
/* initialize other stuff */
stats_init();
assoc_init();
conn_init();
slabs_init(settings.maxbytes, settings.factor, preallocate);
/*
* ignore SIGPIPE signals; we can use errno == EPIPE if we
* need that information
*/
if (sigignore(SIGPIPE) == -1) {
perror("failed to ignore SIGPIPE; sigaction");
exit(EX_OSERR);
}
/* start up worker threads if MT mode */
thread_init(settings.num_threads, main_base);
/* save the PID in if we're a daemon, do this after thread_init due to
a file descriptor handling bug somewhere in libevent */
if (start_assoc_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (do_daemonize)
save_pid(getpid(), pid_file);
/* initialise clock event */
clock_handler(0, 0, 0);
/* create unix mode sockets after dropping privileges */
if (settings.socketpath != NULL) {
errno = 0;
if (server_socket_unix(settings.socketpath,settings.access)) {
vperror("failed to listen on UNIX socket: %s", settings.socketpath);
exit(EX_OSERR);
}
}
/* create the listening socket, bind it, and init */
if (settings.socketpath == NULL) {
int udp_port;
const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME");
char temp_portnumber_filename[PATH_MAX];
FILE *portnumber_file = NULL;
if (portnumber_filename != NULL) {
snprintf(temp_portnumber_filename,
sizeof(temp_portnumber_filename),
"%s.lck", portnumber_filename);
portnumber_file = fopen(temp_portnumber_filename, "a");
if (portnumber_file == NULL) {
fprintf(stderr, "Failed to open \"%s\": %s\n",
temp_portnumber_filename, strerror(errno));
}
}
errno = 0;
if (settings.port && server_socket(settings.port, tcp_transport,
portnumber_file)) {
vperror("failed to listen on TCP port %d", settings.port);
exit(EX_OSERR);
}
/*
* initialization order: first create the listening sockets
* (may need root on low ports), then drop root if needed,
* then daemonise if needed, then init libevent (in some cases
* descriptors created by libevent wouldn't survive forking).
*/
udp_port = settings.udpport ? settings.udpport : settings.port;
/* create the UDP listening socket and bind it */
errno = 0;
if (settings.udpport && server_socket(settings.udpport, udp_transport,
portnumber_file)) {
vperror("failed to listen on UDP port %d", settings.udpport);
exit(EX_OSERR);
}
if (portnumber_file) {
fclose(portnumber_file);
rename(temp_portnumber_filename, portnumber_filename);
}
}
/* Drop privileges no longer needed */
drop_privileges();
/* enter the event loop */
event_base_loop(main_base, 0);
stop_assoc_maintenance_thread();
/* remove the PID file if we're a daemon */
if (do_daemonize)
remove_pidfile(pid_file);
/* Clean up strdup() call for bind() address */
if (settings.inter)
free(settings.inter);
if (l_socket)
free(l_socket);
if (u_socket)
free(u_socket);
return EXIT_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4700_0 |
crossvul-cpp_data_bad_1564_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);
}
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 (!str_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-20/c/bad_1564_0 |
crossvul-cpp_data_good_5845_18 | /*
* net/key/af_key.c An implementation of PF_KEYv2 sockets.
*
* 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.
*
* Authors: Maxim Giryaev <gem@asplinux.ru>
* David S. Miller <davem@redhat.com>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* Kazunori MIYAZAWA / USAGI Project <miyazawa@linux-ipv6.org>
* Derek Atkins <derek@ihtfp.com>
*/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/socket.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/xfrm.h>
#include <net/sock.h>
#define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x))
#define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x))
static int pfkey_net_id __read_mostly;
struct netns_pfkey {
/* List of all pfkey sockets. */
struct hlist_head table;
atomic_t socks_nr;
};
static DEFINE_MUTEX(pfkey_mutex);
#define DUMMY_MARK 0
static const struct xfrm_mark dummy_mark = {0, 0};
struct pfkey_sock {
/* struct sock must be the first member of struct pfkey_sock */
struct sock sk;
int registered;
int promisc;
struct {
uint8_t msg_version;
uint32_t msg_portid;
int (*dump)(struct pfkey_sock *sk);
void (*done)(struct pfkey_sock *sk);
union {
struct xfrm_policy_walk policy;
struct xfrm_state_walk state;
} u;
struct sk_buff *skb;
} dump;
};
static inline struct pfkey_sock *pfkey_sk(struct sock *sk)
{
return (struct pfkey_sock *)sk;
}
static int pfkey_can_dump(const struct sock *sk)
{
if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf)
return 1;
return 0;
}
static void pfkey_terminate_dump(struct pfkey_sock *pfk)
{
if (pfk->dump.dump) {
if (pfk->dump.skb) {
kfree_skb(pfk->dump.skb);
pfk->dump.skb = NULL;
}
pfk->dump.done(pfk);
pfk->dump.dump = NULL;
pfk->dump.done = NULL;
}
}
static void pfkey_sock_destruct(struct sock *sk)
{
struct net *net = sock_net(sk);
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
pfkey_terminate_dump(pfkey_sk(sk));
skb_queue_purge(&sk->sk_receive_queue);
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Attempt to release alive pfkey socket: %p\n", sk);
return;
}
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
atomic_dec(&net_pfkey->socks_nr);
}
static const struct proto_ops pfkey_ops;
static void pfkey_insert(struct sock *sk)
{
struct net *net = sock_net(sk);
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
mutex_lock(&pfkey_mutex);
sk_add_node_rcu(sk, &net_pfkey->table);
mutex_unlock(&pfkey_mutex);
}
static void pfkey_remove(struct sock *sk)
{
mutex_lock(&pfkey_mutex);
sk_del_node_init_rcu(sk);
mutex_unlock(&pfkey_mutex);
}
static struct proto key_proto = {
.name = "KEY",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pfkey_sock),
};
static int pfkey_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
struct sock *sk;
int err;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
if (protocol != PF_KEY_V2)
return -EPROTONOSUPPORT;
err = -ENOMEM;
sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto);
if (sk == NULL)
goto out;
sock->ops = &pfkey_ops;
sock_init_data(sock, sk);
sk->sk_family = PF_KEY;
sk->sk_destruct = pfkey_sock_destruct;
atomic_inc(&net_pfkey->socks_nr);
pfkey_insert(sk);
return 0;
out:
return err;
}
static int pfkey_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
return 0;
pfkey_remove(sk);
sock_orphan(sk);
sock->sk = NULL;
skb_queue_purge(&sk->sk_write_queue);
synchronize_rcu();
sock_put(sk);
return 0;
}
static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2,
gfp_t allocation, struct sock *sk)
{
int err = -ENOBUFS;
sock_hold(sk);
if (*skb2 == NULL) {
if (atomic_read(&skb->users) != 1) {
*skb2 = skb_clone(skb, allocation);
} else {
*skb2 = skb;
atomic_inc(&skb->users);
}
}
if (*skb2 != NULL) {
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
skb_set_owner_r(*skb2, sk);
skb_queue_tail(&sk->sk_receive_queue, *skb2);
sk->sk_data_ready(sk, (*skb2)->len);
*skb2 = NULL;
err = 0;
}
}
sock_put(sk);
return err;
}
/* Send SKB to all pfkey sockets matching selected criteria. */
#define BROADCAST_ALL 0
#define BROADCAST_ONE 1
#define BROADCAST_REGISTERED 2
#define BROADCAST_PROMISC_ONLY 4
static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation,
int broadcast_flags, struct sock *one_sk,
struct net *net)
{
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
struct sock *sk;
struct sk_buff *skb2 = NULL;
int err = -ESRCH;
/* XXX Do we need something like netlink_overrun? I think
* XXX PF_KEY socket apps will not mind current behavior.
*/
if (!skb)
return -ENOMEM;
rcu_read_lock();
sk_for_each_rcu(sk, &net_pfkey->table) {
struct pfkey_sock *pfk = pfkey_sk(sk);
int err2;
/* Yes, it means that if you are meant to receive this
* pfkey message you receive it twice as promiscuous
* socket.
*/
if (pfk->promisc)
pfkey_broadcast_one(skb, &skb2, allocation, sk);
/* the exact target will be processed later */
if (sk == one_sk)
continue;
if (broadcast_flags != BROADCAST_ALL) {
if (broadcast_flags & BROADCAST_PROMISC_ONLY)
continue;
if ((broadcast_flags & BROADCAST_REGISTERED) &&
!pfk->registered)
continue;
if (broadcast_flags & BROADCAST_ONE)
continue;
}
err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk);
/* Error is cleare after succecful sending to at least one
* registered KM */
if ((broadcast_flags & BROADCAST_REGISTERED) && err)
err = err2;
}
rcu_read_unlock();
if (one_sk != NULL)
err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk);
kfree_skb(skb2);
kfree_skb(skb);
return err;
}
static int pfkey_do_dump(struct pfkey_sock *pfk)
{
struct sadb_msg *hdr;
int rc;
rc = pfk->dump.dump(pfk);
if (rc == -ENOBUFS)
return 0;
if (pfk->dump.skb) {
if (!pfkey_can_dump(&pfk->sk))
return 0;
hdr = (struct sadb_msg *) pfk->dump.skb->data;
hdr->sadb_msg_seq = 0;
hdr->sadb_msg_errno = rc;
pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
&pfk->sk, sock_net(&pfk->sk));
pfk->dump.skb = NULL;
}
pfkey_terminate_dump(pfk);
return rc;
}
static inline void pfkey_hdr_dup(struct sadb_msg *new,
const struct sadb_msg *orig)
{
*new = *orig;
}
static int pfkey_error(const struct sadb_msg *orig, int err, struct sock *sk)
{
struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL);
struct sadb_msg *hdr;
if (!skb)
return -ENOBUFS;
/* Woe be to the platform trying to support PFKEY yet
* having normal errnos outside the 1-255 range, inclusive.
*/
err = -err;
if (err == ERESTARTSYS ||
err == ERESTARTNOHAND ||
err == ERESTARTNOINTR)
err = EINTR;
if (err >= 512)
err = EINVAL;
BUG_ON(err <= 0 || err >= 256);
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
pfkey_hdr_dup(hdr, orig);
hdr->sadb_msg_errno = (uint8_t) err;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) /
sizeof(uint64_t));
pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk, sock_net(sk));
return 0;
}
static const u8 sadb_ext_min_len[] = {
[SADB_EXT_RESERVED] = (u8) 0,
[SADB_EXT_SA] = (u8) sizeof(struct sadb_sa),
[SADB_EXT_LIFETIME_CURRENT] = (u8) sizeof(struct sadb_lifetime),
[SADB_EXT_LIFETIME_HARD] = (u8) sizeof(struct sadb_lifetime),
[SADB_EXT_LIFETIME_SOFT] = (u8) sizeof(struct sadb_lifetime),
[SADB_EXT_ADDRESS_SRC] = (u8) sizeof(struct sadb_address),
[SADB_EXT_ADDRESS_DST] = (u8) sizeof(struct sadb_address),
[SADB_EXT_ADDRESS_PROXY] = (u8) sizeof(struct sadb_address),
[SADB_EXT_KEY_AUTH] = (u8) sizeof(struct sadb_key),
[SADB_EXT_KEY_ENCRYPT] = (u8) sizeof(struct sadb_key),
[SADB_EXT_IDENTITY_SRC] = (u8) sizeof(struct sadb_ident),
[SADB_EXT_IDENTITY_DST] = (u8) sizeof(struct sadb_ident),
[SADB_EXT_SENSITIVITY] = (u8) sizeof(struct sadb_sens),
[SADB_EXT_PROPOSAL] = (u8) sizeof(struct sadb_prop),
[SADB_EXT_SUPPORTED_AUTH] = (u8) sizeof(struct sadb_supported),
[SADB_EXT_SUPPORTED_ENCRYPT] = (u8) sizeof(struct sadb_supported),
[SADB_EXT_SPIRANGE] = (u8) sizeof(struct sadb_spirange),
[SADB_X_EXT_KMPRIVATE] = (u8) sizeof(struct sadb_x_kmprivate),
[SADB_X_EXT_POLICY] = (u8) sizeof(struct sadb_x_policy),
[SADB_X_EXT_SA2] = (u8) sizeof(struct sadb_x_sa2),
[SADB_X_EXT_NAT_T_TYPE] = (u8) sizeof(struct sadb_x_nat_t_type),
[SADB_X_EXT_NAT_T_SPORT] = (u8) sizeof(struct sadb_x_nat_t_port),
[SADB_X_EXT_NAT_T_DPORT] = (u8) sizeof(struct sadb_x_nat_t_port),
[SADB_X_EXT_NAT_T_OA] = (u8) sizeof(struct sadb_address),
[SADB_X_EXT_SEC_CTX] = (u8) sizeof(struct sadb_x_sec_ctx),
[SADB_X_EXT_KMADDRESS] = (u8) sizeof(struct sadb_x_kmaddress),
};
/* Verify sadb_address_{len,prefixlen} against sa_family. */
static int verify_address_len(const void *p)
{
const struct sadb_address *sp = p;
const struct sockaddr *addr = (const struct sockaddr *)(sp + 1);
const struct sockaddr_in *sin;
#if IS_ENABLED(CONFIG_IPV6)
const struct sockaddr_in6 *sin6;
#endif
int len;
switch (addr->sa_family) {
case AF_INET:
len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t));
if (sp->sadb_address_len != len ||
sp->sadb_address_prefixlen > 32)
return -EINVAL;
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t));
if (sp->sadb_address_len != len ||
sp->sadb_address_prefixlen > 128)
return -EINVAL;
break;
#endif
default:
/* It is user using kernel to keep track of security
* associations for another protocol, such as
* OSPF/RSVP/RIPV2/MIP. It is user's job to verify
* lengths.
*
* XXX Actually, association/policy database is not yet
* XXX able to cope with arbitrary sockaddr families.
* XXX When it can, remove this -EINVAL. -DaveM
*/
return -EINVAL;
break;
}
return 0;
}
static inline int pfkey_sec_ctx_len(const struct sadb_x_sec_ctx *sec_ctx)
{
return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) +
sec_ctx->sadb_x_ctx_len,
sizeof(uint64_t));
}
static inline int verify_sec_ctx_len(const void *p)
{
const struct sadb_x_sec_ctx *sec_ctx = p;
int len = sec_ctx->sadb_x_ctx_len;
if (len > PAGE_SIZE)
return -EINVAL;
len = pfkey_sec_ctx_len(sec_ctx);
if (sec_ctx->sadb_x_sec_len != len)
return -EINVAL;
return 0;
}
static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(const struct sadb_x_sec_ctx *sec_ctx)
{
struct xfrm_user_sec_ctx *uctx = NULL;
int ctx_size = sec_ctx->sadb_x_ctx_len;
uctx = kmalloc((sizeof(*uctx)+ctx_size), GFP_KERNEL);
if (!uctx)
return NULL;
uctx->len = pfkey_sec_ctx_len(sec_ctx);
uctx->exttype = sec_ctx->sadb_x_sec_exttype;
uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi;
uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg;
uctx->ctx_len = sec_ctx->sadb_x_ctx_len;
memcpy(uctx + 1, sec_ctx + 1,
uctx->ctx_len);
return uctx;
}
static int present_and_same_family(const struct sadb_address *src,
const struct sadb_address *dst)
{
const struct sockaddr *s_addr, *d_addr;
if (!src || !dst)
return 0;
s_addr = (const struct sockaddr *)(src + 1);
d_addr = (const struct sockaddr *)(dst + 1);
if (s_addr->sa_family != d_addr->sa_family)
return 0;
if (s_addr->sa_family != AF_INET
#if IS_ENABLED(CONFIG_IPV6)
&& s_addr->sa_family != AF_INET6
#endif
)
return 0;
return 1;
}
static int parse_exthdrs(struct sk_buff *skb, const struct sadb_msg *hdr, void **ext_hdrs)
{
const char *p = (char *) hdr;
int len = skb->len;
len -= sizeof(*hdr);
p += sizeof(*hdr);
while (len > 0) {
const struct sadb_ext *ehdr = (const struct sadb_ext *) p;
uint16_t ext_type;
int ext_len;
ext_len = ehdr->sadb_ext_len;
ext_len *= sizeof(uint64_t);
ext_type = ehdr->sadb_ext_type;
if (ext_len < sizeof(uint64_t) ||
ext_len > len ||
ext_type == SADB_EXT_RESERVED)
return -EINVAL;
if (ext_type <= SADB_EXT_MAX) {
int min = (int) sadb_ext_min_len[ext_type];
if (ext_len < min)
return -EINVAL;
if (ext_hdrs[ext_type-1] != NULL)
return -EINVAL;
if (ext_type == SADB_EXT_ADDRESS_SRC ||
ext_type == SADB_EXT_ADDRESS_DST ||
ext_type == SADB_EXT_ADDRESS_PROXY ||
ext_type == SADB_X_EXT_NAT_T_OA) {
if (verify_address_len(p))
return -EINVAL;
}
if (ext_type == SADB_X_EXT_SEC_CTX) {
if (verify_sec_ctx_len(p))
return -EINVAL;
}
ext_hdrs[ext_type-1] = (void *) p;
}
p += ext_len;
len -= ext_len;
}
return 0;
}
static uint16_t
pfkey_satype2proto(uint8_t satype)
{
switch (satype) {
case SADB_SATYPE_UNSPEC:
return IPSEC_PROTO_ANY;
case SADB_SATYPE_AH:
return IPPROTO_AH;
case SADB_SATYPE_ESP:
return IPPROTO_ESP;
case SADB_X_SATYPE_IPCOMP:
return IPPROTO_COMP;
break;
default:
return 0;
}
/* NOTREACHED */
}
static uint8_t
pfkey_proto2satype(uint16_t proto)
{
switch (proto) {
case IPPROTO_AH:
return SADB_SATYPE_AH;
case IPPROTO_ESP:
return SADB_SATYPE_ESP;
case IPPROTO_COMP:
return SADB_X_SATYPE_IPCOMP;
break;
default:
return 0;
}
/* NOTREACHED */
}
/* BTW, this scheme means that there is no way with PFKEY2 sockets to
* say specifically 'just raw sockets' as we encode them as 255.
*/
static uint8_t pfkey_proto_to_xfrm(uint8_t proto)
{
return proto == IPSEC_PROTO_ANY ? 0 : proto;
}
static uint8_t pfkey_proto_from_xfrm(uint8_t proto)
{
return proto ? proto : IPSEC_PROTO_ANY;
}
static inline int pfkey_sockaddr_len(sa_family_t family)
{
switch (family) {
case AF_INET:
return sizeof(struct sockaddr_in);
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
return sizeof(struct sockaddr_in6);
#endif
}
return 0;
}
static
int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr)
{
switch (sa->sa_family) {
case AF_INET:
xaddr->a4 =
((struct sockaddr_in *)sa)->sin_addr.s_addr;
return AF_INET;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
memcpy(xaddr->a6,
&((struct sockaddr_in6 *)sa)->sin6_addr,
sizeof(struct in6_addr));
return AF_INET6;
#endif
}
return 0;
}
static
int pfkey_sadb_addr2xfrm_addr(const struct sadb_address *addr, xfrm_address_t *xaddr)
{
return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1),
xaddr);
}
static struct xfrm_state *pfkey_xfrm_state_lookup(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
const struct sadb_sa *sa;
const struct sadb_address *addr;
uint16_t proto;
unsigned short family;
xfrm_address_t *xaddr;
sa = ext_hdrs[SADB_EXT_SA - 1];
if (sa == NULL)
return NULL;
proto = pfkey_satype2proto(hdr->sadb_msg_satype);
if (proto == 0)
return NULL;
/* sadb_address_len should be checked by caller */
addr = ext_hdrs[SADB_EXT_ADDRESS_DST - 1];
if (addr == NULL)
return NULL;
family = ((const struct sockaddr *)(addr + 1))->sa_family;
switch (family) {
case AF_INET:
xaddr = (xfrm_address_t *)&((const struct sockaddr_in *)(addr + 1))->sin_addr;
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
xaddr = (xfrm_address_t *)&((const struct sockaddr_in6 *)(addr + 1))->sin6_addr;
break;
#endif
default:
xaddr = NULL;
}
if (!xaddr)
return NULL;
return xfrm_state_lookup(net, DUMMY_MARK, xaddr, sa->sadb_sa_spi, proto, family);
}
#define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1)))
static int
pfkey_sockaddr_size(sa_family_t family)
{
return PFKEY_ALIGN8(pfkey_sockaddr_len(family));
}
static inline int pfkey_mode_from_xfrm(int mode)
{
switch(mode) {
case XFRM_MODE_TRANSPORT:
return IPSEC_MODE_TRANSPORT;
case XFRM_MODE_TUNNEL:
return IPSEC_MODE_TUNNEL;
case XFRM_MODE_BEET:
return IPSEC_MODE_BEET;
default:
return -1;
}
}
static inline int pfkey_mode_to_xfrm(int mode)
{
switch(mode) {
case IPSEC_MODE_ANY: /*XXX*/
case IPSEC_MODE_TRANSPORT:
return XFRM_MODE_TRANSPORT;
case IPSEC_MODE_TUNNEL:
return XFRM_MODE_TUNNEL;
case IPSEC_MODE_BEET:
return XFRM_MODE_BEET;
default:
return -1;
}
}
static unsigned int pfkey_sockaddr_fill(const xfrm_address_t *xaddr, __be16 port,
struct sockaddr *sa,
unsigned short family)
{
switch (family) {
case AF_INET:
{
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
sin->sin_family = AF_INET;
sin->sin_port = port;
sin->sin_addr.s_addr = xaddr->a4;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
return 32;
}
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
{
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = port;
sin6->sin6_flowinfo = 0;
sin6->sin6_addr = *(struct in6_addr *)xaddr->a6;
sin6->sin6_scope_id = 0;
return 128;
}
#endif
}
return 0;
}
static struct sk_buff *__pfkey_xfrm_state2msg(const struct xfrm_state *x,
int add_keys, int hsc)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
struct sadb_sa *sa;
struct sadb_lifetime *lifetime;
struct sadb_address *addr;
struct sadb_key *key;
struct sadb_x_sa2 *sa2;
struct sadb_x_sec_ctx *sec_ctx;
struct xfrm_sec_ctx *xfrm_ctx;
int ctx_size = 0;
int size;
int auth_key_size = 0;
int encrypt_key_size = 0;
int sockaddr_size;
struct xfrm_encap_tmpl *natt = NULL;
int mode;
/* address family check */
sockaddr_size = pfkey_sockaddr_size(x->props.family);
if (!sockaddr_size)
return ERR_PTR(-EINVAL);
/* base, SA, (lifetime (HSC),) address(SD), (address(P),)
key(AE), (identity(SD),) (sensitivity)> */
size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) +
sizeof(struct sadb_lifetime) +
((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) +
((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) +
sizeof(struct sadb_address)*2 +
sockaddr_size*2 +
sizeof(struct sadb_x_sa2);
if ((xfrm_ctx = x->security)) {
ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
size += sizeof(struct sadb_x_sec_ctx) + ctx_size;
}
/* identity & sensitivity */
if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family))
size += sizeof(struct sadb_address) + sockaddr_size;
if (add_keys) {
if (x->aalg && x->aalg->alg_key_len) {
auth_key_size =
PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8);
size += sizeof(struct sadb_key) + auth_key_size;
}
if (x->ealg && x->ealg->alg_key_len) {
encrypt_key_size =
PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8);
size += sizeof(struct sadb_key) + encrypt_key_size;
}
}
if (x->encap)
natt = x->encap;
if (natt && natt->encap_type) {
size += sizeof(struct sadb_x_nat_t_type);
size += sizeof(struct sadb_x_nat_t_port);
size += sizeof(struct sadb_x_nat_t_port);
}
skb = alloc_skb(size + 16, GFP_ATOMIC);
if (skb == NULL)
return ERR_PTR(-ENOBUFS);
/* call should fill header later */
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
memset(hdr, 0, size); /* XXX do we need this ? */
hdr->sadb_msg_len = size / sizeof(uint64_t);
/* sa */
sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa));
sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
sa->sadb_sa_exttype = SADB_EXT_SA;
sa->sadb_sa_spi = x->id.spi;
sa->sadb_sa_replay = x->props.replay_window;
switch (x->km.state) {
case XFRM_STATE_VALID:
sa->sadb_sa_state = x->km.dying ?
SADB_SASTATE_DYING : SADB_SASTATE_MATURE;
break;
case XFRM_STATE_ACQ:
sa->sadb_sa_state = SADB_SASTATE_LARVAL;
break;
default:
sa->sadb_sa_state = SADB_SASTATE_DEAD;
break;
}
sa->sadb_sa_auth = 0;
if (x->aalg) {
struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
sa->sadb_sa_auth = (a && a->pfkey_supported) ?
a->desc.sadb_alg_id : 0;
}
sa->sadb_sa_encrypt = 0;
BUG_ON(x->ealg && x->calg);
if (x->ealg) {
struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0);
sa->sadb_sa_encrypt = (a && a->pfkey_supported) ?
a->desc.sadb_alg_id : 0;
}
/* KAME compatible: sadb_sa_encrypt is overloaded with calg id */
if (x->calg) {
struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0);
sa->sadb_sa_encrypt = (a && a->pfkey_supported) ?
a->desc.sadb_alg_id : 0;
}
sa->sadb_sa_flags = 0;
if (x->props.flags & XFRM_STATE_NOECN)
sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN;
if (x->props.flags & XFRM_STATE_DECAP_DSCP)
sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP;
if (x->props.flags & XFRM_STATE_NOPMTUDISC)
sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC;
/* hard time */
if (hsc & 2) {
lifetime = (struct sadb_lifetime *) skb_put(skb,
sizeof(struct sadb_lifetime));
lifetime->sadb_lifetime_len =
sizeof(struct sadb_lifetime)/sizeof(uint64_t);
lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.hard_packet_limit);
lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit);
lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds;
lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds;
}
/* soft time */
if (hsc & 1) {
lifetime = (struct sadb_lifetime *) skb_put(skb,
sizeof(struct sadb_lifetime));
lifetime->sadb_lifetime_len =
sizeof(struct sadb_lifetime)/sizeof(uint64_t);
lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.soft_packet_limit);
lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit);
lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds;
lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds;
}
/* current time */
lifetime = (struct sadb_lifetime *) skb_put(skb,
sizeof(struct sadb_lifetime));
lifetime->sadb_lifetime_len =
sizeof(struct sadb_lifetime)/sizeof(uint64_t);
lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
lifetime->sadb_lifetime_allocations = x->curlft.packets;
lifetime->sadb_lifetime_bytes = x->curlft.bytes;
lifetime->sadb_lifetime_addtime = x->curlft.add_time;
lifetime->sadb_lifetime_usetime = x->curlft.use_time;
/* src address */
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
/* "if the ports are non-zero, then the sadb_address_proto field,
normally zero, MUST be filled in with the transport
protocol's number." - RFC2367 */
addr->sadb_address_proto = 0;
addr->sadb_address_reserved = 0;
addr->sadb_address_prefixlen =
pfkey_sockaddr_fill(&x->props.saddr, 0,
(struct sockaddr *) (addr + 1),
x->props.family);
if (!addr->sadb_address_prefixlen)
BUG();
/* dst address */
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
addr->sadb_address_proto = 0;
addr->sadb_address_reserved = 0;
addr->sadb_address_prefixlen =
pfkey_sockaddr_fill(&x->id.daddr, 0,
(struct sockaddr *) (addr + 1),
x->props.family);
if (!addr->sadb_address_prefixlen)
BUG();
if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr,
x->props.family)) {
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
addr->sadb_address_proto =
pfkey_proto_from_xfrm(x->sel.proto);
addr->sadb_address_prefixlen = x->sel.prefixlen_s;
addr->sadb_address_reserved = 0;
pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport,
(struct sockaddr *) (addr + 1),
x->props.family);
}
/* auth key */
if (add_keys && auth_key_size) {
key = (struct sadb_key *) skb_put(skb,
sizeof(struct sadb_key)+auth_key_size);
key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) /
sizeof(uint64_t);
key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
key->sadb_key_bits = x->aalg->alg_key_len;
key->sadb_key_reserved = 0;
memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8);
}
/* encrypt key */
if (add_keys && encrypt_key_size) {
key = (struct sadb_key *) skb_put(skb,
sizeof(struct sadb_key)+encrypt_key_size);
key->sadb_key_len = (sizeof(struct sadb_key) +
encrypt_key_size) / sizeof(uint64_t);
key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
key->sadb_key_bits = x->ealg->alg_key_len;
key->sadb_key_reserved = 0;
memcpy(key + 1, x->ealg->alg_key,
(x->ealg->alg_key_len+7)/8);
}
/* sa */
sa2 = (struct sadb_x_sa2 *) skb_put(skb, sizeof(struct sadb_x_sa2));
sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t);
sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) {
kfree_skb(skb);
return ERR_PTR(-EINVAL);
}
sa2->sadb_x_sa2_mode = mode;
sa2->sadb_x_sa2_reserved1 = 0;
sa2->sadb_x_sa2_reserved2 = 0;
sa2->sadb_x_sa2_sequence = 0;
sa2->sadb_x_sa2_reqid = x->props.reqid;
if (natt && natt->encap_type) {
struct sadb_x_nat_t_type *n_type;
struct sadb_x_nat_t_port *n_port;
/* type */
n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type));
n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t);
n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
n_type->sadb_x_nat_t_type_type = natt->encap_type;
n_type->sadb_x_nat_t_type_reserved[0] = 0;
n_type->sadb_x_nat_t_type_reserved[1] = 0;
n_type->sadb_x_nat_t_type_reserved[2] = 0;
/* source port */
n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
n_port->sadb_x_nat_t_port_port = natt->encap_sport;
n_port->sadb_x_nat_t_port_reserved = 0;
/* dest port */
n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
n_port->sadb_x_nat_t_port_port = natt->encap_dport;
n_port->sadb_x_nat_t_port_reserved = 0;
}
/* security context */
if (xfrm_ctx) {
sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
sizeof(struct sadb_x_sec_ctx) + ctx_size);
sec_ctx->sadb_x_sec_len =
(sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
xfrm_ctx->ctx_len);
}
return skb;
}
static inline struct sk_buff *pfkey_xfrm_state2msg(const struct xfrm_state *x)
{
struct sk_buff *skb;
skb = __pfkey_xfrm_state2msg(x, 1, 3);
return skb;
}
static inline struct sk_buff *pfkey_xfrm_state2msg_expire(const struct xfrm_state *x,
int hsc)
{
return __pfkey_xfrm_state2msg(x, 0, hsc);
}
static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net,
const struct sadb_msg *hdr,
void * const *ext_hdrs)
{
struct xfrm_state *x;
const struct sadb_lifetime *lifetime;
const struct sadb_sa *sa;
const struct sadb_key *key;
const struct sadb_x_sec_ctx *sec_ctx;
uint16_t proto;
int err;
sa = ext_hdrs[SADB_EXT_SA - 1];
if (!sa ||
!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
return ERR_PTR(-EINVAL);
if (hdr->sadb_msg_satype == SADB_SATYPE_ESP &&
!ext_hdrs[SADB_EXT_KEY_ENCRYPT-1])
return ERR_PTR(-EINVAL);
if (hdr->sadb_msg_satype == SADB_SATYPE_AH &&
!ext_hdrs[SADB_EXT_KEY_AUTH-1])
return ERR_PTR(-EINVAL);
if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] !=
!!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1])
return ERR_PTR(-EINVAL);
proto = pfkey_satype2proto(hdr->sadb_msg_satype);
if (proto == 0)
return ERR_PTR(-EINVAL);
/* default error is no buffer space */
err = -ENOBUFS;
/* RFC2367:
Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message.
SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not
sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state.
Therefore, the sadb_sa_state field of all submitted SAs MUST be
SADB_SASTATE_MATURE and the kernel MUST return an error if this is
not true.
However, KAME setkey always uses SADB_SASTATE_LARVAL.
Hence, we have to _ignore_ sadb_sa_state, which is also reasonable.
*/
if (sa->sadb_sa_auth > SADB_AALG_MAX ||
(hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP &&
sa->sadb_sa_encrypt > SADB_X_CALG_MAX) ||
sa->sadb_sa_encrypt > SADB_EALG_MAX)
return ERR_PTR(-EINVAL);
key = ext_hdrs[SADB_EXT_KEY_AUTH - 1];
if (key != NULL &&
sa->sadb_sa_auth != SADB_X_AALG_NULL &&
((key->sadb_key_bits+7) / 8 == 0 ||
(key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t)))
return ERR_PTR(-EINVAL);
key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
if (key != NULL &&
sa->sadb_sa_encrypt != SADB_EALG_NULL &&
((key->sadb_key_bits+7) / 8 == 0 ||
(key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t)))
return ERR_PTR(-EINVAL);
x = xfrm_state_alloc(net);
if (x == NULL)
return ERR_PTR(-ENOBUFS);
x->id.proto = proto;
x->id.spi = sa->sadb_sa_spi;
x->props.replay_window = min_t(unsigned int, sa->sadb_sa_replay,
(sizeof(x->replay.bitmap) * 8));
if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN)
x->props.flags |= XFRM_STATE_NOECN;
if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP)
x->props.flags |= XFRM_STATE_DECAP_DSCP;
if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC)
x->props.flags |= XFRM_STATE_NOPMTUDISC;
lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1];
if (lifetime != NULL) {
x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
}
lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1];
if (lifetime != NULL) {
x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
}
sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
if (sec_ctx != NULL) {
struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
if (!uctx)
goto out;
err = security_xfrm_state_alloc(x, uctx);
kfree(uctx);
if (err)
goto out;
}
key = ext_hdrs[SADB_EXT_KEY_AUTH - 1];
if (sa->sadb_sa_auth) {
int keysize = 0;
struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth);
if (!a || !a->pfkey_supported) {
err = -ENOSYS;
goto out;
}
if (key)
keysize = (key->sadb_key_bits + 7) / 8;
x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL);
if (!x->aalg)
goto out;
strcpy(x->aalg->alg_name, a->name);
x->aalg->alg_key_len = 0;
if (key) {
x->aalg->alg_key_len = key->sadb_key_bits;
memcpy(x->aalg->alg_key, key+1, keysize);
}
x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits;
x->props.aalgo = sa->sadb_sa_auth;
/* x->algo.flags = sa->sadb_sa_flags; */
}
if (sa->sadb_sa_encrypt) {
if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) {
struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt);
if (!a || !a->pfkey_supported) {
err = -ENOSYS;
goto out;
}
x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL);
if (!x->calg)
goto out;
strcpy(x->calg->alg_name, a->name);
x->props.calgo = sa->sadb_sa_encrypt;
} else {
int keysize = 0;
struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt);
if (!a || !a->pfkey_supported) {
err = -ENOSYS;
goto out;
}
key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
if (key)
keysize = (key->sadb_key_bits + 7) / 8;
x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL);
if (!x->ealg)
goto out;
strcpy(x->ealg->alg_name, a->name);
x->ealg->alg_key_len = 0;
if (key) {
x->ealg->alg_key_len = key->sadb_key_bits;
memcpy(x->ealg->alg_key, key+1, keysize);
}
x->props.ealgo = sa->sadb_sa_encrypt;
}
}
/* x->algo.flags = sa->sadb_sa_flags; */
x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
&x->props.saddr);
pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1],
&x->id.daddr);
if (ext_hdrs[SADB_X_EXT_SA2-1]) {
const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1];
int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
if (mode < 0) {
err = -EINVAL;
goto out;
}
x->props.mode = mode;
x->props.reqid = sa2->sadb_x_sa2_reqid;
}
if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) {
const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1];
/* Nobody uses this, but we try. */
x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr);
x->sel.prefixlen_s = addr->sadb_address_prefixlen;
}
if (!x->sel.family)
x->sel.family = x->props.family;
if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) {
const struct sadb_x_nat_t_type* n_type;
struct xfrm_encap_tmpl *natt;
x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL);
if (!x->encap)
goto out;
natt = x->encap;
n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1];
natt->encap_type = n_type->sadb_x_nat_t_type_type;
if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) {
const struct sadb_x_nat_t_port *n_port =
ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1];
natt->encap_sport = n_port->sadb_x_nat_t_port_port;
}
if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) {
const struct sadb_x_nat_t_port *n_port =
ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1];
natt->encap_dport = n_port->sadb_x_nat_t_port_port;
}
memset(&natt->encap_oa, 0, sizeof(natt->encap_oa));
}
err = xfrm_init_state(x);
if (err)
goto out;
x->km.seq = hdr->sadb_msg_seq;
return x;
out:
x->km.state = XFRM_STATE_DEAD;
xfrm_state_put(x);
return ERR_PTR(err);
}
static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
return -EOPNOTSUPP;
}
static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
struct sk_buff *resp_skb;
struct sadb_x_sa2 *sa2;
struct sadb_address *saddr, *daddr;
struct sadb_msg *out_hdr;
struct sadb_spirange *range;
struct xfrm_state *x = NULL;
int mode;
int err;
u32 min_spi, max_spi;
u32 reqid;
u8 proto;
unsigned short family;
xfrm_address_t *xsaddr = NULL, *xdaddr = NULL;
if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
return -EINVAL;
proto = pfkey_satype2proto(hdr->sadb_msg_satype);
if (proto == 0)
return -EINVAL;
if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) {
mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
if (mode < 0)
return -EINVAL;
reqid = sa2->sadb_x_sa2_reqid;
} else {
mode = 0;
reqid = 0;
}
saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
family = ((struct sockaddr *)(saddr + 1))->sa_family;
switch (family) {
case AF_INET:
xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr;
xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr;
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr;
xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr;
break;
#endif
}
if (hdr->sadb_msg_seq) {
x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq);
if (x && !xfrm_addr_equal(&x->id.daddr, xdaddr, family)) {
xfrm_state_put(x);
x = NULL;
}
}
if (!x)
x = xfrm_find_acq(net, &dummy_mark, mode, reqid, proto, xdaddr, xsaddr, 1, family);
if (x == NULL)
return -ENOENT;
min_spi = 0x100;
max_spi = 0x0fffffff;
range = ext_hdrs[SADB_EXT_SPIRANGE-1];
if (range) {
min_spi = range->sadb_spirange_min;
max_spi = range->sadb_spirange_max;
}
err = xfrm_alloc_spi(x, min_spi, max_spi);
resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x);
if (IS_ERR(resp_skb)) {
xfrm_state_put(x);
return PTR_ERR(resp_skb);
}
out_hdr = (struct sadb_msg *) resp_skb->data;
out_hdr->sadb_msg_version = hdr->sadb_msg_version;
out_hdr->sadb_msg_type = SADB_GETSPI;
out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_reserved = 0;
out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
xfrm_state_put(x);
pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net);
return 0;
}
static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
struct xfrm_state *x;
if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8)
return -EOPNOTSUPP;
if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0)
return 0;
x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq);
if (x == NULL)
return 0;
spin_lock_bh(&x->lock);
if (x->km.state == XFRM_STATE_ACQ) {
x->km.state = XFRM_STATE_ERROR;
wake_up(&net->xfrm.km_waitq);
}
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return 0;
}
static inline int event2poltype(int event)
{
switch (event) {
case XFRM_MSG_DELPOLICY:
return SADB_X_SPDDELETE;
case XFRM_MSG_NEWPOLICY:
return SADB_X_SPDADD;
case XFRM_MSG_UPDPOLICY:
return SADB_X_SPDUPDATE;
case XFRM_MSG_POLEXPIRE:
// return SADB_X_SPDEXPIRE;
default:
pr_err("pfkey: Unknown policy event %d\n", event);
break;
}
return 0;
}
static inline int event2keytype(int event)
{
switch (event) {
case XFRM_MSG_DELSA:
return SADB_DELETE;
case XFRM_MSG_NEWSA:
return SADB_ADD;
case XFRM_MSG_UPDSA:
return SADB_UPDATE;
case XFRM_MSG_EXPIRE:
return SADB_EXPIRE;
default:
pr_err("pfkey: Unknown SA event %d\n", event);
break;
}
return 0;
}
/* ADD/UPD/DEL */
static int key_notify_sa(struct xfrm_state *x, const struct km_event *c)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
skb = pfkey_xfrm_state2msg(x);
if (IS_ERR(skb))
return PTR_ERR(skb);
hdr = (struct sadb_msg *) skb->data;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_type = event2keytype(c->event);
hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
hdr->sadb_msg_errno = 0;
hdr->sadb_msg_reserved = 0;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x));
return 0;
}
static int pfkey_add(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
struct xfrm_state *x;
int err;
struct km_event c;
x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs);
if (IS_ERR(x))
return PTR_ERR(x);
xfrm_state_hold(x);
if (hdr->sadb_msg_type == SADB_ADD)
err = xfrm_state_add(x);
else
err = xfrm_state_update(x);
xfrm_audit_state_add(x, err ? 0 : 1,
audit_get_loginuid(current),
audit_get_sessionid(current), 0);
if (err < 0) {
x->km.state = XFRM_STATE_DEAD;
__xfrm_state_put(x);
goto out;
}
if (hdr->sadb_msg_type == SADB_ADD)
c.event = XFRM_MSG_NEWSA;
else
c.event = XFRM_MSG_UPDSA;
c.seq = hdr->sadb_msg_seq;
c.portid = hdr->sadb_msg_pid;
km_state_notify(x, &c);
out:
xfrm_state_put(x);
return err;
}
static int pfkey_delete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
struct xfrm_state *x;
struct km_event c;
int err;
if (!ext_hdrs[SADB_EXT_SA-1] ||
!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
return -EINVAL;
x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs);
if (x == NULL)
return -ESRCH;
if ((err = security_xfrm_state_delete(x)))
goto out;
if (xfrm_state_kern(x)) {
err = -EPERM;
goto out;
}
err = xfrm_state_delete(x);
if (err < 0)
goto out;
c.seq = hdr->sadb_msg_seq;
c.portid = hdr->sadb_msg_pid;
c.event = XFRM_MSG_DELSA;
km_state_notify(x, &c);
out:
xfrm_audit_state_delete(x, err ? 0 : 1,
audit_get_loginuid(current),
audit_get_sessionid(current), 0);
xfrm_state_put(x);
return err;
}
static int pfkey_get(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
__u8 proto;
struct sk_buff *out_skb;
struct sadb_msg *out_hdr;
struct xfrm_state *x;
if (!ext_hdrs[SADB_EXT_SA-1] ||
!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
return -EINVAL;
x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs);
if (x == NULL)
return -ESRCH;
out_skb = pfkey_xfrm_state2msg(x);
proto = x->id.proto;
xfrm_state_put(x);
if (IS_ERR(out_skb))
return PTR_ERR(out_skb);
out_hdr = (struct sadb_msg *) out_skb->data;
out_hdr->sadb_msg_version = hdr->sadb_msg_version;
out_hdr->sadb_msg_type = SADB_GET;
out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_reserved = 0;
out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk));
return 0;
}
static struct sk_buff *compose_sadb_supported(const struct sadb_msg *orig,
gfp_t allocation)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
int len, auth_len, enc_len, i;
auth_len = xfrm_count_pfkey_auth_supported();
if (auth_len) {
auth_len *= sizeof(struct sadb_alg);
auth_len += sizeof(struct sadb_supported);
}
enc_len = xfrm_count_pfkey_enc_supported();
if (enc_len) {
enc_len *= sizeof(struct sadb_alg);
enc_len += sizeof(struct sadb_supported);
}
len = enc_len + auth_len + sizeof(struct sadb_msg);
skb = alloc_skb(len + 16, allocation);
if (!skb)
goto out_put_algs;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr));
pfkey_hdr_dup(hdr, orig);
hdr->sadb_msg_errno = 0;
hdr->sadb_msg_len = len / sizeof(uint64_t);
if (auth_len) {
struct sadb_supported *sp;
struct sadb_alg *ap;
sp = (struct sadb_supported *) skb_put(skb, auth_len);
ap = (struct sadb_alg *) (sp + 1);
sp->sadb_supported_len = auth_len / sizeof(uint64_t);
sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
for (i = 0; ; i++) {
struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
if (!aalg)
break;
if (!aalg->pfkey_supported)
continue;
if (aalg->available)
*ap++ = aalg->desc;
}
}
if (enc_len) {
struct sadb_supported *sp;
struct sadb_alg *ap;
sp = (struct sadb_supported *) skb_put(skb, enc_len);
ap = (struct sadb_alg *) (sp + 1);
sp->sadb_supported_len = enc_len / sizeof(uint64_t);
sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
for (i = 0; ; i++) {
struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
if (!ealg)
break;
if (!ealg->pfkey_supported)
continue;
if (ealg->available)
*ap++ = ealg->desc;
}
}
out_put_algs:
return skb;
}
static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct pfkey_sock *pfk = pfkey_sk(sk);
struct sk_buff *supp_skb;
if (hdr->sadb_msg_satype > SADB_SATYPE_MAX)
return -EINVAL;
if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {
if (pfk->registered&(1<<hdr->sadb_msg_satype))
return -EEXIST;
pfk->registered |= (1<<hdr->sadb_msg_satype);
}
xfrm_probe_algs();
supp_skb = compose_sadb_supported(hdr, GFP_KERNEL);
if (!supp_skb) {
if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)
pfk->registered &= ~(1<<hdr->sadb_msg_satype);
return -ENOBUFS;
}
pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk));
return 0;
}
static int unicast_flush_resp(struct sock *sk, const struct sadb_msg *ihdr)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
memcpy(hdr, ihdr, sizeof(struct sadb_msg));
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk));
}
static int key_notify_sa_flush(const struct km_event *c)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
hdr->sadb_msg_type = SADB_FLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
hdr->sadb_msg_reserved = 0;
pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
static int pfkey_flush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
unsigned int proto;
struct km_event c;
struct xfrm_audit audit_info;
int err, err2;
proto = pfkey_satype2proto(hdr->sadb_msg_satype);
if (proto == 0)
return -EINVAL;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
audit_info.secid = 0;
err = xfrm_state_flush(net, proto, &audit_info);
err2 = unicast_flush_resp(sk, hdr);
if (err || err2) {
if (err == -ESRCH) /* empty table - go quietly */
err = 0;
return err ? err : err2;
}
c.data.proto = proto;
c.seq = hdr->sadb_msg_seq;
c.portid = hdr->sadb_msg_pid;
c.event = XFRM_MSG_FLUSHSA;
c.net = net;
km_state_notify(NULL, &c);
return 0;
}
static int dump_sa(struct xfrm_state *x, int count, void *ptr)
{
struct pfkey_sock *pfk = ptr;
struct sk_buff *out_skb;
struct sadb_msg *out_hdr;
if (!pfkey_can_dump(&pfk->sk))
return -ENOBUFS;
out_skb = pfkey_xfrm_state2msg(x);
if (IS_ERR(out_skb))
return PTR_ERR(out_skb);
out_hdr = (struct sadb_msg *) out_skb->data;
out_hdr->sadb_msg_version = pfk->dump.msg_version;
out_hdr->sadb_msg_type = SADB_DUMP;
out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_reserved = 0;
out_hdr->sadb_msg_seq = count + 1;
out_hdr->sadb_msg_pid = pfk->dump.msg_portid;
if (pfk->dump.skb)
pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
&pfk->sk, sock_net(&pfk->sk));
pfk->dump.skb = out_skb;
return 0;
}
static int pfkey_dump_sa(struct pfkey_sock *pfk)
{
struct net *net = sock_net(&pfk->sk);
return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk);
}
static void pfkey_dump_sa_done(struct pfkey_sock *pfk)
{
xfrm_state_walk_done(&pfk->dump.u.state);
}
static int pfkey_dump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
u8 proto;
struct pfkey_sock *pfk = pfkey_sk(sk);
if (pfk->dump.dump != NULL)
return -EBUSY;
proto = pfkey_satype2proto(hdr->sadb_msg_satype);
if (proto == 0)
return -EINVAL;
pfk->dump.msg_version = hdr->sadb_msg_version;
pfk->dump.msg_portid = hdr->sadb_msg_pid;
pfk->dump.dump = pfkey_dump_sa;
pfk->dump.done = pfkey_dump_sa_done;
xfrm_state_walk_init(&pfk->dump.u.state, proto);
return pfkey_do_dump(pfk);
}
static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct pfkey_sock *pfk = pfkey_sk(sk);
int satype = hdr->sadb_msg_satype;
bool reset_errno = false;
if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) {
reset_errno = true;
if (satype != 0 && satype != 1)
return -EINVAL;
pfk->promisc = satype;
}
if (reset_errno && skb_cloned(skb))
skb = skb_copy(skb, GFP_KERNEL);
else
skb = skb_clone(skb, GFP_KERNEL);
if (reset_errno && skb) {
struct sadb_msg *new_hdr = (struct sadb_msg *) skb->data;
new_hdr->sadb_msg_errno = 0;
}
pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk));
return 0;
}
static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
int i;
u32 reqid = *(u32*)ptr;
for (i=0; i<xp->xfrm_nr; i++) {
if (xp->xfrm_vec[i].reqid == reqid)
return -EEXIST;
}
return 0;
}
static u32 gen_reqid(struct net *net)
{
struct xfrm_policy_walk walk;
u32 start;
int rc;
static u32 reqid = IPSEC_MANUAL_REQID_MAX;
start = reqid;
do {
++reqid;
if (reqid == 0)
reqid = IPSEC_MANUAL_REQID_MAX+1;
xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN);
rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid);
xfrm_policy_walk_done(&walk);
if (rc != -EEXIST)
return reqid;
} while (reqid != start);
return 0;
}
static int
parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq)
{
struct net *net = xp_net(xp);
struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr;
int mode;
if (xp->xfrm_nr >= XFRM_MAX_DEPTH)
return -ELOOP;
if (rq->sadb_x_ipsecrequest_mode == 0)
return -EINVAL;
t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */
if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0)
return -EINVAL;
t->mode = mode;
if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE)
t->optional = 1;
else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) {
t->reqid = rq->sadb_x_ipsecrequest_reqid;
if (t->reqid > IPSEC_MANUAL_REQID_MAX)
t->reqid = 0;
if (!t->reqid && !(t->reqid = gen_reqid(net)))
return -ENOBUFS;
}
/* addresses present only in tunnel mode */
if (t->mode == XFRM_MODE_TUNNEL) {
u8 *sa = (u8 *) (rq + 1);
int family, socklen;
family = pfkey_sockaddr_extract((struct sockaddr *)sa,
&t->saddr);
if (!family)
return -EINVAL;
socklen = pfkey_sockaddr_len(family);
if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen),
&t->id.daddr) != family)
return -EINVAL;
t->encap_family = family;
} else
t->encap_family = xp->family;
/* No way to set this via kame pfkey */
t->allalgs = 1;
xp->xfrm_nr++;
return 0;
}
static int
parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol)
{
int err;
int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy);
struct sadb_x_ipsecrequest *rq = (void*)(pol+1);
if (pol->sadb_x_policy_len * 8 < sizeof(struct sadb_x_policy))
return -EINVAL;
while (len >= sizeof(struct sadb_x_ipsecrequest)) {
if ((err = parse_ipsecrequest(xp, rq)) < 0)
return err;
len -= rq->sadb_x_ipsecrequest_len;
rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len);
}
return 0;
}
static inline int pfkey_xfrm_policy2sec_ctx_size(const struct xfrm_policy *xp)
{
struct xfrm_sec_ctx *xfrm_ctx = xp->security;
if (xfrm_ctx) {
int len = sizeof(struct sadb_x_sec_ctx);
len += xfrm_ctx->ctx_len;
return PFKEY_ALIGN8(len);
}
return 0;
}
static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp)
{
const struct xfrm_tmpl *t;
int sockaddr_size = pfkey_sockaddr_size(xp->family);
int socklen = 0;
int i;
for (i=0; i<xp->xfrm_nr; i++) {
t = xp->xfrm_vec + i;
socklen += pfkey_sockaddr_len(t->encap_family);
}
return sizeof(struct sadb_msg) +
(sizeof(struct sadb_lifetime) * 3) +
(sizeof(struct sadb_address) * 2) +
(sockaddr_size * 2) +
sizeof(struct sadb_x_policy) +
(xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) +
(socklen * 2) +
pfkey_xfrm_policy2sec_ctx_size(xp);
}
static struct sk_buff * pfkey_xfrm_policy2msg_prep(const struct xfrm_policy *xp)
{
struct sk_buff *skb;
int size;
size = pfkey_xfrm_policy2msg_size(xp);
skb = alloc_skb(size + 16, GFP_ATOMIC);
if (skb == NULL)
return ERR_PTR(-ENOBUFS);
return skb;
}
static int pfkey_xfrm_policy2msg(struct sk_buff *skb, const struct xfrm_policy *xp, int dir)
{
struct sadb_msg *hdr;
struct sadb_address *addr;
struct sadb_lifetime *lifetime;
struct sadb_x_policy *pol;
struct sadb_x_sec_ctx *sec_ctx;
struct xfrm_sec_ctx *xfrm_ctx;
int i;
int size;
int sockaddr_size = pfkey_sockaddr_size(xp->family);
int socklen = pfkey_sockaddr_len(xp->family);
size = pfkey_xfrm_policy2msg_size(xp);
/* call should fill header later */
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
memset(hdr, 0, size); /* XXX do we need this ? */
/* src address */
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
addr->sadb_address_prefixlen = xp->selector.prefixlen_s;
addr->sadb_address_reserved = 0;
if (!pfkey_sockaddr_fill(&xp->selector.saddr,
xp->selector.sport,
(struct sockaddr *) (addr + 1),
xp->family))
BUG();
/* dst address */
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
addr->sadb_address_prefixlen = xp->selector.prefixlen_d;
addr->sadb_address_reserved = 0;
pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport,
(struct sockaddr *) (addr + 1),
xp->family);
/* hard time */
lifetime = (struct sadb_lifetime *) skb_put(skb,
sizeof(struct sadb_lifetime));
lifetime->sadb_lifetime_len =
sizeof(struct sadb_lifetime)/sizeof(uint64_t);
lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.hard_packet_limit);
lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit);
lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds;
lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds;
/* soft time */
lifetime = (struct sadb_lifetime *) skb_put(skb,
sizeof(struct sadb_lifetime));
lifetime->sadb_lifetime_len =
sizeof(struct sadb_lifetime)/sizeof(uint64_t);
lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.soft_packet_limit);
lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit);
lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds;
lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds;
/* current time */
lifetime = (struct sadb_lifetime *) skb_put(skb,
sizeof(struct sadb_lifetime));
lifetime->sadb_lifetime_len =
sizeof(struct sadb_lifetime)/sizeof(uint64_t);
lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
lifetime->sadb_lifetime_allocations = xp->curlft.packets;
lifetime->sadb_lifetime_bytes = xp->curlft.bytes;
lifetime->sadb_lifetime_addtime = xp->curlft.add_time;
lifetime->sadb_lifetime_usetime = xp->curlft.use_time;
pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy));
pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD;
if (xp->action == XFRM_POLICY_ALLOW) {
if (xp->xfrm_nr)
pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
else
pol->sadb_x_policy_type = IPSEC_POLICY_NONE;
}
pol->sadb_x_policy_dir = dir+1;
pol->sadb_x_policy_reserved = 0;
pol->sadb_x_policy_id = xp->index;
pol->sadb_x_policy_priority = xp->priority;
for (i=0; i<xp->xfrm_nr; i++) {
const struct xfrm_tmpl *t = xp->xfrm_vec + i;
struct sadb_x_ipsecrequest *rq;
int req_size;
int mode;
req_size = sizeof(struct sadb_x_ipsecrequest);
if (t->mode == XFRM_MODE_TUNNEL) {
socklen = pfkey_sockaddr_len(t->encap_family);
req_size += socklen * 2;
} else {
size -= 2*socklen;
}
rq = (void*)skb_put(skb, req_size);
pol->sadb_x_policy_len += req_size/8;
memset(rq, 0, sizeof(*rq));
rq->sadb_x_ipsecrequest_len = req_size;
rq->sadb_x_ipsecrequest_proto = t->id.proto;
if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0)
return -EINVAL;
rq->sadb_x_ipsecrequest_mode = mode;
rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
if (t->reqid)
rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
if (t->optional)
rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE;
rq->sadb_x_ipsecrequest_reqid = t->reqid;
if (t->mode == XFRM_MODE_TUNNEL) {
u8 *sa = (void *)(rq + 1);
pfkey_sockaddr_fill(&t->saddr, 0,
(struct sockaddr *)sa,
t->encap_family);
pfkey_sockaddr_fill(&t->id.daddr, 0,
(struct sockaddr *) (sa + socklen),
t->encap_family);
}
}
/* security context */
if ((xfrm_ctx = xp->security)) {
int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp);
sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size);
sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t);
sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
xfrm_ctx->ctx_len);
}
hdr->sadb_msg_len = size / sizeof(uint64_t);
hdr->sadb_msg_reserved = atomic_read(&xp->refcnt);
return 0;
}
static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct sk_buff *out_skb;
struct sadb_msg *out_hdr;
int err;
out_skb = pfkey_xfrm_policy2msg_prep(xp);
if (IS_ERR(out_skb))
return PTR_ERR(out_skb);
err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
if (err < 0)
return err;
out_hdr = (struct sadb_msg *) out_skb->data;
out_hdr->sadb_msg_version = PF_KEY_V2;
if (c->data.byid && c->event == XFRM_MSG_DELPOLICY)
out_hdr->sadb_msg_type = SADB_X_SPDDELETE2;
else
out_hdr->sadb_msg_type = event2poltype(c->event);
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_seq = c->seq;
out_hdr->sadb_msg_pid = c->portid;
pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp));
return 0;
}
static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
int err = 0;
struct sadb_lifetime *lifetime;
struct sadb_address *sa;
struct sadb_x_policy *pol;
struct xfrm_policy *xp;
struct km_event c;
struct sadb_x_sec_ctx *sec_ctx;
if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
!ext_hdrs[SADB_X_EXT_POLICY-1])
return -EINVAL;
pol = ext_hdrs[SADB_X_EXT_POLICY-1];
if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC)
return -EINVAL;
if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
return -EINVAL;
xp = xfrm_policy_alloc(net, GFP_KERNEL);
if (xp == NULL)
return -ENOBUFS;
xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
xp->priority = pol->sadb_x_policy_priority;
sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr);
xp->selector.family = xp->family;
xp->selector.prefixlen_s = sa->sadb_address_prefixlen;
xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
if (xp->selector.sport)
xp->selector.sport_mask = htons(0xffff);
sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr);
xp->selector.prefixlen_d = sa->sadb_address_prefixlen;
/* Amusing, we set this twice. KAME apps appear to set same value
* in both addresses.
*/
xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
if (xp->selector.dport)
xp->selector.dport_mask = htons(0xffff);
sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
if (sec_ctx != NULL) {
struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
if (!uctx) {
err = -ENOBUFS;
goto out;
}
err = security_xfrm_policy_alloc(&xp->security, uctx);
kfree(uctx);
if (err)
goto out;
}
xp->lft.soft_byte_limit = XFRM_INF;
xp->lft.hard_byte_limit = XFRM_INF;
xp->lft.soft_packet_limit = XFRM_INF;
xp->lft.hard_packet_limit = XFRM_INF;
if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) {
xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
}
if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) {
xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
}
xp->xfrm_nr = 0;
if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
(err = parse_ipsecrequests(xp, pol)) < 0)
goto out;
err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp,
hdr->sadb_msg_type != SADB_X_SPDUPDATE);
xfrm_audit_policy_add(xp, err ? 0 : 1,
audit_get_loginuid(current),
audit_get_sessionid(current), 0);
if (err)
goto out;
if (hdr->sadb_msg_type == SADB_X_SPDUPDATE)
c.event = XFRM_MSG_UPDPOLICY;
else
c.event = XFRM_MSG_NEWPOLICY;
c.seq = hdr->sadb_msg_seq;
c.portid = hdr->sadb_msg_pid;
km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
xfrm_pol_put(xp);
return 0;
out:
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return err;
}
static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
int err;
struct sadb_address *sa;
struct sadb_x_policy *pol;
struct xfrm_policy *xp;
struct xfrm_selector sel;
struct km_event c;
struct sadb_x_sec_ctx *sec_ctx;
struct xfrm_sec_ctx *pol_ctx = NULL;
if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
!ext_hdrs[SADB_X_EXT_POLICY-1])
return -EINVAL;
pol = ext_hdrs[SADB_X_EXT_POLICY-1];
if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
return -EINVAL;
memset(&sel, 0, sizeof(sel));
sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
sel.prefixlen_s = sa->sadb_address_prefixlen;
sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
if (sel.sport)
sel.sport_mask = htons(0xffff);
sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
sel.prefixlen_d = sa->sadb_address_prefixlen;
sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
if (sel.dport)
sel.dport_mask = htons(0xffff);
sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
if (sec_ctx != NULL) {
struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
if (!uctx)
return -ENOMEM;
err = security_xfrm_policy_alloc(&pol_ctx, uctx);
kfree(uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
pol->sadb_x_policy_dir - 1, &sel, pol_ctx,
1, &err);
security_xfrm_policy_free(pol_ctx);
if (xp == NULL)
return -ENOENT;
xfrm_audit_policy_delete(xp, err ? 0 : 1,
audit_get_loginuid(current),
audit_get_sessionid(current), 0);
if (err)
goto out;
c.seq = hdr->sadb_msg_seq;
c.portid = hdr->sadb_msg_pid;
c.data.byid = 0;
c.event = XFRM_MSG_DELPOLICY;
km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
out:
xfrm_pol_put(xp);
if (err == 0)
xfrm_garbage_collect(net);
return err;
}
static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, const struct sadb_msg *hdr, int dir)
{
int err;
struct sk_buff *out_skb;
struct sadb_msg *out_hdr;
err = 0;
out_skb = pfkey_xfrm_policy2msg_prep(xp);
if (IS_ERR(out_skb)) {
err = PTR_ERR(out_skb);
goto out;
}
err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
if (err < 0)
goto out;
out_hdr = (struct sadb_msg *) out_skb->data;
out_hdr->sadb_msg_version = hdr->sadb_msg_version;
out_hdr->sadb_msg_type = hdr->sadb_msg_type;
out_hdr->sadb_msg_satype = 0;
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp));
err = 0;
out:
return err;
}
#ifdef CONFIG_NET_KEY_MIGRATE
static int pfkey_sockaddr_pair_size(sa_family_t family)
{
return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2);
}
static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len,
xfrm_address_t *saddr, xfrm_address_t *daddr,
u16 *family)
{
int af, socklen;
if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family))
return -EINVAL;
af = pfkey_sockaddr_extract(sa, saddr);
if (!af)
return -EINVAL;
socklen = pfkey_sockaddr_len(af);
if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen),
daddr) != af)
return -EINVAL;
*family = af;
return 0;
}
static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len,
struct xfrm_migrate *m)
{
int err;
struct sadb_x_ipsecrequest *rq2;
int mode;
if (len <= sizeof(struct sadb_x_ipsecrequest) ||
len < rq1->sadb_x_ipsecrequest_len)
return -EINVAL;
/* old endoints */
err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1),
rq1->sadb_x_ipsecrequest_len,
&m->old_saddr, &m->old_daddr,
&m->old_family);
if (err)
return err;
rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len);
len -= rq1->sadb_x_ipsecrequest_len;
if (len <= sizeof(struct sadb_x_ipsecrequest) ||
len < rq2->sadb_x_ipsecrequest_len)
return -EINVAL;
/* new endpoints */
err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1),
rq2->sadb_x_ipsecrequest_len,
&m->new_saddr, &m->new_daddr,
&m->new_family);
if (err)
return err;
if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto ||
rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode ||
rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid)
return -EINVAL;
m->proto = rq1->sadb_x_ipsecrequest_proto;
if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0)
return -EINVAL;
m->mode = mode;
m->reqid = rq1->sadb_x_ipsecrequest_reqid;
return ((int)(rq1->sadb_x_ipsecrequest_len +
rq2->sadb_x_ipsecrequest_len));
}
static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
const struct sadb_msg *hdr, void * const *ext_hdrs)
{
int i, len, ret, err = -EINVAL;
u8 dir;
struct sadb_address *sa;
struct sadb_x_kmaddress *kma;
struct sadb_x_policy *pol;
struct sadb_x_ipsecrequest *rq;
struct xfrm_selector sel;
struct xfrm_migrate m[XFRM_MAX_DEPTH];
struct xfrm_kmaddress k;
if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1],
ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) ||
!ext_hdrs[SADB_X_EXT_POLICY - 1]) {
err = -EINVAL;
goto out;
}
kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1];
pol = ext_hdrs[SADB_X_EXT_POLICY - 1];
if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) {
err = -EINVAL;
goto out;
}
if (kma) {
/* convert sadb_x_kmaddress to xfrm_kmaddress */
k.reserved = kma->sadb_x_kmaddress_reserved;
ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1),
8*(kma->sadb_x_kmaddress_len) - sizeof(*kma),
&k.local, &k.remote, &k.family);
if (ret < 0) {
err = ret;
goto out;
}
}
dir = pol->sadb_x_policy_dir - 1;
memset(&sel, 0, sizeof(sel));
/* set source address info of selector */
sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1];
sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
sel.prefixlen_s = sa->sadb_address_prefixlen;
sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port;
if (sel.sport)
sel.sport_mask = htons(0xffff);
/* set destination address info of selector */
sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1],
pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
sel.prefixlen_d = sa->sadb_address_prefixlen;
sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port;
if (sel.dport)
sel.dport_mask = htons(0xffff);
rq = (struct sadb_x_ipsecrequest *)(pol + 1);
/* extract ipsecrequests */
i = 0;
len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy);
while (len > 0 && i < XFRM_MAX_DEPTH) {
ret = ipsecrequests_to_migrate(rq, len, &m[i]);
if (ret < 0) {
err = ret;
goto out;
} else {
rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret);
len -= ret;
i++;
}
}
if (!i || len > 0) {
err = -EINVAL;
goto out;
}
return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i,
kma ? &k : NULL);
out:
return err;
}
#else
static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
const struct sadb_msg *hdr, void * const *ext_hdrs)
{
return -ENOPROTOOPT;
}
#endif
static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
unsigned int dir;
int err = 0, delete;
struct sadb_x_policy *pol;
struct xfrm_policy *xp;
struct km_event c;
if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL)
return -EINVAL;
dir = xfrm_policy_id2dir(pol->sadb_x_policy_id);
if (dir >= XFRM_POLICY_MAX)
return -EINVAL;
delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2);
xp = xfrm_policy_byid(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
dir, pol->sadb_x_policy_id, delete, &err);
if (xp == NULL)
return -ENOENT;
if (delete) {
xfrm_audit_policy_delete(xp, err ? 0 : 1,
audit_get_loginuid(current),
audit_get_sessionid(current), 0);
if (err)
goto out;
c.seq = hdr->sadb_msg_seq;
c.portid = hdr->sadb_msg_pid;
c.data.byid = 1;
c.event = XFRM_MSG_DELPOLICY;
km_policy_notify(xp, dir, &c);
} else {
err = key_pol_get_resp(sk, xp, hdr, dir);
}
out:
xfrm_pol_put(xp);
if (delete && err == 0)
xfrm_garbage_collect(net);
return err;
}
static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
struct pfkey_sock *pfk = ptr;
struct sk_buff *out_skb;
struct sadb_msg *out_hdr;
int err;
if (!pfkey_can_dump(&pfk->sk))
return -ENOBUFS;
out_skb = pfkey_xfrm_policy2msg_prep(xp);
if (IS_ERR(out_skb))
return PTR_ERR(out_skb);
err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
if (err < 0)
return err;
out_hdr = (struct sadb_msg *) out_skb->data;
out_hdr->sadb_msg_version = pfk->dump.msg_version;
out_hdr->sadb_msg_type = SADB_X_SPDDUMP;
out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_seq = count + 1;
out_hdr->sadb_msg_pid = pfk->dump.msg_portid;
if (pfk->dump.skb)
pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
&pfk->sk, sock_net(&pfk->sk));
pfk->dump.skb = out_skb;
return 0;
}
static int pfkey_dump_sp(struct pfkey_sock *pfk)
{
struct net *net = sock_net(&pfk->sk);
return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk);
}
static void pfkey_dump_sp_done(struct pfkey_sock *pfk)
{
xfrm_policy_walk_done(&pfk->dump.u.policy);
}
static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct pfkey_sock *pfk = pfkey_sk(sk);
if (pfk->dump.dump != NULL)
return -EBUSY;
pfk->dump.msg_version = hdr->sadb_msg_version;
pfk->dump.msg_portid = hdr->sadb_msg_pid;
pfk->dump.dump = pfkey_dump_sp;
pfk->dump.done = pfkey_dump_sp_done;
xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN);
return pfkey_do_dump(pfk);
}
static int key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
hdr->sadb_msg_reserved = 0;
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
{
struct net *net = sock_net(sk);
struct km_event c;
struct xfrm_audit audit_info;
int err, err2;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
audit_info.secid = 0;
err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info);
err2 = unicast_flush_resp(sk, hdr);
if (err || err2) {
if (err == -ESRCH) /* empty table - old silent behavior */
return 0;
return err;
}
c.data.type = XFRM_POLICY_TYPE_MAIN;
c.event = XFRM_MSG_FLUSHPOLICY;
c.portid = hdr->sadb_msg_pid;
c.seq = hdr->sadb_msg_seq;
c.net = net;
km_policy_notify(NULL, 0, &c);
return 0;
}
typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb,
const struct sadb_msg *hdr, void * const *ext_hdrs);
static const pfkey_handler pfkey_funcs[SADB_MAX + 1] = {
[SADB_RESERVED] = pfkey_reserved,
[SADB_GETSPI] = pfkey_getspi,
[SADB_UPDATE] = pfkey_add,
[SADB_ADD] = pfkey_add,
[SADB_DELETE] = pfkey_delete,
[SADB_GET] = pfkey_get,
[SADB_ACQUIRE] = pfkey_acquire,
[SADB_REGISTER] = pfkey_register,
[SADB_EXPIRE] = NULL,
[SADB_FLUSH] = pfkey_flush,
[SADB_DUMP] = pfkey_dump,
[SADB_X_PROMISC] = pfkey_promisc,
[SADB_X_PCHANGE] = NULL,
[SADB_X_SPDUPDATE] = pfkey_spdadd,
[SADB_X_SPDADD] = pfkey_spdadd,
[SADB_X_SPDDELETE] = pfkey_spddelete,
[SADB_X_SPDGET] = pfkey_spdget,
[SADB_X_SPDACQUIRE] = NULL,
[SADB_X_SPDDUMP] = pfkey_spddump,
[SADB_X_SPDFLUSH] = pfkey_spdflush,
[SADB_X_SPDSETIDX] = pfkey_spdadd,
[SADB_X_SPDDELETE2] = pfkey_spdget,
[SADB_X_MIGRATE] = pfkey_migrate,
};
static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr)
{
void *ext_hdrs[SADB_EXT_MAX];
int err;
pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL,
BROADCAST_PROMISC_ONLY, NULL, sock_net(sk));
memset(ext_hdrs, 0, sizeof(ext_hdrs));
err = parse_exthdrs(skb, hdr, ext_hdrs);
if (!err) {
err = -EOPNOTSUPP;
if (pfkey_funcs[hdr->sadb_msg_type])
err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs);
}
return err;
}
static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp)
{
struct sadb_msg *hdr = NULL;
if (skb->len < sizeof(*hdr)) {
*errp = -EMSGSIZE;
} else {
hdr = (struct sadb_msg *) skb->data;
if (hdr->sadb_msg_version != PF_KEY_V2 ||
hdr->sadb_msg_reserved != 0 ||
(hdr->sadb_msg_type <= SADB_RESERVED ||
hdr->sadb_msg_type > SADB_MAX)) {
hdr = NULL;
*errp = -EINVAL;
} else if (hdr->sadb_msg_len != (skb->len /
sizeof(uint64_t)) ||
hdr->sadb_msg_len < (sizeof(struct sadb_msg) /
sizeof(uint64_t))) {
hdr = NULL;
*errp = -EMSGSIZE;
} else {
*errp = 0;
}
}
return hdr;
}
static inline int aalg_tmpl_set(const struct xfrm_tmpl *t,
const struct xfrm_algo_desc *d)
{
unsigned int id = d->desc.sadb_alg_id;
if (id >= sizeof(t->aalgos) * 8)
return 0;
return (t->aalgos >> id) & 1;
}
static inline int ealg_tmpl_set(const struct xfrm_tmpl *t,
const struct xfrm_algo_desc *d)
{
unsigned int id = d->desc.sadb_alg_id;
if (id >= sizeof(t->ealgos) * 8)
return 0;
return (t->ealgos >> id) & 1;
}
static int count_ah_combs(const struct xfrm_tmpl *t)
{
int i, sz = 0;
for (i = 0; ; i++) {
const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
if (!aalg)
break;
if (!aalg->pfkey_supported)
continue;
if (aalg_tmpl_set(t, aalg) && aalg->available)
sz += sizeof(struct sadb_comb);
}
return sz + sizeof(struct sadb_prop);
}
static int count_esp_combs(const struct xfrm_tmpl *t)
{
int i, k, sz = 0;
for (i = 0; ; i++) {
const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
if (!ealg)
break;
if (!ealg->pfkey_supported)
continue;
if (!(ealg_tmpl_set(t, ealg) && ealg->available))
continue;
for (k = 1; ; k++) {
const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
if (!aalg)
break;
if (!aalg->pfkey_supported)
continue;
if (aalg_tmpl_set(t, aalg) && aalg->available)
sz += sizeof(struct sadb_comb);
}
}
return sz + sizeof(struct sadb_prop);
}
static void dump_ah_combs(struct sk_buff *skb, const struct xfrm_tmpl *t)
{
struct sadb_prop *p;
int i;
p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
p->sadb_prop_len = sizeof(struct sadb_prop)/8;
p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
p->sadb_prop_replay = 32;
memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
for (i = 0; ; i++) {
const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
if (!aalg)
break;
if (!aalg->pfkey_supported)
continue;
if (aalg_tmpl_set(t, aalg) && aalg->available) {
struct sadb_comb *c;
c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
memset(c, 0, sizeof(*c));
p->sadb_prop_len += sizeof(struct sadb_comb)/8;
c->sadb_comb_auth = aalg->desc.sadb_alg_id;
c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
c->sadb_comb_hard_addtime = 24*60*60;
c->sadb_comb_soft_addtime = 20*60*60;
c->sadb_comb_hard_usetime = 8*60*60;
c->sadb_comb_soft_usetime = 7*60*60;
}
}
}
static void dump_esp_combs(struct sk_buff *skb, const struct xfrm_tmpl *t)
{
struct sadb_prop *p;
int i, k;
p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
p->sadb_prop_len = sizeof(struct sadb_prop)/8;
p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
p->sadb_prop_replay = 32;
memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
for (i=0; ; i++) {
const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
if (!ealg)
break;
if (!ealg->pfkey_supported)
continue;
if (!(ealg_tmpl_set(t, ealg) && ealg->available))
continue;
for (k = 1; ; k++) {
struct sadb_comb *c;
const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
if (!aalg)
break;
if (!aalg->pfkey_supported)
continue;
if (!(aalg_tmpl_set(t, aalg) && aalg->available))
continue;
c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
memset(c, 0, sizeof(*c));
p->sadb_prop_len += sizeof(struct sadb_comb)/8;
c->sadb_comb_auth = aalg->desc.sadb_alg_id;
c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
c->sadb_comb_encrypt = ealg->desc.sadb_alg_id;
c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits;
c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits;
c->sadb_comb_hard_addtime = 24*60*60;
c->sadb_comb_soft_addtime = 20*60*60;
c->sadb_comb_hard_usetime = 8*60*60;
c->sadb_comb_soft_usetime = 7*60*60;
}
}
}
static int key_notify_policy_expire(struct xfrm_policy *xp, const struct km_event *c)
{
return 0;
}
static int key_notify_sa_expire(struct xfrm_state *x, const struct km_event *c)
{
struct sk_buff *out_skb;
struct sadb_msg *out_hdr;
int hard;
int hsc;
hard = c->data.hard;
if (hard)
hsc = 2;
else
hsc = 1;
out_skb = pfkey_xfrm_state2msg_expire(x, hsc);
if (IS_ERR(out_skb))
return PTR_ERR(out_skb);
out_hdr = (struct sadb_msg *) out_skb->data;
out_hdr->sadb_msg_version = PF_KEY_V2;
out_hdr->sadb_msg_type = SADB_EXPIRE;
out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
out_hdr->sadb_msg_errno = 0;
out_hdr->sadb_msg_reserved = 0;
out_hdr->sadb_msg_seq = 0;
out_hdr->sadb_msg_pid = 0;
pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x));
return 0;
}
static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = x ? xs_net(x) : c->net;
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
if (atomic_read(&net_pfkey->socks_nr) == 0)
return 0;
switch (c->event) {
case XFRM_MSG_EXPIRE:
return key_notify_sa_expire(x, c);
case XFRM_MSG_DELSA:
case XFRM_MSG_NEWSA:
case XFRM_MSG_UPDSA:
return key_notify_sa(x, c);
case XFRM_MSG_FLUSHSA:
return key_notify_sa_flush(c);
case XFRM_MSG_NEWAE: /* not yet supported */
break;
default:
pr_err("pfkey: Unknown SA event %d\n", c->event);
break;
}
return 0;
}
static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
if (xp && xp->type != XFRM_POLICY_TYPE_MAIN)
return 0;
switch (c->event) {
case XFRM_MSG_POLEXPIRE:
return key_notify_policy_expire(xp, c);
case XFRM_MSG_DELPOLICY:
case XFRM_MSG_NEWPOLICY:
case XFRM_MSG_UPDPOLICY:
return key_notify_policy(xp, dir, c);
case XFRM_MSG_FLUSHPOLICY:
if (c->data.type != XFRM_POLICY_TYPE_MAIN)
break;
return key_notify_policy_flush(c);
default:
pr_err("pfkey: Unknown policy event %d\n", c->event);
break;
}
return 0;
}
static u32 get_acqseq(void)
{
u32 res;
static atomic_t acqseq;
do {
res = atomic_inc_return(&acqseq);
} while (!res);
return res;
}
static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
struct sadb_address *addr;
struct sadb_x_policy *pol;
int sockaddr_size;
int size;
struct sadb_x_sec_ctx *sec_ctx;
struct xfrm_sec_ctx *xfrm_ctx;
int ctx_size = 0;
sockaddr_size = pfkey_sockaddr_size(x->props.family);
if (!sockaddr_size)
return -EINVAL;
size = sizeof(struct sadb_msg) +
(sizeof(struct sadb_address) * 2) +
(sockaddr_size * 2) +
sizeof(struct sadb_x_policy);
if (x->id.proto == IPPROTO_AH)
size += count_ah_combs(t);
else if (x->id.proto == IPPROTO_ESP)
size += count_esp_combs(t);
if ((xfrm_ctx = x->security)) {
ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
size += sizeof(struct sadb_x_sec_ctx) + ctx_size;
}
skb = alloc_skb(size + 16, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_type = SADB_ACQUIRE;
hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
hdr->sadb_msg_len = size / sizeof(uint64_t);
hdr->sadb_msg_errno = 0;
hdr->sadb_msg_reserved = 0;
hdr->sadb_msg_seq = x->km.seq = get_acqseq();
hdr->sadb_msg_pid = 0;
/* src address */
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
addr->sadb_address_proto = 0;
addr->sadb_address_reserved = 0;
addr->sadb_address_prefixlen =
pfkey_sockaddr_fill(&x->props.saddr, 0,
(struct sockaddr *) (addr + 1),
x->props.family);
if (!addr->sadb_address_prefixlen)
BUG();
/* dst address */
addr = (struct sadb_address*) skb_put(skb,
sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
addr->sadb_address_proto = 0;
addr->sadb_address_reserved = 0;
addr->sadb_address_prefixlen =
pfkey_sockaddr_fill(&x->id.daddr, 0,
(struct sockaddr *) (addr + 1),
x->props.family);
if (!addr->sadb_address_prefixlen)
BUG();
pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy));
pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
pol->sadb_x_policy_dir = XFRM_POLICY_OUT + 1;
pol->sadb_x_policy_reserved = 0;
pol->sadb_x_policy_id = xp->index;
pol->sadb_x_policy_priority = xp->priority;
/* Set sadb_comb's. */
if (x->id.proto == IPPROTO_AH)
dump_ah_combs(skb, t);
else if (x->id.proto == IPPROTO_ESP)
dump_esp_combs(skb, t);
/* security context */
if (xfrm_ctx) {
sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
sizeof(struct sadb_x_sec_ctx) + ctx_size);
sec_ctx->sadb_x_sec_len =
(sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
xfrm_ctx->ctx_len);
}
return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x));
}
static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt,
u8 *data, int len, int *dir)
{
struct net *net = sock_net(sk);
struct xfrm_policy *xp;
struct sadb_x_policy *pol = (struct sadb_x_policy*)data;
struct sadb_x_sec_ctx *sec_ctx;
switch (sk->sk_family) {
case AF_INET:
if (opt != IP_IPSEC_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
if (opt != IPV6_IPSEC_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#endif
default:
*dir = -EINVAL;
return NULL;
}
*dir = -EINVAL;
if (len < sizeof(struct sadb_x_policy) ||
pol->sadb_x_policy_len*8 > len ||
pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS ||
(!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND))
return NULL;
xp = xfrm_policy_alloc(net, GFP_ATOMIC);
if (xp == NULL) {
*dir = -ENOBUFS;
return NULL;
}
xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
xp->lft.soft_byte_limit = XFRM_INF;
xp->lft.hard_byte_limit = XFRM_INF;
xp->lft.soft_packet_limit = XFRM_INF;
xp->lft.hard_packet_limit = XFRM_INF;
xp->family = sk->sk_family;
xp->xfrm_nr = 0;
if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
(*dir = parse_ipsecrequests(xp, pol)) < 0)
goto out;
/* security context too */
if (len >= (pol->sadb_x_policy_len*8 +
sizeof(struct sadb_x_sec_ctx))) {
char *p = (char *)pol;
struct xfrm_user_sec_ctx *uctx;
p += pol->sadb_x_policy_len*8;
sec_ctx = (struct sadb_x_sec_ctx *)p;
if (len < pol->sadb_x_policy_len*8 +
sec_ctx->sadb_x_sec_len) {
*dir = -EINVAL;
goto out;
}
if ((*dir = verify_sec_ctx_len(p)))
goto out;
uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
*dir = security_xfrm_policy_alloc(&xp->security, uctx);
kfree(uctx);
if (*dir)
goto out;
}
*dir = pol->sadb_x_policy_dir-1;
return xp;
out:
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return NULL;
}
static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport)
{
struct sk_buff *skb;
struct sadb_msg *hdr;
struct sadb_sa *sa;
struct sadb_address *addr;
struct sadb_x_nat_t_port *n_port;
int sockaddr_size;
int size;
__u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0);
struct xfrm_encap_tmpl *natt = NULL;
sockaddr_size = pfkey_sockaddr_size(x->props.family);
if (!sockaddr_size)
return -EINVAL;
if (!satype)
return -EINVAL;
if (!x->encap)
return -EINVAL;
natt = x->encap;
/* Build an SADB_X_NAT_T_NEW_MAPPING message:
*
* HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) |
* ADDRESS_DST (new addr) | NAT_T_DPORT (new port)
*/
size = sizeof(struct sadb_msg) +
sizeof(struct sadb_sa) +
(sizeof(struct sadb_address) * 2) +
(sockaddr_size * 2) +
(sizeof(struct sadb_x_nat_t_port) * 2);
skb = alloc_skb(size + 16, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING;
hdr->sadb_msg_satype = satype;
hdr->sadb_msg_len = size / sizeof(uint64_t);
hdr->sadb_msg_errno = 0;
hdr->sadb_msg_reserved = 0;
hdr->sadb_msg_seq = x->km.seq = get_acqseq();
hdr->sadb_msg_pid = 0;
/* SA */
sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa));
sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
sa->sadb_sa_exttype = SADB_EXT_SA;
sa->sadb_sa_spi = x->id.spi;
sa->sadb_sa_replay = 0;
sa->sadb_sa_state = 0;
sa->sadb_sa_auth = 0;
sa->sadb_sa_encrypt = 0;
sa->sadb_sa_flags = 0;
/* ADDRESS_SRC (old addr) */
addr = (struct sadb_address*)
skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
addr->sadb_address_proto = 0;
addr->sadb_address_reserved = 0;
addr->sadb_address_prefixlen =
pfkey_sockaddr_fill(&x->props.saddr, 0,
(struct sockaddr *) (addr + 1),
x->props.family);
if (!addr->sadb_address_prefixlen)
BUG();
/* NAT_T_SPORT (old port) */
n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
n_port->sadb_x_nat_t_port_port = natt->encap_sport;
n_port->sadb_x_nat_t_port_reserved = 0;
/* ADDRESS_DST (new addr) */
addr = (struct sadb_address*)
skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
addr->sadb_address_len =
(sizeof(struct sadb_address)+sockaddr_size)/
sizeof(uint64_t);
addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
addr->sadb_address_proto = 0;
addr->sadb_address_reserved = 0;
addr->sadb_address_prefixlen =
pfkey_sockaddr_fill(ipaddr, 0,
(struct sockaddr *) (addr + 1),
x->props.family);
if (!addr->sadb_address_prefixlen)
BUG();
/* NAT_T_DPORT (new port) */
n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
n_port->sadb_x_nat_t_port_port = sport;
n_port->sadb_x_nat_t_port_reserved = 0;
return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x));
}
#ifdef CONFIG_NET_KEY_MIGRATE
static int set_sadb_address(struct sk_buff *skb, int sasize, int type,
const struct xfrm_selector *sel)
{
struct sadb_address *addr;
addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize);
addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8;
addr->sadb_address_exttype = type;
addr->sadb_address_proto = sel->proto;
addr->sadb_address_reserved = 0;
switch (type) {
case SADB_EXT_ADDRESS_SRC:
addr->sadb_address_prefixlen = sel->prefixlen_s;
pfkey_sockaddr_fill(&sel->saddr, 0,
(struct sockaddr *)(addr + 1),
sel->family);
break;
case SADB_EXT_ADDRESS_DST:
addr->sadb_address_prefixlen = sel->prefixlen_d;
pfkey_sockaddr_fill(&sel->daddr, 0,
(struct sockaddr *)(addr + 1),
sel->family);
break;
default:
return -EINVAL;
}
return 0;
}
static int set_sadb_kmaddress(struct sk_buff *skb, const struct xfrm_kmaddress *k)
{
struct sadb_x_kmaddress *kma;
u8 *sa;
int family = k->family;
int socklen = pfkey_sockaddr_len(family);
int size_req;
size_req = (sizeof(struct sadb_x_kmaddress) +
pfkey_sockaddr_pair_size(family));
kma = (struct sadb_x_kmaddress *)skb_put(skb, size_req);
memset(kma, 0, size_req);
kma->sadb_x_kmaddress_len = size_req / 8;
kma->sadb_x_kmaddress_exttype = SADB_X_EXT_KMADDRESS;
kma->sadb_x_kmaddress_reserved = k->reserved;
sa = (u8 *)(kma + 1);
if (!pfkey_sockaddr_fill(&k->local, 0, (struct sockaddr *)sa, family) ||
!pfkey_sockaddr_fill(&k->remote, 0, (struct sockaddr *)(sa+socklen), family))
return -EINVAL;
return 0;
}
static int set_ipsecrequest(struct sk_buff *skb,
uint8_t proto, uint8_t mode, int level,
uint32_t reqid, uint8_t family,
const xfrm_address_t *src, const xfrm_address_t *dst)
{
struct sadb_x_ipsecrequest *rq;
u8 *sa;
int socklen = pfkey_sockaddr_len(family);
int size_req;
size_req = sizeof(struct sadb_x_ipsecrequest) +
pfkey_sockaddr_pair_size(family);
rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req);
memset(rq, 0, size_req);
rq->sadb_x_ipsecrequest_len = size_req;
rq->sadb_x_ipsecrequest_proto = proto;
rq->sadb_x_ipsecrequest_mode = mode;
rq->sadb_x_ipsecrequest_level = level;
rq->sadb_x_ipsecrequest_reqid = reqid;
sa = (u8 *) (rq + 1);
if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) ||
!pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family))
return -EINVAL;
return 0;
}
#endif
#ifdef CONFIG_NET_KEY_MIGRATE
static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_bundles,
const struct xfrm_kmaddress *k)
{
int i;
int sasize_sel;
int size = 0;
int size_pol = 0;
struct sk_buff *skb;
struct sadb_msg *hdr;
struct sadb_x_policy *pol;
const struct xfrm_migrate *mp;
if (type != XFRM_POLICY_TYPE_MAIN)
return 0;
if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH)
return -EINVAL;
if (k != NULL) {
/* addresses for KM */
size += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) +
pfkey_sockaddr_pair_size(k->family));
}
/* selector */
sasize_sel = pfkey_sockaddr_size(sel->family);
if (!sasize_sel)
return -EINVAL;
size += (sizeof(struct sadb_address) + sasize_sel) * 2;
/* policy info */
size_pol += sizeof(struct sadb_x_policy);
/* ipsecrequests */
for (i = 0, mp = m; i < num_bundles; i++, mp++) {
/* old locator pair */
size_pol += sizeof(struct sadb_x_ipsecrequest) +
pfkey_sockaddr_pair_size(mp->old_family);
/* new locator pair */
size_pol += sizeof(struct sadb_x_ipsecrequest) +
pfkey_sockaddr_pair_size(mp->new_family);
}
size += sizeof(struct sadb_msg) + size_pol;
/* alloc buffer */
skb = alloc_skb(size, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg));
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_type = SADB_X_MIGRATE;
hdr->sadb_msg_satype = pfkey_proto2satype(m->proto);
hdr->sadb_msg_len = size / 8;
hdr->sadb_msg_errno = 0;
hdr->sadb_msg_reserved = 0;
hdr->sadb_msg_seq = 0;
hdr->sadb_msg_pid = 0;
/* Addresses to be used by KM for negotiation, if ext is available */
if (k != NULL && (set_sadb_kmaddress(skb, k) < 0))
goto err;
/* selector src */
set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel);
/* selector dst */
set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel);
/* policy information */
pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy));
pol->sadb_x_policy_len = size_pol / 8;
pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
pol->sadb_x_policy_dir = dir + 1;
pol->sadb_x_policy_reserved = 0;
pol->sadb_x_policy_id = 0;
pol->sadb_x_policy_priority = 0;
for (i = 0, mp = m; i < num_bundles; i++, mp++) {
/* old ipsecrequest */
int mode = pfkey_mode_from_xfrm(mp->mode);
if (mode < 0)
goto err;
if (set_ipsecrequest(skb, mp->proto, mode,
(mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),
mp->reqid, mp->old_family,
&mp->old_saddr, &mp->old_daddr) < 0)
goto err;
/* new ipsecrequest */
if (set_ipsecrequest(skb, mp->proto, mode,
(mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),
mp->reqid, mp->new_family,
&mp->new_saddr, &mp->new_daddr) < 0)
goto err;
}
/* broadcast migrate message to sockets */
pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net);
return 0;
err:
kfree_skb(skb);
return -EINVAL;
}
#else
static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_bundles,
const struct xfrm_kmaddress *k)
{
return -ENOPROTOOPT;
}
#endif
static int pfkey_sendmsg(struct kiocb *kiocb,
struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct sk_buff *skb = NULL;
struct sadb_msg *hdr = NULL;
int err;
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB)
goto out;
err = -EMSGSIZE;
if ((unsigned int)len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = alloc_skb(len, GFP_KERNEL);
if (skb == NULL)
goto out;
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len))
goto out;
hdr = pfkey_get_base_msg(skb, &err);
if (!hdr)
goto out;
mutex_lock(&xfrm_cfg_mutex);
err = pfkey_process(sk, skb, hdr);
mutex_unlock(&xfrm_cfg_mutex);
out:
if (err && hdr && pfkey_error(hdr, err, sk) == 0)
err = 0;
kfree_skb(skb);
return err ? : len;
}
static int pfkey_recvmsg(struct kiocb *kiocb,
struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
struct sock *sk = sock->sk;
struct pfkey_sock *pfk = pfkey_sk(sk);
struct sk_buff *skb;
int copied, err;
err = -EINVAL;
if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))
goto out;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
copied = skb->len;
if (copied > len) {
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)
goto out_free;
sock_recv_ts_and_drops(msg, sk, skb);
err = (flags & MSG_TRUNC) ? skb->len : copied;
if (pfk->dump.dump != NULL &&
3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
pfkey_do_dump(pfk);
out_free:
skb_free_datagram(sk, skb);
out:
return err;
}
static const struct proto_ops pfkey_ops = {
.family = PF_KEY,
.owner = THIS_MODULE,
/* Operations that make no sense on pfkey sockets. */
.bind = sock_no_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
/* Now the operations that really occur. */
.release = pfkey_release,
.poll = datagram_poll,
.sendmsg = pfkey_sendmsg,
.recvmsg = pfkey_recvmsg,
};
static const struct net_proto_family pfkey_family_ops = {
.family = PF_KEY,
.create = pfkey_create,
.owner = THIS_MODULE,
};
#ifdef CONFIG_PROC_FS
static int pfkey_seq_show(struct seq_file *f, void *v)
{
struct sock *s = sk_entry(v);
if (v == SEQ_START_TOKEN)
seq_printf(f ,"sk RefCnt Rmem Wmem User Inode\n");
else
seq_printf(f, "%pK %-6d %-6u %-6u %-6u %-6lu\n",
s,
atomic_read(&s->sk_refcnt),
sk_rmem_alloc_get(s),
sk_wmem_alloc_get(s),
from_kuid_munged(seq_user_ns(f), sock_i_uid(s)),
sock_i_ino(s)
);
return 0;
}
static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos)
__acquires(rcu)
{
struct net *net = seq_file_net(f);
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
rcu_read_lock();
return seq_hlist_start_head_rcu(&net_pfkey->table, *ppos);
}
static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos)
{
struct net *net = seq_file_net(f);
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
return seq_hlist_next_rcu(v, &net_pfkey->table, ppos);
}
static void pfkey_seq_stop(struct seq_file *f, void *v)
__releases(rcu)
{
rcu_read_unlock();
}
static const struct seq_operations pfkey_seq_ops = {
.start = pfkey_seq_start,
.next = pfkey_seq_next,
.stop = pfkey_seq_stop,
.show = pfkey_seq_show,
};
static int pfkey_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pfkey_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations pfkey_proc_ops = {
.open = pfkey_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init pfkey_init_proc(struct net *net)
{
struct proc_dir_entry *e;
e = proc_create("pfkey", 0, net->proc_net, &pfkey_proc_ops);
if (e == NULL)
return -ENOMEM;
return 0;
}
static void __net_exit pfkey_exit_proc(struct net *net)
{
remove_proc_entry("pfkey", net->proc_net);
}
#else
static inline int pfkey_init_proc(struct net *net)
{
return 0;
}
static inline void pfkey_exit_proc(struct net *net)
{
}
#endif
static struct xfrm_mgr pfkeyv2_mgr =
{
.id = "pfkeyv2",
.notify = pfkey_send_notify,
.acquire = pfkey_send_acquire,
.compile_policy = pfkey_compile_policy,
.new_mapping = pfkey_send_new_mapping,
.notify_policy = pfkey_send_policy_notify,
.migrate = pfkey_send_migrate,
};
static int __net_init pfkey_net_init(struct net *net)
{
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
int rv;
INIT_HLIST_HEAD(&net_pfkey->table);
atomic_set(&net_pfkey->socks_nr, 0);
rv = pfkey_init_proc(net);
return rv;
}
static void __net_exit pfkey_net_exit(struct net *net)
{
struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
pfkey_exit_proc(net);
BUG_ON(!hlist_empty(&net_pfkey->table));
}
static struct pernet_operations pfkey_net_ops = {
.init = pfkey_net_init,
.exit = pfkey_net_exit,
.id = &pfkey_net_id,
.size = sizeof(struct netns_pfkey),
};
static void __exit ipsec_pfkey_exit(void)
{
xfrm_unregister_km(&pfkeyv2_mgr);
sock_unregister(PF_KEY);
unregister_pernet_subsys(&pfkey_net_ops);
proto_unregister(&key_proto);
}
static int __init ipsec_pfkey_init(void)
{
int err = proto_register(&key_proto, 0);
if (err != 0)
goto out;
err = register_pernet_subsys(&pfkey_net_ops);
if (err != 0)
goto out_unregister_key_proto;
err = sock_register(&pfkey_family_ops);
if (err != 0)
goto out_unregister_pernet;
err = xfrm_register_km(&pfkeyv2_mgr);
if (err != 0)
goto out_sock_unregister;
out:
return err;
out_sock_unregister:
sock_unregister(PF_KEY);
out_unregister_pernet:
unregister_pernet_subsys(&pfkey_net_ops);
out_unregister_key_proto:
proto_unregister(&key_proto);
goto out;
}
module_init(ipsec_pfkey_init);
module_exit(ipsec_pfkey_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_KEY);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_18 |
crossvul-cpp_data_bad_5600_0 | /*
* Copyright (c) 2000-2006 Silicon Graphics, 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.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include <linux/stddef.h>
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/bio.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/workqueue.h>
#include <linux/percpu.h>
#include <linux/blkdev.h>
#include <linux/hash.h>
#include <linux/kthread.h>
#include <linux/migrate.h>
#include <linux/backing-dev.h>
#include <linux/freezer.h>
#include "xfs_sb.h"
#include "xfs_log.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_trace.h"
static kmem_zone_t *xfs_buf_zone;
static struct workqueue_struct *xfslogd_workqueue;
#ifdef XFS_BUF_LOCK_TRACKING
# define XB_SET_OWNER(bp) ((bp)->b_last_holder = current->pid)
# define XB_CLEAR_OWNER(bp) ((bp)->b_last_holder = -1)
# define XB_GET_OWNER(bp) ((bp)->b_last_holder)
#else
# define XB_SET_OWNER(bp) do { } while (0)
# define XB_CLEAR_OWNER(bp) do { } while (0)
# define XB_GET_OWNER(bp) do { } while (0)
#endif
#define xb_to_gfp(flags) \
((((flags) & XBF_READ_AHEAD) ? __GFP_NORETRY : GFP_NOFS) | __GFP_NOWARN)
static inline int
xfs_buf_is_vmapped(
struct xfs_buf *bp)
{
/*
* Return true if the buffer is vmapped.
*
* b_addr is null if the buffer is not mapped, but the code is clever
* enough to know it doesn't have to map a single page, so the check has
* to be both for b_addr and bp->b_page_count > 1.
*/
return bp->b_addr && bp->b_page_count > 1;
}
static inline int
xfs_buf_vmap_len(
struct xfs_buf *bp)
{
return (bp->b_page_count * PAGE_SIZE) - bp->b_offset;
}
/*
* xfs_buf_lru_add - add a buffer to the LRU.
*
* The LRU takes a new reference to the buffer so that it will only be freed
* once the shrinker takes the buffer off the LRU.
*/
STATIC void
xfs_buf_lru_add(
struct xfs_buf *bp)
{
struct xfs_buftarg *btp = bp->b_target;
spin_lock(&btp->bt_lru_lock);
if (list_empty(&bp->b_lru)) {
atomic_inc(&bp->b_hold);
list_add_tail(&bp->b_lru, &btp->bt_lru);
btp->bt_lru_nr++;
bp->b_lru_flags &= ~_XBF_LRU_DISPOSE;
}
spin_unlock(&btp->bt_lru_lock);
}
/*
* xfs_buf_lru_del - remove a buffer from the LRU
*
* The unlocked check is safe here because it only occurs when there are not
* b_lru_ref counts left on the inode under the pag->pag_buf_lock. it is there
* to optimise the shrinker removing the buffer from the LRU and calling
* xfs_buf_free(). i.e. it removes an unnecessary round trip on the
* bt_lru_lock.
*/
STATIC void
xfs_buf_lru_del(
struct xfs_buf *bp)
{
struct xfs_buftarg *btp = bp->b_target;
if (list_empty(&bp->b_lru))
return;
spin_lock(&btp->bt_lru_lock);
if (!list_empty(&bp->b_lru)) {
list_del_init(&bp->b_lru);
btp->bt_lru_nr--;
}
spin_unlock(&btp->bt_lru_lock);
}
/*
* When we mark a buffer stale, we remove the buffer from the LRU and clear the
* b_lru_ref count so that the buffer is freed immediately when the buffer
* reference count falls to zero. If the buffer is already on the LRU, we need
* to remove the reference that LRU holds on the buffer.
*
* This prevents build-up of stale buffers on the LRU.
*/
void
xfs_buf_stale(
struct xfs_buf *bp)
{
ASSERT(xfs_buf_islocked(bp));
bp->b_flags |= XBF_STALE;
/*
* Clear the delwri status so that a delwri queue walker will not
* flush this buffer to disk now that it is stale. The delwri queue has
* a reference to the buffer, so this is safe to do.
*/
bp->b_flags &= ~_XBF_DELWRI_Q;
atomic_set(&(bp)->b_lru_ref, 0);
if (!list_empty(&bp->b_lru)) {
struct xfs_buftarg *btp = bp->b_target;
spin_lock(&btp->bt_lru_lock);
if (!list_empty(&bp->b_lru) &&
!(bp->b_lru_flags & _XBF_LRU_DISPOSE)) {
list_del_init(&bp->b_lru);
btp->bt_lru_nr--;
atomic_dec(&bp->b_hold);
}
spin_unlock(&btp->bt_lru_lock);
}
ASSERT(atomic_read(&bp->b_hold) >= 1);
}
static int
xfs_buf_get_maps(
struct xfs_buf *bp,
int map_count)
{
ASSERT(bp->b_maps == NULL);
bp->b_map_count = map_count;
if (map_count == 1) {
bp->b_maps = &bp->__b_map;
return 0;
}
bp->b_maps = kmem_zalloc(map_count * sizeof(struct xfs_buf_map),
KM_NOFS);
if (!bp->b_maps)
return ENOMEM;
return 0;
}
/*
* Frees b_pages if it was allocated.
*/
static void
xfs_buf_free_maps(
struct xfs_buf *bp)
{
if (bp->b_maps != &bp->__b_map) {
kmem_free(bp->b_maps);
bp->b_maps = NULL;
}
}
struct xfs_buf *
_xfs_buf_alloc(
struct xfs_buftarg *target,
struct xfs_buf_map *map,
int nmaps,
xfs_buf_flags_t flags)
{
struct xfs_buf *bp;
int error;
int i;
bp = kmem_zone_zalloc(xfs_buf_zone, KM_NOFS);
if (unlikely(!bp))
return NULL;
/*
* We don't want certain flags to appear in b_flags unless they are
* specifically set by later operations on the buffer.
*/
flags &= ~(XBF_UNMAPPED | XBF_TRYLOCK | XBF_ASYNC | XBF_READ_AHEAD);
atomic_set(&bp->b_hold, 1);
atomic_set(&bp->b_lru_ref, 1);
init_completion(&bp->b_iowait);
INIT_LIST_HEAD(&bp->b_lru);
INIT_LIST_HEAD(&bp->b_list);
RB_CLEAR_NODE(&bp->b_rbnode);
sema_init(&bp->b_sema, 0); /* held, no waiters */
XB_SET_OWNER(bp);
bp->b_target = target;
bp->b_flags = flags;
/*
* Set length and io_length to the same value initially.
* I/O routines should use io_length, which will be the same in
* most cases but may be reset (e.g. XFS recovery).
*/
error = xfs_buf_get_maps(bp, nmaps);
if (error) {
kmem_zone_free(xfs_buf_zone, bp);
return NULL;
}
bp->b_bn = map[0].bm_bn;
bp->b_length = 0;
for (i = 0; i < nmaps; i++) {
bp->b_maps[i].bm_bn = map[i].bm_bn;
bp->b_maps[i].bm_len = map[i].bm_len;
bp->b_length += map[i].bm_len;
}
bp->b_io_length = bp->b_length;
atomic_set(&bp->b_pin_count, 0);
init_waitqueue_head(&bp->b_waiters);
XFS_STATS_INC(xb_create);
trace_xfs_buf_init(bp, _RET_IP_);
return bp;
}
/*
* Allocate a page array capable of holding a specified number
* of pages, and point the page buf at it.
*/
STATIC int
_xfs_buf_get_pages(
xfs_buf_t *bp,
int page_count,
xfs_buf_flags_t flags)
{
/* Make sure that we have a page list */
if (bp->b_pages == NULL) {
bp->b_page_count = page_count;
if (page_count <= XB_PAGES) {
bp->b_pages = bp->b_page_array;
} else {
bp->b_pages = kmem_alloc(sizeof(struct page *) *
page_count, KM_NOFS);
if (bp->b_pages == NULL)
return -ENOMEM;
}
memset(bp->b_pages, 0, sizeof(struct page *) * page_count);
}
return 0;
}
/*
* Frees b_pages if it was allocated.
*/
STATIC void
_xfs_buf_free_pages(
xfs_buf_t *bp)
{
if (bp->b_pages != bp->b_page_array) {
kmem_free(bp->b_pages);
bp->b_pages = NULL;
}
}
/*
* Releases the specified buffer.
*
* The modification state of any associated pages is left unchanged.
* The buffer most not be on any hash - use xfs_buf_rele instead for
* hashed and refcounted buffers
*/
void
xfs_buf_free(
xfs_buf_t *bp)
{
trace_xfs_buf_free(bp, _RET_IP_);
ASSERT(list_empty(&bp->b_lru));
if (bp->b_flags & _XBF_PAGES) {
uint i;
if (xfs_buf_is_vmapped(bp))
vm_unmap_ram(bp->b_addr - bp->b_offset,
bp->b_page_count);
for (i = 0; i < bp->b_page_count; i++) {
struct page *page = bp->b_pages[i];
__free_page(page);
}
} else if (bp->b_flags & _XBF_KMEM)
kmem_free(bp->b_addr);
_xfs_buf_free_pages(bp);
xfs_buf_free_maps(bp);
kmem_zone_free(xfs_buf_zone, bp);
}
/*
* Allocates all the pages for buffer in question and builds it's page list.
*/
STATIC int
xfs_buf_allocate_memory(
xfs_buf_t *bp,
uint flags)
{
size_t size;
size_t nbytes, offset;
gfp_t gfp_mask = xb_to_gfp(flags);
unsigned short page_count, i;
xfs_off_t start, end;
int error;
/*
* for buffers that are contained within a single page, just allocate
* the memory from the heap - there's no need for the complexity of
* page arrays to keep allocation down to order 0.
*/
size = BBTOB(bp->b_length);
if (size < PAGE_SIZE) {
bp->b_addr = kmem_alloc(size, KM_NOFS);
if (!bp->b_addr) {
/* low memory - use alloc_page loop instead */
goto use_alloc_page;
}
if (((unsigned long)(bp->b_addr + size - 1) & PAGE_MASK) !=
((unsigned long)bp->b_addr & PAGE_MASK)) {
/* b_addr spans two pages - use alloc_page instead */
kmem_free(bp->b_addr);
bp->b_addr = NULL;
goto use_alloc_page;
}
bp->b_offset = offset_in_page(bp->b_addr);
bp->b_pages = bp->b_page_array;
bp->b_pages[0] = virt_to_page(bp->b_addr);
bp->b_page_count = 1;
bp->b_flags |= _XBF_KMEM;
return 0;
}
use_alloc_page:
start = BBTOB(bp->b_maps[0].bm_bn) >> PAGE_SHIFT;
end = (BBTOB(bp->b_maps[0].bm_bn + bp->b_length) + PAGE_SIZE - 1)
>> PAGE_SHIFT;
page_count = end - start;
error = _xfs_buf_get_pages(bp, page_count, flags);
if (unlikely(error))
return error;
offset = bp->b_offset;
bp->b_flags |= _XBF_PAGES;
for (i = 0; i < bp->b_page_count; i++) {
struct page *page;
uint retries = 0;
retry:
page = alloc_page(gfp_mask);
if (unlikely(page == NULL)) {
if (flags & XBF_READ_AHEAD) {
bp->b_page_count = i;
error = ENOMEM;
goto out_free_pages;
}
/*
* This could deadlock.
*
* But until all the XFS lowlevel code is revamped to
* handle buffer allocation failures we can't do much.
*/
if (!(++retries % 100))
xfs_err(NULL,
"possible memory allocation deadlock in %s (mode:0x%x)",
__func__, gfp_mask);
XFS_STATS_INC(xb_page_retries);
congestion_wait(BLK_RW_ASYNC, HZ/50);
goto retry;
}
XFS_STATS_INC(xb_page_found);
nbytes = min_t(size_t, size, PAGE_SIZE - offset);
size -= nbytes;
bp->b_pages[i] = page;
offset = 0;
}
return 0;
out_free_pages:
for (i = 0; i < bp->b_page_count; i++)
__free_page(bp->b_pages[i]);
return error;
}
/*
* Map buffer into kernel address-space if necessary.
*/
STATIC int
_xfs_buf_map_pages(
xfs_buf_t *bp,
uint flags)
{
ASSERT(bp->b_flags & _XBF_PAGES);
if (bp->b_page_count == 1) {
/* A single page buffer is always mappable */
bp->b_addr = page_address(bp->b_pages[0]) + bp->b_offset;
} else if (flags & XBF_UNMAPPED) {
bp->b_addr = NULL;
} else {
int retried = 0;
do {
bp->b_addr = vm_map_ram(bp->b_pages, bp->b_page_count,
-1, PAGE_KERNEL);
if (bp->b_addr)
break;
vm_unmap_aliases();
} while (retried++ <= 1);
if (!bp->b_addr)
return -ENOMEM;
bp->b_addr += bp->b_offset;
}
return 0;
}
/*
* Finding and Reading Buffers
*/
/*
* Look up, and creates if absent, a lockable buffer for
* a given range of an inode. The buffer is returned
* locked. No I/O is implied by this call.
*/
xfs_buf_t *
_xfs_buf_find(
struct xfs_buftarg *btp,
struct xfs_buf_map *map,
int nmaps,
xfs_buf_flags_t flags,
xfs_buf_t *new_bp)
{
size_t numbytes;
struct xfs_perag *pag;
struct rb_node **rbp;
struct rb_node *parent;
xfs_buf_t *bp;
xfs_daddr_t blkno = map[0].bm_bn;
int numblks = 0;
int i;
for (i = 0; i < nmaps; i++)
numblks += map[i].bm_len;
numbytes = BBTOB(numblks);
/* Check for IOs smaller than the sector size / not sector aligned */
ASSERT(!(numbytes < (1 << btp->bt_sshift)));
ASSERT(!(BBTOB(blkno) & (xfs_off_t)btp->bt_smask));
/* get tree root */
pag = xfs_perag_get(btp->bt_mount,
xfs_daddr_to_agno(btp->bt_mount, blkno));
/* walk tree */
spin_lock(&pag->pag_buf_lock);
rbp = &pag->pag_buf_tree.rb_node;
parent = NULL;
bp = NULL;
while (*rbp) {
parent = *rbp;
bp = rb_entry(parent, struct xfs_buf, b_rbnode);
if (blkno < bp->b_bn)
rbp = &(*rbp)->rb_left;
else if (blkno > bp->b_bn)
rbp = &(*rbp)->rb_right;
else {
/*
* found a block number match. If the range doesn't
* match, the only way this is allowed is if the buffer
* in the cache is stale and the transaction that made
* it stale has not yet committed. i.e. we are
* reallocating a busy extent. Skip this buffer and
* continue searching to the right for an exact match.
*/
if (bp->b_length != numblks) {
ASSERT(bp->b_flags & XBF_STALE);
rbp = &(*rbp)->rb_right;
continue;
}
atomic_inc(&bp->b_hold);
goto found;
}
}
/* No match found */
if (new_bp) {
rb_link_node(&new_bp->b_rbnode, parent, rbp);
rb_insert_color(&new_bp->b_rbnode, &pag->pag_buf_tree);
/* the buffer keeps the perag reference until it is freed */
new_bp->b_pag = pag;
spin_unlock(&pag->pag_buf_lock);
} else {
XFS_STATS_INC(xb_miss_locked);
spin_unlock(&pag->pag_buf_lock);
xfs_perag_put(pag);
}
return new_bp;
found:
spin_unlock(&pag->pag_buf_lock);
xfs_perag_put(pag);
if (!xfs_buf_trylock(bp)) {
if (flags & XBF_TRYLOCK) {
xfs_buf_rele(bp);
XFS_STATS_INC(xb_busy_locked);
return NULL;
}
xfs_buf_lock(bp);
XFS_STATS_INC(xb_get_locked_waited);
}
/*
* if the buffer is stale, clear all the external state associated with
* it. We need to keep flags such as how we allocated the buffer memory
* intact here.
*/
if (bp->b_flags & XBF_STALE) {
ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0);
ASSERT(bp->b_iodone == NULL);
bp->b_flags &= _XBF_KMEM | _XBF_PAGES;
bp->b_ops = NULL;
}
trace_xfs_buf_find(bp, flags, _RET_IP_);
XFS_STATS_INC(xb_get_locked);
return bp;
}
/*
* Assembles a buffer covering the specified range. The code is optimised for
* cache hits, as metadata intensive workloads will see 3 orders of magnitude
* more hits than misses.
*/
struct xfs_buf *
xfs_buf_get_map(
struct xfs_buftarg *target,
struct xfs_buf_map *map,
int nmaps,
xfs_buf_flags_t flags)
{
struct xfs_buf *bp;
struct xfs_buf *new_bp;
int error = 0;
bp = _xfs_buf_find(target, map, nmaps, flags, NULL);
if (likely(bp))
goto found;
new_bp = _xfs_buf_alloc(target, map, nmaps, flags);
if (unlikely(!new_bp))
return NULL;
error = xfs_buf_allocate_memory(new_bp, flags);
if (error) {
xfs_buf_free(new_bp);
return NULL;
}
bp = _xfs_buf_find(target, map, nmaps, flags, new_bp);
if (!bp) {
xfs_buf_free(new_bp);
return NULL;
}
if (bp != new_bp)
xfs_buf_free(new_bp);
found:
if (!bp->b_addr) {
error = _xfs_buf_map_pages(bp, flags);
if (unlikely(error)) {
xfs_warn(target->bt_mount,
"%s: failed to map pages\n", __func__);
xfs_buf_relse(bp);
return NULL;
}
}
XFS_STATS_INC(xb_get);
trace_xfs_buf_get(bp, flags, _RET_IP_);
return bp;
}
STATIC int
_xfs_buf_read(
xfs_buf_t *bp,
xfs_buf_flags_t flags)
{
ASSERT(!(flags & XBF_WRITE));
ASSERT(bp->b_maps[0].bm_bn != XFS_BUF_DADDR_NULL);
bp->b_flags &= ~(XBF_WRITE | XBF_ASYNC | XBF_READ_AHEAD);
bp->b_flags |= flags & (XBF_READ | XBF_ASYNC | XBF_READ_AHEAD);
xfs_buf_iorequest(bp);
if (flags & XBF_ASYNC)
return 0;
return xfs_buf_iowait(bp);
}
xfs_buf_t *
xfs_buf_read_map(
struct xfs_buftarg *target,
struct xfs_buf_map *map,
int nmaps,
xfs_buf_flags_t flags,
const struct xfs_buf_ops *ops)
{
struct xfs_buf *bp;
flags |= XBF_READ;
bp = xfs_buf_get_map(target, map, nmaps, flags);
if (bp) {
trace_xfs_buf_read(bp, flags, _RET_IP_);
if (!XFS_BUF_ISDONE(bp)) {
XFS_STATS_INC(xb_get_read);
bp->b_ops = ops;
_xfs_buf_read(bp, flags);
} else if (flags & XBF_ASYNC) {
/*
* Read ahead call which is already satisfied,
* drop the buffer
*/
xfs_buf_relse(bp);
return NULL;
} else {
/* We do not want read in the flags */
bp->b_flags &= ~XBF_READ;
}
}
return bp;
}
/*
* If we are not low on memory then do the readahead in a deadlock
* safe manner.
*/
void
xfs_buf_readahead_map(
struct xfs_buftarg *target,
struct xfs_buf_map *map,
int nmaps,
const struct xfs_buf_ops *ops)
{
if (bdi_read_congested(target->bt_bdi))
return;
xfs_buf_read_map(target, map, nmaps,
XBF_TRYLOCK|XBF_ASYNC|XBF_READ_AHEAD, ops);
}
/*
* Read an uncached buffer from disk. Allocates and returns a locked
* buffer containing the disk contents or nothing.
*/
struct xfs_buf *
xfs_buf_read_uncached(
struct xfs_buftarg *target,
xfs_daddr_t daddr,
size_t numblks,
int flags,
const struct xfs_buf_ops *ops)
{
struct xfs_buf *bp;
bp = xfs_buf_get_uncached(target, numblks, flags);
if (!bp)
return NULL;
/* set up the buffer for a read IO */
ASSERT(bp->b_map_count == 1);
bp->b_bn = daddr;
bp->b_maps[0].bm_bn = daddr;
bp->b_flags |= XBF_READ;
bp->b_ops = ops;
xfsbdstrat(target->bt_mount, bp);
xfs_buf_iowait(bp);
return bp;
}
/*
* Return a buffer allocated as an empty buffer and associated to external
* memory via xfs_buf_associate_memory() back to it's empty state.
*/
void
xfs_buf_set_empty(
struct xfs_buf *bp,
size_t numblks)
{
if (bp->b_pages)
_xfs_buf_free_pages(bp);
bp->b_pages = NULL;
bp->b_page_count = 0;
bp->b_addr = NULL;
bp->b_length = numblks;
bp->b_io_length = numblks;
ASSERT(bp->b_map_count == 1);
bp->b_bn = XFS_BUF_DADDR_NULL;
bp->b_maps[0].bm_bn = XFS_BUF_DADDR_NULL;
bp->b_maps[0].bm_len = bp->b_length;
}
static inline struct page *
mem_to_page(
void *addr)
{
if ((!is_vmalloc_addr(addr))) {
return virt_to_page(addr);
} else {
return vmalloc_to_page(addr);
}
}
int
xfs_buf_associate_memory(
xfs_buf_t *bp,
void *mem,
size_t len)
{
int rval;
int i = 0;
unsigned long pageaddr;
unsigned long offset;
size_t buflen;
int page_count;
pageaddr = (unsigned long)mem & PAGE_MASK;
offset = (unsigned long)mem - pageaddr;
buflen = PAGE_ALIGN(len + offset);
page_count = buflen >> PAGE_SHIFT;
/* Free any previous set of page pointers */
if (bp->b_pages)
_xfs_buf_free_pages(bp);
bp->b_pages = NULL;
bp->b_addr = mem;
rval = _xfs_buf_get_pages(bp, page_count, 0);
if (rval)
return rval;
bp->b_offset = offset;
for (i = 0; i < bp->b_page_count; i++) {
bp->b_pages[i] = mem_to_page((void *)pageaddr);
pageaddr += PAGE_SIZE;
}
bp->b_io_length = BTOBB(len);
bp->b_length = BTOBB(buflen);
return 0;
}
xfs_buf_t *
xfs_buf_get_uncached(
struct xfs_buftarg *target,
size_t numblks,
int flags)
{
unsigned long page_count;
int error, i;
struct xfs_buf *bp;
DEFINE_SINGLE_BUF_MAP(map, XFS_BUF_DADDR_NULL, numblks);
bp = _xfs_buf_alloc(target, &map, 1, 0);
if (unlikely(bp == NULL))
goto fail;
page_count = PAGE_ALIGN(numblks << BBSHIFT) >> PAGE_SHIFT;
error = _xfs_buf_get_pages(bp, page_count, 0);
if (error)
goto fail_free_buf;
for (i = 0; i < page_count; i++) {
bp->b_pages[i] = alloc_page(xb_to_gfp(flags));
if (!bp->b_pages[i])
goto fail_free_mem;
}
bp->b_flags |= _XBF_PAGES;
error = _xfs_buf_map_pages(bp, 0);
if (unlikely(error)) {
xfs_warn(target->bt_mount,
"%s: failed to map pages\n", __func__);
goto fail_free_mem;
}
trace_xfs_buf_get_uncached(bp, _RET_IP_);
return bp;
fail_free_mem:
while (--i >= 0)
__free_page(bp->b_pages[i]);
_xfs_buf_free_pages(bp);
fail_free_buf:
xfs_buf_free_maps(bp);
kmem_zone_free(xfs_buf_zone, bp);
fail:
return NULL;
}
/*
* Increment reference count on buffer, to hold the buffer concurrently
* with another thread which may release (free) the buffer asynchronously.
* Must hold the buffer already to call this function.
*/
void
xfs_buf_hold(
xfs_buf_t *bp)
{
trace_xfs_buf_hold(bp, _RET_IP_);
atomic_inc(&bp->b_hold);
}
/*
* Releases a hold on the specified buffer. If the
* the hold count is 1, calls xfs_buf_free.
*/
void
xfs_buf_rele(
xfs_buf_t *bp)
{
struct xfs_perag *pag = bp->b_pag;
trace_xfs_buf_rele(bp, _RET_IP_);
if (!pag) {
ASSERT(list_empty(&bp->b_lru));
ASSERT(RB_EMPTY_NODE(&bp->b_rbnode));
if (atomic_dec_and_test(&bp->b_hold))
xfs_buf_free(bp);
return;
}
ASSERT(!RB_EMPTY_NODE(&bp->b_rbnode));
ASSERT(atomic_read(&bp->b_hold) > 0);
if (atomic_dec_and_lock(&bp->b_hold, &pag->pag_buf_lock)) {
if (!(bp->b_flags & XBF_STALE) &&
atomic_read(&bp->b_lru_ref)) {
xfs_buf_lru_add(bp);
spin_unlock(&pag->pag_buf_lock);
} else {
xfs_buf_lru_del(bp);
ASSERT(!(bp->b_flags & _XBF_DELWRI_Q));
rb_erase(&bp->b_rbnode, &pag->pag_buf_tree);
spin_unlock(&pag->pag_buf_lock);
xfs_perag_put(pag);
xfs_buf_free(bp);
}
}
}
/*
* Lock a buffer object, if it is not already locked.
*
* If we come across a stale, pinned, locked buffer, we know that we are
* being asked to lock a buffer that has been reallocated. Because it is
* pinned, we know that the log has not been pushed to disk and hence it
* will still be locked. Rather than continuing to have trylock attempts
* fail until someone else pushes the log, push it ourselves before
* returning. This means that the xfsaild will not get stuck trying
* to push on stale inode buffers.
*/
int
xfs_buf_trylock(
struct xfs_buf *bp)
{
int locked;
locked = down_trylock(&bp->b_sema) == 0;
if (locked)
XB_SET_OWNER(bp);
else if (atomic_read(&bp->b_pin_count) && (bp->b_flags & XBF_STALE))
xfs_log_force(bp->b_target->bt_mount, 0);
trace_xfs_buf_trylock(bp, _RET_IP_);
return locked;
}
/*
* Lock a buffer object.
*
* If we come across a stale, pinned, locked buffer, we know that we
* are being asked to lock a buffer that has been reallocated. Because
* it is pinned, we know that the log has not been pushed to disk and
* hence it will still be locked. Rather than sleeping until someone
* else pushes the log, push it ourselves before trying to get the lock.
*/
void
xfs_buf_lock(
struct xfs_buf *bp)
{
trace_xfs_buf_lock(bp, _RET_IP_);
if (atomic_read(&bp->b_pin_count) && (bp->b_flags & XBF_STALE))
xfs_log_force(bp->b_target->bt_mount, 0);
down(&bp->b_sema);
XB_SET_OWNER(bp);
trace_xfs_buf_lock_done(bp, _RET_IP_);
}
void
xfs_buf_unlock(
struct xfs_buf *bp)
{
XB_CLEAR_OWNER(bp);
up(&bp->b_sema);
trace_xfs_buf_unlock(bp, _RET_IP_);
}
STATIC void
xfs_buf_wait_unpin(
xfs_buf_t *bp)
{
DECLARE_WAITQUEUE (wait, current);
if (atomic_read(&bp->b_pin_count) == 0)
return;
add_wait_queue(&bp->b_waiters, &wait);
for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (atomic_read(&bp->b_pin_count) == 0)
break;
io_schedule();
}
remove_wait_queue(&bp->b_waiters, &wait);
set_current_state(TASK_RUNNING);
}
/*
* Buffer Utility Routines
*/
STATIC void
xfs_buf_iodone_work(
struct work_struct *work)
{
struct xfs_buf *bp =
container_of(work, xfs_buf_t, b_iodone_work);
bool read = !!(bp->b_flags & XBF_READ);
bp->b_flags &= ~(XBF_READ | XBF_WRITE | XBF_READ_AHEAD);
if (read && bp->b_ops)
bp->b_ops->verify_read(bp);
if (bp->b_iodone)
(*(bp->b_iodone))(bp);
else if (bp->b_flags & XBF_ASYNC)
xfs_buf_relse(bp);
else {
ASSERT(read && bp->b_ops);
complete(&bp->b_iowait);
}
}
void
xfs_buf_ioend(
struct xfs_buf *bp,
int schedule)
{
bool read = !!(bp->b_flags & XBF_READ);
trace_xfs_buf_iodone(bp, _RET_IP_);
if (bp->b_error == 0)
bp->b_flags |= XBF_DONE;
if (bp->b_iodone || (read && bp->b_ops) || (bp->b_flags & XBF_ASYNC)) {
if (schedule) {
INIT_WORK(&bp->b_iodone_work, xfs_buf_iodone_work);
queue_work(xfslogd_workqueue, &bp->b_iodone_work);
} else {
xfs_buf_iodone_work(&bp->b_iodone_work);
}
} else {
bp->b_flags &= ~(XBF_READ | XBF_WRITE | XBF_READ_AHEAD);
complete(&bp->b_iowait);
}
}
void
xfs_buf_ioerror(
xfs_buf_t *bp,
int error)
{
ASSERT(error >= 0 && error <= 0xffff);
bp->b_error = (unsigned short)error;
trace_xfs_buf_ioerror(bp, error, _RET_IP_);
}
void
xfs_buf_ioerror_alert(
struct xfs_buf *bp,
const char *func)
{
xfs_alert(bp->b_target->bt_mount,
"metadata I/O error: block 0x%llx (\"%s\") error %d numblks %d",
(__uint64_t)XFS_BUF_ADDR(bp), func, bp->b_error, bp->b_length);
}
/*
* Called when we want to stop a buffer from getting written or read.
* We attach the EIO error, muck with its flags, and call xfs_buf_ioend
* so that the proper iodone callbacks get called.
*/
STATIC int
xfs_bioerror(
xfs_buf_t *bp)
{
#ifdef XFSERRORDEBUG
ASSERT(XFS_BUF_ISREAD(bp) || bp->b_iodone);
#endif
/*
* No need to wait until the buffer is unpinned, we aren't flushing it.
*/
xfs_buf_ioerror(bp, EIO);
/*
* We're calling xfs_buf_ioend, so delete XBF_DONE flag.
*/
XFS_BUF_UNREAD(bp);
XFS_BUF_UNDONE(bp);
xfs_buf_stale(bp);
xfs_buf_ioend(bp, 0);
return EIO;
}
/*
* Same as xfs_bioerror, except that we are releasing the buffer
* here ourselves, and avoiding the xfs_buf_ioend call.
* This is meant for userdata errors; metadata bufs come with
* iodone functions attached, so that we can track down errors.
*/
STATIC int
xfs_bioerror_relse(
struct xfs_buf *bp)
{
int64_t fl = bp->b_flags;
/*
* No need to wait until the buffer is unpinned.
* We aren't flushing it.
*
* chunkhold expects B_DONE to be set, whether
* we actually finish the I/O or not. We don't want to
* change that interface.
*/
XFS_BUF_UNREAD(bp);
XFS_BUF_DONE(bp);
xfs_buf_stale(bp);
bp->b_iodone = NULL;
if (!(fl & XBF_ASYNC)) {
/*
* Mark b_error and B_ERROR _both_.
* Lot's of chunkcache code assumes that.
* There's no reason to mark error for
* ASYNC buffers.
*/
xfs_buf_ioerror(bp, EIO);
complete(&bp->b_iowait);
} else {
xfs_buf_relse(bp);
}
return EIO;
}
STATIC int
xfs_bdstrat_cb(
struct xfs_buf *bp)
{
if (XFS_FORCED_SHUTDOWN(bp->b_target->bt_mount)) {
trace_xfs_bdstrat_shut(bp, _RET_IP_);
/*
* Metadata write that didn't get logged but
* written delayed anyway. These aren't associated
* with a transaction, and can be ignored.
*/
if (!bp->b_iodone && !XFS_BUF_ISREAD(bp))
return xfs_bioerror_relse(bp);
else
return xfs_bioerror(bp);
}
xfs_buf_iorequest(bp);
return 0;
}
int
xfs_bwrite(
struct xfs_buf *bp)
{
int error;
ASSERT(xfs_buf_islocked(bp));
bp->b_flags |= XBF_WRITE;
bp->b_flags &= ~(XBF_ASYNC | XBF_READ | _XBF_DELWRI_Q);
xfs_bdstrat_cb(bp);
error = xfs_buf_iowait(bp);
if (error) {
xfs_force_shutdown(bp->b_target->bt_mount,
SHUTDOWN_META_IO_ERROR);
}
return error;
}
/*
* Wrapper around bdstrat so that we can stop data from going to disk in case
* we are shutting down the filesystem. Typically user data goes thru this
* path; one of the exceptions is the superblock.
*/
void
xfsbdstrat(
struct xfs_mount *mp,
struct xfs_buf *bp)
{
if (XFS_FORCED_SHUTDOWN(mp)) {
trace_xfs_bdstrat_shut(bp, _RET_IP_);
xfs_bioerror_relse(bp);
return;
}
xfs_buf_iorequest(bp);
}
STATIC void
_xfs_buf_ioend(
xfs_buf_t *bp,
int schedule)
{
if (atomic_dec_and_test(&bp->b_io_remaining) == 1)
xfs_buf_ioend(bp, schedule);
}
STATIC void
xfs_buf_bio_end_io(
struct bio *bio,
int error)
{
xfs_buf_t *bp = (xfs_buf_t *)bio->bi_private;
/*
* don't overwrite existing errors - otherwise we can lose errors on
* buffers that require multiple bios to complete.
*/
if (!bp->b_error)
xfs_buf_ioerror(bp, -error);
if (!bp->b_error && xfs_buf_is_vmapped(bp) && (bp->b_flags & XBF_READ))
invalidate_kernel_vmap_range(bp->b_addr, xfs_buf_vmap_len(bp));
_xfs_buf_ioend(bp, 1);
bio_put(bio);
}
static void
xfs_buf_ioapply_map(
struct xfs_buf *bp,
int map,
int *buf_offset,
int *count,
int rw)
{
int page_index;
int total_nr_pages = bp->b_page_count;
int nr_pages;
struct bio *bio;
sector_t sector = bp->b_maps[map].bm_bn;
int size;
int offset;
total_nr_pages = bp->b_page_count;
/* skip the pages in the buffer before the start offset */
page_index = 0;
offset = *buf_offset;
while (offset >= PAGE_SIZE) {
page_index++;
offset -= PAGE_SIZE;
}
/*
* Limit the IO size to the length of the current vector, and update the
* remaining IO count for the next time around.
*/
size = min_t(int, BBTOB(bp->b_maps[map].bm_len), *count);
*count -= size;
*buf_offset += size;
next_chunk:
atomic_inc(&bp->b_io_remaining);
nr_pages = BIO_MAX_SECTORS >> (PAGE_SHIFT - BBSHIFT);
if (nr_pages > total_nr_pages)
nr_pages = total_nr_pages;
bio = bio_alloc(GFP_NOIO, nr_pages);
bio->bi_bdev = bp->b_target->bt_bdev;
bio->bi_sector = sector;
bio->bi_end_io = xfs_buf_bio_end_io;
bio->bi_private = bp;
for (; size && nr_pages; nr_pages--, page_index++) {
int rbytes, nbytes = PAGE_SIZE - offset;
if (nbytes > size)
nbytes = size;
rbytes = bio_add_page(bio, bp->b_pages[page_index], nbytes,
offset);
if (rbytes < nbytes)
break;
offset = 0;
sector += BTOBB(nbytes);
size -= nbytes;
total_nr_pages--;
}
if (likely(bio->bi_size)) {
if (xfs_buf_is_vmapped(bp)) {
flush_kernel_vmap_range(bp->b_addr,
xfs_buf_vmap_len(bp));
}
submit_bio(rw, bio);
if (size)
goto next_chunk;
} else {
/*
* This is guaranteed not to be the last io reference count
* because the caller (xfs_buf_iorequest) holds a count itself.
*/
atomic_dec(&bp->b_io_remaining);
xfs_buf_ioerror(bp, EIO);
bio_put(bio);
}
}
STATIC void
_xfs_buf_ioapply(
struct xfs_buf *bp)
{
struct blk_plug plug;
int rw;
int offset;
int size;
int i;
if (bp->b_flags & XBF_WRITE) {
if (bp->b_flags & XBF_SYNCIO)
rw = WRITE_SYNC;
else
rw = WRITE;
if (bp->b_flags & XBF_FUA)
rw |= REQ_FUA;
if (bp->b_flags & XBF_FLUSH)
rw |= REQ_FLUSH;
/*
* Run the write verifier callback function if it exists. If
* this function fails it will mark the buffer with an error and
* the IO should not be dispatched.
*/
if (bp->b_ops) {
bp->b_ops->verify_write(bp);
if (bp->b_error) {
xfs_force_shutdown(bp->b_target->bt_mount,
SHUTDOWN_CORRUPT_INCORE);
return;
}
}
} else if (bp->b_flags & XBF_READ_AHEAD) {
rw = READA;
} else {
rw = READ;
}
/* we only use the buffer cache for meta-data */
rw |= REQ_META;
/*
* Walk all the vectors issuing IO on them. Set up the initial offset
* into the buffer and the desired IO size before we start -
* _xfs_buf_ioapply_vec() will modify them appropriately for each
* subsequent call.
*/
offset = bp->b_offset;
size = BBTOB(bp->b_io_length);
blk_start_plug(&plug);
for (i = 0; i < bp->b_map_count; i++) {
xfs_buf_ioapply_map(bp, i, &offset, &size, rw);
if (bp->b_error)
break;
if (size <= 0)
break; /* all done */
}
blk_finish_plug(&plug);
}
void
xfs_buf_iorequest(
xfs_buf_t *bp)
{
trace_xfs_buf_iorequest(bp, _RET_IP_);
ASSERT(!(bp->b_flags & _XBF_DELWRI_Q));
if (bp->b_flags & XBF_WRITE)
xfs_buf_wait_unpin(bp);
xfs_buf_hold(bp);
/* Set the count to 1 initially, this will stop an I/O
* completion callout which happens before we have started
* all the I/O from calling xfs_buf_ioend too early.
*/
atomic_set(&bp->b_io_remaining, 1);
_xfs_buf_ioapply(bp);
_xfs_buf_ioend(bp, 1);
xfs_buf_rele(bp);
}
/*
* Waits for I/O to complete on the buffer supplied. It returns immediately if
* no I/O is pending or there is already a pending error on the buffer. It
* returns the I/O error code, if any, or 0 if there was no error.
*/
int
xfs_buf_iowait(
xfs_buf_t *bp)
{
trace_xfs_buf_iowait(bp, _RET_IP_);
if (!bp->b_error)
wait_for_completion(&bp->b_iowait);
trace_xfs_buf_iowait_done(bp, _RET_IP_);
return bp->b_error;
}
xfs_caddr_t
xfs_buf_offset(
xfs_buf_t *bp,
size_t offset)
{
struct page *page;
if (bp->b_addr)
return bp->b_addr + offset;
offset += bp->b_offset;
page = bp->b_pages[offset >> PAGE_SHIFT];
return (xfs_caddr_t)page_address(page) + (offset & (PAGE_SIZE-1));
}
/*
* Move data into or out of a buffer.
*/
void
xfs_buf_iomove(
xfs_buf_t *bp, /* buffer to process */
size_t boff, /* starting buffer offset */
size_t bsize, /* length to copy */
void *data, /* data address */
xfs_buf_rw_t mode) /* read/write/zero flag */
{
size_t bend;
bend = boff + bsize;
while (boff < bend) {
struct page *page;
int page_index, page_offset, csize;
page_index = (boff + bp->b_offset) >> PAGE_SHIFT;
page_offset = (boff + bp->b_offset) & ~PAGE_MASK;
page = bp->b_pages[page_index];
csize = min_t(size_t, PAGE_SIZE - page_offset,
BBTOB(bp->b_io_length) - boff);
ASSERT((csize + page_offset) <= PAGE_SIZE);
switch (mode) {
case XBRW_ZERO:
memset(page_address(page) + page_offset, 0, csize);
break;
case XBRW_READ:
memcpy(data, page_address(page) + page_offset, csize);
break;
case XBRW_WRITE:
memcpy(page_address(page) + page_offset, data, csize);
}
boff += csize;
data += csize;
}
}
/*
* Handling of buffer targets (buftargs).
*/
/*
* Wait for any bufs with callbacks that have been submitted but have not yet
* returned. These buffers will have an elevated hold count, so wait on those
* while freeing all the buffers only held by the LRU.
*/
void
xfs_wait_buftarg(
struct xfs_buftarg *btp)
{
struct xfs_buf *bp;
restart:
spin_lock(&btp->bt_lru_lock);
while (!list_empty(&btp->bt_lru)) {
bp = list_first_entry(&btp->bt_lru, struct xfs_buf, b_lru);
if (atomic_read(&bp->b_hold) > 1) {
spin_unlock(&btp->bt_lru_lock);
delay(100);
goto restart;
}
/*
* clear the LRU reference count so the buffer doesn't get
* ignored in xfs_buf_rele().
*/
atomic_set(&bp->b_lru_ref, 0);
spin_unlock(&btp->bt_lru_lock);
xfs_buf_rele(bp);
spin_lock(&btp->bt_lru_lock);
}
spin_unlock(&btp->bt_lru_lock);
}
int
xfs_buftarg_shrink(
struct shrinker *shrink,
struct shrink_control *sc)
{
struct xfs_buftarg *btp = container_of(shrink,
struct xfs_buftarg, bt_shrinker);
struct xfs_buf *bp;
int nr_to_scan = sc->nr_to_scan;
LIST_HEAD(dispose);
if (!nr_to_scan)
return btp->bt_lru_nr;
spin_lock(&btp->bt_lru_lock);
while (!list_empty(&btp->bt_lru)) {
if (nr_to_scan-- <= 0)
break;
bp = list_first_entry(&btp->bt_lru, struct xfs_buf, b_lru);
/*
* Decrement the b_lru_ref count unless the value is already
* zero. If the value is already zero, we need to reclaim the
* buffer, otherwise it gets another trip through the LRU.
*/
if (!atomic_add_unless(&bp->b_lru_ref, -1, 0)) {
list_move_tail(&bp->b_lru, &btp->bt_lru);
continue;
}
/*
* remove the buffer from the LRU now to avoid needing another
* lock round trip inside xfs_buf_rele().
*/
list_move(&bp->b_lru, &dispose);
btp->bt_lru_nr--;
bp->b_lru_flags |= _XBF_LRU_DISPOSE;
}
spin_unlock(&btp->bt_lru_lock);
while (!list_empty(&dispose)) {
bp = list_first_entry(&dispose, struct xfs_buf, b_lru);
list_del_init(&bp->b_lru);
xfs_buf_rele(bp);
}
return btp->bt_lru_nr;
}
void
xfs_free_buftarg(
struct xfs_mount *mp,
struct xfs_buftarg *btp)
{
unregister_shrinker(&btp->bt_shrinker);
if (mp->m_flags & XFS_MOUNT_BARRIER)
xfs_blkdev_issue_flush(btp);
kmem_free(btp);
}
STATIC int
xfs_setsize_buftarg_flags(
xfs_buftarg_t *btp,
unsigned int blocksize,
unsigned int sectorsize,
int verbose)
{
btp->bt_bsize = blocksize;
btp->bt_sshift = ffs(sectorsize) - 1;
btp->bt_smask = sectorsize - 1;
if (set_blocksize(btp->bt_bdev, sectorsize)) {
char name[BDEVNAME_SIZE];
bdevname(btp->bt_bdev, name);
xfs_warn(btp->bt_mount,
"Cannot set_blocksize to %u on device %s\n",
sectorsize, name);
return EINVAL;
}
return 0;
}
/*
* When allocating the initial buffer target we have not yet
* read in the superblock, so don't know what sized sectors
* are being used is at this early stage. Play safe.
*/
STATIC int
xfs_setsize_buftarg_early(
xfs_buftarg_t *btp,
struct block_device *bdev)
{
return xfs_setsize_buftarg_flags(btp,
PAGE_SIZE, bdev_logical_block_size(bdev), 0);
}
int
xfs_setsize_buftarg(
xfs_buftarg_t *btp,
unsigned int blocksize,
unsigned int sectorsize)
{
return xfs_setsize_buftarg_flags(btp, blocksize, sectorsize, 1);
}
xfs_buftarg_t *
xfs_alloc_buftarg(
struct xfs_mount *mp,
struct block_device *bdev,
int external,
const char *fsname)
{
xfs_buftarg_t *btp;
btp = kmem_zalloc(sizeof(*btp), KM_SLEEP);
btp->bt_mount = mp;
btp->bt_dev = bdev->bd_dev;
btp->bt_bdev = bdev;
btp->bt_bdi = blk_get_backing_dev_info(bdev);
if (!btp->bt_bdi)
goto error;
INIT_LIST_HEAD(&btp->bt_lru);
spin_lock_init(&btp->bt_lru_lock);
if (xfs_setsize_buftarg_early(btp, bdev))
goto error;
btp->bt_shrinker.shrink = xfs_buftarg_shrink;
btp->bt_shrinker.seeks = DEFAULT_SEEKS;
register_shrinker(&btp->bt_shrinker);
return btp;
error:
kmem_free(btp);
return NULL;
}
/*
* Add a buffer to the delayed write list.
*
* This queues a buffer for writeout if it hasn't already been. Note that
* neither this routine nor the buffer list submission functions perform
* any internal synchronization. It is expected that the lists are thread-local
* to the callers.
*
* Returns true if we queued up the buffer, or false if it already had
* been on the buffer list.
*/
bool
xfs_buf_delwri_queue(
struct xfs_buf *bp,
struct list_head *list)
{
ASSERT(xfs_buf_islocked(bp));
ASSERT(!(bp->b_flags & XBF_READ));
/*
* If the buffer is already marked delwri it already is queued up
* by someone else for imediate writeout. Just ignore it in that
* case.
*/
if (bp->b_flags & _XBF_DELWRI_Q) {
trace_xfs_buf_delwri_queued(bp, _RET_IP_);
return false;
}
trace_xfs_buf_delwri_queue(bp, _RET_IP_);
/*
* If a buffer gets written out synchronously or marked stale while it
* is on a delwri list we lazily remove it. To do this, the other party
* clears the _XBF_DELWRI_Q flag but otherwise leaves the buffer alone.
* It remains referenced and on the list. In a rare corner case it
* might get readded to a delwri list after the synchronous writeout, in
* which case we need just need to re-add the flag here.
*/
bp->b_flags |= _XBF_DELWRI_Q;
if (list_empty(&bp->b_list)) {
atomic_inc(&bp->b_hold);
list_add_tail(&bp->b_list, list);
}
return true;
}
/*
* Compare function is more complex than it needs to be because
* the return value is only 32 bits and we are doing comparisons
* on 64 bit values
*/
static int
xfs_buf_cmp(
void *priv,
struct list_head *a,
struct list_head *b)
{
struct xfs_buf *ap = container_of(a, struct xfs_buf, b_list);
struct xfs_buf *bp = container_of(b, struct xfs_buf, b_list);
xfs_daddr_t diff;
diff = ap->b_maps[0].bm_bn - bp->b_maps[0].bm_bn;
if (diff < 0)
return -1;
if (diff > 0)
return 1;
return 0;
}
static int
__xfs_buf_delwri_submit(
struct list_head *buffer_list,
struct list_head *io_list,
bool wait)
{
struct blk_plug plug;
struct xfs_buf *bp, *n;
int pinned = 0;
list_for_each_entry_safe(bp, n, buffer_list, b_list) {
if (!wait) {
if (xfs_buf_ispinned(bp)) {
pinned++;
continue;
}
if (!xfs_buf_trylock(bp))
continue;
} else {
xfs_buf_lock(bp);
}
/*
* Someone else might have written the buffer synchronously or
* marked it stale in the meantime. In that case only the
* _XBF_DELWRI_Q flag got cleared, and we have to drop the
* reference and remove it from the list here.
*/
if (!(bp->b_flags & _XBF_DELWRI_Q)) {
list_del_init(&bp->b_list);
xfs_buf_relse(bp);
continue;
}
list_move_tail(&bp->b_list, io_list);
trace_xfs_buf_delwri_split(bp, _RET_IP_);
}
list_sort(NULL, io_list, xfs_buf_cmp);
blk_start_plug(&plug);
list_for_each_entry_safe(bp, n, io_list, b_list) {
bp->b_flags &= ~(_XBF_DELWRI_Q | XBF_ASYNC);
bp->b_flags |= XBF_WRITE;
if (!wait) {
bp->b_flags |= XBF_ASYNC;
list_del_init(&bp->b_list);
}
xfs_bdstrat_cb(bp);
}
blk_finish_plug(&plug);
return pinned;
}
/*
* Write out a buffer list asynchronously.
*
* This will take the @buffer_list, write all non-locked and non-pinned buffers
* out and not wait for I/O completion on any of the buffers. This interface
* is only safely useable for callers that can track I/O completion by higher
* level means, e.g. AIL pushing as the @buffer_list is consumed in this
* function.
*/
int
xfs_buf_delwri_submit_nowait(
struct list_head *buffer_list)
{
LIST_HEAD (io_list);
return __xfs_buf_delwri_submit(buffer_list, &io_list, false);
}
/*
* Write out a buffer list synchronously.
*
* This will take the @buffer_list, write all buffers out and wait for I/O
* completion on all of the buffers. @buffer_list is consumed by the function,
* so callers must have some other way of tracking buffers if they require such
* functionality.
*/
int
xfs_buf_delwri_submit(
struct list_head *buffer_list)
{
LIST_HEAD (io_list);
int error = 0, error2;
struct xfs_buf *bp;
__xfs_buf_delwri_submit(buffer_list, &io_list, true);
/* Wait for IO to complete. */
while (!list_empty(&io_list)) {
bp = list_first_entry(&io_list, struct xfs_buf, b_list);
list_del_init(&bp->b_list);
error2 = xfs_buf_iowait(bp);
xfs_buf_relse(bp);
if (!error)
error = error2;
}
return error;
}
int __init
xfs_buf_init(void)
{
xfs_buf_zone = kmem_zone_init_flags(sizeof(xfs_buf_t), "xfs_buf",
KM_ZONE_HWALIGN, NULL);
if (!xfs_buf_zone)
goto out;
xfslogd_workqueue = alloc_workqueue("xfslogd",
WQ_MEM_RECLAIM | WQ_HIGHPRI, 1);
if (!xfslogd_workqueue)
goto out_free_buf_zone;
return 0;
out_free_buf_zone:
kmem_zone_destroy(xfs_buf_zone);
out:
return -ENOMEM;
}
void
xfs_buf_terminate(void)
{
destroy_workqueue(xfslogd_workqueue);
kmem_zone_destroy(xfs_buf_zone);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5600_0 |
crossvul-cpp_data_good_2212_0 | /*
* Copyright 2011-2013 Con Kolivas
* Copyright 2010 Jeff Garzik
*
* 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 3 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <jansson.h>
#ifdef HAVE_LIBCURL
#include <curl/curl.h>
#endif
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#ifndef WIN32
#include <fcntl.h>
# ifdef __linux__
# include <sys/prctl.h>
# endif
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <netdb.h>
#else
# include <windows.h>
# include <winsock2.h>
# include <ws2tcpip.h>
# include <mmsystem.h>
#endif
#include "miner.h"
#include "elist.h"
#include "compat.h"
#include "util.h"
#include "pool.h"
#define DEFAULT_SOCKWAIT 60
extern double opt_diff_mult;
bool successful_connect = false;
static void keep_sockalive(SOCKETTYPE fd)
{
const int tcp_one = 1;
#ifndef WIN32
const int tcp_keepidle = 45;
const int tcp_keepintvl = 30;
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, O_NONBLOCK | flags);
#else
u_long flags = 1;
ioctlsocket(fd, FIONBIO, &flags);
#endif
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one));
if (!opt_delaynet)
#ifndef __linux
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&tcp_one, sizeof(tcp_one));
#else /* __linux */
setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
#endif /* __linux__ */
#ifdef __APPLE_CC__
setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
#endif /* __APPLE_CC__ */
}
struct tq_ent {
void *data;
struct list_head q_node;
};
#ifdef HAVE_LIBCURL
struct timeval nettime;
struct data_buffer {
void *buf;
size_t len;
};
struct upload_buffer {
const void *buf;
size_t len;
};
struct header_info {
char *lp_path;
int rolltime;
char *reason;
char *stratum_url;
bool hadrolltime;
bool canroll;
bool hadexpire;
};
static void databuf_free(struct data_buffer *db)
{
if (!db)
return;
free(db->buf);
memset(db, 0, sizeof(*db));
}
static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct data_buffer *db = (struct data_buffer *)user_data;
size_t len = size * nmemb;
size_t oldlen, newlen;
void *newmem;
static const unsigned char zero = 0;
oldlen = db->len;
newlen = oldlen + len;
newmem = realloc(db->buf, newlen + 1);
if (!newmem)
return 0;
db->buf = newmem;
db->len = newlen;
memcpy((uint8_t*)db->buf + oldlen, ptr, len);
memcpy((uint8_t*)db->buf + newlen, &zero, 1); /* null terminate */
return len;
}
static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct upload_buffer *ub = (struct upload_buffer *)user_data;
unsigned int len = size * nmemb;
if (len > ub->len)
len = ub->len;
if (len) {
memcpy(ptr, ub->buf, len);
ub->buf = (uint8_t*)ub->buf + len;
ub->len -= len;
}
return len;
}
static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
{
struct header_info *hi = (struct header_info *)user_data;
size_t remlen, slen, ptrlen = size * nmemb;
char *rem, *val = NULL, *key = NULL;
void *tmp;
val = (char *)calloc(1, ptrlen);
key = (char *)calloc(1, ptrlen);
if (!key || !val)
goto out;
tmp = memchr(ptr, ':', ptrlen);
if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
goto out;
slen = (uint8_t*)tmp - (uint8_t*)ptr;
if ((slen + 1) == ptrlen) /* skip key w/ no value */
goto out;
memcpy(key, ptr, slen); /* store & nul term key */
key[slen] = 0;
rem = (char*)ptr + slen + 1; /* trim value's leading whitespace */
remlen = ptrlen - slen - 1;
while ((remlen > 0) && (isspace(*rem))) {
remlen--;
rem++;
}
memcpy(val, rem, remlen); /* store value, trim trailing ws */
val[remlen] = 0;
while ((*val) && (isspace(val[strlen(val) - 1])))
val[strlen(val) - 1] = 0;
if (!*val) /* skip blank value */
goto out;
if (opt_protocol)
applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
if (!strcasecmp("X-Roll-Ntime", key)) {
hi->hadrolltime = true;
if (!strncasecmp("N", val, 1))
applog(LOG_DEBUG, "X-Roll-Ntime: N found");
else {
hi->canroll = true;
/* Check to see if expire= is supported and if not, set
* the rolltime to the default scantime */
if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
sscanf(val + 7, "%d", &hi->rolltime);
hi->hadexpire = true;
} else
hi->rolltime = opt_scantime;
applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
}
}
if (!strcasecmp("X-Long-Polling", key)) {
hi->lp_path = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Reject-Reason", key)) {
hi->reason = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Stratum", key)) {
hi->stratum_url = val;
val = NULL;
}
out:
free(key);
free(val);
return ptrlen;
}
static void last_nettime(struct timeval *last)
{
rd_lock(&netacc_lock);
last->tv_sec = nettime.tv_sec;
last->tv_usec = nettime.tv_usec;
rd_unlock(&netacc_lock);
}
static void set_nettime(void)
{
wr_lock(&netacc_lock);
cgtime(&nettime);
wr_unlock(&netacc_lock);
}
#if CURL_HAS_KEEPALIVE
static void keep_curlalive(CURL *curl)
{
const long int keepalive = 1;
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, opt_tcp_keepalive);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, opt_tcp_keepalive);
}
#else
static void keep_curlalive(CURL *curl)
{
SOCKETTYPE sock;
curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
keep_sockalive(sock);
}
#endif
static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
__maybe_unused char *data, size_t size, void *userdata)
{
struct pool *pool = (struct pool *)userdata;
switch(type) {
case CURLINFO_HEADER_IN:
case CURLINFO_DATA_IN:
case CURLINFO_SSL_DATA_IN:
pool->sgminer_pool_stats.net_bytes_received += size;
break;
case CURLINFO_HEADER_OUT:
case CURLINFO_DATA_OUT:
case CURLINFO_SSL_DATA_OUT:
pool->sgminer_pool_stats.net_bytes_sent += size;
break;
case CURLINFO_TEXT:
default:
break;
}
return 0;
}
json_t *json_rpc_call(CURL *curl, const char *url,
const char *userpass, const char *rpc_req,
bool probe, bool longpoll, int *rolltime,
struct pool *pool, bool share)
{
long timeout = longpoll ? (60 * 60) : 60;
struct data_buffer all_data = {NULL, 0};
struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
char len_hdr[64], user_agent_hdr[128];
char curl_err_str[CURL_ERROR_SIZE];
struct curl_slist *headers = NULL;
struct upload_buffer upload_data;
json_t *val, *err_val, *res_val;
bool probing = false;
double byte_count;
json_error_t err;
int rc;
memset(&err, 0, sizeof(err));
/* it is assumed that 'curl' is freshly [re]initialized at this pt */
if (probe)
probing = !pool->probed;
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ENCODING, "");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
/* Shares are staggered already and delays in submission can be costly
* so do not delay them */
if (!opt_delaynet || share)
curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
if (pool->rpc_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
} else if (opt_socks_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
if (userpass) {
curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
if (longpoll)
keep_curlalive(curl);
curl_easy_setopt(curl, CURLOPT_POST, 1);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
upload_data.buf = rpc_req;
upload_data.len = strlen(rpc_req);
sprintf(len_hdr, "Content-Length: %lu",
(unsigned long) upload_data.len);
sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
headers = curl_slist_append(headers,
"Content-type: application/json");
headers = curl_slist_append(headers,
"X-Mining-Extensions: longpoll midstate rollntime submitold");
if (likely(global_hashrate)) {
char ghashrate[255];
sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
headers = curl_slist_append(headers, ghashrate);
}
headers = curl_slist_append(headers, len_hdr);
headers = curl_slist_append(headers, user_agent_hdr);
headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
if (opt_delaynet) {
/* Don't delay share submission, but still track the nettime */
if (!share) {
long long now_msecs, last_msecs;
struct timeval now, last;
cgtime(&now);
last_nettime(&last);
now_msecs = (long long)now.tv_sec * 1000;
now_msecs += now.tv_usec / 1000;
last_msecs = (long long)last.tv_sec * 1000;
last_msecs += last.tv_usec / 1000;
if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
struct timespec rgtp;
rgtp.tv_sec = 0;
rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
nanosleep(&rgtp, NULL);
}
}
set_nettime();
}
rc = curl_easy_perform(curl);
if (rc) {
applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
goto err_out;
}
if (!all_data.buf) {
applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
goto err_out;
}
pool->sgminer_pool_stats.times_sent++;
if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
pool->sgminer_pool_stats.bytes_sent += byte_count;
pool->sgminer_pool_stats.times_received++;
if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
pool->sgminer_pool_stats.bytes_received += byte_count;
if (probing) {
pool->probed = true;
/* If X-Long-Polling was found, activate long polling */
if (hi.lp_path) {
if (pool->hdr_path != NULL)
free(pool->hdr_path);
pool->hdr_path = hi.lp_path;
} else
pool->hdr_path = NULL;
if (hi.stratum_url) {
pool->stratum_url = hi.stratum_url;
hi.stratum_url = NULL;
}
} else {
if (hi.lp_path) {
free(hi.lp_path);
hi.lp_path = NULL;
}
if (hi.stratum_url) {
free(hi.stratum_url);
hi.stratum_url = NULL;
}
}
*rolltime = hi.rolltime;
pool->sgminer_pool_stats.rolltime = hi.rolltime;
pool->sgminer_pool_stats.hadrolltime = hi.hadrolltime;
pool->sgminer_pool_stats.canroll = hi.canroll;
pool->sgminer_pool_stats.hadexpire = hi.hadexpire;
val = JSON_LOADS((const char *)all_data.buf, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
goto err_out;
}
if (opt_protocol) {
char *s = json_dumps(val, JSON_INDENT(3));
applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
free(s);
}
/* JSON-RPC valid response returns a non-null 'result',
* and a null 'error'.
*/
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val ||(err_val && !json_is_null(err_val))) {
char *s;
if (err_val)
s = json_dumps(err_val, JSON_INDENT(3));
else
s = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC call failed: %s", s);
free(s);
goto err_out;
}
if (hi.reason) {
json_object_set_new(val, "reject-reason", json_string(hi.reason));
free(hi.reason);
hi.reason = NULL;
}
successful_connect = true;
databuf_free(&all_data);
curl_slist_free_all(headers);
curl_easy_reset(curl);
return val;
err_out:
databuf_free(&all_data);
curl_slist_free_all(headers);
curl_easy_reset(curl);
if (!successful_connect)
applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
return NULL;
}
#define PROXY_HTTP CURLPROXY_HTTP
#define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
#define PROXY_SOCKS4 CURLPROXY_SOCKS4
#define PROXY_SOCKS5 CURLPROXY_SOCKS5
#define PROXY_SOCKS4A CURLPROXY_SOCKS4A
#define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
#else /* HAVE_LIBCURL */
#define PROXY_HTTP 0
#define PROXY_HTTP_1_0 1
#define PROXY_SOCKS4 2
#define PROXY_SOCKS5 3
#define PROXY_SOCKS4A 4
#define PROXY_SOCKS5H 5
#endif /* HAVE_LIBCURL */
static struct {
const char *name;
proxytypes_t proxytype;
} proxynames[] = {
{ "http:", PROXY_HTTP },
{ "http0:", PROXY_HTTP_1_0 },
{ "socks4:", PROXY_SOCKS4 },
{ "socks5:", PROXY_SOCKS5 },
{ "socks4a:", PROXY_SOCKS4A },
{ "socks5h:", PROXY_SOCKS5H },
{ NULL, (proxytypes_t)NULL }
};
const char *proxytype(proxytypes_t proxytype)
{
int i;
for (i = 0; proxynames[i].name; i++)
if (proxynames[i].proxytype == proxytype)
return proxynames[i].name;
return "invalid";
}
char *get_proxy(char *url, struct pool *pool)
{
pool->rpc_proxy = NULL;
char *split;
int plen, len, i;
for (i = 0; proxynames[i].name; i++) {
plen = strlen(proxynames[i].name);
if (strncmp(url, proxynames[i].name, plen) == 0) {
if (!(split = strchr(url, '|')))
return url;
*split = '\0';
len = split - url;
pool->rpc_proxy = (char *)malloc(1 + len - plen);
if (!(pool->rpc_proxy))
quithere(1, "Failed to malloc rpc_proxy");
strcpy(pool->rpc_proxy, url + plen);
extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
pool->rpc_proxytype = proxynames[i].proxytype;
url = split + 1;
break;
}
}
return url;
}
/* Adequate size s==len*2 + 1 must be alloced to use this variant */
void __bin2hex(char *s, const unsigned char *p, size_t len)
{
int i;
static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (i = 0; i < (int)len; i++) {
*s++ = hex[p[i] >> 4];
*s++ = hex[p[i] & 0xF];
}
*s++ = '\0';
}
/* Returns a malloced array string of a binary value of arbitrary length. The
* array is rounded up to a 4 byte size to appease architectures that need
* aligned array sizes */
char *bin2hex(const unsigned char *p, size_t len)
{
ssize_t slen;
char *s;
slen = len * 2 + 1;
if (slen % 4)
slen += 4 - (slen % 4);
s = (char *)calloc(slen, 1);
if (unlikely(!s))
quithere(1, "Failed to calloc");
__bin2hex(s, p, len);
return s;
}
/* Does the reverse of bin2hex but does not allocate any ram */
static const int hex2bin_tbl[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
{
int nibble1, nibble2;
unsigned char idx;
bool ret = false;
while (*hexstr && len) {
if (unlikely(!hexstr[1])) {
applog(LOG_ERR, "hex2bin str truncated");
return ret;
}
idx = *hexstr++;
nibble1 = hex2bin_tbl[idx];
idx = *hexstr++;
nibble2 = hex2bin_tbl[idx];
if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
applog(LOG_ERR, "hex2bin scan failed");
return ret;
}
*p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
--len;
}
if (likely(len == 0 && *hexstr == 0))
ret = true;
return ret;
}
bool fulltest(const unsigned char *hash, const unsigned char *target)
{
uint32_t *hash32 = (uint32_t *)hash;
uint32_t *target32 = (uint32_t *)target;
bool rc = true;
int i;
for (i = 28 / 4; i >= 0; i--) {
uint32_t h32tmp = le32toh(hash32[i]);
uint32_t t32tmp = le32toh(target32[i]);
if (h32tmp > t32tmp) {
rc = false;
break;
}
if (h32tmp < t32tmp) {
rc = true;
break;
}
}
if (opt_debug) {
unsigned char hash_swap[32], target_swap[32];
char *hash_str, *target_str;
swab256(hash_swap, hash);
swab256(target_swap, target);
hash_str = bin2hex(hash_swap, 32);
target_str = bin2hex(target_swap, 32);
applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
hash_str,
target_str,
rc ? "YES (hash <= target)" :
"no (false positive; hash > target)");
free(hash_str);
free(target_str);
}
return rc;
}
struct thread_q *tq_new(void)
{
struct thread_q *tq;
tq = (struct thread_q *)calloc(1, sizeof(*tq));
if (!tq)
return NULL;
INIT_LIST_HEAD(&tq->q);
pthread_mutex_init(&tq->mutex, NULL);
pthread_cond_init(&tq->cond, NULL);
return tq;
}
void tq_free(struct thread_q *tq)
{
struct tq_ent *ent, *iter;
if (!tq)
return;
list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
list_del(&ent->q_node);
free(ent);
}
pthread_cond_destroy(&tq->cond);
pthread_mutex_destroy(&tq->mutex);
memset(tq, 0, sizeof(*tq)); /* poison */
free(tq);
}
static void tq_freezethaw(struct thread_q *tq, bool frozen)
{
mutex_lock(&tq->mutex);
tq->frozen = frozen;
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
}
void tq_freeze(struct thread_q *tq)
{
tq_freezethaw(tq, true);
}
void tq_thaw(struct thread_q *tq)
{
tq_freezethaw(tq, false);
}
bool tq_push(struct thread_q *tq, void *data)
{
struct tq_ent *ent;
bool rc = true;
ent = (struct tq_ent *)calloc(1, sizeof(*ent));
if (!ent)
return false;
ent->data = data;
INIT_LIST_HEAD(&ent->q_node);
mutex_lock(&tq->mutex);
if (!tq->frozen) {
list_add_tail(&ent->q_node, &tq->q);
} else {
free(ent);
rc = false;
}
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
return rc;
}
void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
{
struct tq_ent *ent;
void *rval = NULL;
int rc;
mutex_lock(&tq->mutex);
if (!list_empty(&tq->q))
goto pop;
if (abstime)
rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
else
rc = pthread_cond_wait(&tq->cond, &tq->mutex);
if (rc)
goto out;
if (list_empty(&tq->q))
goto out;
pop:
ent = list_entry(tq->q.next, struct tq_ent*, q_node);
rval = ent->data;
list_del(&ent->q_node);
free(ent);
out:
mutex_unlock(&tq->mutex);
return rval;
}
int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
{
cgsem_init(&thr->sem);
return pthread_create(&thr->pth, attr, start, arg);
}
void thr_info_cancel(struct thr_info *thr)
{
if (!thr)
return;
if (PTH(thr) != 0L) {
pthread_cancel(thr->pth);
PTH(thr) = 0L;
}
cgsem_destroy(&thr->sem);
}
void subtime(struct timeval *a, struct timeval *b)
{
timersub(a, b, b);
}
void addtime(struct timeval *a, struct timeval *b)
{
timeradd(a, b, b);
}
bool time_more(struct timeval *a, struct timeval *b)
{
return timercmp(a, b, >);
}
bool time_less(struct timeval *a, struct timeval *b)
{
return timercmp(a, b, <);
}
void copy_time(struct timeval *dest, const struct timeval *src)
{
memcpy(dest, src, sizeof(struct timeval));
}
void timespec_to_val(struct timeval *val, const struct timespec *spec)
{
val->tv_sec = spec->tv_sec;
val->tv_usec = spec->tv_nsec / 1000;
}
void timeval_to_spec(struct timespec *spec, const struct timeval *val)
{
spec->tv_sec = val->tv_sec;
spec->tv_nsec = val->tv_usec * 1000;
}
void us_to_timeval(struct timeval *val, int64_t us)
{
lldiv_t tvdiv = lldiv(us, 1000000);
val->tv_sec = tvdiv.quot;
val->tv_usec = tvdiv.rem;
}
void us_to_timespec(struct timespec *spec, int64_t us)
{
lldiv_t tvdiv = lldiv(us, 1000000);
spec->tv_sec = tvdiv.quot;
spec->tv_nsec = tvdiv.rem * 1000;
}
void ms_to_timespec(struct timespec *spec, int64_t ms)
{
lldiv_t tvdiv = lldiv(ms, 1000);
spec->tv_sec = tvdiv.quot;
spec->tv_nsec = tvdiv.rem * 1000000;
}
void ms_to_timeval(struct timeval *val, int64_t ms)
{
lldiv_t tvdiv = lldiv(ms, 1000);
val->tv_sec = tvdiv.quot;
val->tv_usec = tvdiv.rem * 1000;
}
void timeraddspec(struct timespec *a, const struct timespec *b)
{
a->tv_sec += b->tv_sec;
a->tv_nsec += b->tv_nsec;
if (a->tv_nsec >= 1000000000) {
a->tv_nsec -= 1000000000;
a->tv_sec++;
}
}
static int __maybe_unused timespec_to_ms(struct timespec *ts)
{
return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
}
/* Subtract b from a */
static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
{
a->tv_sec -= b->tv_sec;
a->tv_nsec -= b->tv_nsec;
if (a->tv_nsec < 0) {
a->tv_nsec += 1000000000;
a->tv_sec--;
}
}
/* These are sgminer specific sleep functions that use an absolute nanosecond
* resolution timer to avoid poor usleep accuracy and overruns. */
#ifdef WIN32
/* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
#define EPOCHFILETIME (116444736000000000LL)
/* Return the system time as an lldiv_t in decimicroseconds. */
static void decius_time(lldiv_t *lidiv)
{
FILETIME ft;
LARGE_INTEGER li;
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
li.QuadPart -= EPOCHFILETIME;
/* SystemTime is in decimicroseconds so divide by an unusual number */
*lidiv = lldiv(li.QuadPart, 10000000);
}
/* This is a sgminer gettimeofday wrapper. Since we always call gettimeofday
* with tz set to NULL, and windows' default resolution is only 15ms, this
* gives us higher resolution times on windows. */
void cgtime(struct timeval *tv)
{
lldiv_t lidiv;
decius_time(&lidiv);
tv->tv_sec = lidiv.quot;
tv->tv_usec = lidiv.rem / 10;
}
#else /* WIN32 */
void cgtime(struct timeval *tv)
{
gettimeofday(tv, NULL);
}
int cgtimer_to_ms(cgtimer_t *cgt)
{
return timespec_to_ms(cgt);
}
/* Subtracts b from a and stores it in res. */
void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
{
res->tv_sec = a->tv_sec - b->tv_sec;
res->tv_nsec = a->tv_nsec - b->tv_nsec;
if (res->tv_nsec < 0) {
res->tv_nsec += 1000000000;
res->tv_sec--;
}
}
#endif /* WIN32 */
#ifdef CLOCK_MONOTONIC /* Essentially just linux */
void cgtimer_time(cgtimer_t *ts_start)
{
clock_gettime(CLOCK_MONOTONIC, ts_start);
}
static void nanosleep_abstime(struct timespec *ts_end)
{
int ret;
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
} while (ret == EINTR);
}
/* Reentrant version of cgsleep functions allow start time to be set separately
* from the beginning of the actual sleep, allowing scheduling delays to be
* counted in the sleep. */
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
struct timespec ts_end;
ms_to_timespec(&ts_end, ms);
timeraddspec(&ts_end, ts_start);
nanosleep_abstime(&ts_end);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
struct timespec ts_end;
us_to_timespec(&ts_end, us);
timeraddspec(&ts_end, ts_start);
nanosleep_abstime(&ts_end);
}
#else /* CLOCK_MONOTONIC */
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
void cgtimer_time(cgtimer_t *ts_start)
{
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts_start->tv_sec = mts.tv_sec;
ts_start->tv_nsec = mts.tv_nsec;
}
#elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
void cgtimer_time(cgtimer_t *ts_start)
{
struct timeval tv;
cgtime(&tv);
ts_start->tv_sec = tv->tv_sec;
ts_start->tv_nsec = tv->tv_usec * 1000;
}
#endif /* __MACH__ */
#ifdef WIN32
/* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
* typedef, allowing us to have sub-microsecond resolution for times, do simple
* arithmetic for timer calculations, and use windows' own hTimers to get
* accurate absolute timeouts. */
int cgtimer_to_ms(cgtimer_t *cgt)
{
return (int)(cgt->QuadPart / 10000LL);
}
/* Subtracts b from a and stores it in res. */
void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
{
res->QuadPart = a->QuadPart - b->QuadPart;
}
/* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
* timeouts with hTimers. */
void cgtimer_time(cgtimer_t *ts_start)
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
ts_start->LowPart = ft.dwLowDateTime;
ts_start->HighPart = ft.dwHighDateTime;
}
static void liSleep(LARGE_INTEGER *li, int timeout)
{
HANDLE hTimer;
DWORD ret;
if (unlikely(timeout <= 0))
return;
hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
if (unlikely(!hTimer))
quit(1, "Failed to create hTimer in liSleep");
ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
if (unlikely(!ret))
quit(1, "Failed to SetWaitableTimer in liSleep");
/* We still use a timeout as a sanity check in case the system time
* is changed while we're running */
ret = WaitForSingleObject(hTimer, timeout);
if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
quit(1, "Failed to WaitForSingleObject in liSleep");
CloseHandle(hTimer);
}
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
LARGE_INTEGER li;
li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
liSleep(&li, ms);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
LARGE_INTEGER li;
int ms;
li.QuadPart = ts_start->QuadPart + us * 10LL;
ms = us / 1000;
if (!ms)
ms = 1;
liSleep(&li, ms);
}
#else /* WIN32 */
static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
{
struct timespec now;
timeraddspec(ts_diff, ts_start);
cgtimer_time(&now);
timersubspec(ts_diff, &now);
if (unlikely(ts_diff->tv_sec < 0))
return;
nanosleep(ts_diff, NULL);
}
void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
{
struct timespec ts_diff;
ms_to_timespec(&ts_diff, ms);
cgsleep_spec(&ts_diff, ts_start);
}
void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
{
struct timespec ts_diff;
us_to_timespec(&ts_diff, us);
cgsleep_spec(&ts_diff, ts_start);
}
#endif /* WIN32 */
#endif /* CLOCK_MONOTONIC */
void cgsleep_ms(int ms)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_ms_r(&ts_start, ms);
}
void cgsleep_us(int64_t us)
{
cgtimer_t ts_start;
cgsleep_prepare_r(&ts_start);
cgsleep_us_r(&ts_start, us);
}
/* Returns the microseconds difference between end and start times as a double */
double us_tdiff(struct timeval *end, struct timeval *start)
{
/* Sanity check. We should only be using this for small differences so
* limit the max to 60 seconds. */
if (unlikely(end->tv_sec - start->tv_sec > 60))
return 60000000;
return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
}
/* Returns the milliseconds difference between end and start times */
int ms_tdiff(struct timeval *end, struct timeval *start)
{
/* Like us_tdiff, limit to 1 hour. */
if (unlikely(end->tv_sec - start->tv_sec > 3600))
return 3600000;
return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
}
/* Returns the seconds difference between end and start times as a double */
double tdiff(struct timeval *end, struct timeval *start)
{
return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
}
bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
if (url_len >= sizeof(url_address))
{
applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
__func__, url_len, url_begin);
url_len = sizeof(url_address) - 1;
}
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
enum send_ret {
SEND_OK,
SEND_SELECTFAIL,
SEND_SENDFAIL,
SEND_INACTIVE
};
/* Send a single command across a socket, appending \n to it. This should all
* be done under stratum lock except when first establishing the socket */
static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
{
SOCKETTYPE sock = pool->sock;
ssize_t ssent = 0;
strcat(s, "\n");
len++;
while (len > 0 ) {
struct timeval timeout = {1, 0};
ssize_t sent;
fd_set wd;
retry:
FD_ZERO(&wd);
FD_SET(sock, &wd);
if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
if (interrupted())
goto retry;
return SEND_SELECTFAIL;
}
#ifdef __APPLE__
sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
#elif WIN32
sent = send(pool->sock, s + ssent, len, 0);
#else
sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
#endif
if (sent < 0) {
if (!sock_blocks())
return SEND_SENDFAIL;
sent = 0;
}
ssent += sent;
len -= sent;
}
pool->sgminer_pool_stats.times_sent++;
pool->sgminer_pool_stats.bytes_sent += ssent;
pool->sgminer_pool_stats.net_bytes_sent += ssent;
return SEND_OK;
}
bool stratum_send(struct pool *pool, char *s, ssize_t len)
{
enum send_ret ret = SEND_INACTIVE;
if (opt_protocol)
applog(LOG_DEBUG, "SEND: %s", s);
mutex_lock(&pool->stratum_lock);
if (pool->stratum_active)
ret = __stratum_send(pool, s, len);
mutex_unlock(&pool->stratum_lock);
/* This is to avoid doing applog under stratum_lock */
switch (ret) {
default:
case SEND_OK:
break;
case SEND_SELECTFAIL:
applog(LOG_DEBUG, "Write select failed on %s sock", get_pool_name(pool));
suspend_stratum(pool);
break;
case SEND_SENDFAIL:
applog(LOG_DEBUG, "Failed to send in stratum_send");
suspend_stratum(pool);
break;
case SEND_INACTIVE:
applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
break;
}
return (ret == SEND_OK);
}
static bool socket_full(struct pool *pool, int wait)
{
SOCKETTYPE sock = pool->sock;
struct timeval timeout;
fd_set rd;
if (unlikely(wait < 0))
wait = 0;
FD_ZERO(&rd);
FD_SET(sock, &rd);
timeout.tv_usec = 0;
timeout.tv_sec = wait;
if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
return true;
return false;
}
/* Check to see if Santa's been good to you */
bool sock_full(struct pool *pool)
{
if (strlen(pool->sockbuf))
return true;
return (socket_full(pool, 0));
}
static void clear_sockbuf(struct pool *pool)
{
strcpy(pool->sockbuf, "");
}
static void clear_sock(struct pool *pool)
{
ssize_t n;
mutex_lock(&pool->stratum_lock);
do {
if (pool->sock)
n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
else
n = 0;
} while (n > 0);
mutex_unlock(&pool->stratum_lock);
clear_sockbuf(pool);
}
/* Make sure the pool sockbuf is large enough to cope with any coinbase size
* by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
* and zeroing the new memory */
static void recalloc_sock(struct pool *pool, size_t len)
{
size_t old, newlen;
old = strlen(pool->sockbuf);
newlen = old + len + 1;
if (newlen < pool->sockbuf_size)
return;
newlen = newlen + (RBUFSIZE - (newlen % RBUFSIZE));
// Avoid potentially recursive locking
// applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
pool->sockbuf = (char *)realloc(pool->sockbuf, newlen);
if (!pool->sockbuf)
quithere(1, "Failed to realloc pool sockbuf");
memset(pool->sockbuf + old, 0, newlen - old);
pool->sockbuf_size = newlen;
}
/* Peeks at a socket to find the first end of line and then reads just that
* from the socket and returns that as a malloced char */
char *recv_line(struct pool *pool)
{
char *tok, *sret = NULL;
ssize_t len, buflen;
int waited = 0;
if (!strstr(pool->sockbuf, "\n")) {
struct timeval rstart, now;
cgtime(&rstart);
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
goto out;
}
do {
char s[RBUFSIZE];
size_t slen;
ssize_t n;
memset(s, 0, RBUFSIZE);
n = recv(pool->sock, s, RECVSIZE, 0);
if (!n) {
applog(LOG_DEBUG, "Socket closed waiting in recv_line");
suspend_stratum(pool);
break;
}
cgtime(&now);
waited = tdiff(&now, &rstart);
if (n < 0) {
if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
applog(LOG_DEBUG, "Failed to recv sock in recv_line");
suspend_stratum(pool);
break;
}
} else {
slen = strlen(s);
recalloc_sock(pool, slen);
strcat(pool->sockbuf, s);
}
} while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
}
buflen = strlen(pool->sockbuf);
tok = strtok(pool->sockbuf, "\n");
if (!tok) {
applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
goto out;
}
sret = strdup(tok);
len = strlen(sret);
/* Copy what's left in the buffer after the \n, including the
* terminating \0 */
if (buflen > len + 1)
memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
else
strcpy(pool->sockbuf, "");
pool->sgminer_pool_stats.times_received++;
pool->sgminer_pool_stats.bytes_received += len;
pool->sgminer_pool_stats.net_bytes_received += len;
out:
if (!sret)
clear_sock(pool);
else if (opt_protocol)
applog(LOG_DEBUG, "RECVD: %s", sret);
return sret;
}
/* Extracts a string value from a json array with error checking. To be used
* when the value of the string returned is only examined and not to be stored.
* See json_array_string below */
static char *__json_array_string(json_t *val, unsigned int entry)
{
json_t *arr_entry;
if (json_is_null(val))
return NULL;
if (!json_is_array(val))
return NULL;
if (entry > json_array_size(val))
return NULL;
arr_entry = json_array_get(val, entry);
if (!json_is_string(arr_entry))
return NULL;
return (char *)json_string_value(arr_entry);
}
/* Creates a freshly malloced dup of __json_array_string */
static char *json_array_string(json_t *val, unsigned int entry)
{
char *buf = __json_array_string(val, entry);
if (buf)
return strdup(buf);
return NULL;
}
static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, *header;
size_t cb1_len, cb2_len, alloc_len;
unsigned char *cb1, *cb2;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = json_array_string(val, 5);
nbit = json_array_string(val, 6);
ntime = json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (prev_hash)
free(prev_hash);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
if (bbversion)
free(bbversion);
if (nbit)
free(nbit);
if (ntime)
free(ntime);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
free(pool->swork.prev_hash);
free(pool->swork.bbversion);
free(pool->swork.nbit);
free(pool->swork.ntime);
pool->swork.job_id = job_id;
pool->swork.prev_hash = prev_hash;
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
pool->swork.bbversion = bbversion;
pool->swork.nbit = nbit;
pool->swork.ntime = ntime;
pool->swork.clean = clean;
alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->swork.merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin,
sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++) {
char *merkle = json_array_string(arr, i);
pool->swork.merkle_bin[i] = (unsigned char *)malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
}
}
pool->swork.merkles = merkles;
if (clean)
pool->nonce2 = 0;
pool->merkle_offset = strlen(pool->swork.bbversion) +
strlen(pool->swork.prev_hash);
pool->swork.header_len = pool->merkle_offset +
/* merkle_hash */ 32 +
strlen(pool->swork.ntime) +
strlen(pool->swork.nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
pool->merkle_offset /= 2;
pool->swork.header_len = pool->swork.header_len * 2 + 1;
align_len(&pool->swork.header_len);
header = (char *)alloca(pool->swork.header_len);
snprintf(header, pool->swork.header_len,
"%s%s%s%s%s%s%s",
pool->swork.bbversion,
pool->swork.prev_hash,
blank_merkel,
pool->swork.ntime,
pool->swork.nbit,
"00000000", /* nonce */
workpadding);
if (unlikely(!hex2bin(pool->header_bin, header, 128))) {
applog(LOG_WARNING, "%s: Failed to convert header to header_bin, got %s", __func__, header);
pool_failed(pool);
// TODO: memory leaks? goto out, clean up there?
return false;
}
cb1 = (unsigned char *)calloc(cb1_len, 1);
if (unlikely(!cb1))
quithere(1, "Failed to calloc cb1 in parse_notify");
hex2bin(cb1, coinbase1, cb1_len);
cb2 = (unsigned char *)calloc(cb2_len, 1);
if (unlikely(!cb2))
quithere(1, "Failed to calloc cb2 in parse_notify");
hex2bin(cb2, coinbase2, cb2_len);
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = (unsigned char *)calloc(alloc_len, 1);
if (unlikely(!pool->coinbase))
quit(1, "Failed to calloc pool coinbase in parse_notify");
memcpy(pool->coinbase, cb1, cb1_len);
memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
// NOTE: gap for nonce2, filled at work generation time
memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
cg_wunlock(&pool->data_lock);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
free(coinbase1);
free(coinbase2);
free(cb1);
free(cb2);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
ret = true;
if (pool == current_pool())
opt_work_update = true;
out:
return ret;
}
static bool parse_diff(struct pool *pool, json_t *val)
{
double old_diff, diff;
if (opt_diff_mult == 0.0)
diff = json_number_value(json_array_get(val, 0)) * pool->algorithm.diff_multiplier1;
else
diff = json_number_value(json_array_get(val, 0)) * opt_diff_mult;
if (diff == 0)
return false;
cg_wlock(&pool->data_lock);
old_diff = pool->swork.diff;
pool->swork.diff = diff;
cg_wunlock(&pool->data_lock);
if (old_diff != diff) {
int idiff = diff;
if ((double)idiff == diff)
applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %d", get_pool_name(pool), idiff);
else
applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %.3f", get_pool_name(pool), diff);
} else
applog(LOG_DEBUG, "%s difficulty set to %f", get_pool_name(pool), diff);
return true;
}
static bool parse_extranonce(struct pool *pool, json_t *val)
{
char *nonce1;
int n2size;
nonce1 = json_array_string(val, 0);
if (!nonce1) {
return false;
}
n2size = json_integer_value(json_array_get(val, 1));
if (!n2size) {
free(nonce1);
return false;
}
cg_wlock(&pool->data_lock);
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
applog(LOG_NOTICE, "%s extranonce change requested", get_pool_name(pool));
return true;
}
static void __suspend_stratum(struct pool *pool)
{
clear_sockbuf(pool);
pool->stratum_active = pool->stratum_notify = false;
if (pool->sock)
CLOSESOCKET(pool->sock);
pool->sock = 0;
}
static bool parse_reconnect(struct pool *pool, json_t *val)
{
if (opt_disable_client_reconnect) {
applog(LOG_WARNING, "Stratum client.reconnect received but is disabled, not reconnecting.");
return false;
}
char *url, *port, address[256];
char *sockaddr_url, *stratum_port, *tmp; /* Tempvars. */
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
snprintf(address, sizeof(address), "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
static bool send_version(struct pool *pool, json_t *val)
{
char s[RBUFSIZE];
int id = json_integer_value(json_object_get(val, "id"));
if (!id)
return false;
sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
if (!stratum_send(pool, s, strlen(s)))
return false;
return true;
}
static bool show_message(struct pool *pool, json_t *val)
{
char *msg;
if (!json_is_array(val))
return false;
msg = (char *)json_string_value(json_array_get(val, 0));
if (!msg)
return false;
applog(LOG_NOTICE, "%s message: %s", get_pool_name(pool), msg);
return true;
}
bool parse_method(struct pool *pool, char *s)
{
json_t *val = NULL, *method, *err_val, *params;
json_error_t err;
bool ret = false;
char *buf;
if (!s)
return ret;
val = JSON_LOADS(s, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
return ret;
}
method = json_object_get(val, "method");
if (!method) {
json_decref(val);
return ret;
}
err_val = json_object_get(val, "error");
params = json_object_get(val, "params");
if (err_val && !json_is_null(err_val)) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
json_decref(val);
free(ss);
return ret;
}
buf = (char *)json_string_value(method);
if (!buf) {
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.notify", 13)) {
if (parse_notify(pool, params))
pool->stratum_notify = ret = true;
else
pool->stratum_notify = ret = false;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "mining.set_extranonce", 21) && parse_extranonce(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
ret = true;
json_decref(val);
return ret;
}
if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
ret = true;
json_decref(val);
return ret;
}
json_decref(val);
return ret;
}
bool subscribe_extranonce(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}",
swork_id++);
if (!stratum_send(pool, s, strlen(s)))
return ret;
/* Parse all data in the queue and anything left should be the response */
while (42) {
if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) {
applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe");
/* some pool doesnt send anything, so this is normal */
ret = true;
goto out;
}
sret = recv_line(pool);
if (!sret)
return ret;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val) {
ss = __json_array_string(err_val, 1);
if (!ss)
ss = (char *)json_string_value(err_val);
if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) {
applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool));
ret = true;
goto out;
}
if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) {
applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool));
ret = true;
goto out;
}
ss = json_dumps(err_val, JSON_INDENT(3));
}
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss);
free(ss);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum extranonce subscribe for %s", get_pool_name(pool));
out:
json_decref(val);
return ret;
}
bool auth_stratum(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
swork_id++, pool->rpc_user, pool->rpc_pass);
if (!stratum_send(pool, s, strlen(s)))
return ret;
/* Parse all data in the queue and anything left should be auth */
while (42) {
sret = recv_line(pool);
if (!sret)
return ret;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss);
free(ss);
suspend_stratum(pool);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum authorisation success for %s", get_pool_name(pool));
pool->probed = true;
successful_connect = true;
out:
json_decref(val);
return ret;
}
static int recv_byte(int sockd)
{
char c;
if (recv(sockd, &c, 1, 0) != -1)
return c;
return -1;
}
static bool http_negotiate(struct pool *pool, int sockd, bool http0)
{
char buf[1024];
int i, len;
if (http0) {
snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
pool->sockaddr_url, pool->stratum_port);
} else {
snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
pool->stratum_port);
}
applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
send(sockd, buf, strlen(buf), 0);
len = recv(sockd, buf, 12, 0);
if (len <= 0) {
applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
buf[len] = '\0';
applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
return false;
}
/* Ignore unwanted headers till we get desired response */
for (i = 0; i < 4; i++) {
buf[i] = recv_byte(sockd);
if (buf[i] == (char)-1) {
applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
}
while (strncmp(buf, "\r\n\r\n", 4)) {
for (i = 0; i < 3; i++)
buf[i] = buf[i + 1];
buf[3] = recv_byte(sockd);
if (buf[3] == (char)-1) {
applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
}
applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return true;
}
static bool socks5_negotiate(struct pool *pool, int sockd)
{
unsigned char atyp, uclen;
unsigned short port;
char buf[515];
int i, len;
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
send(sockd, buf, 3, 0);
if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
buf[3] = 0x03;
len = (strlen(pool->sockaddr_url));
if (len > 255)
len = 255;
uclen = len;
buf[4] = (uclen & 0xff);
memcpy(buf + 5, pool->sockaddr_url, len);
port = atoi(pool->stratum_port);
buf[5 + len] = (port >> 8);
buf[6 + len] = (port & 0xff);
send(sockd, buf, (7 + len), 0);
if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
recv_byte(sockd);
atyp = recv_byte(sockd);
if (atyp == 0x01) {
for (i = 0; i < 4; i++)
recv_byte(sockd);
} else if (atyp == 0x03) {
len = recv_byte(sockd);
for (i = 0; i < len; i++)
recv_byte(sockd);
} else {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
return false;
}
for (i = 0; i < 2; i++)
recv_byte(sockd);
applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return true;
}
static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
{
unsigned short port;
in_addr_t inp;
char buf[515];
int i, len;
int ret;
buf[0] = 0x04;
buf[1] = 0x01;
port = atoi(pool->stratum_port);
buf[2] = port >> 8;
buf[3] = port & 0xff;
sprintf(&buf[8], "SGMINER");
/* See if we've been given an IP address directly to avoid needing to
* resolve it. */
inp = inet_addr(pool->sockaddr_url);
inp = ntohl(inp);
if ((int)inp != -1)
socks4a = false;
else {
/* Try to extract the IP address ourselves first */
struct addrinfo servinfobase, *servinfo, hints;
servinfo = &servinfobase;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* IPV4 only */
ret = getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo);
if (!ret) {
applog(LOG_ERR, "getaddrinfo() in socks4_negotiate() returned %i: %s", ret, gai_strerror(ret));
struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
inp = ntohl(saddr_in->sin_addr.s_addr);
socks4a = false;
freeaddrinfo(servinfo);
}
}
if (!socks4a) {
if ((int)inp == -1) {
applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
pool->sockaddr_url);
return false;
}
buf[4] = (inp >> 24) & 0xFF;
buf[5] = (inp >> 16) & 0xFF;
buf[6] = (inp >> 8) & 0xFF;
buf[7] = (inp >> 0) & 0xFF;
send(sockd, buf, 16, 0);
} else {
/* This appears to not be working but hopefully most will be
* able to resolve IP addresses themselves. */
buf[4] = 0;
buf[5] = 0;
buf[6] = 0;
buf[7] = 1;
len = strlen(pool->sockaddr_url);
if (len > 255)
len = 255;
memcpy(&buf[16], pool->sockaddr_url, len);
len += 16;
buf[len++] = '\0';
send(sockd, buf, len, 0);
}
if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
}
for (i = 0; i < 6; i++)
recv_byte(sockd);
return true;
}
static void noblock_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, O_NONBLOCK | flags);
#else
u_long flags = 1;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
static void block_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
#else
u_long flags = 0;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
static bool sock_connecting(void)
{
#ifndef WIN32
return errno == EINPROGRESS;
#else
return WSAGetLastError() == WSAEWOULDBLOCK;
#endif
}
static bool setup_stratum_socket(struct pool *pool)
{
struct addrinfo servinfobase, *servinfo, *hints, *p;
char *sockaddr_url, *sockaddr_port;
int sockd;
int ret;
mutex_lock(&pool->stratum_lock);
pool->stratum_active = false;
if (pool->sock) {
/* FIXME: change to LOG_DEBUG if issue #88 resolved */
applog(LOG_INFO, "Closing %s socket", get_pool_name(pool));
CLOSESOCKET(pool->sock);
}
pool->sock = 0;
mutex_unlock(&pool->stratum_lock);
hints = &pool->stratum_hints;
memset(hints, 0, sizeof(struct addrinfo));
hints->ai_family = AF_UNSPEC;
hints->ai_socktype = SOCK_STREAM;
servinfo = &servinfobase;
if (!pool->rpc_proxy && opt_socks_proxy) {
pool->rpc_proxy = opt_socks_proxy;
extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
pool->rpc_proxytype = PROXY_SOCKS5;
}
if (pool->rpc_proxy) {
sockaddr_url = pool->sockaddr_proxy_url;
sockaddr_port = pool->sockaddr_proxy_port;
} else {
sockaddr_url = pool->sockaddr_url;
sockaddr_port = pool->stratum_port;
}
ret = getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo);
if (ret) {
applog(LOG_INFO, "getaddrinfo() in setup_stratum_socket() returned %i: %s", ret, gai_strerror(ret));
if (!pool->probed) {
applog(LOG_WARNING, "Failed to resolve (wrong URL?) %s:%s",
sockaddr_url, sockaddr_port);
pool->probed = true;
} else {
applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
sockaddr_url, sockaddr_port);
}
return false;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockd == -1) {
applog(LOG_DEBUG, "Failed socket");
continue;
}
/* Iterate non blocking over entries returned by getaddrinfo
* to cope with round robin DNS entries, finding the first one
* we can connect to quickly. */
noblock_socket(sockd);
if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
struct timeval tv_timeout = {1, 0};
int selret;
fd_set rw;
if (!sock_connecting()) {
CLOSESOCKET(sockd);
applog(LOG_DEBUG, "Failed sock connect");
continue;
}
retry:
FD_ZERO(&rw);
FD_SET(sockd, &rw);
selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
if (selret > 0 && FD_ISSET(sockd, &rw)) {
socklen_t len;
int err, n;
len = sizeof(err);
n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
if (!n && !err) {
applog(LOG_DEBUG, "Succeeded delayed connect");
block_socket(sockd);
break;
}
}
if (selret < 0 && interrupted())
goto retry;
CLOSESOCKET(sockd);
applog(LOG_DEBUG, "Select timeout/failed connect");
continue;
}
applog(LOG_WARNING, "Succeeded immediate connect");
block_socket(sockd);
break;
}
if (p == NULL) {
applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
sockaddr_url, sockaddr_port);
freeaddrinfo(servinfo);
return false;
}
freeaddrinfo(servinfo);
if (pool->rpc_proxy) {
switch (pool->rpc_proxytype) {
case PROXY_HTTP_1_0:
if (!http_negotiate(pool, sockd, true))
return false;
break;
case PROXY_HTTP:
if (!http_negotiate(pool, sockd, false))
return false;
break;
case PROXY_SOCKS5:
case PROXY_SOCKS5H:
if (!socks5_negotiate(pool, sockd))
return false;
break;
case PROXY_SOCKS4:
if (!socks4_negotiate(pool, sockd, false))
return false;
break;
case PROXY_SOCKS4A:
if (!socks4_negotiate(pool, sockd, true))
return false;
break;
default:
applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
return false;
break;
}
}
if (!pool->sockbuf) {
pool->sockbuf = (char *)calloc(RBUFSIZE, 1);
if (!pool->sockbuf)
quithere(1, "Failed to calloc pool sockbuf");
pool->sockbuf_size = RBUFSIZE;
}
pool->sock = sockd;
keep_sockalive(sockd);
return true;
}
static char *get_sessionid(json_t *val)
{
char *ret = NULL;
json_t *arr_val;
int arrsize, i;
arr_val = json_array_get(val, 0);
if (!arr_val || !json_is_array(arr_val))
goto out;
arrsize = json_array_size(arr_val);
for (i = 0; i < arrsize; i++) {
json_t *arr = json_array_get(arr_val, i);
char *notify;
if (!arr | !json_is_array(arr))
break;
notify = __json_array_string(arr, 0);
if (!notify)
continue;
if (!strncasecmp(notify, "mining.notify", 13)) {
ret = json_array_string(arr, 1);
break;
}
}
out:
return ret;
}
void suspend_stratum(struct pool *pool)
{
applog(LOG_INFO, "Closing socket for stratum %s", get_pool_name(pool));
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
mutex_unlock(&pool->stratum_lock);
}
bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (n2size < 1)
{
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
bool restart_stratum(struct pool *pool)
{
applog(LOG_DEBUG, "Restarting stratum on pool %s", get_pool_name(pool));
if (pool->stratum_active)
suspend_stratum(pool);
if (!initiate_stratum(pool))
return false;
if (pool->extranonce_subscribe && !subscribe_extranonce(pool))
return false;
if (!auth_stratum(pool))
return false;
return true;
}
void dev_error(struct cgpu_info *dev, enum dev_reason reason)
{
dev->device_last_not_well = time(NULL);
dev->device_not_well_reason = reason;
switch (reason) {
case REASON_THREAD_FAIL_INIT:
dev->thread_fail_init_count++;
break;
case REASON_THREAD_ZERO_HASH:
dev->thread_zero_hash_count++;
break;
case REASON_THREAD_FAIL_QUEUE:
dev->thread_fail_queue_count++;
break;
case REASON_DEV_SICK_IDLE_60:
dev->dev_sick_idle_60_count++;
break;
case REASON_DEV_DEAD_IDLE_600:
dev->dev_dead_idle_600_count++;
break;
case REASON_DEV_NOSTART:
dev->dev_nostart_count++;
break;
case REASON_DEV_OVER_HEAT:
dev->dev_over_heat_count++;
break;
case REASON_DEV_THERMAL_CUTOFF:
dev->dev_thermal_cutoff_count++;
break;
case REASON_DEV_COMMS_ERROR:
dev->dev_comms_error_count++;
break;
case REASON_DEV_THROTTLE:
dev->dev_throttle_count++;
break;
}
}
/* Realloc an existing string to fit an extra string s, appending s to it. */
void *realloc_strcat(char *ptr, char *s)
{
size_t old = strlen(ptr), len = strlen(s);
char *ret;
if (!len)
return ptr;
len += old + 1;
align_len(&len);
ret = (char *)malloc(len);
if (unlikely(!ret))
quithere(1, "Failed to malloc");
sprintf(ret, "%s%s", ptr, s);
free(ptr);
return ret;
}
void RenameThread(const char* name)
{
char buf[16];
snprintf(buf, sizeof(buf), "cg@%s", name);
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
prctl(PR_SET_NAME, buf, 0, 0, 0);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__))
pthread_set_name_np(pthread_self(), buf);
#elif defined(MAC_OSX)
pthread_setname_np(buf);
#else
// Prevent warnings
(void)buf;
#endif
}
/* sgminer specific wrappers for true unnamed semaphore usage on platforms
* that support them and for apple which does not. We use a single byte across
* a pipe to emulate semaphore behaviour there. */
#ifdef __APPLE__
void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int flags, fd, i;
if (pipe(cgsem->pipefd) == -1)
quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
/* Make the pipes FD_CLOEXEC to allow them to close should we call
* execv on restart. */
for (i = 0; i < 2; i++) {
fd = cgsem->pipefd[i];
flags = fcntl(fd, F_GETFD, 0);
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1)
quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
}
}
void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
const char buf = 1;
int ret;
retry:
ret = write(cgsem->pipefd[1], &buf, 1);
if (unlikely(ret == 0))
applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
else if (unlikely(ret < 0 && interrupted))
goto retry;
}
void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
char buf;
int ret;
retry:
ret = read(cgsem->pipefd[0], &buf, 1);
if (unlikely(ret == 0))
applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
else if (unlikely(ret < 0 && interrupted))
goto retry;
}
void cgsem_destroy(cgsem_t *cgsem)
{
close(cgsem->pipefd[1]);
close(cgsem->pipefd[0]);
}
/* This is similar to sem_timedwait but takes a millisecond value */
int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
{
struct timeval timeout;
int ret, fd;
fd_set rd;
char buf;
retry:
fd = cgsem->pipefd[0];
FD_ZERO(&rd);
FD_SET(fd, &rd);
ms_to_timeval(&timeout, ms);
ret = select(fd + 1, &rd, NULL, NULL, &timeout);
if (ret > 0) {
ret = read(fd, &buf, 1);
return 0;
}
if (likely(!ret))
return ETIMEDOUT;
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
/* We don't reach here */
return 0;
}
/* Reset semaphore count back to zero */
void cgsem_reset(cgsem_t *cgsem)
{
int ret, fd;
fd_set rd;
char buf;
fd = cgsem->pipefd[0];
FD_ZERO(&rd);
FD_SET(fd, &rd);
do {
struct timeval timeout = {0, 0};
ret = select(fd + 1, &rd, NULL, NULL, &timeout);
if (ret > 0)
ret = read(fd, &buf, 1);
else if (unlikely(ret < 0 && interrupted()))
ret = 1;
} while (ret > 0);
}
#else
void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int ret;
if ((ret = sem_init(cgsem, 0, 0)))
quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
}
void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
if (unlikely(sem_post(cgsem)))
quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
}
void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
retry:
if (unlikely(sem_wait(cgsem))) {
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
}
}
int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
{
struct timespec abs_timeout, ts_now;
struct timeval tv_now;
int ret;
cgtime(&tv_now);
timeval_to_spec(&ts_now, &tv_now);
ms_to_timespec(&abs_timeout, ms);
retry:
timeraddspec(&abs_timeout, &ts_now);
ret = sem_timedwait(cgsem, &abs_timeout);
if (ret) {
if (likely(sock_timeout()))
return ETIMEDOUT;
if (interrupted())
goto retry;
quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
}
return 0;
}
void cgsem_reset(cgsem_t *cgsem)
{
int ret;
do {
ret = sem_trywait(cgsem);
if (unlikely(ret < 0 && interrupted()))
ret = 0;
} while (!ret);
}
void cgsem_destroy(cgsem_t *cgsem)
{
sem_destroy(cgsem);
}
#endif
/* Provide a completion_timeout helper function for unreliable functions that
* may die due to driver issues etc that time out if the function fails and
* can then reliably return. */
struct cg_completion {
cgsem_t cgsem;
void (*fn)(void *fnarg);
void *fnarg;
};
void *completion_thread(void *arg)
{
struct cg_completion *cgc = (struct cg_completion *)arg;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
cgc->fn(cgc->fnarg);
cgsem_post(&cgc->cgsem);
return NULL;
}
bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
{
struct cg_completion *cgc;
pthread_t pthread;
bool ret = false;
cgc = (struct cg_completion *)malloc(sizeof(struct cg_completion));
if (unlikely(!cgc))
return ret;
cgsem_init(&cgc->cgsem);
#ifdef _MSC_VER
cgc->fn = (void(__cdecl *)(void *))fn;
#else
cgc->fn = fn;
#endif
cgc->fnarg = fnarg;
pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
ret = cgsem_mswait(&cgc->cgsem, timeout);
if (ret)
pthread_cancel(pthread);
pthread_join(pthread, NULL);
free(cgc);
return !ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2212_0 |
crossvul-cpp_data_bad_3989_1 | #include "clar_libgit2.h"
#include "checkout_helpers.h"
#include "git2/checkout.h"
#include "repository.h"
#include "buffer.h"
#include "futils.h"
static const char *repo_name = "nasty";
static git_repository *repo;
static git_checkout_options checkout_opts;
void test_checkout_nasty__initialize(void)
{
repo = cl_git_sandbox_init(repo_name);
GIT_INIT_STRUCTURE(&checkout_opts, GIT_CHECKOUT_OPTIONS_VERSION);
checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE;
}
void test_checkout_nasty__cleanup(void)
{
cl_git_sandbox_cleanup();
}
static void test_checkout_passes(const char *refname, const char *filename)
{
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
git_buf path = GIT_BUF_INIT;
cl_git_pass(git_buf_joinpath(&path, repo_name, filename));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, refname));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE |
GIT_CHECKOUT_DONT_UPDATE_INDEX;
cl_git_pass(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(!git_path_exists(path.ptr));
git_commit_free(commit);
git_buf_dispose(&path);
}
static void test_checkout_fails(const char *refname, const char *filename)
{
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
git_buf path = GIT_BUF_INIT;
cl_git_pass(git_buf_joinpath(&path, repo_name, filename));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, refname));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
cl_git_fail(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(!git_path_exists(path.ptr));
git_commit_free(commit);
git_buf_dispose(&path);
}
/* A tree that contains ".git" as a tree, with a blob inside
* (".git/foobar").
*/
void test_checkout_nasty__dotgit_tree(void)
{
test_checkout_fails("refs/heads/dotgit_tree", ".git/foobar");
}
/* A tree that contains ".GIT" as a tree, with a blob inside
* (".GIT/foobar").
*/
void test_checkout_nasty__dotcapitalgit_tree(void)
{
test_checkout_fails("refs/heads/dotcapitalgit_tree", ".GIT/foobar");
}
/* A tree that contains a tree ".", with a blob inside ("./foobar").
*/
void test_checkout_nasty__dot_tree(void)
{
test_checkout_fails("refs/heads/dot_tree", "foobar");
}
/* A tree that contains a tree ".", with a tree ".git", with a blob
* inside ("./.git/foobar").
*/
void test_checkout_nasty__dot_dotgit_tree(void)
{
test_checkout_fails("refs/heads/dot_dotgit_tree", ".git/foobar");
}
/* A tree that contains a tree, with a tree "..", with a tree ".git", with a
* blob inside ("foo/../.git/foobar").
*/
void test_checkout_nasty__dotdot_dotgit_tree(void)
{
test_checkout_fails("refs/heads/dotdot_dotgit_tree", ".git/foobar");
}
/* A tree that contains a tree, with a tree "..", with a blob inside
* ("foo/../foobar").
*/
void test_checkout_nasty__dotdot_tree(void)
{
test_checkout_fails("refs/heads/dotdot_tree", "foobar");
}
/* A tree that contains a blob with the rogue name ".git/foobar" */
void test_checkout_nasty__dotgit_path(void)
{
test_checkout_fails("refs/heads/dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name ".GIT/foobar" */
void test_checkout_nasty__dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "./.git/foobar" */
void test_checkout_nasty__dot_dotgit_path(void)
{
test_checkout_fails("refs/heads/dot_dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name "./.GIT/foobar" */
void test_checkout_nasty__dot_dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dot_dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "foo/../.git/foobar" */
void test_checkout_nasty__dotdot_dotgit_path(void)
{
test_checkout_fails("refs/heads/dotdot_dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name "foo/../.GIT/foobar" */
void test_checkout_nasty__dotdot_dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dotdot_dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "foo/." */
void test_checkout_nasty__dot_path(void)
{
test_checkout_fails("refs/heads/dot_path", "./foobar");
}
/* A tree that contains a blob with the rogue name "foo/." */
void test_checkout_nasty__dot_path_two(void)
{
test_checkout_fails("refs/heads/dot_path_two", "foo/.");
}
/* A tree that contains a blob with the rogue name "foo/../foobar" */
void test_checkout_nasty__dotdot_path(void)
{
test_checkout_fails("refs/heads/dotdot_path", "foobar");
}
/* A tree that contains an entry with a backslash ".git\foobar" */
void test_checkout_nasty__dotgit_backslash_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dotgit_backslash_path", ".git/foobar");
#endif
}
/* A tree that contains an entry with a backslash ".GIT\foobar" */
void test_checkout_nasty__dotcapitalgit_backslash_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dotcapitalgit_backslash_path", ".GIT/foobar");
#endif
}
/* A tree that contains an entry with a backslash ".\.GIT\foobar" */
void test_checkout_nasty__dot_backslash_dotcapitalgit_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_backslash_dotcapitalgit_path", ".GIT/foobar");
#endif
}
/* A tree that contains an entry ".git.", because Win32 APIs will drop the
* trailing slash.
*/
void test_checkout_nasty__dot_git_dot(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_dot", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~1", because that is typically the
* short name for ".git".
*/
void test_checkout_nasty__git_tilde1(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/git_tilde1", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~2", when we have forced the short
* name for ".git" into "GIT~2".
*/
void test_checkout_nasty__git_custom_shortname(void)
{
#ifdef GIT_WIN32
if (!cl_sandbox_supports_8dot3())
clar__skip();
cl_must_pass(p_rename("nasty/.git", "nasty/_temp"));
cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666);
cl_must_pass(p_rename("nasty/_temp", "nasty/.git"));
test_checkout_fails("refs/heads/git_tilde2", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~3", which should be allowed, since
* it is not the typical short name ("GIT~1") or the actual short name
* ("GIT~2") for ".git".
*/
void test_checkout_nasty__only_looks_like_a_git_shortname(void)
{
#ifdef GIT_WIN32
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
cl_must_pass(p_rename("nasty/.git", "nasty/_temp"));
cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666);
cl_must_pass(p_rename("nasty/_temp", "nasty/.git"));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, "refs/heads/git_tilde3"));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
cl_git_pass(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(git_path_exists("nasty/git~3/foobar"));
git_commit_free(commit);
#endif
}
/* A tree that contains an entry "git:", because Win32 APIs will reject
* that as looking too similar to a drive letter.
*/
void test_checkout_nasty__dot_git_colon(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_colon", ".git/foobar");
#endif
}
/* A tree that contains an entry "git:foo", because Win32 APIs will turn
* that into ".git".
*/
void test_checkout_nasty__dot_git_colon_stuff(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_colon_stuff", ".git/foobar");
#endif
}
/* Trees that contains entries with a tree ".git" that contain
* byte sequences:
* { 0xe2, 0x80, 0x8c }
* { 0xe2, 0x80, 0x8d }
* { 0xe2, 0x80, 0x8e }
* { 0xe2, 0x80, 0x8f }
* { 0xe2, 0x80, 0xaa }
* { 0xe2, 0x80, 0xab }
* { 0xe2, 0x80, 0xac }
* { 0xe2, 0x80, 0xad }
* { 0xe2, 0x81, 0xae }
* { 0xe2, 0x81, 0xaa }
* { 0xe2, 0x81, 0xab }
* { 0xe2, 0x81, 0xac }
* { 0xe2, 0x81, 0xad }
* { 0xe2, 0x81, 0xae }
* { 0xe2, 0x81, 0xaf }
* { 0xef, 0xbb, 0xbf }
* Because these map to characters that HFS filesystems "ignore". Thus
* ".git<U+200C>" will map to ".git".
*/
void test_checkout_nasty__dot_git_hfs_ignorable(void)
{
#ifdef __APPLE__
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_1", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_2", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_3", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_4", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_5", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_6", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_7", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_8", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_9", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_10", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_11", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_12", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_13", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_14", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_15", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_16", ".git/foobar");
#endif
}
void test_checkout_nasty__honors_core_protecthfs(void)
{
cl_repo_set_bool(repo, "core.protectHFS", true);
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_1", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_2", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_3", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_4", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_5", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_6", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_7", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_8", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_9", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_10", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_11", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_12", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_13", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_14", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_15", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_16", ".git/foobar");
}
void test_checkout_nasty__honors_core_protectntfs(void)
{
cl_repo_set_bool(repo, "core.protectNTFS", true);
test_checkout_fails("refs/heads/dotgit_backslash_path", ".git/foobar");
test_checkout_fails("refs/heads/dotcapitalgit_backslash_path", ".GIT/foobar");
test_checkout_fails("refs/heads/dot_git_dot", ".git/foobar");
test_checkout_fails("refs/heads/git_tilde1", ".git/foobar");
}
void test_checkout_nasty__symlink1(void)
{
test_checkout_passes("refs/heads/symlink1", ".git/foobar");
}
void test_checkout_nasty__symlink2(void)
{
test_checkout_passes("refs/heads/symlink2", ".git/foobar");
}
void test_checkout_nasty__symlink3(void)
{
test_checkout_passes("refs/heads/symlink3", ".git/foobar");
}
void test_checkout_nasty__gitmodules_symlink(void)
{
cl_repo_set_bool(repo, "core.protectHFS", true);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
cl_repo_set_bool(repo, "core.protectHFS", false);
cl_repo_set_bool(repo, "core.protectNTFS", true);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
cl_repo_set_bool(repo, "core.protectNTFS", false);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3989_1 |
crossvul-cpp_data_good_2628_0 | /* dlist.c - list protocol for dump and sync
*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR 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.
*/
#include <config.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <syslog.h>
#include <string.h>
#include <sys/wait.h>
#include <dirent.h>
#include "global.h"
#include "assert.h"
#include "mboxlist.h"
#include "mailbox.h"
#include "quota.h"
#include "xmalloc.h"
#include "seen.h"
#include "mboxname.h"
#include "map.h"
#include "imapd.h"
#include "message.h"
#include "util.h"
#include "prot.h"
/* generated headers are not necessarily in current directory */
#include "imap/imap_err.h"
#include "dlist.h"
/* Parse routines */
static const char *lastkey = NULL;
static void printfile(struct protstream *out, const struct dlist *dl)
{
struct stat sbuf;
FILE *f;
unsigned long size;
struct message_guid guid2;
const char *msg_base = NULL;
size_t msg_len = 0;
assert(dlist_isfile(dl));
f = fopen(dl->sval, "r");
if (!f) {
syslog(LOG_ERR, "IOERROR: Failed to read file %s", dl->sval);
prot_printf(out, "NIL");
return;
}
if (fstat(fileno(f), &sbuf) == -1) {
syslog(LOG_ERR, "IOERROR: Failed to stat file %s", dl->sval);
prot_printf(out, "NIL");
fclose(f);
return;
}
size = sbuf.st_size;
if (size != dl->nval) {
syslog(LOG_ERR, "IOERROR: Size mismatch %s (%lu != " MODSEQ_FMT ")",
dl->sval, size, dl->nval);
prot_printf(out, "NIL");
fclose(f);
return;
}
map_refresh(fileno(f), 1, &msg_base, &msg_len, sbuf.st_size,
"new message", 0);
message_guid_generate(&guid2, msg_base, msg_len);
if (!message_guid_equal(&guid2, dl->gval)) {
syslog(LOG_ERR, "IOERROR: GUID mismatch %s",
dl->sval);
prot_printf(out, "NIL");
fclose(f);
map_free(&msg_base, &msg_len);
return;
}
prot_printf(out, "%%{");
prot_printastring(out, dl->part);
prot_printf(out, " ");
prot_printastring(out, message_guid_encode(dl->gval));
prot_printf(out, " %lu}\r\n", size);
prot_write(out, msg_base, msg_len);
fclose(f);
map_free(&msg_base, &msg_len);
}
/* XXX - these two functions should be out in append.c or reserve.c
* or something more general */
EXPORTED const char *dlist_reserve_path(const char *part, int isarchive,
const struct message_guid *guid)
{
static char buf[MAX_MAILBOX_PATH];
/* part must be a configured partition name on this server */
const char *base = isarchive ? config_archivepartitiondir(part)
: config_partitiondir(part);
/* we expect to have a base at this point, so let's assert that */
assert(base != NULL);
snprintf(buf, MAX_MAILBOX_PATH, "%s/sync./%lu/%s",
base, (unsigned long)getpid(),
message_guid_encode(guid));
/* gotta make sure we can create files */
if (cyrus_mkdir(buf, 0755)) {
/* it's going to fail later, but at least this will help */
syslog(LOG_ERR, "IOERROR: failed to create %s/sync./%lu/ for reserve: %m",
base, (unsigned long)getpid());
}
return buf;
}
static int reservefile(struct protstream *in, const char *part,
struct message_guid *guid, unsigned long size,
const char **fname)
{
FILE *file;
char buf[8192+1];
int r = 0;
/* XXX - write to a temporary file then move in to place! */
*fname = dlist_reserve_path(part, /*isarchive*/0, guid);
/* remove any duplicates if they're still here */
unlink(*fname);
file = fopen(*fname, "w+");
if (!file) {
syslog(LOG_ERR,
"IOERROR: failed to upload file %s", message_guid_encode(guid));
r = IMAP_IOERROR;
/* Note: we still read the file's data from the wire,
* to avoid losing protocol sync */
}
/* XXX - calculate sha1 on the fly? */
while (size) {
size_t n = prot_read(in, buf, size > 8192 ? 8192 : size);
if (!n) {
syslog(LOG_ERR,
"IOERROR: reading message: unexpected end of file");
r = IMAP_IOERROR;
break;
}
size -= n;
if (fwrite(buf, 1, n, file) != n) {
syslog(LOG_ERR, "IOERROR: writing to file '%s': %m", *fname);
r = IMAP_IOERROR;
break;
}
}
if (r)
goto error;
/* Make sure that message flushed to disk just incase mmap has problems */
fflush(file);
if (ferror(file)) {
r = IMAP_IOERROR;
goto error;
}
if (fsync(fileno(file)) < 0) {
syslog(LOG_ERR, "IOERROR: fsyncing file '%s': %m", *fname);
r = IMAP_IOERROR;
goto error;
}
fclose(file);
return 0;
error:
if (file) {
fclose(file);
unlink(*fname);
*fname = NULL;
}
return r;
}
/* DLIST STUFF */
EXPORTED void dlist_stitch(struct dlist *parent, struct dlist *child)
{
assert(!child->next);
if (parent->tail) {
parent->tail->next = child;
parent->tail = child;
}
else {
parent->head = parent->tail = child;
}
}
EXPORTED void dlist_unstitch(struct dlist *parent, struct dlist *child)
{
struct dlist *prev = NULL;
struct dlist *replace = NULL;
/* find old record */
for (replace = parent->head; replace; replace = replace->next) {
if (replace == child) break;
prev = replace;
}
assert(replace);
if (prev) prev->next = child->next;
else parent->head = child->next;
if (parent->tail == child) parent->tail = prev;
child->next = NULL;
}
static struct dlist *dlist_child(struct dlist *dl, const char *name)
{
struct dlist *i = xzmalloc(sizeof(struct dlist));
if (name) i->name = xstrdup(name);
i->type = DL_NIL;
if (dl)
dlist_stitch(dl, i);
return i;
}
static void _dlist_free_children(struct dlist *dl)
{
struct dlist *next;
struct dlist *i;
if (!dl) return;
i = dl->head;
while (i) {
next = i->next;
dlist_free(&i);
i = next;
}
dl->head = dl->tail = NULL;
}
static void _dlist_clean(struct dlist *dl)
{
if (!dl) return;
/* remove any children */
_dlist_free_children(dl);
/* clean out values */
free(dl->part);
dl->part = NULL;
free(dl->sval);
dl->sval = NULL;
free(dl->gval);
dl->gval = NULL;
dl->nval = 0;
}
void dlist_makeatom(struct dlist *dl, const char *val)
{
if (!dl) return;
_dlist_clean(dl);
if (val) {
dl->type = DL_ATOM;
dl->sval = xstrdup(val);
dl->nval = strlen(val);
}
else
dl->type = DL_NIL;
}
void dlist_makeflag(struct dlist *dl, const char *val)
{
if (!dl) return;
_dlist_clean(dl);
if (val) {
dl->type = DL_FLAG;
dl->sval = xstrdup(val);
dl->nval = strlen(val);
}
else
dl->type = DL_NIL;
}
void dlist_makenum32(struct dlist *dl, uint32_t val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_NUM;
dl->nval = val;
}
void dlist_makenum64(struct dlist *dl, bit64 val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_NUM;
dl->nval = val;
}
void dlist_makedate(struct dlist *dl, time_t val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_DATE;
dl->nval = val;
}
void dlist_makehex64(struct dlist *dl, bit64 val)
{
if (!dl) return;
_dlist_clean(dl);
dl->type = DL_HEX;
dl->nval = val;
}
void dlist_makeguid(struct dlist *dl, const struct message_guid *guid)
{
if (!dl) return;
_dlist_clean(dl);
if (guid) {
dl->type = DL_GUID,
dl->gval = xzmalloc(sizeof(struct message_guid));
message_guid_copy(dl->gval, guid);
}
else
dl->type = DL_NIL;
}
void dlist_makefile(struct dlist *dl,
const char *part, const struct message_guid *guid,
unsigned long size, const char *fname)
{
if (!dl) return;
_dlist_clean(dl);
if (part && guid && fname) {
dl->type = DL_FILE;
dl->gval = xzmalloc(sizeof(struct message_guid));
message_guid_copy(dl->gval, guid);
dl->sval = xstrdup(fname);
dl->nval = size;
dl->part = xstrdup(part);
}
else
dl->type = DL_NIL;
}
EXPORTED void dlist_makemap(struct dlist *dl, const char *val, size_t len)
{
if (!dl) return;
_dlist_clean(dl);
if (val) {
dl->type = DL_BUF;
/* WARNING - DO NOT replace this with xstrndup - the
* data may be binary, and xstrndup does not copy
* binary data correctly - but we still want to NULL
* terminate for non-binary data */
dl->sval = xmalloc(len+1);
memcpy(dl->sval, val, len);
dl->sval[len] = '\0'; /* make it string safe too */
dl->nval = len;
}
else
dl->type = DL_NIL;
}
EXPORTED struct dlist *dlist_newkvlist(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_child(parent, name);
dl->type = DL_KVLIST;
return dl;
}
EXPORTED struct dlist *dlist_newlist(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_child(parent, name);
dl->type = DL_ATOMLIST;
return dl;
}
EXPORTED struct dlist *dlist_newpklist(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_child(parent, name);
dl->type = DL_ATOMLIST;
dl->nval = 1;
return dl;
}
EXPORTED struct dlist *dlist_setatom(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makeatom(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setflag(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makeflag(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setnum64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makenum64(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setnum32(struct dlist *parent, const char *name, uint32_t val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makenum32(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setdate(struct dlist *parent, const char *name, time_t val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makedate(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_sethex64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makehex64(dl, val);
return dl;
}
EXPORTED struct dlist *dlist_setmap(struct dlist *parent, const char *name,
const char *val, size_t len)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makemap(dl, val, len);
return dl;
}
EXPORTED struct dlist *dlist_setguid(struct dlist *parent, const char *name,
const struct message_guid *guid)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makeguid(dl, guid);
return dl;
}
EXPORTED struct dlist *dlist_setfile(struct dlist *parent, const char *name,
const char *part, const struct message_guid *guid,
size_t size, const char *fname)
{
struct dlist *dl = dlist_child(parent, name);
dlist_makefile(dl, part, guid, size, fname);
return dl;
}
static struct dlist *dlist_updatechild(struct dlist *parent, const char *name)
{
struct dlist *dl = dlist_getchild(parent, name);
if (!dl) dl = dlist_child(parent, name);
return dl;
}
struct dlist *dlist_updateatom(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makeatom(dl, val);
return dl;
}
struct dlist *dlist_updateflag(struct dlist *parent, const char *name, const char *val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makeflag(dl, val);
return dl;
}
struct dlist *dlist_updatenum64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makenum64(dl, val);
return dl;
}
struct dlist *dlist_updatenum32(struct dlist *parent, const char *name, uint32_t val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makenum32(dl, val);
return dl;
}
struct dlist *dlist_updatedate(struct dlist *parent, const char *name, time_t val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makedate(dl, val);
return dl;
}
struct dlist *dlist_updatehex64(struct dlist *parent, const char *name, bit64 val)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makehex64(dl, val);
return dl;
}
struct dlist *dlist_updatemap(struct dlist *parent, const char *name,
const char *val, size_t len)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makemap(dl, val, len);
return dl;
}
struct dlist *dlist_updateguid(struct dlist *parent, const char *name,
const struct message_guid *guid)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makeguid(dl, guid);
return dl;
}
struct dlist *dlist_updatefile(struct dlist *parent, const char *name,
const char *part, const struct message_guid *guid,
size_t size, const char *fname)
{
struct dlist *dl = dlist_updatechild(parent, name);
dlist_makefile(dl, part, guid, size, fname);
return dl;
}
EXPORTED void dlist_print(const struct dlist *dl, int printkeys,
struct protstream *out)
{
struct dlist *di;
if (printkeys) {
prot_printastring(out, dl->name);
prot_putc(' ', out);
}
switch (dl->type) {
case DL_NIL:
prot_printf(out, "NIL");
break;
case DL_ATOM:
prot_printastring(out, dl->sval);
break;
case DL_FLAG:
prot_printf(out, "%s", dl->sval);
break;
case DL_NUM:
case DL_DATE: /* for now, we will format it later */
prot_printf(out, "%llu", dl->nval);
break;
case DL_FILE:
printfile(out, dl);
break;
case DL_BUF:
if (strlen(dl->sval) == dl->nval)
prot_printastring(out, dl->sval);
else
prot_printliteral(out, dl->sval, dl->nval);
break;
case DL_GUID:
prot_printf(out, "%s", message_guid_encode(dl->gval));
break;
case DL_HEX:
{
char buf[17];
snprintf(buf, 17, "%016llx", dl->nval);
prot_printf(out, "%s", buf);
}
break;
case DL_KVLIST:
prot_printf(out, "%%(");
for (di = dl->head; di; di = di->next) {
dlist_print(di, 1, out);
if (di->next) {
prot_printf(out, " ");
}
}
prot_printf(out, ")");
break;
case DL_ATOMLIST:
prot_printf(out, "(");
for (di = dl->head; di; di = di->next) {
dlist_print(di, dl->nval, out);
if (di->next)
prot_printf(out, " ");
}
prot_printf(out, ")");
break;
}
}
EXPORTED void dlist_printbuf(const struct dlist *dl, int printkeys, struct buf *outbuf)
{
struct protstream *outstream;
outstream = prot_writebuf(outbuf);
dlist_print(dl, printkeys, outstream);
prot_flush(outstream);
prot_free(outstream);
}
EXPORTED void dlist_unlink_files(struct dlist *dl)
{
struct dlist *i;
if (!dl) return;
for (i = dl->head; i; i = i->next) {
dlist_unlink_files(i);
}
if (dl->type != DL_FILE) return;
if (!dl->sval) return;
syslog(LOG_DEBUG, "%s: unlinking %s", __func__, dl->sval);
unlink(dl->sval);
}
EXPORTED void dlist_free(struct dlist **dlp)
{
if (!*dlp) return;
_dlist_clean(*dlp);
free((*dlp)->name);
free(*dlp);
*dlp = NULL;
}
struct dlist_stack_node {
const struct dlist *dl;
int printkeys;
struct dlist_stack_node *next;
};
struct dlist_print_iter {
int printkeys;
struct dlist_stack_node *parent;
const struct dlist *next;
};
EXPORTED struct dlist_print_iter *dlist_print_iter_new(const struct dlist *dl, int printkeys)
{
struct dlist_print_iter *iter = xzmalloc(sizeof *iter);
iter->printkeys = printkeys;
iter->next = dl;
return iter;
}
EXPORTED const char *dlist_print_iter_step(struct dlist_print_iter *iter, struct buf *outbuf)
{
/* already finished */
if (!iter->next) return NULL;
buf_reset(outbuf);
/* Bundle short steps together to minimise call overhead.
* Note that outbuf can grow significantly longer than this limit, if a
* single item in the dlist is very long (e.g. a message), but then it
* won't bundle up more than that.
*/
while (iter->next != NULL && buf_len(outbuf) < 1024) {
const struct dlist *curr = iter->next;
struct dlist_stack_node *parent = NULL;
int descend = 0;
/* output */
switch (curr->type) {
case DL_KVLIST:
case DL_ATOMLIST:
// XXX should use equiv to "prot_printastring" for curr->name
if (iter->printkeys)
buf_printf(outbuf, "%s ", curr->name);
buf_appendcstr(outbuf, curr->type == DL_KVLIST ? "%(" : "(");
if (curr->head) {
descend = 1;
}
else {
buf_putc(outbuf, ')');
if (curr->next)
buf_putc(outbuf, ' ');
}
break;
default:
dlist_printbuf(curr, iter->printkeys, outbuf);
if (curr->next)
buf_putc(outbuf, ' ');
break;
}
/* increment */
if (descend) {
parent = xmalloc(sizeof *parent);
parent->printkeys = iter->printkeys;
parent->dl = curr;
parent->next = iter->parent;
iter->parent = parent;
iter->next = curr->head;
// XXX can this always be 1? we know an atom list here is non-empty
iter->printkeys = curr->type == DL_KVLIST ? 1 : curr->nval;
}
else if (curr->next) {
iter->next = curr->next;
}
else if (iter->parent) {
/* multiple parents might be ending at the same point
* don't mistake one parent ending for end of entire tree
*/
do {
buf_putc(outbuf, ')');
parent = iter->parent;
iter->parent = iter->parent->next;
iter->next = parent->dl->next;
iter->printkeys = parent->printkeys;
free(parent);
if (iter->next) {
/* found an unfinished dlist, stop closing parents */
buf_putc(outbuf, ' ');
break;
}
} while (iter->parent);
}
else {
iter->next = NULL;
}
}
/* and return */
return buf_cstringnull(outbuf);
}
EXPORTED void dlist_print_iter_free(struct dlist_print_iter **iterp)
{
struct dlist_print_iter *iter = *iterp;
struct dlist_stack_node *tmp = NULL;
*iterp = NULL;
while (iter->parent) {
tmp = iter->parent;
iter->parent = iter->parent->next;
free(tmp);
}
free(iter);
}
struct dlistsax_state {
const char *base;
const char *p;
const char *end;
dlistsax_cb_t *proc;
int depth;
struct dlistsax_data d;
struct buf gbuf;
};
static int _parseqstring(struct dlistsax_state *s, struct buf *buf)
{
buf->len = 0;
/* get over the first quote */
if (*s->p++ != '"') return IMAP_INVALID_IDENTIFIER;
while (s->p < s->end) {
/* found the end quote */
if (*s->p == '"') {
s->p++;
return 0;
}
/* backslash just quotes the next char, no matter what it is */
if (*s->p == '\\') {
s->p++;
if (s->p == s->end) break;
/* fall through */
}
buf_putc(buf, *s->p++);
}
return IMAP_INVALID_IDENTIFIER;
}
static int _parseliteral(struct dlistsax_state *s, struct buf *buf)
{
size_t len = 0;
if (*s->p++ != '{') return IMAP_INVALID_IDENTIFIER;
while (s->p < s->end) {
if (cyrus_isdigit(*s->p)) {
len = (len * 10) + (*s->p++ - '0');
}
else if (*s->p == '}') {
if (s->p + 3 + len >= s->end) break;
if (s->p[1] != '\r') break;
if (s->p[2] != '\n') break;
buf_setmap(buf, s->p+3, len);
s->p += len = 3;
return 0;
}
}
return IMAP_INVALID_IDENTIFIER;
}
static int _parseitem(struct dlistsax_state *s, struct buf *buf)
{
const char *sp;
if (*s->p == '"')
return _parseqstring(s, buf);
else if (*s->p == '{')
return _parseliteral(s, buf);
sp = memchr(s->p, ' ', s->end - s->p);
if (!sp) sp = s->end;
while (sp[-1] == ')' && sp > s->p) sp--;
/* this is much faster because it doesn't do a reset and check the MMAP flag */
buf->len = 0;
buf_appendmap(buf, s->p, sp - s->p);
s->p = sp;
return 0; /* this could be the last thing, so end is OK */
}
static int _parsesax(struct dlistsax_state *s, int parsekey)
{
int r = 0;
s->depth++;
/* handle the key if wanted */
if (parsekey) {
r = _parseitem(s, &s->d.kbuf);
if (r) return r;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
if (*s->p == ' ') s->p++;
else return IMAP_INVALID_IDENTIFIER;
}
else {
s->d.kbuf.len = 0;
}
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
/* check what sort of value we have */
if (*s->p == '(') {
r = s->proc(DLISTSAX_LISTSTART, &s->d);
if (r) return r;
s->p++;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
while (*s->p != ')') {
r = _parsesax(s, 0);
if (r) return r;
if (*s->p == ')') break;
if (*s->p == ' ') s->p++;
else return IMAP_INVALID_IDENTIFIER;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
}
r = s->proc(DLISTSAX_LISTEND, &s->d);
if (r) return r;
s->p++;
}
else if (*s->p == '%') {
s->p++;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
/* no whitespace allowed here */
if (*s->p == '(') {
r = s->proc(DLISTSAX_KVLISTSTART, &s->d);
if (r) return r;
s->p++;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
while (*s->p != ')') {
r = _parsesax(s, 1);
if (r) return r;
if (*s->p == ')') break;
if (*s->p == ' ') s->p++;
else return IMAP_INVALID_IDENTIFIER;
if (s->p >= s->end) return IMAP_INVALID_IDENTIFIER;
}
r = s->proc(DLISTSAX_KVLISTEND, &s->d);
if (r) return r;
s->p++;
}
else {
/* unknown percent type */
return IMAP_INVALID_IDENTIFIER;
}
}
else {
r = _parseitem(s, &s->d.buf);
if (r) return r;
r = s->proc(DLISTSAX_STRING, &s->d);
if (r) return r;
}
s->depth--;
/* success */
return 0;
}
EXPORTED int dlist_parsesax(const char *base, size_t len, int parsekey,
dlistsax_cb_t *proc, void *rock)
{
static struct dlistsax_state state;
int r;
state.base = base;
state.p = base;
state.end = base + len;
state.proc = proc;
state.d.rock = rock;
r = _parsesax(&state, parsekey);
if (r) return r;
if (state.p < state.end)
return IMAP_IOERROR;
return 0;
}
static char next_nonspace(struct protstream *in, char c)
{
while (Uisspace(c)) c = prot_getc(in);
return c;
}
EXPORTED int dlist_parse(struct dlist **dlp, int parsekey,
struct protstream *in, const char *alt_reserve_base)
{
struct dlist *dl = NULL;
static struct buf kbuf;
static struct buf vbuf;
int c;
/* handle the key if wanted */
if (parsekey) {
c = getastring(in, NULL, &kbuf);
c = next_nonspace(in, c);
}
else {
buf_setcstr(&kbuf, "");
c = prot_getc(in);
}
/* connection dropped? */
if (c == EOF) goto fail;
/* check what sort of value we have */
if (c == '(') {
dl = dlist_newlist(NULL, kbuf.s);
c = next_nonspace(in, ' ');
while (c != ')') {
struct dlist *di = NULL;
prot_ungetc(c, in);
c = dlist_parse(&di, 0, in, alt_reserve_base);
if (di) dlist_stitch(dl, di);
c = next_nonspace(in, c);
if (c == EOF) goto fail;
}
c = prot_getc(in);
}
else if (c == '%') {
/* no whitespace allowed here */
c = prot_getc(in);
if (c == '(') {
dl = dlist_newkvlist(NULL, kbuf.s);
c = next_nonspace(in, ' ');
while (c != ')') {
struct dlist *di = NULL;
prot_ungetc(c, in);
c = dlist_parse(&di, 1, in, alt_reserve_base);
if (di) dlist_stitch(dl, di);
c = next_nonspace(in, c);
if (c == EOF) goto fail;
}
}
else if (c == '{') {
struct message_guid tmp_guid;
static struct buf pbuf, gbuf;
unsigned size = 0;
const char *fname;
const char *part;
c = getastring(in, NULL, &pbuf);
if (c != ' ') goto fail;
c = getastring(in, NULL, &gbuf);
if (c != ' ') goto fail;
c = getuint32(in, &size);
if (c != '}') goto fail;
c = prot_getc(in);
if (c == '\r') c = prot_getc(in);
if (c != '\n') goto fail;
if (!message_guid_decode(&tmp_guid, gbuf.s)) goto fail;
part = alt_reserve_base ? alt_reserve_base : pbuf.s;
if (reservefile(in, part, &tmp_guid, size, &fname)) goto fail;
dl = dlist_setfile(NULL, kbuf.s, pbuf.s, &tmp_guid, size, fname);
/* file literal */
}
else {
/* unknown percent type */
goto fail;
}
c = prot_getc(in);
}
else if (c == '{') {
prot_ungetc(c, in);
/* could be binary in a literal */
c = getbastring(in, NULL, &vbuf);
dl = dlist_setmap(NULL, kbuf.s, vbuf.s, vbuf.len);
}
else if (c == '\\') { /* special case for flags */
prot_ungetc(c, in);
c = getastring(in, NULL, &vbuf);
dl = dlist_setflag(NULL, kbuf.s, vbuf.s);
}
else {
prot_ungetc(c, in);
c = getnastring(in, NULL, &vbuf);
dl = dlist_setatom(NULL, kbuf.s, vbuf.s);
}
/* success */
*dlp = dl;
return c;
fail:
dlist_free(&dl);
return EOF;
}
EXPORTED int dlist_parse_asatomlist(struct dlist **dlp, int parsekey,
struct protstream *in)
{
int c = dlist_parse(dlp, parsekey, in, NULL);
/* make a list with one item */
if (*dlp && !dlist_isatomlist(*dlp)) {
struct dlist *tmp = dlist_newlist(NULL, "");
dlist_stitch(tmp, *dlp);
*dlp = tmp;
}
return c;
}
EXPORTED int dlist_parsemap(struct dlist **dlp, int parsekey,
const char *base, unsigned len)
{
struct protstream *stream;
int c;
struct dlist *dl = NULL;
stream = prot_readmap(base, len);
prot_setisclient(stream, 1); /* don't sync literals */
c = dlist_parse(&dl, parsekey, stream, NULL);
prot_free(stream);
if (c != EOF) {
dlist_free(&dl);
return IMAP_IOERROR; /* failed to slurp entire buffer */
}
*dlp = dl;
return 0;
}
EXPORTED struct dlist *dlist_getchild(struct dlist *dl, const char *name)
{
struct dlist *i;
if (!dl) return NULL;
for (i = dl->head; i; i = i->next) {
if (i->name && !strcmp(name, i->name))
return i;
}
lastkey = name;
return NULL;
}
EXPORTED struct dlist *dlist_getchildn(struct dlist *dl, int num)
{
struct dlist *i;
if (!dl) return NULL;
for (i = dl->head; i && num; i = i->next)
num--;
return i;
}
/* duplicate the parent list as a new list, and then move @num
* of the children from the parent onto the new list */
EXPORTED struct dlist *dlist_splice(struct dlist *dl, int num)
{
struct dlist *ret = dlist_newlist(NULL, dl->name);
/* clone exact type */
ret->type = dl->type;
ret->nval = dl->nval;
if (num > 0) {
struct dlist *end = dlist_getchildn(dl, num - 1);
/* take the start of the list */
ret->head = dl->head;
/* leave the end (if any) */
if (end) {
ret->tail = end;
dl->head = end->next;
end->next = NULL;
}
else {
ret->tail = dl->tail;
dl->head = NULL;
dl->tail = NULL;
}
}
return ret;
}
EXPORTED void dlist_splat(struct dlist *parent, struct dlist *child)
{
struct dlist *prev = NULL;
struct dlist *replace;
/* find old record */
for (replace = parent->head; replace; replace = replace->next) {
if (replace == child) break;
prev = replace;
}
assert(replace);
if (child->head) {
/* stitch in children */
if (prev) prev->next = child->head;
else parent->head = child->head;
if (child->next) child->tail->next = child->next;
else parent->tail = child->tail;
}
else {
/* just remove the record */
if (prev) prev->next = child->next;
else parent->head = child->next;
if (!child->next) parent->tail = prev;
}
/* remove the node itself, carefully blanking out
* the now unlinked children */
child->head = NULL;
child->tail = NULL;
dlist_free(&child);
}
struct dlist *dlist_getkvchild_bykey(struct dlist *dl,
const char *key, const char *val)
{
struct dlist *i;
struct dlist *tmp;
if (!dl) return NULL;
for (i = dl->head; i; i = i->next) {
tmp = dlist_getchild(i, key);
if (tmp && !strcmp(tmp->sval, val))
return i;
}
return NULL;
}
int dlist_toatom(struct dlist *dl, const char **valp)
{
const char *str;
size_t len;
if (!dl) return 0;
/* atom can be NULL */
if (dl->type == DL_NIL) {
*valp = NULL;
return 1;
}
/* tomap always adds a trailing \0 */
if (!dlist_tomap(dl, &str, &len))
return 0;
/* got NULLs? */
if (dl->type == DL_BUF && strlen(str) != len)
return 0;
if (valp) *valp = str;
return 1;
}
HIDDEN int dlist_tomap(struct dlist *dl, const char **valp, size_t *lenp)
{
char tmp[30];
if (!dl) return 0;
switch (dl->type) {
case DL_NUM:
case DL_DATE:
snprintf(tmp, 30, "%llu", dl->nval);
dlist_makeatom(dl, tmp);
break;
case DL_HEX:
snprintf(tmp, 30, "%016llx", dl->nval);
dlist_makeatom(dl, tmp);
break;
case DL_GUID:
dlist_makeatom(dl, message_guid_encode(dl->gval));
break;
case DL_ATOM:
case DL_FLAG:
case DL_BUF:
break;
default:
return 0;
}
if (valp) *valp = dl->sval;
if (lenp) *lenp = dl->nval;
return 1;
}
/* ensure value is exactly one number */
static int dlist_tonum64(struct dlist *dl, bit64 *valp)
{
const char *end;
bit64 newval;
if (!dl) return 0;
switch (dl->type) {
case DL_ATOM:
case DL_BUF:
if (parsenum(dl->sval, &end, dl->nval, &newval))
return 0;
if (end - dl->sval != (int)dl->nval)
return 0;
/* successfully parsed - switch to a numeric value */
dlist_makenum64(dl, newval);
break;
case DL_NUM:
case DL_HEX:
case DL_DATE:
break;
default:
return 0;
}
if (valp) *valp = dl->nval;
return 1;
}
EXPORTED int dlist_tonum32(struct dlist *dl, uint32_t *valp)
{
bit64 v;
if (dlist_tonum64(dl, &v)) {
if (valp) *valp = (uint32_t)v;
return 1;
}
return 0;
}
int dlist_todate(struct dlist *dl, time_t *valp)
{
bit64 v;
if (dlist_tonum64(dl, &v)) {
if (valp) *valp = (time_t)v;
dl->type = DL_DATE;
return 1;
}
return 0;
}
static int dlist_tohex64(struct dlist *dl, bit64 *valp)
{
const char *end = NULL;
bit64 newval;
if (!dl) return 0;
switch (dl->type) {
case DL_ATOM:
case DL_BUF:
if (parsehex(dl->sval, &end, dl->nval, &newval))
return 0;
if (end - dl->sval != (int)dl->nval)
return 0;
/* successfully parsed - switch to a numeric value */
dlist_makehex64(dl, newval);
break;
case DL_NUM:
case DL_HEX:
case DL_DATE:
dl->type = DL_HEX;
break;
default:
return 0;
}
if (valp) *valp = dl->nval;
return 1;
}
EXPORTED int dlist_toguid(struct dlist *dl, struct message_guid **valp)
{
struct message_guid tmpguid;
if (!dl) return 0;
switch (dl->type) {
case DL_ATOM:
case DL_BUF:
if (dl->nval != 40)
return 0;
if (!message_guid_decode(&tmpguid, dl->sval))
return 0;
/* successfully parsed - switch to guid value */
dlist_makeguid(dl, &tmpguid);
break;
case DL_GUID:
break;
default:
return 0;
}
if (valp) *valp = dl->gval;
return 1;
}
EXPORTED int dlist_tofile(struct dlist *dl,
const char **partp, struct message_guid **guidp,
unsigned long *sizep, const char **fnamep)
{
if (!dlist_isfile(dl)) return 0;
if (guidp) *guidp = dl->gval;
if (sizep) *sizep = dl->nval;
if (fnamep) *fnamep = dl->sval;
if (partp) *partp = dl->part;
return 1;
}
EXPORTED int dlist_isatomlist(const struct dlist *dl)
{
if (!dl) return 0;
return (dl->type == DL_ATOMLIST);
}
int dlist_iskvlist(const struct dlist *dl)
{
if (!dl) return 0;
return (dl->type == DL_KVLIST);
}
int dlist_isfile(const struct dlist *dl)
{
if (!dl) return 0;
return (dl->type == DL_FILE);
}
/* XXX - these ones aren't const, because they can change
* things... */
int dlist_isnum(struct dlist *dl)
{
bit64 tmp;
if (!dl) return 0;
/* see if it can be parsed as a number */
return dlist_tonum64(dl, &tmp);
}
/* XXX - these ones aren't const, because they can change
* things... */
EXPORTED int dlist_ishex64(struct dlist *dl)
{
bit64 tmp;
if (!dl) return 0;
/* see if it can be parsed as a number */
return dlist_tohex64(dl, &tmp);
}
/* XXX - these ones aren't const, because they can change
* things... */
int dlist_isguid(struct dlist *dl)
{
struct message_guid *tmp = NULL;
if (!dl) return 0;
return dlist_toguid(dl, &tmp);
}
/* XXX - this stuff is all shitty, rationalise later */
EXPORTED bit64 dlist_num(struct dlist *dl)
{
bit64 v;
if (!dl) return 0;
if (dlist_tonum64(dl, &v))
return v;
return 0;
}
/* XXX - this stuff is all shitty, rationalise later */
EXPORTED const char *dlist_cstring(struct dlist *dl)
{
static char zerochar = '\0';
if (dl) {
const char *res = NULL;
dlist_toatom(dl, &res);
if (res) return res;
}
return &zerochar;
}
EXPORTED int dlist_getatom(struct dlist *parent, const char *name, const char **valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_toatom(child, valp);
}
EXPORTED int dlist_getnum32(struct dlist *parent, const char *name, uint32_t *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tonum32(child, valp);
}
EXPORTED int dlist_getnum64(struct dlist *parent, const char *name, bit64 *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tonum64(child, valp);
}
EXPORTED int dlist_getdate(struct dlist *parent, const char *name, time_t *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_todate(child, valp);
}
EXPORTED int dlist_gethex64(struct dlist *parent, const char *name, bit64 *valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tohex64(child, valp);
}
EXPORTED int dlist_getguid(struct dlist *parent, const char *name,
struct message_guid **valp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_toguid(child, valp);
}
EXPORTED int dlist_getmap(struct dlist *parent, const char *name,
const char **valp, size_t *lenp)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tomap(child, valp, lenp);
}
EXPORTED int dlist_getbuf(struct dlist *parent, const char *name,
struct buf *value)
{
const char *v = NULL;
size_t l = 0;
if (dlist_getmap(parent, name, &v, &l)) {
buf_init_ro(value, v, l);
return 1;
}
return 0;
}
int dlist_getfile(struct dlist *parent, const char *name,
const char **partp,
struct message_guid **guidp,
unsigned long *sizep,
const char **fnamep)
{
struct dlist *child = dlist_getchild(parent, name);
return dlist_tofile(child, partp, guidp, sizep, fnamep);
}
EXPORTED int dlist_getlist(struct dlist *dl, const char *name, struct dlist **valp)
{
struct dlist *i = dlist_getchild(dl, name);
if (!i) return 0;
*valp = i;
return 1;
}
EXPORTED const char *dlist_lastkey(void)
{
return lastkey;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2628_0 |
crossvul-cpp_data_good_5105_0 | /* airpdcap.c
*
* Copyright (c) 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
*/
/*
* The files matching airpcap*.[ch] were originally developed as part of
* Wireshark's support for AirPcap adapters. However, they've been used
* for general 802.11 decryption for quite some time. It might make sense
* to rename them accordingly.
*/
/****************************************************************************/
/* File includes */
#include "config.h"
#include <glib.h>
#include <wsutil/crc32.h>
#include <wsutil/rc4.h>
#include <wsutil/sha1.h>
#include <wsutil/sha2.h>
#include <wsutil/md5.h>
#include <wsutil/pint.h>
#include <wsutil/aes.h>
#include <epan/tvbuff.h>
#include <epan/to_str.h>
#include <epan/strutil.h>
#include <epan/crypt/airpdcap_rijndael.h>
#include "airpdcap_system.h"
#include "airpdcap_int.h"
#include "airpdcap_debug.h"
#include "wep-wpadefs.h"
/****************************************************************************/
/****************************************************************************/
/* Constant definitions */
/* EAPOL definitions */
/**
* Length of the EAPOL-Key key confirmation key (KCK) used to calculate
* MIC over EAPOL frame and validate an EAPOL packet (128 bits)
*/
#define AIRPDCAP_WPA_KCK_LEN 16
/**
*Offset of the Key MIC in the EAPOL packet body
*/
#define AIRPDCAP_WPA_MICKEY_OFFSET 77
/**
* Maximum length of the EAPOL packet (it depends on the maximum MAC
* frame size)
*/
#define AIRPDCAP_WPA_MAX_EAPOL_LEN 4095
/**
* EAPOL Key Descriptor Version 1, used for all EAPOL-Key frames to and
* from a STA when neither the group nor pairwise ciphers are CCMP for
* Key Descriptor 1.
* @note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_NOT_CCMP 1
/**
* EAPOL Key Descriptor Version 2, used for all EAPOL-Key frames to and
* from a STA when either the pairwise or the group cipher is AES-CCMP
* for Key Descriptor 2.
* /note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_AES_CCMP 2
/** Define EAPOL Key Descriptor type values: use 254 for WPA and 2 for WPA2 **/
#define AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR 254
#define AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR 2
/****************************************************************************/
/****************************************************************************/
/* Macro definitions */
extern const UINT32 crc32_table[256];
#define CRC(crc, ch) (crc = (crc >> 8) ^ crc32_table[(crc ^ (ch)) & 0xff])
#define AIRPDCAP_GET_TK(ptk) (ptk + 32)
/****************************************************************************/
/****************************************************************************/
/* Type definitions */
/* Internal function prototype declarations */
#ifdef __cplusplus
extern "C" {
#endif
/**
* It is a step of the PBKDF2 (specifically the PKCS #5 v2.0) defined in
* the RFC 2898 to derive a key (used as PMK in WPA)
* @param ppbytes [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param iterations [IN] times to hash the password (4096 for WPA)
* @param count [IN] ???
* @param output [OUT] pointer to a preallocated buffer of
* SHA1_DIGEST_LEN characters that will contain a part of the key
*/
static INT AirPDcapRsnaPwd2PskStep(
const guint8 *ppbytes,
const guint passLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
;
/**
* It calculates the passphrase-to-PSK mapping reccomanded for use with
* RSNAs. This implementation uses the PBKDF2 method defined in the RFC
* 2898.
* @param passphrase [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param output [OUT] calculated PSK (to use as PMK in WPA)
* @note
* Described in 802.11i-2004, page 165
*/
static INT AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
;
static INT AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
;
/**
* It checks whether the specified key is corrected or not.
* @note
* For a standard WEP key the length will be changed to the standard
* length, and the type changed in a generic WEP key.
* @param key [IN] pointer to the key to validate
* @return
* - TRUE: the key contains valid fields and values
* - FALSE: the key has some invalid field or value
*/
static INT AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
;
static INT AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
;
/**
* @param ctx [IN] pointer to the current context
* @param id [IN] id of the association (composed by BSSID and MAC of
* the station)
* @return
* - index of the Security Association structure if found
* - -1, if the specified addresses pair BSSID-STA MAC has not been found
*/
static INT AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static const UCHAR * AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static const UCHAR * AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static void AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
;
/**
* @param sa [IN/OUT] pointer to SA that will hold the key
* @param data [IN] Frame
* @param offset_rsne [IN] RSNE IE offset in the frame
* @param offset_fte [IN] Fast BSS Transition IE offset in the frame
* @param offset_timeout [IN] Timeout Interval IE offset in the frame
* @param offset_link [IN] Link Identifier IE offset in the frame
* @param action [IN] Tdls Action code (response or confirm)
*
* @return
* AIRPDCAP_RET_SUCCESS if Key has been sucessfully derived (and MIC verified)
* AIRPDCAP_RET_UNSUCCESS otherwise
*/
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
;
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Exported function definitions */
#ifdef __cplusplus
extern "C" {
#endif
const guint8 broadcast_mac[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
#define EAPKEY_MIC_LEN 16 /* length of the MIC key for EAPoL_Key packet's MIC using MD5 */
#define NONCE_LEN 32
#define TKIP_GROUP_KEY_LEN 32
#define CCMP_GROUP_KEY_LEN 16
typedef struct {
guint8 type;
guint8 key_information[2]; /* Make this an array to avoid alignment issues */
guint8 key_length[2]; /* Make this an array to avoid alignment issues */
guint8 replay_counter[8];
guint8 key_nonce[NONCE_LEN];
guint8 key_iv[16];
guint8 key_sequence_counter[8]; /* also called the RSC */
guint8 key_id[8];
guint8 key_mic[EAPKEY_MIC_LEN];
guint8 key_data_len[2]; /* Make this an array rather than a U16 to avoid alignment shifting */
} EAPOL_RSN_KEY, * P_EAPOL_RSN_KEY;
/* Minimum possible key data size (at least one GTK KDE with CCMP key) */
#define GROUP_KEY_MIN_LEN 8 + CCMP_GROUP_KEY_LEN
/* Minimum possible group key msg size (group key msg using CCMP as cipher)*/
#define GROUP_KEY_PAYLOAD_LEN_MIN sizeof(EAPOL_RSN_KEY) + GROUP_KEY_MIN_LEN
/* XXX - what if this doesn't get the key? */
static INT
AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if ((key_bytes_len < GROUP_KEY_MIN_LEN) ||
(eapol_len < sizeof(EAPOL_RSN_KEY)) ||
(key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* Return a pointer the the requested SA. If it doesn't exist create it. */
static PAIRPDCAP_SEC_ASSOCIATION
AirPDcapGetSaPtr(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
int sa_index;
/* search for a cached Security Association for supplied BSSID and STA MAC */
if ((sa_index=AirPDcapGetSa(ctx, id))==-1) {
/* create a new Security Association if it doesn't currently exist */
if ((sa_index=AirPDcapStoreSa(ctx, id))==-1) {
return NULL;
}
}
/* get the Security Association structure */
return &ctx->sa[sa_index];
}
static INT AirPDcapScanForKeys(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
AIRPDCAP_SEC_ASSOCIATION_ID id
)
{
const UCHAR *addr;
guint bodyLength;
PAIRPDCAP_SEC_ASSOCIATION sta_sa;
PAIRPDCAP_SEC_ASSOCIATION sa;
guint offset = 0;
const guint8 dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x88, 0x8E /* Type: 802.1X authentication */
};
const guint8 bt_dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */
0x00, 0x03 /* Type: Bluetooth Security */
};
const guint8 tdls_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */
0x02, /* Payload Type: TDLS */
0X0C /* Action Category: TDLS */
};
const EAPOL_RSN_KEY *pEAPKey;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapScanForKeys");
/* cache offset in the packet data */
offset = mac_header_len;
/* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */
if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=8;
/* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */
if (data[offset+1]!=3) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not EAPOL-Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* get and check the body length (IEEE 802.1X-2004, pg. 25) */
bodyLength=pntoh16(data+offset+2);
if (((tot_len-offset-4) < bodyLength) || (bodyLength < sizeof(EAPOL_RSN_KEY))) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "EAPOL body too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip EAPOL MPDU and go to the first byte of the body */
offset+=4;
pEAPKey = (const EAPOL_RSN_KEY *) (data+offset);
/* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */
if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */
pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */
pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not valid key descriptor type", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* start with descriptor body */
offset+=1;
/* search for a cached Security Association for current BSSID and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "No SA for BSSID found", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_REQ_DATA;
}
/* It could be a Pairwise Key exchange, check */
if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE)
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Message too short for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 ||
AIRPDCAP_EAP_ACK(data[offset+1])!=1 ||
AIRPDCAP_EAP_MIC(data[offset]) != 1 ||
AIRPDCAP_EAP_SEC(data[offset]) != 1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Key bitfields not correct for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* force STA address to be the broadcast MAC so we create an SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
/* get the Security Association structure for the broadcast MAC and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */
/* get STA address */
if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) {
memcpy(id.sta, addr, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
#endif
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "SA not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
sta_sa = AirPDcapGetSaPtr(ctx, &id);
if (sta_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Try to extract the group key and install it in the SA */
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1));
} else if (memcmp(data+offset, tdls_header, 10) == 0) {
const guint8 *initiator, *responder;
guint8 action;
guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: TDLS Action Frame", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=10;
/* check if the packet is a TDLS response or confirm */
action = data[offset];
if (action!=1 && action!=2) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not Response nor confirm", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* check status */
offset++;
status=pntoh16(data+offset);
if (status!=0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "TDLS setup not successfull", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip Token + capabilities */
offset+=5;
/* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */
while(offset < (tot_len - 2)) {
if (data[offset] == 48) {
offset_rsne = offset;
} else if (data[offset] == 55) {
offset_fte = offset;
} else if (data[offset] == 56) {
offset_timeout = offset;
} else if (data[offset] == 101) {
offset_link = offset;
}
if (tot_len < offset + data[offset + 1] + 2) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
offset += data[offset + 1] + 2;
}
if (offset_rsne == 0 || offset_fte == 0 ||
offset_timeout == 0 || offset_link == 0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Cannot Find all necessary IEs", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Found RSNE/Fast BSS/Timeout Interval/Link IEs", AIRPDCAP_DEBUG_LEVEL_3);
/* Will create a Security Association between 2 STA. Need to get both MAC address */
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN);
} else {
memcpy(id.sta, responder, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN);
}
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
if (sa->validKey) {
if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) {
/* Already have valid key for this SA, no need to redo key derivation */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* We are opening a new session with the same two STA, save previous sa */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
sa->validKey = FALSE;
}
}
if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action)
== AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Skipping: not an EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
INT AirPDcapPacketProcess(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
UCHAR *decrypt_data,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
gboolean scanHandshake)
{
AIRPDCAP_SEC_ASSOCIATION_ID id;
UCHAR tmp_data[AIRPDCAP_MAX_CAPLEN];
guint tmp_len;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapPacketProcess");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
if (data==NULL || tot_len==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL data or length=0", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
/* check if the packet is of data or robust managment type */
if (!((AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_DATA) ||
(AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_MANAGEMENT &&
(AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DISASS ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DEAUTHENTICATION ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_ACTION)))) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "not data nor robust mgmt packet", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_DATA;
}
/* check correct packet size, to avoid wrong elaboration of encryption algorithms */
if (tot_len < (UINT)(mac_header_len+AIRPDCAP_CRYPTED_DATA_MINLEN)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "minimum length violated", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_WRONG_DATA_SIZE;
}
/* Assume that the decrypt_data field is at least this size. */
if (tot_len > AIRPDCAP_MAX_CAPLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "length too large", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* get STA/BSSID address */
if (AirPDcapGetSaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data), &id) != AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "STA/BSSID not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
/* check if data is encrypted (use the WEP bit in the Frame Control field) */
if (AIRPDCAP_WEP(data[1])==0) {
if (scanHandshake) {
/* data is sent in cleartext, check if is an authentication message or end the process */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Unencrypted data", AIRPDCAP_DEBUG_LEVEL_3);
return (AirPDcapScanForKeys(ctx, data, mac_header_len, tot_len, id));
}
return AIRPDCAP_RET_NO_DATA_ENCRYPTED;
} else {
PAIRPDCAP_SEC_ASSOCIATION sa;
int offset = 0;
/* get the Security Association structure for the STA and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* cache offset in the packet data (to scan encryption data) */
offset = mac_header_len;
if (decrypt_data==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "no decrypt buffer, use local", AIRPDCAP_DEBUG_LEVEL_3);
decrypt_data=tmp_data;
decrypt_len=&tmp_len;
}
/* create new header and data to modify */
*decrypt_len = tot_len;
memcpy(decrypt_data, data, *decrypt_len);
/* encrypted data */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Encrypted data", AIRPDCAP_DEBUG_LEVEL_3);
/* check the Extension IV to distinguish between WEP encryption and WPA encryption */
/* refer to IEEE 802.11i-2004, 8.2.1.2, pag.35 for WEP, */
/* IEEE 802.11i-2004, 8.3.2.2, pag. 45 for TKIP, */
/* IEEE 802.11i-2004, 8.3.3.2, pag. 57 for CCMP */
if (AIRPDCAP_EXTIV(data[offset+3])==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "WEP encryption", AIRPDCAP_DEBUG_LEVEL_3);
return AirPDcapWepMng(ctx, decrypt_data, mac_header_len, decrypt_len, key, sa, offset);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "TKIP or CCMP encryption", AIRPDCAP_DEBUG_LEVEL_3);
/* If index >= 1, then use the group key. This will not work if the AP is using
more than one group key simultaneously. I've not seen this in practice, however.
Usually an AP will rotate between the two key index values of 1 and 2 whenever
it needs to change the group key to be used. */
if (AIRPDCAP_KEY_INDEX(data[offset+3])>=1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "The key index >= 1. This is encrypted with a group key.", AIRPDCAP_DEBUG_LEVEL_3);
/* force STA address to broadcast MAC so we load the SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
/* search for a cached Security Association for current BSSID and broadcast MAC */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL)
return AIRPDCAP_RET_REQ_DATA;
}
/* Decrypt the packet using the appropriate SA */
if (AirPDcapRsnaMng(decrypt_data, mac_header_len, decrypt_len, key, sa, offset) == AIRPDCAP_RET_SUCCESS) {
/* If we successfully decrypted a packet, scan it to see if it contains a key handshake.
The group key handshake could be sent at any time the AP wants to change the key (such as when
it is using key rotation) and it also could be a rekey for the Pairwise key. So we must scan every packet. */
if (scanHandshake) {
return (AirPDcapScanForKeys(ctx, decrypt_data, mac_header_len, *decrypt_len, id));
} else {
return AIRPDCAP_RET_SUCCESS;
}
}
}
}
return AIRPDCAP_RET_UNSUCCESS;
}
INT AirPDcapSetKeys(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
INT i;
INT success;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapSetKeys");
if (ctx==NULL || keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "NULL context or NULL keys array", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
if (keys_nr>AIRPDCAP_MAX_KEYS_NR) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Keys number greater than maximum", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
/* clean key and SA collections before setting new ones */
AirPDcapInitContext(ctx);
/* check and insert keys */
for (i=0, success=0; i<(INT)keys_nr; i++) {
if (AirPDcapValidateKey(keys+i)==TRUE) {
if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PWD key", AIRPDCAP_DEBUG_LEVEL_4);
AirPDcapRsnaPwd2Psk(keys[i].UserPwd.Passphrase, keys[i].UserPwd.Ssid, keys[i].UserPwd.SsidLen, keys[i].KeyData.Wpa.Psk);
}
#ifdef _DEBUG
else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PMK key", AIRPDCAP_DEBUG_LEVEL_4);
} else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WEP key", AIRPDCAP_DEBUG_LEVEL_4);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a key", AIRPDCAP_DEBUG_LEVEL_4);
}
#endif
memcpy(&ctx->keys[success], &keys[i], sizeof(keys[i]));
success++;
}
}
ctx->keys_nr=success;
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return success;
}
static void
AirPDcapCleanKeys(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapCleanKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
return;
}
memset(ctx->keys, 0, sizeof(AIRPDCAP_KEY_ITEM) * AIRPDCAP_MAX_KEYS_NR);
ctx->keys_nr=0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "Keys collection cleaned!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
}
static void
AirPDcapRecurseCleanSA(
PAIRPDCAP_SEC_ASSOCIATION sa)
{
if (sa->next != NULL) {
AirPDcapRecurseCleanSA(sa->next);
g_free(sa->next);
sa->next = NULL;
}
}
static void
AirPDcapCleanSecAssoc(
PAIRPDCAP_CONTEXT ctx)
{
PAIRPDCAP_SEC_ASSOCIATION psa;
int i;
for (psa = ctx->sa, i = 0; i < AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; i++, psa++) {
/* To iterate is human, to recurse, divine */
AirPDcapRecurseCleanSA(psa);
}
}
INT AirPDcapGetKeys(
const PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
UINT i;
UINT j;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapGetKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return 0;
} else if (keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL keys array", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return (INT)ctx->keys_nr;
} else {
for (i=0, j=0; i<ctx->keys_nr && i<keys_nr && i<AIRPDCAP_MAX_KEYS_NR; i++) {
memcpy(&keys[j], &ctx->keys[i], sizeof(keys[j]));
j++;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "Got a key", AIRPDCAP_DEBUG_LEVEL_5);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return j;
}
}
/*
* XXX - This won't be reliable if a packet containing SSID "B" shows
* up in the middle of a 4-way handshake for SSID "A".
* We should probably use a small array or hash table to keep multiple
* SSIDs.
*/
INT AirPDcapSetLastSSID(
PAIRPDCAP_CONTEXT ctx,
CHAR *pkt_ssid,
size_t pkt_ssid_len)
{
if (!ctx || !pkt_ssid || pkt_ssid_len < 1 || pkt_ssid_len > WPA_SSID_MAX_SIZE)
return AIRPDCAP_RET_UNSUCCESS;
memcpy(ctx->pkt_ssid, pkt_ssid, pkt_ssid_len);
ctx->pkt_ssid_len = pkt_ssid_len;
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapInitContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapInitContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
ctx->pkt_ssid_len = 0;
memset(ctx->sa, 0, AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR * sizeof(AIRPDCAP_SEC_ASSOCIATION));
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "Context initialized!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapDestroyContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapDestroyContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
AirPDcapCleanSecAssoc(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "Context destroyed!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Internal function definitions */
#ifdef __cplusplus
extern "C" {
#endif
static INT
AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
INT ret_value=1;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
if (*decrypt_len > try_data_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* allocate a temp buffer for the decryption loop */
try_data=(UCHAR *)g_malloc(try_data_len);
/* start of loop added by GCS */
for(/* sa */; sa != NULL ;sa=sa->next) {
if (sa->validKey==FALSE) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Key not yet valid", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
/* copy the encrypted data into a temp buffer */
memcpy(try_data, decrypt_data, *decrypt_len);
if (sa->wpa.key_ver==1) {
/* CCMP -> HMAC-MD5 is the EAPOL-Key MIC, RC4 is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP", AIRPDCAP_DEBUG_LEVEL_3);
DEBUG_DUMP("ptk", sa->wpa.ptk, 64);
DEBUG_DUMP("ptk portion used", AIRPDCAP_GET_TK(sa->wpa.ptk), 16);
ret_value=AirPDcapTkipDecrypt(try_data+offset, *decrypt_len-offset, try_data+AIRPDCAP_TA_OFFSET, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP failed!", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) and ICV (4bytes) from the end of packet */
*decrypt_len-=12;
break;
} else {
/* AES-CCMP -> HMAC-SHA1-128 is the EAPOL-Key MIC, AES wep_key wrap is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP", AIRPDCAP_DEBUG_LEVEL_3);
ret_value=AirPDcapCcmpDecrypt(try_data, mac_header_len, (INT)*decrypt_len, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value)
continue;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) from the end of packet */
*decrypt_len-=8;
break;
}
}
/* end of loop */
/* none of the keys worked */
if(sa == NULL) {
g_free(try_data);
return ret_value;
}
if (*decrypt_len > try_data_len || *decrypt_len < 8) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
g_free(try_data);
return AIRPDCAP_RET_UNSUCCESS;
}
/* copy the decrypted data into the decrypt buffer GCS*/
memcpy(decrypt_data, try_data, *decrypt_len);
g_free(try_data);
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove TKIP/CCMP header */
offset = mac_header_len;
*decrypt_len-=8;
memmove(decrypt_data+offset, decrypt_data+offset+8, *decrypt_len-offset);
if (key!=NULL) {
if (sa->key!=NULL)
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
else
memset(key, 0, sizeof(AIRPDCAP_KEY_ITEM));
memcpy(key->KeyData.Wpa.Ptk, sa->wpa.ptk, AIRPDCAP_WPA_PTK_LEN); /* copy the PTK to the key structure for future use by wireshark */
if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_TKIP;
else if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_CCMP;
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
UCHAR wep_key[AIRPDCAP_WEP_KEY_MAXLEN+AIRPDCAP_WEP_IVLEN];
size_t keylen;
INT ret_value=1;
INT key_index;
AIRPDCAP_KEY_ITEM *tmp_key;
UINT8 useCache=FALSE;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
try_data = (UCHAR *)g_malloc(try_data_len);
if (sa->key!=NULL)
useCache=TRUE;
for (key_index=0; key_index<(INT)ctx->keys_nr; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
tmp_key=&ctx->keys[key_index];
} else {
if (sa->key!=NULL && sa->key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try cached WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Cached key is not valid, try another WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WEP keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
memset(wep_key, 0, sizeof(wep_key));
memcpy(try_data, decrypt_data, *decrypt_len);
/* Costruct the WEP seed: copy the IV in first 3 bytes and then the WEP key (refer to 802-11i-2004, 8.2.1.4.3, pag. 36) */
memcpy(wep_key, try_data+mac_header_len, AIRPDCAP_WEP_IVLEN);
keylen=tmp_key->KeyData.Wep.WepKeyLen;
memcpy(wep_key+AIRPDCAP_WEP_IVLEN, tmp_key->KeyData.Wep.WepKey, keylen);
ret_value=AirPDcapWepDecrypt(wep_key,
keylen+AIRPDCAP_WEP_IVLEN,
try_data + (mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN),
*decrypt_len-(mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN+AIRPDCAP_CRC_LEN));
if (ret_value == AIRPDCAP_RET_SUCCESS)
memcpy(decrypt_data, try_data, *decrypt_len);
}
if (!ret_value && tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
/* the tried key is the correct one, cached in the Security Association */
sa->key=tmp_key;
if (key!=NULL) {
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
}
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
g_free(try_data);
if (ret_value)
return AIRPDCAP_RET_UNSUCCESS;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "WEP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove ICV (4bytes) from the end of packet */
*decrypt_len-=4;
if (*decrypt_len < 4) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Decryption length too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove IC header */
offset = mac_header_len;
*decrypt_len-=4;
memmove(decrypt_data+offset, decrypt_data+offset+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN, *decrypt_len-offset);
return AIRPDCAP_RET_SUCCESS;
}
/* Refer to IEEE 802.11i-2004, 8.5.3, pag. 85 */
static INT
AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
{
AIRPDCAP_KEY_ITEM *tmp_key, *tmp_pkt_key, pkt_key;
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
INT key_index;
INT ret_value=1;
UCHAR useCache=FALSE;
UCHAR eapol[AIRPDCAP_EAPOL_MAX_LEN];
USHORT eapol_len;
if (sa->key!=NULL)
useCache=TRUE;
/* a 4-way handshake packet use a Pairwise key type (IEEE 802.11i-2004, pg. 79) */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=1) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Group/STAKey message (not used)", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* TODO timeouts? */
/* TODO consider key-index */
/* TODO considera Deauthentications */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake...", AIRPDCAP_DEBUG_LEVEL_5);
/* manage 4-way handshake packets; this step completes the 802.1X authentication process (IEEE 802.11i-2004, pag. 85) */
/* message 1: Authenticator->Supplicant (Sec=0, Mic=0, Ack=1, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=ANonce, MIC=0) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 1", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 1, the Supplicant determines whether the Key Replay Counter field value has been */
/* used before with the current PMKSA. If the Key Replay Counter field value is less than or equal to the current */
/* local value, the Supplicant discards the message. */
/* -> not checked, the Authenticator will be send another Message 1 (hopefully!) */
/* This saves the sa since we are reauthenticating which will overwrite our current sa GCS*/
if( sa->handshake >= 2) {
tmp_sa= g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->validKey=FALSE;
sa->next=tmp_sa;
}
/* save ANonce (from authenticator) to derive the PTK with the SNonce (from the 2 message) */
memcpy(sa->wpa.nonce, data+offset+12, 32);
/* get the Key Descriptor Version (to select algorithm used in decryption -CCMP or TKIP-) */
sa->wpa.key_ver=AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1]);
sa->handshake=1;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* message 2|4: Supplicant->Authenticator (Sec=0|1, Mic=1, Ack=0, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=SNonce|0, MIC=MIC(KCK,EAPOL)) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==0 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
/* Check key data length to differentiate between message 2 or 4, same as in epan/dissectors/packet-ieee80211.c */
if (pntoh16(data+offset+92)) {
/* message 2 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 2", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 2, the Authenticator checks that the key replay counter corresponds to the */
/* outstanding Message 1. If not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, */
/* the Authenticator silently discards Message 2. */
/* -> not checked; the Supplicant will send another message 2 (hopefully!) */
/* now you can derive the PTK */
for (key_index=0; key_index<(INT)ctx->keys_nr || useCache; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
} else {
/* there is a cached key in the security association, if it's a WPA key try it... */
if (sa->key!=NULL &&
(sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try cached WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Cached key is of a wrong type, try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WPA keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)
{
if (tmp_key->KeyType == AIRPDCAP_KEY_TYPE_WPA_PWD && tmp_key->UserPwd.SsidLen == 0 && ctx->pkt_ssid_len > 0 && ctx->pkt_ssid_len <= AIRPDCAP_WPA_SSID_MAX_LEN) {
/* We have a "wildcard" SSID. Use the one from the packet. */
memcpy(&pkt_key, tmp_key, sizeof(pkt_key));
memcpy(&pkt_key.UserPwd.Ssid, ctx->pkt_ssid, ctx->pkt_ssid_len);
pkt_key.UserPwd.SsidLen = ctx->pkt_ssid_len;
AirPDcapRsnaPwd2Psk(pkt_key.UserPwd.Passphrase, pkt_key.UserPwd.Ssid,
pkt_key.UserPwd.SsidLen, pkt_key.KeyData.Wpa.Psk);
tmp_pkt_key = &pkt_key;
} else {
tmp_pkt_key = tmp_key;
}
/* derive the PTK from the BSSID, STA MAC, PMK, SNonce, ANonce */
AirPDcapRsnaPrfX(sa, /* authenticator nonce, bssid, station mac */
tmp_pkt_key->KeyData.Wpa.Psk, /* PSK == PMK */
data+offset+12, /* supplicant nonce */
512,
sa->wpa.ptk);
/* verify the MIC (compare the MIC in the packet included in this message with a MIC calculated with the PTK) */
eapol_len=pntoh16(data+offset-3)+4;
memcpy(eapol, &data[offset-5], (eapol_len<AIRPDCAP_EAPOL_MAX_LEN?eapol_len:AIRPDCAP_EAPOL_MAX_LEN));
ret_value=AirPDcapRsnaMicCheck(eapol, /* eapol frame (header also) */
eapol_len, /* eapol frame length */
sa->wpa.ptk, /* Key Confirmation Key */
AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1])); /* EAPOL-Key description version */
/* If the MIC is valid, the Authenticator checks that the RSN information element bit-wise matches */
/* that from the (Re)Association Request message. */
/* i) TODO If these are not exactly the same, the Authenticator uses MLME-DEAUTHENTICATE.request */
/* primitive to terminate the association. */
/* ii) If they do match bit-wise, the Authenticator constructs Message 3. */
}
if (!ret_value &&
(tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK))
{
/* the temporary key is the correct one, cached in the Security Association */
sa->key=tmp_key;
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
if (ret_value) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "handshake step failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
sa->handshake=2;
sa->validKey=TRUE; /* we can use the key to decode, even if we have not captured the other eapol packets */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* message 4 */
/* TODO "Note that when the 4-Way Handshake is first used Message 4 is sent in the clear." */
/* TODO check MIC and Replay Counter */
/* On reception of Message 4, the Authenticator verifies that the Key Replay Counter field value is one */
/* that it used on this 4-Way Handshake; if it is not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, the */
/* Authenticator silently discards Message 4. */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 4", AIRPDCAP_DEBUG_LEVEL_3);
sa->handshake=4;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
}
/* message 3: Authenticator->Supplicant (Sec=1, Mic=1, Ack=1, Inst=0/1, Key=1(pairwise), KeyRSC=???, Nonce=ANonce, MIC=1) */
if (AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
const EAPOL_RSN_KEY *pEAPKey;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 3", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 3, the Supplicant silently discards the message if the Key Replay Counter field */
/* value has already been used or if the ANonce value in Message 3 differs from the ANonce value in Message 1. */
/* -> not checked, the Authenticator will send another message 3 (hopefully!) */
/* TODO check page 88 (RNS) */
/* If using WPA2 PSK, message 3 will contain an RSN for the group key (GTK KDE).
In order to properly support decrypting WPA2-PSK packets, we need to parse this to get the group key. */
pEAPKey = (const EAPOL_RSN_KEY *)(&(data[offset-1]));
if (pEAPKey->type == AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR){
PAIRPDCAP_SEC_ASSOCIATION broadcast_sa;
AIRPDCAP_SEC_ASSOCIATION_ID id;
/* Get broadcacst SA for the current BSSID */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, sa->saId.bssid, AIRPDCAP_MAC_LEN);
broadcast_sa = AirPDcapGetSaPtr(ctx, &id);
if (broadcast_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sa->wpa.ptk+16, broadcast_sa, tot_len-offset+1));
}
}
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
static INT
AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
{
UCHAR mic[AIRPDCAP_WPA_MICKEY_LEN];
UCHAR c_mic[20]; /* MIC 16 byte, the HMAC-SHA1 use a buffer of 20 bytes */
/* copy the MIC from the EAPOL packet */
memcpy(mic, eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, AIRPDCAP_WPA_MICKEY_LEN);
/* set to 0 the MIC in the EAPOL packet (to calculate the MIC) */
memset(eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, 0, AIRPDCAP_WPA_MICKEY_LEN);
if (key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP) {
/* use HMAC-MD5 for the EAPOL-Key MIC */
md5_hmac(eapol, eapol_len, KCK, AIRPDCAP_WPA_KCK_LEN, c_mic);
} else if (key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP) {
/* use HMAC-SHA1-128 for the EAPOL-Key MIC */
sha1_hmac(KCK, AIRPDCAP_WPA_KCK_LEN, eapol, eapol_len, c_mic);
} else
/* key descriptor version not recognized */
return AIRPDCAP_RET_UNSUCCESS;
/* compare calculated MIC with the Key MIC and return result (0 means success) */
return memcmp(mic, c_mic, AIRPDCAP_WPA_MICKEY_LEN);
}
static INT
AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
{
size_t len;
UCHAR ret=TRUE;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
if (key==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "NULL key", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
return FALSE;
}
switch (key->KeyType) {
case AIRPDCAP_KEY_TYPE_WEP:
/* check key size limits */
len=key->KeyData.Wep.WepKeyLen;
if (len<AIRPDCAP_WEP_KEY_MINLEN || len>AIRPDCAP_WEP_KEY_MAXLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WEP key: key length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WEP_40:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_40_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WEP_104:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_104_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
/* check passphrase and SSID size limits */
len=strlen(key->UserPwd.Passphrase);
if (len<AIRPDCAP_WPA_PASSPHRASE_MIN_LEN || len>AIRPDCAP_WPA_PASSPHRASE_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: passphrase length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
len=key->UserPwd.SsidLen;
if (len>AIRPDCAP_WPA_SSID_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: ssid length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
break;
default:
ret=FALSE;
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapValidateKey");
return ret;
}
static INT
AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT sa_index;
if (ctx->sa_index!=-1) {
/* at least one association was stored */
/* search for the association from sa_index to 0 (most recent added) */
for (sa_index=ctx->sa_index; sa_index>=0; sa_index--) {
if (ctx->sa[sa_index].used) {
if (memcmp(id, &(ctx->sa[sa_index].saId), sizeof(AIRPDCAP_SEC_ASSOCIATION_ID))==0) {
ctx->index=sa_index;
return sa_index;
}
}
}
}
return -1;
}
static INT
AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT last_free;
if (ctx->first_free_index>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
if (ctx->sa[ctx->first_free_index].used) {
/* last addition was in the middle of the array (and the first_free_index was just incremented by 1) */
/* search for a free space from the first_free_index to AIRPDCAP_STA_INFOS_NR (to avoid free blocks in */
/* the middle) */
for (last_free=ctx->first_free_index; last_free<AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; last_free++)
if (!ctx->sa[last_free].used)
break;
if (last_free>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
/* store first free space index */
ctx->first_free_index=last_free;
}
/* use this info */
ctx->index=ctx->first_free_index;
/* reset the info structure */
memset(ctx->sa+ctx->index, 0, sizeof(AIRPDCAP_SEC_ASSOCIATION));
ctx->sa[ctx->index].used=1;
/* set the info structure */
memcpy(&(ctx->sa[ctx->index].saId), id, sizeof(AIRPDCAP_SEC_ASSOCIATION_ID));
/* increment by 1 the first_free_index (heuristic) */
ctx->first_free_index++;
/* set the sa_index if the added index is greater the the sa_index */
if (ctx->index > ctx->sa_index)
ctx->sa_index=ctx->index;
return ctx->index;
}
static INT
AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
if ((AIRPDCAP_TYPE(frame->fc[0])==AIRPDCAP_TYPE_DATA) &&
(AIRPDCAP_DS_BITS(frame->fc[1]) == 0) &&
(memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) != 0) &&
(memcmp(frame->addr1, frame->addr3, AIRPDCAP_MAC_LEN) != 0)) {
/* DATA frame with fromDS=0 ToDS=0 and neither RA or SA is BSSID
=> TDLS traffic. Use highest MAC address for bssid */
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id->sta, frame->addr1, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr2, AIRPDCAP_MAC_LEN);
} else {
memcpy(id->sta, frame->addr2, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr1, AIRPDCAP_MAC_LEN);
}
} else {
const UCHAR *addr;
/* Normal Case: SA between STA and AP */
if ((addr = AirPDcapGetBssidAddress(frame)) != NULL) {
memcpy(id->bssid, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
if ((addr = AirPDcapGetStaAddress(frame)) != NULL) {
memcpy(id->sta, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
}
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "BSSID_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->bssid[0],id->bssid[1],id->bssid[2],id->bssid[3],id->bssid[4],id->bssid[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
g_snprintf(msgbuf, MSGBUF_LEN, "STA_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->sta[0],id->sta[1],id->sta[2],id->sta[3],id->sta[4],id->sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
return AIRPDCAP_RET_SUCCESS;
}
/*
* AirPDcapGetBssidAddress() and AirPDcapGetBssidAddress() are used for
* key caching. In each case, it's more important to return a value than
* to return a _correct_ value, so we fudge addresses in some cases, e.g.
* the BSSID in bridged connections.
* FromDS ToDS Sta BSSID
* 0 0 addr1/2 addr3
* 0 1 addr2 addr1
* 1 0 addr1 addr2
* 1 1 addr2 addr1
*/
static const UCHAR *
AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
if (memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) == 0)
return frame->addr1;
else
return frame->addr2;
case 1:
return frame->addr2;
case 2:
return frame->addr1;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
static const UCHAR *
AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
return frame->addr3;
case 1:
return frame->addr1;
case 2:
return frame->addr2;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) > 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
/* Function used to derive the PTK. Refer to IEEE 802.11I-2004, pag. 74
* and IEEE 802.11i-2004, pag. 164 */
static void
AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
{
UINT8 i;
UCHAR R[100];
INT offset=sizeof("Pairwise key expansion");
UCHAR output[80]; /* allow for sha1 overflow. */
memset(R, 0, 100);
memcpy(R, "Pairwise key expansion", offset);
/* Min(AA, SPA) || Max(AA, SPA) */
if (memcmp(sa->saId.sta, sa->saId.bssid, AIRPDCAP_MAC_LEN) < 0)
{
memcpy(R + offset, sa->saId.sta, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.bssid, AIRPDCAP_MAC_LEN);
}
else
{
memcpy(R + offset, sa->saId.bssid, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.sta, AIRPDCAP_MAC_LEN);
}
offset+=AIRPDCAP_MAC_LEN*2;
/* Min(ANonce,SNonce) || Max(ANonce,SNonce) */
if( memcmp(snonce, sa->wpa.nonce, 32) < 0 )
{
memcpy(R + offset, snonce, 32);
memcpy(R + offset + 32, sa->wpa.nonce, 32);
}
else
{
memcpy(R + offset, sa->wpa.nonce, 32);
memcpy(R + offset + 32, snonce, 32);
}
offset+=32*2;
for(i = 0; i < (x+159)/160; i++)
{
R[offset] = i;
sha1_hmac(pmk, 32, R, 100, &output[20 * i]);
}
memcpy(ptk, output, x/8);
}
#define MAX_SSID_LENGTH 32 /* maximum SSID length */
static INT
AirPDcapRsnaPwd2PskStep(
const guint8 *ppBytes,
const guint ppLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
{
UCHAR digest[MAX_SSID_LENGTH+4]; /* SSID plus 4 bytes of count */
UCHAR digest1[SHA1_DIGEST_LEN];
INT i, j;
if (ssidLength > MAX_SSID_LENGTH) {
/* This "should not happen" */
return AIRPDCAP_RET_UNSUCCESS;
}
memset(digest, 0, sizeof digest);
memset(digest1, 0, sizeof digest1);
/* U1 = PRF(P, S || INT(i)) */
memcpy(digest, ssid, ssidLength);
digest[ssidLength] = (UCHAR)((count>>24) & 0xff);
digest[ssidLength+1] = (UCHAR)((count>>16) & 0xff);
digest[ssidLength+2] = (UCHAR)((count>>8) & 0xff);
digest[ssidLength+3] = (UCHAR)(count & 0xff);
sha1_hmac(ppBytes, ppLength, digest, (guint32) ssidLength+4, digest1);
/* output = U1 */
memcpy(output, digest1, SHA1_DIGEST_LEN);
for (i = 1; i < iterations; i++) {
/* Un = PRF(P, Un-1) */
sha1_hmac(ppBytes, ppLength, digest1, SHA1_DIGEST_LEN, digest);
memcpy(digest1, digest, SHA1_DIGEST_LEN);
/* output = output xor Un */
for (j = 0; j < SHA1_DIGEST_LEN; j++) {
output[j] ^= digest[j];
}
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
{
UCHAR m_output[2*SHA1_DIGEST_LEN];
GByteArray *pp_ba = g_byte_array_new();
memset(m_output, 0, 2*SHA1_DIGEST_LEN);
if (!uri_str_to_bytes(passphrase, pp_ba)) {
g_byte_array_free(pp_ba, TRUE);
return 0;
}
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 1, m_output);
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 2, &m_output[SHA1_DIGEST_LEN]);
memcpy(output, m_output, AIRPDCAP_WPA_PSK_LEN);
g_byte_array_free(pp_ba, TRUE);
return 0;
}
/*
* Returns the decryption_key_t struct given a string describing the key.
* Returns NULL if the input_string cannot be parsed.
*/
decryption_key_t*
parse_key_string(gchar* input_string, guint8 key_type)
{
gchar *key, *tmp_str;
gchar *ssid;
GString *key_string = NULL;
GByteArray *ssid_ba = NULL, *key_ba;
gboolean res;
gchar **tokens;
guint n = 0;
decryption_key_t *dk;
if(input_string == NULL)
return NULL;
/*
* Parse the input_string. WEP and WPA will be just a string
* of hexadecimal characters (if key is wrong, null will be
* returned...).
* WPA-PWD should be in the form
* <key data>[:<ssid>]
*/
switch(key_type)
{
case AIRPDCAP_KEY_TYPE_WEP:
case AIRPDCAP_KEY_TYPE_WEP_40:
case AIRPDCAP_KEY_TYPE_WEP_104:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
if (res && key_ba->len > 0) {
/* Key is correct! It was probably an 'old style' WEP key */
/* Create the decryption_key_t structure, fill it and return it*/
dk = (decryption_key_t *)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WEP;
/* XXX - The current key handling code in the GUI requires
* no separators and lower case */
tmp_str = bytes_to_str(NULL, key_ba->data, key_ba->len);
dk->key = g_string_new(tmp_str);
g_string_ascii_down(dk->key);
dk->bits = key_ba->len * 8;
dk->ssid = NULL;
wmem_free(NULL, tmp_str);
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Key doesn't work */
g_byte_array_free(key_ba, TRUE);
return NULL;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
tokens = g_strsplit(input_string,":",0);
/* Tokens is a null termiated array of strings ... */
while(tokens[n] != NULL)
n++;
if(n < 1)
{
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
/*
* The first token is the key
*/
key = g_strdup(tokens[0]);
ssid = NULL;
/* Maybe there is a second token (an ssid, if everything else is ok) */
if(n >= 2)
{
ssid = g_strdup(tokens[1]);
}
/* Create a new string */
key_string = g_string_new(key);
ssid_ba = NULL;
/* Two (or more) tokens mean that the user entered a WPA-PWD key ... */
if( ((key_string->len) > WPA_KEY_MAX_CHAR_SIZE) || ((key_string->len) < WPA_KEY_MIN_CHAR_SIZE))
{
g_string_free(key_string, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid != NULL) /* more than two tokens found, means that the user specified the ssid */
{
ssid_ba = g_byte_array_new();
if (! uri_str_to_bytes(ssid, ssid_ba)) {
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid_ba->len > WPA_SSID_MAX_CHAR_SIZE)
{
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PWD;
dk->key = g_string_new(key);
dk->bits = 256; /* This is the length of the array pf bytes that will be generated using key+ssid ...*/
dk->ssid = byte_array_dup(ssid_ba); /* NULL if ssid_ba is NULL */
g_string_free(key_string, TRUE);
if (ssid_ba != NULL)
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
if(ssid != NULL)
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return dk;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
/* Two tokens means that the user should have entered a WPA-BIN key ... */
if(!res || ((key_ba->len) != WPA_PSK_KEY_SIZE))
{
g_byte_array_free(key_ba, TRUE);
/* No ssid has been created ... */
return NULL;
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PSK;
dk->key = g_string_new(input_string);
dk->bits = (guint) dk->key->len * 4;
dk->ssid = NULL;
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Type not supported */
return NULL;
}
void
free_key_string(decryption_key_t *dk)
{
if (dk->key)
g_string_free(dk->key, TRUE);
if (dk->ssid)
g_byte_array_free(dk->ssid, TRUE);
g_free(dk);
}
/*
* Returns a newly allocated string representing the given decryption_key_t
* struct, or NULL if something is wrong...
*/
gchar*
get_key_string(decryption_key_t* dk)
{
gchar* output_string = NULL;
if(dk == NULL || dk->key == NULL)
return NULL;
switch(dk->type) {
case AIRPDCAP_KEY_TYPE_WEP:
output_string = g_strdup(dk->key->str);
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
if(dk->ssid == NULL)
output_string = g_strdup(dk->key->str);
else
output_string = g_strdup_printf("%s:%s",
dk->key->str, format_uri(dk->ssid, ":"));
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
output_string = g_strdup(dk->key->str);
break;
default:
return NULL;
}
return output_string;
}
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
{
sha256_hmac_context sha_ctx;
aes_cmac_ctx aes_ctx;
const guint8 *snonce, *anonce, *initiator, *responder, *bssid;
guint8 key_input[SHA256_DIGEST_LEN];
guint8 mic[16], iter[2], length[2], seq_num = action + 1;
/* Get key input */
anonce = &data[offset_fte + 20];
snonce = &data[offset_fte + 52];
sha256_starts(&(sha_ctx.ctx));
if (memcmp(anonce, snonce, AIRPDCAP_WPA_NONCE_LEN) < 0) {
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
} else {
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
}
sha256_finish(&(sha_ctx.ctx), key_input);
/* Derive key */
bssid = &data[offset_link + 2];
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
sha256_hmac_starts(&sha_ctx, key_input, SHA256_DIGEST_LEN);
iter[0] = 1;
iter[1] = 0;
sha256_hmac_update(&sha_ctx, (const guint8 *)&iter, 2);
sha256_hmac_update(&sha_ctx, "TDLS PMK", 8);
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
} else {
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
}
sha256_hmac_update(&sha_ctx, bssid, AIRPDCAP_MAC_LEN);
length[0] = 256 & 0xff;
length[1] = (256 >> 8) & 0xff;
sha256_hmac_update(&sha_ctx, (const guint8 *)&length, 2);
sha256_hmac_finish(&sha_ctx, key_input);
/* Check MIC */
aes_cmac_encrypt_starts(&aes_ctx, key_input, 16);
aes_cmac_encrypt_update(&aes_ctx, initiator, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, responder, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, &seq_num, 1);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_link], data[offset_link + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_rsne], data[offset_rsne + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_timeout], data[offset_timeout + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte], 4);
memset(mic, 0, 16);
aes_cmac_encrypt_update(&aes_ctx, mic, 16);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte + 20], data[offset_fte + 1] + 2 - 20);
aes_cmac_encrypt_finish(&aes_ctx, mic);
if (memcmp(mic, &data[offset_fte + 4],16)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verification failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
memcpy(AIRPDCAP_GET_TK(sa->wpa.ptk), &key_input[16], 16);
memcpy(sa->wpa.nonce, snonce, AIRPDCAP_WPA_NONCE_LEN);
sa->validKey = TRUE;
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verified", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5105_0 |
crossvul-cpp_data_bad_2778_0 | /*
* MXF demuxer.
* Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
*
* 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
*/
/*
* References
* SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
* SMPTE 377M MXF File Format Specifications
* SMPTE 378M Operational Pattern 1a
* SMPTE 379M MXF Generic Container
* SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
* SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
* SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
*
* Principle
* Search for Track numbers which will identify essence element KLV packets.
* Search for SourcePackage which define tracks which contains Track numbers.
* Material Package contains tracks with reference to SourcePackage tracks.
* Search for Descriptors (Picture, Sound) which contains codec info and parameters.
* Assign Descriptors to correct Tracks.
*
* Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
* Metadata parsing resolves Strong References to objects.
*
* Simple demuxer, only OP1A supported and some files might not work at all.
* Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
*/
#include <inttypes.h>
#include "libavutil/aes.h"
#include "libavutil/avassert.h"
#include "libavutil/mathematics.h"
#include "libavcodec/bytestream.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/parseutils.h"
#include "libavutil/timecode.h"
#include "avformat.h"
#include "internal.h"
#include "mxf.h"
typedef enum {
Header,
BodyPartition,
Footer
} MXFPartitionType;
typedef enum {
OP1a = 1,
OP1b,
OP1c,
OP2a,
OP2b,
OP2c,
OP3a,
OP3b,
OP3c,
OPAtom,
OPSONYOpt, /* FATE sample, violates the spec in places */
} MXFOP;
typedef struct MXFPartition {
int closed;
int complete;
MXFPartitionType type;
uint64_t previous_partition;
int index_sid;
int body_sid;
int64_t this_partition;
int64_t essence_offset; ///< absolute offset of essence
int64_t essence_length;
int32_t kag_size;
int64_t header_byte_count;
int64_t index_byte_count;
int pack_length;
int64_t pack_ofs; ///< absolute offset of pack in file, including run-in
} MXFPartition;
typedef struct MXFCryptoContext {
UID uid;
enum MXFMetadataSetType type;
UID source_container_ul;
} MXFCryptoContext;
typedef struct MXFStructuralComponent {
UID uid;
enum MXFMetadataSetType type;
UID source_package_ul;
UID source_package_uid;
UID data_definition_ul;
int64_t duration;
int64_t start_position;
int source_track_id;
} MXFStructuralComponent;
typedef struct MXFSequence {
UID uid;
enum MXFMetadataSetType type;
UID data_definition_ul;
UID *structural_components_refs;
int structural_components_count;
int64_t duration;
uint8_t origin;
} MXFSequence;
typedef struct MXFTrack {
UID uid;
enum MXFMetadataSetType type;
int drop_frame;
int start_frame;
struct AVRational rate;
AVTimecode tc;
} MXFTimecodeComponent;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
UID input_segment_ref;
} MXFPulldownComponent;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
UID *structural_components_refs;
int structural_components_count;
int64_t duration;
} MXFEssenceGroup;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
char *name;
char *value;
} MXFTaggedValue;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
MXFSequence *sequence; /* mandatory, and only one */
UID sequence_ref;
int track_id;
char *name;
uint8_t track_number[4];
AVRational edit_rate;
int intra_only;
uint64_t sample_count;
int64_t original_duration; /* st->duration in SampleRate/EditRate units */
} MXFTrack;
typedef struct MXFDescriptor {
UID uid;
enum MXFMetadataSetType type;
UID essence_container_ul;
UID essence_codec_ul;
UID codec_ul;
AVRational sample_rate;
AVRational aspect_ratio;
int width;
int height; /* Field height, not frame height */
int frame_layout; /* See MXFFrameLayout enum */
int video_line_map[2];
#define MXF_FIELD_DOMINANCE_DEFAULT 0
#define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */
#define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */
int field_dominance;
int channels;
int bits_per_sample;
int64_t duration; /* ContainerDuration optional property */
unsigned int component_depth;
unsigned int horiz_subsampling;
unsigned int vert_subsampling;
UID *sub_descriptors_refs;
int sub_descriptors_count;
int linked_track_id;
uint8_t *extradata;
int extradata_size;
enum AVPixelFormat pix_fmt;
} MXFDescriptor;
typedef struct MXFIndexTableSegment {
UID uid;
enum MXFMetadataSetType type;
int edit_unit_byte_count;
int index_sid;
int body_sid;
AVRational index_edit_rate;
uint64_t index_start_position;
uint64_t index_duration;
int8_t *temporal_offset_entries;
int *flag_entries;
uint64_t *stream_offset_entries;
int nb_index_entries;
} MXFIndexTableSegment;
typedef struct MXFPackage {
UID uid;
enum MXFMetadataSetType type;
UID package_uid;
UID package_ul;
UID *tracks_refs;
int tracks_count;
MXFDescriptor *descriptor; /* only one */
UID descriptor_ref;
char *name;
UID *comment_refs;
int comment_count;
} MXFPackage;
typedef struct MXFMetadataSet {
UID uid;
enum MXFMetadataSetType type;
} MXFMetadataSet;
/* decoded index table */
typedef struct MXFIndexTable {
int index_sid;
int body_sid;
int nb_ptses; /* number of PTSes or total duration of index */
int64_t first_dts; /* DTS = EditUnit + first_dts */
int64_t *ptses; /* maps EditUnit -> PTS */
int nb_segments;
MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
int8_t *offsets; /* temporal offsets for display order to stored order conversion */
} MXFIndexTable;
typedef struct MXFContext {
MXFPartition *partitions;
unsigned partitions_count;
MXFOP op;
UID *packages_refs;
int packages_count;
MXFMetadataSet **metadata_sets;
int metadata_sets_count;
AVFormatContext *fc;
struct AVAES *aesc;
uint8_t *local_tags;
int local_tags_count;
uint64_t footer_partition;
KLVPacket current_klv_data;
int current_klv_index;
int run_in;
MXFPartition *current_partition;
int parsing_backward;
int64_t last_forward_tell;
int last_forward_partition;
int current_edit_unit;
int nb_index_tables;
MXFIndexTable *index_tables;
int edit_units_per_packet; ///< how many edit units to read at a time (PCM, OPAtom)
} MXFContext;
enum MXFWrappingScheme {
Frame,
Clip,
};
/* NOTE: klv_offset is not set (-1) for local keys */
typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
typedef struct MXFMetadataReadTableEntry {
const UID key;
MXFMetadataReadFunc *read;
int ctx_size;
enum MXFMetadataSetType type;
} MXFMetadataReadTableEntry;
static int mxf_read_close(AVFormatContext *s);
/* partial keys to match */
static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 };
static const uint8_t mxf_system_item_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
/* complete keys to match */
static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 };
static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
static const uint8_t mxf_random_index_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf };
static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 };
static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
static const uint8_t mxf_indirect_value_utf16be[] = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
#define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx)
{
MXFIndexTableSegment *seg;
switch ((*ctx)->type) {
case Descriptor:
av_freep(&((MXFDescriptor *)*ctx)->extradata);
break;
case MultipleDescriptor:
av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs);
break;
case Sequence:
av_freep(&((MXFSequence *)*ctx)->structural_components_refs);
break;
case EssenceGroup:
av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs);
break;
case SourcePackage:
case MaterialPackage:
av_freep(&((MXFPackage *)*ctx)->tracks_refs);
av_freep(&((MXFPackage *)*ctx)->name);
av_freep(&((MXFPackage *)*ctx)->comment_refs);
break;
case TaggedValue:
av_freep(&((MXFTaggedValue *)*ctx)->name);
av_freep(&((MXFTaggedValue *)*ctx)->value);
break;
case Track:
av_freep(&((MXFTrack *)*ctx)->name);
break;
case IndexTableSegment:
seg = (MXFIndexTableSegment *)*ctx;
av_freep(&seg->temporal_offset_entries);
av_freep(&seg->flag_entries);
av_freep(&seg->stream_offset_entries);
default:
break;
}
if (freectx)
av_freep(ctx);
}
static int64_t klv_decode_ber_length(AVIOContext *pb)
{
uint64_t size = avio_r8(pb);
if (size & 0x80) { /* long form */
int bytes_num = size & 0x7f;
/* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
if (bytes_num > 8)
return AVERROR_INVALIDDATA;
size = 0;
while (bytes_num--)
size = size << 8 | avio_r8(pb);
}
return size;
}
static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
{
int i, b;
for (i = 0; i < size && !avio_feof(pb); i++) {
b = avio_r8(pb);
if (b == key[0])
i = 0;
else if (b != key[i])
i = -1;
}
return i == size;
}
static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
{
if (!mxf_read_sync(pb, mxf_klv_key, 4))
return AVERROR_INVALIDDATA;
klv->offset = avio_tell(pb) - 4;
memcpy(klv->key, mxf_klv_key, 4);
avio_read(pb, klv->key + 4, 12);
klv->length = klv_decode_ber_length(pb);
return klv->length == -1 ? -1 : 0;
}
static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
{
int i;
for (i = 0; i < s->nb_streams; i++) {
MXFTrack *track = s->streams[i]->priv_data;
/* SMPTE 379M 7.3 */
if (track && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
return i;
}
/* return 0 if only one stream, for OP Atom files with 0 as track number */
return s->nb_streams == 1 ? 0 : -1;
}
/* XXX: use AVBitStreamFilter */
static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
{
const uint8_t *buf_ptr, *end_ptr;
uint8_t *data_ptr;
int i;
if (length > 61444) /* worst case PAL 1920 samples 8 channels */
return AVERROR_INVALIDDATA;
length = av_get_packet(pb, pkt, length);
if (length < 0)
return length;
data_ptr = pkt->data;
end_ptr = pkt->data + length;
buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
for (; end_ptr - buf_ptr >= st->codecpar->channels * 4; ) {
for (i = 0; i < st->codecpar->channels; i++) {
uint32_t sample = bytestream_get_le32(&buf_ptr);
if (st->codecpar->bits_per_coded_sample == 24)
bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
else
bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
}
buf_ptr += 32 - st->codecpar->channels*4; // always 8 channels stored SMPTE 331M
}
av_shrink_packet(pkt, data_ptr - pkt->data);
return 0;
}
static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
{
static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
MXFContext *mxf = s->priv_data;
AVIOContext *pb = s->pb;
int64_t end = avio_tell(pb) + klv->length;
int64_t size;
uint64_t orig_size;
uint64_t plaintext_size;
uint8_t ivec[16];
uint8_t tmpbuf[16];
int index;
if (!mxf->aesc && s->key && s->keylen == 16) {
mxf->aesc = av_aes_alloc();
if (!mxf->aesc)
return AVERROR(ENOMEM);
av_aes_init(mxf->aesc, s->key, 128, 1);
}
// crypto context
avio_skip(pb, klv_decode_ber_length(pb));
// plaintext offset
klv_decode_ber_length(pb);
plaintext_size = avio_rb64(pb);
// source klv key
klv_decode_ber_length(pb);
avio_read(pb, klv->key, 16);
if (!IS_KLV_KEY(klv, mxf_essence_element_key))
return AVERROR_INVALIDDATA;
index = mxf_get_stream_index(s, klv);
if (index < 0)
return AVERROR_INVALIDDATA;
// source size
klv_decode_ber_length(pb);
orig_size = avio_rb64(pb);
if (orig_size < plaintext_size)
return AVERROR_INVALIDDATA;
// enc. code
size = klv_decode_ber_length(pb);
if (size < 32 || size - 32 < orig_size)
return AVERROR_INVALIDDATA;
avio_read(pb, ivec, 16);
avio_read(pb, tmpbuf, 16);
if (mxf->aesc)
av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
if (memcmp(tmpbuf, checkv, 16))
av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
size -= 32;
size = av_get_packet(pb, pkt, size);
if (size < 0)
return size;
else if (size < plaintext_size)
return AVERROR_INVALIDDATA;
size -= plaintext_size;
if (mxf->aesc)
av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
&pkt->data[plaintext_size], size >> 4, ivec, 1);
av_shrink_packet(pkt, orig_size);
pkt->stream_index = index;
avio_skip(pb, end - avio_tell(pb));
return 0;
}
static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
int item_num = avio_rb32(pb);
int item_len = avio_rb32(pb);
if (item_len != 18) {
avpriv_request_sample(pb, "Primer pack item length %d", item_len);
return AVERROR_PATCHWELCOME;
}
if (item_num > 65536) {
av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
return AVERROR_INVALIDDATA;
}
if (mxf->local_tags)
av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n");
av_free(mxf->local_tags);
mxf->local_tags_count = 0;
mxf->local_tags = av_calloc(item_num, item_len);
if (!mxf->local_tags)
return AVERROR(ENOMEM);
mxf->local_tags_count = item_num;
avio_read(pb, mxf->local_tags, item_num*item_len);
return 0;
}
static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
MXFPartition *partition, *tmp_part;
UID op;
uint64_t footer_partition;
uint32_t nb_essence_containers;
tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions));
if (!tmp_part)
return AVERROR(ENOMEM);
mxf->partitions = tmp_part;
if (mxf->parsing_backward) {
/* insert the new partition pack in the middle
* this makes the entries in mxf->partitions sorted by offset */
memmove(&mxf->partitions[mxf->last_forward_partition+1],
&mxf->partitions[mxf->last_forward_partition],
(mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
} else {
mxf->last_forward_partition++;
partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
}
memset(partition, 0, sizeof(*partition));
mxf->partitions_count++;
partition->pack_length = avio_tell(pb) - klv_offset + size;
partition->pack_ofs = klv_offset;
switch(uid[13]) {
case 2:
partition->type = Header;
break;
case 3:
partition->type = BodyPartition;
break;
case 4:
partition->type = Footer;
break;
default:
av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
return AVERROR_INVALIDDATA;
}
/* consider both footers to be closed (there is only Footer and CompleteFooter) */
partition->closed = partition->type == Footer || !(uid[14] & 1);
partition->complete = uid[14] > 2;
avio_skip(pb, 4);
partition->kag_size = avio_rb32(pb);
partition->this_partition = avio_rb64(pb);
partition->previous_partition = avio_rb64(pb);
footer_partition = avio_rb64(pb);
partition->header_byte_count = avio_rb64(pb);
partition->index_byte_count = avio_rb64(pb);
partition->index_sid = avio_rb32(pb);
avio_skip(pb, 8);
partition->body_sid = avio_rb32(pb);
if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) {
av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n");
return AVERROR_INVALIDDATA;
}
nb_essence_containers = avio_rb32(pb);
if (partition->this_partition &&
partition->previous_partition == partition->this_partition) {
av_log(mxf->fc, AV_LOG_ERROR,
"PreviousPartition equal to ThisPartition %"PRIx64"\n",
partition->previous_partition);
/* override with the actual previous partition offset */
if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
MXFPartition *prev =
mxf->partitions + mxf->last_forward_partition - 2;
partition->previous_partition = prev->this_partition;
}
/* if no previous body partition are found point to the header
* partition */
if (partition->previous_partition == partition->this_partition)
partition->previous_partition = 0;
av_log(mxf->fc, AV_LOG_ERROR,
"Overriding PreviousPartition with %"PRIx64"\n",
partition->previous_partition);
}
/* some files don't have FooterPartition set in every partition */
if (footer_partition) {
if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
av_log(mxf->fc, AV_LOG_ERROR,
"inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
mxf->footer_partition, footer_partition);
} else {
mxf->footer_partition = footer_partition;
}
}
av_log(mxf->fc, AV_LOG_TRACE,
"PartitionPack: ThisPartition = 0x%"PRIX64
", PreviousPartition = 0x%"PRIX64", "
"FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
partition->this_partition,
partition->previous_partition, footer_partition,
partition->index_sid, partition->body_sid);
/* sanity check PreviousPartition if set */
//NOTE: this isn't actually enough, see mxf_seek_to_previous_partition()
if (partition->previous_partition &&
mxf->run_in + partition->previous_partition >= klv_offset) {
av_log(mxf->fc, AV_LOG_ERROR,
"PreviousPartition points to this partition or forward\n");
return AVERROR_INVALIDDATA;
}
if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
else if (op[12] == 0x10) {
/* SMPTE 390m: "There shall be exactly one essence container"
* The following block deals with files that violate this, namely:
* 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
* abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
if (nb_essence_containers != 1) {
MXFOP op = nb_essence_containers ? OP1a : OPAtom;
/* only nag once */
if (!mxf->op)
av_log(mxf->fc, AV_LOG_WARNING,
"\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
nb_essence_containers,
op == OP1a ? "OP1a" : "OPAtom");
mxf->op = op;
} else
mxf->op = OPAtom;
} else {
av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
mxf->op = OP1a;
}
if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
partition->kag_size);
if (mxf->op == OPSONYOpt)
partition->kag_size = 512;
else
partition->kag_size = 1;
av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
}
return 0;
}
static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
{
MXFMetadataSet **tmp;
tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets));
if (!tmp)
return AVERROR(ENOMEM);
mxf->metadata_sets = tmp;
mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
mxf->metadata_sets_count++;
return 0;
}
static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFCryptoContext *cryptocontext = arg;
if (size != 16)
return AVERROR_INVALIDDATA;
if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
avio_read(pb, cryptocontext->source_container_ul, 16);
return 0;
}
static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count)
{
*count = avio_rb32(pb);
*refs = av_calloc(*count, sizeof(UID));
if (!*refs) {
*count = 0;
return AVERROR(ENOMEM);
}
avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID));
return 0;
}
static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)
{
int ret;
size_t buf_size;
if (size < 0 || size > INT_MAX/2)
return AVERROR(EINVAL);
buf_size = size + size / 2 + 1;
*str = av_malloc(buf_size);
if (!*str)
return AVERROR(ENOMEM);
if (be)
ret = avio_get_str16be(pb, size, *str, buf_size);
else
ret = avio_get_str16le(pb, size, *str, buf_size);
if (ret < 0) {
av_freep(str);
return ret;
}
return ret;
}
#define READ_STR16(type, big_endian) \
static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \
{ \
return mxf_read_utf16_string(pb, size, str, big_endian); \
}
READ_STR16(be, 1)
READ_STR16(le, 0)
#undef READ_STR16
static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
switch (tag) {
case 0x1901:
if (mxf->packages_refs)
av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
av_free(mxf->packages_refs);
return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count);
}
return 0;
}
static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFStructuralComponent *source_clip = arg;
switch(tag) {
case 0x0202:
source_clip->duration = avio_rb64(pb);
break;
case 0x1201:
source_clip->start_position = avio_rb64(pb);
break;
case 0x1101:
/* UMID, only get last 16 bytes */
avio_read(pb, source_clip->source_package_ul, 16);
avio_read(pb, source_clip->source_package_uid, 16);
break;
case 0x1102:
source_clip->source_track_id = avio_rb32(pb);
break;
}
return 0;
}
static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFTimecodeComponent *mxf_timecode = arg;
switch(tag) {
case 0x1501:
mxf_timecode->start_frame = avio_rb64(pb);
break;
case 0x1502:
mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
break;
case 0x1503:
mxf_timecode->drop_frame = avio_r8(pb);
break;
}
return 0;
}
static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFPulldownComponent *mxf_pulldown = arg;
switch(tag) {
case 0x0d01:
avio_read(pb, mxf_pulldown->input_segment_ref, 16);
break;
}
return 0;
}
static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFTrack *track = arg;
switch(tag) {
case 0x4801:
track->track_id = avio_rb32(pb);
break;
case 0x4804:
avio_read(pb, track->track_number, 4);
break;
case 0x4802:
mxf_read_utf16be_string(pb, size, &track->name);
break;
case 0x4b01:
track->edit_rate.num = avio_rb32(pb);
track->edit_rate.den = avio_rb32(pb);
break;
case 0x4803:
avio_read(pb, track->sequence_ref, 16);
break;
}
return 0;
}
static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFSequence *sequence = arg;
switch(tag) {
case 0x0202:
sequence->duration = avio_rb64(pb);
break;
case 0x0201:
avio_read(pb, sequence->data_definition_ul, 16);
break;
case 0x4b02:
sequence->origin = avio_r8(pb);
break;
case 0x1001:
return mxf_read_strong_ref_array(pb, &sequence->structural_components_refs,
&sequence->structural_components_count);
}
return 0;
}
static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFEssenceGroup *essence_group = arg;
switch (tag) {
case 0x0202:
essence_group->duration = avio_rb64(pb);
break;
case 0x0501:
return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs,
&essence_group->structural_components_count);
}
return 0;
}
static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFPackage *package = arg;
switch(tag) {
case 0x4403:
return mxf_read_strong_ref_array(pb, &package->tracks_refs,
&package->tracks_count);
case 0x4401:
/* UMID */
avio_read(pb, package->package_ul, 16);
avio_read(pb, package->package_uid, 16);
break;
case 0x4701:
avio_read(pb, package->descriptor_ref, 16);
break;
case 0x4402:
return mxf_read_utf16be_string(pb, size, &package->name);
case 0x4406:
return mxf_read_strong_ref_array(pb, &package->comment_refs,
&package->comment_count);
}
return 0;
}
static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
{
int i, length;
segment->nb_index_entries = avio_rb32(pb);
length = avio_rb32(pb);
if(segment->nb_index_entries && length < 11)
return AVERROR_INVALIDDATA;
if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
!(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
!(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) {
av_freep(&segment->temporal_offset_entries);
av_freep(&segment->flag_entries);
return AVERROR(ENOMEM);
}
for (i = 0; i < segment->nb_index_entries; i++) {
if(avio_feof(pb))
return AVERROR_INVALIDDATA;
segment->temporal_offset_entries[i] = avio_r8(pb);
avio_r8(pb); /* KeyFrameOffset */
segment->flag_entries[i] = avio_r8(pb);
segment->stream_offset_entries[i] = avio_rb64(pb);
avio_skip(pb, length - 11);
}
return 0;
}
static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFIndexTableSegment *segment = arg;
switch(tag) {
case 0x3F05:
segment->edit_unit_byte_count = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
break;
case 0x3F06:
segment->index_sid = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid);
break;
case 0x3F07:
segment->body_sid = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid);
break;
case 0x3F0A:
av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n");
return mxf_read_index_entry_array(pb, segment);
case 0x3F0B:
segment->index_edit_rate.num = avio_rb32(pb);
segment->index_edit_rate.den = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
segment->index_edit_rate.den);
break;
case 0x3F0C:
segment->index_start_position = avio_rb64(pb);
av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
break;
case 0x3F0D:
segment->index_duration = avio_rb64(pb);
av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration);
break;
}
return 0;
}
static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
{
int code, value, ofs = 0;
char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
do {
code = avio_r8(pb);
value = avio_r8(pb);
av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code);
if (ofs <= 14) {
layout[ofs++] = code;
layout[ofs++] = value;
} else
break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
} while (code != 0); /* SMPTE 377M E.2.46 */
ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
}
static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFDescriptor *descriptor = arg;
int entry_count, entry_size;
switch(tag) {
case 0x3F01:
return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs,
&descriptor->sub_descriptors_count);
case 0x3002: /* ContainerDuration */
descriptor->duration = avio_rb64(pb);
break;
case 0x3004:
avio_read(pb, descriptor->essence_container_ul, 16);
break;
case 0x3005:
avio_read(pb, descriptor->codec_ul, 16);
break;
case 0x3006:
descriptor->linked_track_id = avio_rb32(pb);
break;
case 0x3201: /* PictureEssenceCoding */
avio_read(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3203:
descriptor->width = avio_rb32(pb);
break;
case 0x3202:
descriptor->height = avio_rb32(pb);
break;
case 0x320C:
descriptor->frame_layout = avio_r8(pb);
break;
case 0x320D:
entry_count = avio_rb32(pb);
entry_size = avio_rb32(pb);
if (entry_size == 4) {
if (entry_count > 0)
descriptor->video_line_map[0] = avio_rb32(pb);
else
descriptor->video_line_map[0] = 0;
if (entry_count > 1)
descriptor->video_line_map[1] = avio_rb32(pb);
else
descriptor->video_line_map[1] = 0;
} else
av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size);
break;
case 0x320E:
descriptor->aspect_ratio.num = avio_rb32(pb);
descriptor->aspect_ratio.den = avio_rb32(pb);
break;
case 0x3212:
descriptor->field_dominance = avio_r8(pb);
break;
case 0x3301:
descriptor->component_depth = avio_rb32(pb);
break;
case 0x3302:
descriptor->horiz_subsampling = avio_rb32(pb);
break;
case 0x3308:
descriptor->vert_subsampling = avio_rb32(pb);
break;
case 0x3D03:
descriptor->sample_rate.num = avio_rb32(pb);
descriptor->sample_rate.den = avio_rb32(pb);
break;
case 0x3D06: /* SoundEssenceCompression */
avio_read(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3D07:
descriptor->channels = avio_rb32(pb);
break;
case 0x3D01:
descriptor->bits_per_sample = avio_rb32(pb);
break;
case 0x3401:
mxf_read_pixel_layout(pb, descriptor);
break;
default:
/* Private uid used by SONY C0023S01.mxf */
if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
if (descriptor->extradata)
av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n");
av_free(descriptor->extradata);
descriptor->extradata_size = 0;
descriptor->extradata = av_malloc(size);
if (!descriptor->extradata)
return AVERROR(ENOMEM);
descriptor->extradata_size = size;
avio_read(pb, descriptor->extradata, size);
}
if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) {
uint32_t rsiz = avio_rb16(pb);
if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K ||
rsiz == FF_PROFILE_JPEG2000_DCINEMA_4K)
descriptor->pix_fmt = AV_PIX_FMT_XYZ12;
}
break;
}
return 0;
}
static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size)
{
MXFTaggedValue *tagged_value = arg;
uint8_t key[17];
if (size <= 17)
return 0;
avio_read(pb, key, 17);
/* TODO: handle other types of of indirect values */
if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) {
return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value);
} else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) {
return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value);
}
return 0;
}
static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFTaggedValue *tagged_value = arg;
switch (tag){
case 0x5001:
return mxf_read_utf16be_string(pb, size, &tagged_value->name);
case 0x5003:
return mxf_read_indirect_value(tagged_value, pb, size);
}
return 0;
}
/*
* Match an uid independently of the version byte and up to len common bytes
* Returns: boolean
*/
static int mxf_match_uid(const UID key, const UID uid, int len)
{
int i;
for (i = 0; i < len; i++) {
if (i != 7 && key[i] != uid[i])
return 0;
}
return 1;
}
static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
{
while (uls->uid[0]) {
if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
break;
uls++;
}
return uls;
}
static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
{
int i;
if (!strong_ref)
return NULL;
for (i = 0; i < mxf->metadata_sets_count; i++) {
if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
(type == AnyType || mxf->metadata_sets[i]->type == type)) {
return mxf->metadata_sets[i];
}
}
return NULL;
}
static const MXFCodecUL mxf_picture_essence_container_uls[] = {
// video essence container uls
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x10,0x60,0x01 }, 14, AV_CODEC_ID_H264 }, /* H.264 frame wrapped */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x12,0x01,0x00 }, 14, AV_CODEC_ID_VC1 }, /* VC-1 frame wrapped */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MPEG-ES frame wrapped */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* Type D-10 mapping of 40Mbps 525/60-I */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO }, /* uncompressed picture */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX },
{ { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
/* EC ULs for intra-only formats */
static const MXFCodecUL mxf_intra_only_essence_container_uls[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 mappings */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
/* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG 2000 code stream */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
/* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */
static const MXFCodecUL mxf_intra_only_picture_coded_width[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 },
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 },
};
static const MXFCodecUL mxf_sound_essence_container_uls[] = {
// sound essence container uls
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
{ { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG-2 AAC ADTS (legacy) */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
static const MXFCodecUL mxf_data_essence_container_uls[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, 0 },
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
static const char* const mxf_data_essence_descriptor[] = {
"vbi_vanc_smpte_436M",
};
static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
{
int i, j, nb_segments = 0;
MXFIndexTableSegment **unsorted_segments;
int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
/* count number of segments, allocate arrays and copy unsorted segments */
for (i = 0; i < mxf->metadata_sets_count; i++)
if (mxf->metadata_sets[i]->type == IndexTableSegment)
nb_segments++;
if (!nb_segments)
return AVERROR_INVALIDDATA;
if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
!(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
av_freep(sorted_segments);
av_free(unsorted_segments);
return AVERROR(ENOMEM);
}
for (i = j = 0; i < mxf->metadata_sets_count; i++)
if (mxf->metadata_sets[i]->type == IndexTableSegment)
unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
*nb_sorted_segments = 0;
/* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
for (i = 0; i < nb_segments; i++) {
int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
uint64_t best_index_duration = 0;
for (j = 0; j < nb_segments; j++) {
MXFIndexTableSegment *s = unsorted_segments[j];
/* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
* We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
* If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
*/
if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
(best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start ||
(s->index_start_position == best_index_start && s->index_duration > best_index_duration))) {
best = j;
best_body_sid = s->body_sid;
best_index_sid = s->index_sid;
best_index_start = s->index_start_position;
best_index_duration = s->index_duration;
}
}
/* no suitable entry found -> we're done */
if (best == -1)
break;
(*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
last_body_sid = best_body_sid;
last_index_sid = best_index_sid;
last_index_start = best_index_start;
}
av_free(unsorted_segments);
return 0;
}
/**
* Computes the absolute file offset of the given essence container offset
*/
static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
{
int x;
int64_t offset_in = offset; /* for logging */
for (x = 0; x < mxf->partitions_count; x++) {
MXFPartition *p = &mxf->partitions[x];
if (p->body_sid != body_sid)
continue;
if (offset < p->essence_length || !p->essence_length) {
*offset_out = p->essence_offset + offset;
return 0;
}
offset -= p->essence_length;
}
av_log(mxf->fc, AV_LOG_ERROR,
"failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
offset_in, body_sid);
return AVERROR_INVALIDDATA;
}
/**
* Returns the end position of the essence container with given BodySID, or zero if unknown
*/
static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
{
int x;
int64_t ret = 0;
for (x = 0; x < mxf->partitions_count; x++) {
MXFPartition *p = &mxf->partitions[x];
if (p->body_sid != body_sid)
continue;
if (!p->essence_length)
return 0;
ret = p->essence_offset + p->essence_length;
}
return ret;
}
/* EditUnit -> absolute offset */
static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag)
{
int i;
int64_t offset_temp = 0;
for (i = 0; i < index_table->nb_segments; i++) {
MXFIndexTableSegment *s = index_table->segments[i];
edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
if (edit_unit < s->index_start_position + s->index_duration) {
int64_t index = edit_unit - s->index_start_position;
if (s->edit_unit_byte_count)
offset_temp += s->edit_unit_byte_count * index;
else if (s->nb_index_entries) {
if (s->nb_index_entries == 2 * s->index_duration + 1)
index *= 2; /* Avid index */
if (index < 0 || index >= s->nb_index_entries) {
av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
index_table->index_sid, s->index_start_position);
return AVERROR_INVALIDDATA;
}
offset_temp = s->stream_offset_entries[index];
} else {
av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
index_table->index_sid, s->index_start_position);
return AVERROR_INVALIDDATA;
}
if (edit_unit_out)
*edit_unit_out = edit_unit;
return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
} else {
/* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
offset_temp += s->edit_unit_byte_count * s->index_duration;
}
}
if (nag)
av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid);
return AVERROR_INVALIDDATA;
}
static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
{
int i, j, x;
int8_t max_temporal_offset = -128;
uint8_t *flags;
/* first compute how many entries we have */
for (i = 0; i < index_table->nb_segments; i++) {
MXFIndexTableSegment *s = index_table->segments[i];
if (!s->nb_index_entries) {
index_table->nb_ptses = 0;
return 0; /* no TemporalOffsets */
}
index_table->nb_ptses += s->index_duration;
}
/* paranoid check */
if (index_table->nb_ptses <= 0)
return 0;
if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
!(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) ||
!(index_table->offsets = av_calloc(index_table->nb_ptses, sizeof(int8_t))) ||
!(flags = av_calloc(index_table->nb_ptses, sizeof(uint8_t)))) {
av_freep(&index_table->ptses);
av_freep(&index_table->fake_index);
av_freep(&index_table->offsets);
return AVERROR(ENOMEM);
}
/* we may have a few bad TemporalOffsets
* make sure the corresponding PTSes don't have the bogus value 0 */
for (x = 0; x < index_table->nb_ptses; x++)
index_table->ptses[x] = AV_NOPTS_VALUE;
/**
* We have this:
*
* x TemporalOffset
* 0: 0
* 1: 1
* 2: 1
* 3: -2
* 4: 1
* 5: 1
* 6: -2
*
* We want to transform it into this:
*
* x DTS PTS
* 0: -1 0
* 1: 0 3
* 2: 1 1
* 3: 2 2
* 4: 3 6
* 5: 4 4
* 6: 5 5
*
* We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
* then settings mxf->first_dts = -max(TemporalOffset[x]).
* The latter makes DTS <= PTS.
*/
for (i = x = 0; i < index_table->nb_segments; i++) {
MXFIndexTableSegment *s = index_table->segments[i];
int index_delta = 1;
int n = s->nb_index_entries;
if (s->nb_index_entries == 2 * s->index_duration + 1) {
index_delta = 2; /* Avid index */
/* ignore the last entry - it's the size of the essence container */
n--;
}
for (j = 0; j < n; j += index_delta, x++) {
int offset = s->temporal_offset_entries[j] / index_delta;
int index = x + offset;
if (x >= index_table->nb_ptses) {
av_log(mxf->fc, AV_LOG_ERROR,
"x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
s->nb_index_entries, s->index_duration);
break;
}
flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
if (index < 0 || index >= index_table->nb_ptses) {
av_log(mxf->fc, AV_LOG_ERROR,
"index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
x, offset, index);
continue;
}
index_table->offsets[x] = offset;
index_table->ptses[index] = x;
max_temporal_offset = FFMAX(max_temporal_offset, offset);
}
}
/* calculate the fake index table in display order */
for (x = 0; x < index_table->nb_ptses; x++) {
index_table->fake_index[x].timestamp = x;
if (index_table->ptses[x] != AV_NOPTS_VALUE)
index_table->fake_index[index_table->ptses[x]].flags = flags[x];
}
av_freep(&flags);
index_table->first_dts = -max_temporal_offset;
return 0;
}
/**
* Sorts and collects index table segments into index tables.
* Also computes PTSes if possible.
*/
static int mxf_compute_index_tables(MXFContext *mxf)
{
int i, j, k, ret, nb_sorted_segments;
MXFIndexTableSegment **sorted_segments = NULL;
AVStream *st = NULL;
for (i = 0; i < mxf->fc->nb_streams; i++) {
if (mxf->fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA)
continue;
st = mxf->fc->streams[i];
break;
}
if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
nb_sorted_segments <= 0) {
av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
return 0;
}
/* sanity check and count unique BodySIDs/IndexSIDs */
for (i = 0; i < nb_sorted_segments; i++) {
if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
mxf->nb_index_tables++;
else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
ret = AVERROR_INVALIDDATA;
goto finish_decoding_index;
}
}
mxf->index_tables = av_mallocz_array(mxf->nb_index_tables,
sizeof(*mxf->index_tables));
if (!mxf->index_tables) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
ret = AVERROR(ENOMEM);
goto finish_decoding_index;
}
/* distribute sorted segments to index tables */
for (i = j = 0; i < nb_sorted_segments; i++) {
if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
/* next IndexSID */
j++;
}
mxf->index_tables[j].nb_segments++;
}
for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
MXFIndexTable *t = &mxf->index_tables[j];
t->segments = av_mallocz_array(t->nb_segments,
sizeof(*t->segments));
if (!t->segments) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
" pointer array\n");
ret = AVERROR(ENOMEM);
goto finish_decoding_index;
}
if (sorted_segments[i]->index_start_position)
av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
t->index_sid = sorted_segments[i]->index_sid;
t->body_sid = sorted_segments[i]->body_sid;
if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
goto finish_decoding_index;
/* fix zero IndexDurations */
for (k = 0; k < t->nb_segments; k++) {
if (t->segments[k]->index_duration)
continue;
if (t->nb_segments > 1)
av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
t->index_sid, k);
if (!st) {
av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
break;
}
/* assume the first stream's duration is reasonable
* leave index_duration = 0 on further segments in case we have any (unlikely)
*/
t->segments[k]->index_duration = st->duration;
break;
}
}
ret = 0;
finish_decoding_index:
av_free(sorted_segments);
return ret;
}
static int mxf_is_intra_only(MXFDescriptor *descriptor)
{
return mxf_get_codec_ul(mxf_intra_only_essence_container_uls,
&descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls,
&descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE;
}
static int mxf_uid_to_str(UID uid, char **str)
{
int i;
char *p;
p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1);
if (!p)
return AVERROR(ENOMEM);
for (i = 0; i < sizeof(UID); i++) {
snprintf(p, 2 + 1, "%.2x", uid[i]);
p += 2;
if (i == 3 || i == 5 || i == 7 || i == 9) {
snprintf(p, 1 + 1, "-");
p++;
}
}
return 0;
}
static int mxf_umid_to_str(UID ul, UID uid, char **str)
{
int i;
char *p;
p = *str = av_mallocz(sizeof(UID) * 4 + 2 + 1);
if (!p)
return AVERROR(ENOMEM);
snprintf(p, 2 + 1, "0x");
p += 2;
for (i = 0; i < sizeof(UID); i++) {
snprintf(p, 2 + 1, "%.2X", ul[i]);
p += 2;
}
for (i = 0; i < sizeof(UID); i++) {
snprintf(p, 2 + 1, "%.2X", uid[i]);
p += 2;
}
return 0;
}
static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package)
{
char *str;
int ret;
if (!package)
return 0;
if ((ret = mxf_umid_to_str(package->package_ul, package->package_uid, &str)) < 0)
return ret;
av_dict_set(pm, key, str, AV_DICT_DONT_STRDUP_VAL);
return 0;
}
static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
{
char buf[AV_TIMECODE_STR_SIZE];
av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
return 0;
}
static MXFTimecodeComponent* mxf_resolve_timecode_component(MXFContext *mxf, UID *strong_ref)
{
MXFStructuralComponent *component = NULL;
MXFPulldownComponent *pulldown = NULL;
component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
if (!component)
return NULL;
switch (component->type) {
case TimecodeComponent:
return (MXFTimecodeComponent*)component;
case PulldownComponent: /* timcode component may be located on a pulldown component */
pulldown = (MXFPulldownComponent*)component;
return mxf_resolve_strong_ref(mxf, &pulldown->input_segment_ref, TimecodeComponent);
default:
break;
}
return NULL;
}
static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_uid)
{
MXFPackage *package = NULL;
int i;
for (i = 0; i < mxf->packages_count; i++) {
package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage);
if (!package)
continue;
if (!memcmp(package->package_uid, package_uid, 16))
return package;
}
return NULL;
}
static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id)
{
MXFDescriptor *sub_descriptor = NULL;
int i;
if (!descriptor)
return NULL;
if (descriptor->type == MultipleDescriptor) {
for (i = 0; i < descriptor->sub_descriptors_count; i++) {
sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], Descriptor);
if (!sub_descriptor) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
continue;
}
if (sub_descriptor->linked_track_id == track_id) {
return sub_descriptor;
}
}
} else if (descriptor->type == Descriptor)
return descriptor;
return NULL;
}
static MXFStructuralComponent* mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group)
{
MXFStructuralComponent *component = NULL;
MXFPackage *package = NULL;
MXFDescriptor *descriptor = NULL;
int i;
if (!essence_group || !essence_group->structural_components_count)
return NULL;
/* essence groups contains multiple representations of the same media,
this return the first components with a valid Descriptor typically index 0 */
for (i =0; i < essence_group->structural_components_count; i++){
component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip);
if (!component)
continue;
if (!(package = mxf_resolve_source_package(mxf, component->source_package_uid)))
continue;
descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor);
if (descriptor)
return component;
}
return NULL;
}
static MXFStructuralComponent* mxf_resolve_sourceclip(MXFContext *mxf, UID *strong_ref)
{
MXFStructuralComponent *component = NULL;
component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
if (!component)
return NULL;
switch (component->type) {
case SourceClip:
return component;
case EssenceGroup:
return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component);
default:
break;
}
return NULL;
}
static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package)
{
MXFTaggedValue *tag;
int size, i;
char *key = NULL;
for (i = 0; i < package->comment_count; i++) {
tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue);
if (!tag || !tag->name || !tag->value)
continue;
size = strlen(tag->name) + 8 + 1;
key = av_mallocz(size);
if (!key)
return AVERROR(ENOMEM);
snprintf(key, size, "comment_%s", tag->name);
av_dict_set(pm, key, tag->value, AV_DICT_DONT_STRDUP_KEY);
}
return 0;
}
static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st)
{
MXFPackage *physical_package = NULL;
MXFTrack *physical_track = NULL;
MXFStructuralComponent *sourceclip = NULL;
MXFTimecodeComponent *mxf_tc = NULL;
int i, j, k;
AVTimecode tc;
int flags;
int64_t start_position;
for (i = 0; i < source_track->sequence->structural_components_count; i++) {
sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);
if (!sourceclip)
continue;
if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_uid)))
break;
mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package);
/* the name of physical source package is name of the reel or tape */
if (physical_package->name && physical_package->name[0])
av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);
/* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track
* to the start_frame of the timecode component located on one of the tracks of the physical source package.
*/
for (j = 0; j < physical_package->tracks_count; j++) {
if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
continue;
}
if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
continue;
}
if (physical_track->edit_rate.num <= 0 ||
physical_track->edit_rate.den <= 0) {
av_log(mxf->fc, AV_LOG_WARNING,
"Invalid edit rate (%d/%d) found on structural"
" component #%d, defaulting to 25/1\n",
physical_track->edit_rate.num,
physical_track->edit_rate.den, i);
physical_track->edit_rate = (AVRational){25, 1};
}
for (k = 0; k < physical_track->sequence->structural_components_count; k++) {
if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k])))
continue;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
/* scale sourceclip start_position to match physical track edit rate */
start_position = av_rescale_q(sourceclip->start_position,
physical_track->edit_rate,
source_track->edit_rate);
if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);
return 0;
}
}
}
}
return 0;
}
static int mxf_add_metadata_stream(MXFContext *mxf, MXFTrack *track)
{
MXFStructuralComponent *component = NULL;
const MXFCodecUL *codec_ul = NULL;
MXFPackage tmp_package;
AVStream *st;
int j;
for (j = 0; j < track->sequence->structural_components_count; j++) {
component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]);
if (!component)
continue;
break;
}
if (!component)
return 0;
st = avformat_new_stream(mxf->fc, NULL);
if (!st) {
av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n");
return AVERROR(ENOMEM);
}
st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
st->codecpar->codec_id = AV_CODEC_ID_NONE;
st->id = track->track_id;
memcpy(&tmp_package.package_ul, component->source_package_ul, 16);
memcpy(&tmp_package.package_uid, component->source_package_uid, 16);
mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package);
if (track->name && track->name[0])
av_dict_set(&st->metadata, "track_name", track->name, 0);
codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &track->sequence->data_definition_ul);
av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0);
return 0;
}
static int mxf_parse_structural_metadata(MXFContext *mxf)
{
MXFPackage *material_package = NULL;
int i, j, k, ret;
av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
/* TODO: handle multiple material packages (OP3x) */
for (i = 0; i < mxf->packages_count; i++) {
material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
if (material_package) break;
}
if (!material_package) {
av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
return AVERROR_INVALIDDATA;
}
mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
if (material_package->name && material_package->name[0])
av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
for (i = 0; i < material_package->tracks_count; i++) {
MXFPackage *source_package = NULL;
MXFTrack *material_track = NULL;
MXFTrack *source_track = NULL;
MXFTrack *temp_track = NULL;
MXFDescriptor *descriptor = NULL;
MXFStructuralComponent *component = NULL;
MXFTimecodeComponent *mxf_tc = NULL;
UID *essence_container_ul = NULL;
const MXFCodecUL *codec_ul = NULL;
const MXFCodecUL *container_ul = NULL;
const MXFCodecUL *pix_fmt_ul = NULL;
AVStream *st;
AVTimecode tc;
int flags;
if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
continue;
}
if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
}
}
if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
continue;
}
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
if (!component)
continue;
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
break;
}
}
/* TODO: handle multiple source clips, only finds first valid source clip */
if(material_track->sequence->structural_components_count > 1)
av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
material_track->track_id, material_track->sequence->structural_components_count);
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
if (!component)
continue;
source_package = mxf_resolve_source_package(mxf, component->source_package_uid);
if (!source_package) {
av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
break;
}
for (k = 0; k < source_package->tracks_count; k++) {
if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
if (temp_track->track_id == component->source_track_id) {
source_track = temp_track;
break;
}
}
if (!source_track) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
break;
}
if(source_track && component)
break;
}
if (!source_track || !component || !source_package) {
if((ret = mxf_add_metadata_stream(mxf, material_track)))
goto fail_and_free;
continue;
}
if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
/* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
* This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
continue;
}
st = avformat_new_stream(mxf->fc, NULL);
if (!st) {
av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
ret = AVERROR(ENOMEM);
goto fail_and_free;
}
st->id = material_track->track_id;
st->priv_data = source_track;
source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id);
/* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
* frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
else
source_track->original_duration = st->duration = component->duration;
if (st->duration == -1)
st->duration = AV_NOPTS_VALUE;
st->start_time = component->start_position;
if (material_track->edit_rate.num <= 0 ||
material_track->edit_rate.den <= 0) {
av_log(mxf->fc, AV_LOG_WARNING,
"Invalid edit rate (%d/%d) found on stream #%d, "
"defaulting to 25/1\n",
material_track->edit_rate.num,
material_track->edit_rate.den, st->index);
material_track->edit_rate = (AVRational){25, 1};
}
avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
/* ensure SourceTrack EditRate == MaterialTrack EditRate since only
* the former is accessible via st->priv_data */
source_track->edit_rate = material_track->edit_rate;
PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
st->codecpar->codec_type = codec_ul->id;
if (!descriptor) {
av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
continue;
}
PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
essence_container_ul = &descriptor->essence_container_ul;
/* HACK: replacing the original key with mxf_encrypted_essence_container
* is not allowed according to s429-6, try to find correct information anyway */
if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
for (k = 0; k < mxf->metadata_sets_count; k++) {
MXFMetadataSet *metadata = mxf->metadata_sets[k];
if (metadata->type == CryptoContext) {
essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
break;
}
}
}
/* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
}
av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
avcodec_get_name(st->codecpar->codec_id));
for (k = 0; k < 16; k++) {
av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
descriptor->essence_codec_ul[k]);
if (!(k+1 & 19) || k == 5)
av_log(mxf->fc, AV_LOG_VERBOSE, ".");
}
av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
if (source_package->name && source_package->name[0])
av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
if (material_track->name && material_track->name[0])
av_dict_set(&st->metadata, "track_name", material_track->name, 0);
mxf_parse_physical_source_package(mxf, source_track, st);
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
source_track->intra_only = mxf_is_intra_only(descriptor);
container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
st->codecpar->width = descriptor->width;
st->codecpar->height = descriptor->height; /* Field height, not frame height */
switch (descriptor->frame_layout) {
case FullFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
break;
case OneField:
/* Every other line is stored and needs to be duplicated. */
av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
break; /* The correct thing to do here is fall through, but by breaking we might be
able to decode some streams at half the vertical resolution, rather than not al all.
It's also for compatibility with the old behavior. */
case MixedFields:
break;
case SegmentedFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
case SeparateFields:
av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
descriptor->video_line_map[0], descriptor->video_line_map[1],
descriptor->field_dominance);
if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
/* Detect coded field order from VideoLineMap:
* (even, even) => bottom field coded first
* (even, odd) => top field coded first
* (odd, even) => top field coded first
* (odd, odd) => bottom field coded first
*/
if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_TT;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_TB;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
} else {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_BB;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_BT;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
}
}
/* Turn field height into frame height. */
st->codecpar->height *= 2;
break;
default:
av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
}
if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
st->codecpar->format = descriptor->pix_fmt;
if (st->codecpar->format == AV_PIX_FMT_NONE) {
pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
&descriptor->essence_codec_ul);
st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
if (st->codecpar->format== AV_PIX_FMT_NONE) {
st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls,
&descriptor->essence_codec_ul)->id;
if (!st->codecpar->codec_tag) {
/* support files created before RP224v10 by defaulting to UYVY422
if subsampling is 4:2:2 and component depth is 8-bit */
if (descriptor->horiz_subsampling == 2 &&
descriptor->vert_subsampling == 1 &&
descriptor->component_depth == 8) {
st->codecpar->format = AV_PIX_FMT_UYVY422;
}
}
}
}
}
st->need_parsing = AVSTREAM_PARSE_HEADERS;
if (material_track->sequence->origin) {
av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
}
if (source_track->sequence->origin) {
av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
}
if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
st->display_aspect_ratio = descriptor->aspect_ratio;
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
/* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE))
st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
st->codecpar->channels = descriptor->channels;
st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample;
if (descriptor->sample_rate.den > 0) {
st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
} else {
av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
"found for stream #%d, time base forced to 1/48000\n",
descriptor->sample_rate.num, descriptor->sample_rate.den,
st->index);
avpriv_set_pts_info(st, 64, 1, 48000);
}
/* if duration is set, rescale it from EditRate to SampleRate */
if (st->duration != AV_NOPTS_VALUE)
st->duration = av_rescale_q(st->duration,
av_inv_q(material_track->edit_rate),
st->time_base);
/* TODO: implement AV_CODEC_ID_RAWAUDIO */
if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
st->need_parsing = AVSTREAM_PARSE_FULL;
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
int codec_id = mxf_get_codec_ul(mxf_data_essence_container_uls,
essence_container_ul)->id;
if (codec_id >= 0 &&
codec_id < FF_ARRAY_ELEMS(mxf_data_essence_descriptor)) {
av_dict_set(&st->metadata, "data_type",
mxf_data_essence_descriptor[codec_id], 0);
}
}
if (descriptor->extradata) {
if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
}
} else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width,
&descriptor->essence_codec_ul)->id;
if (coded_width)
st->codecpar->width = coded_width;
ret = ff_generate_avci_extradata(st);
if (ret < 0)
return ret;
}
if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
/* TODO: decode timestamps */
st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
}
}
ret = 0;
fail_and_free:
return ret;
}
static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
{
struct tm time = { 0 };
time.tm_year = (timestamp >> 48) - 1900;
time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
time.tm_mday = (timestamp >> 32 & 0xFF);
time.tm_hour = (timestamp >> 24 & 0xFF);
time.tm_min = (timestamp >> 16 & 0xFF);
time.tm_sec = (timestamp >> 8 & 0xFF);
/* msvcrt versions of strftime calls the invalid parameter handler
* (aborting the process if one isn't set) if the parameters are out
* of range. */
time.tm_mon = av_clip(time.tm_mon, 0, 11);
time.tm_mday = av_clip(time.tm_mday, 1, 31);
time.tm_hour = av_clip(time.tm_hour, 0, 23);
time.tm_min = av_clip(time.tm_min, 0, 59);
time.tm_sec = av_clip(time.tm_sec, 0, 59);
return (int64_t)av_timegm(&time) * 1000000;
}
#define SET_STR_METADATA(pb, name, str) do { \
if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \
return ret; \
av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
} while (0)
#define SET_UID_METADATA(pb, name, var, str) do { \
avio_read(pb, var, 16); \
if ((ret = mxf_uid_to_str(var, &str)) < 0) \
return ret; \
av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
} while (0)
#define SET_TS_METADATA(pb, name, var, str) do { \
var = avio_rb64(pb); \
if ((ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var)) < 0)) \
return ret; \
} while (0)
static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
AVFormatContext *s = mxf->fc;
int ret;
UID uid = { 0 };
char *str = NULL;
uint64_t ts;
switch (tag) {
case 0x3C01:
SET_STR_METADATA(pb, "company_name", str);
break;
case 0x3C02:
SET_STR_METADATA(pb, "product_name", str);
break;
case 0x3C04:
SET_STR_METADATA(pb, "product_version", str);
break;
case 0x3C05:
SET_UID_METADATA(pb, "product_uid", uid, str);
break;
case 0x3C06:
SET_TS_METADATA(pb, "modification_date", ts, str);
break;
case 0x3C08:
SET_STR_METADATA(pb, "application_platform", str);
break;
case 0x3C09:
SET_UID_METADATA(pb, "generation_uid", uid, str);
break;
case 0x3C0A:
SET_UID_METADATA(pb, "uid", uid, str);
break;
}
return 0;
}
static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
AVFormatContext *s = mxf->fc;
int ret;
char *str = NULL;
if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) {
SET_STR_METADATA(pb, "project_name", str);
}
return 0;
}
static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
{ { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup},
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VANC/VBI - SMPTE 436M */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
};
static int mxf_metadataset_init(MXFMetadataSet *ctx, enum MXFMetadataSetType type)
{
switch (type){
case MultipleDescriptor:
case Descriptor:
((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE;
((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE;
break;
default:
break;
}
return 0;
}
static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
{
AVIOContext *pb = mxf->fc->pb;
MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
uint64_t klv_end = avio_tell(pb) + klv->length;
if (!ctx)
return AVERROR(ENOMEM);
mxf_metadataset_init(ctx, type);
while (avio_tell(pb) + 4 < klv_end && !avio_feof(pb)) {
int ret;
int tag = avio_rb16(pb);
int size = avio_rb16(pb); /* KLV specified by 0x53 */
uint64_t next = avio_tell(pb) + size;
UID uid = {0};
av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size);
if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
continue;
}
if (tag > 0x7FFF) { /* dynamic tag */
int i;
for (i = 0; i < mxf->local_tags_count; i++) {
int local_tag = AV_RB16(mxf->local_tags+i*18);
if (local_tag == tag) {
memcpy(uid, mxf->local_tags+i*18+2, 16);
av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag);
PRINT_KEY(mxf->fc, "uid", uid);
}
}
}
if (ctx_size && tag == 0x3C0A) {
avio_read(pb, ctx->uid, 16);
} else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) {
mxf_free_metadataset(&ctx, !!ctx_size);
return ret;
}
/* Accept the 64k local set limit being exceeded (Avid). Don't accept
* it extending past the end of the KLV though (zzuf5.mxf). */
if (avio_tell(pb) > klv_end) {
if (ctx_size) {
ctx->type = type;
mxf_free_metadataset(&ctx, !!ctx_size);
}
av_log(mxf->fc, AV_LOG_ERROR,
"local tag %#04x extends past end of local set @ %#"PRIx64"\n",
tag, klv->offset);
return AVERROR_INVALIDDATA;
} else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
avio_seek(pb, next, SEEK_SET);
}
if (ctx_size) ctx->type = type;
return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
}
/**
* Matches any partition pack key, in other words:
* - HeaderPartition
* - BodyPartition
* - FooterPartition
* @return non-zero if the key is a partition pack key, zero otherwise
*/
static int mxf_is_partition_pack_key(UID key)
{
//NOTE: this is a little lax since it doesn't constraint key[14]
return !memcmp(key, mxf_header_partition_pack_key, 13) &&
key[13] >= 2 && key[13] <= 4;
}
/**
* Parses a metadata KLV
* @return <0 on error, 0 otherwise
*/
static int mxf_parse_klv(MXFContext *mxf, KLVPacket klv, MXFMetadataReadFunc *read,
int ctx_size, enum MXFMetadataSetType type)
{
AVFormatContext *s = mxf->fc;
int res;
if (klv.key[5] == 0x53) {
res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type);
} else {
uint64_t next = avio_tell(s->pb) + klv.length;
res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
/* only seek forward, else this can loop for a long time */
if (avio_tell(s->pb) > next) {
av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
klv.offset);
return AVERROR_INVALIDDATA;
}
avio_seek(s->pb, next, SEEK_SET);
}
if (res < 0) {
av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
return res;
}
return 0;
}
/**
* Seeks to the previous partition and parses it, if possible
* @return <= 0 if we should stop parsing, > 0 if we should keep going
*/
static int mxf_seek_to_previous_partition(MXFContext *mxf)
{
AVIOContext *pb = mxf->fc->pb;
KLVPacket klv;
int64_t current_partition_ofs;
int ret;
if (!mxf->current_partition ||
mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
return 0; /* we've parsed all partitions */
/* seek to previous partition */
current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in
avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
mxf->current_partition = NULL;
av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n");
/* Make sure this is actually a PartitionPack, and if so parse it.
* See deadlock2.mxf
*/
if ((ret = klv_read_packet(&klv, pb)) < 0) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n");
return ret;
}
if (!mxf_is_partition_pack_key(klv.key)) {
av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset);
return AVERROR_INVALIDDATA;
}
/* We can't just check ofs >= current_partition_ofs because PreviousPartition
* can point to just before the current partition, causing klv_read_packet()
* to sync back up to it. See deadlock3.mxf
*/
if (klv.offset >= current_partition_ofs) {
av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %"
PRIx64 " indirectly points to itself\n", current_partition_ofs);
return AVERROR_INVALIDDATA;
}
if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0)
return ret;
return 1;
}
/**
* Called when essence is encountered
* @return <= 0 if we should stop parsing, > 0 if we should keep going
*/
static int mxf_parse_handle_essence(MXFContext *mxf)
{
AVIOContext *pb = mxf->fc->pb;
int64_t ret;
if (mxf->parsing_backward) {
return mxf_seek_to_previous_partition(mxf);
} else {
if (!mxf->footer_partition) {
av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n");
return 0;
}
av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n");
/* remember where we were so we don't end up seeking further back than this */
mxf->last_forward_tell = avio_tell(pb);
if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n");
return -1;
}
/* seek to FooterPartition and parse backward */
if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
av_log(mxf->fc, AV_LOG_ERROR,
"failed to seek to FooterPartition @ 0x%" PRIx64
" (%"PRId64") - partial file?\n",
mxf->run_in + mxf->footer_partition, ret);
return ret;
}
mxf->current_partition = NULL;
mxf->parsing_backward = 1;
}
return 1;
}
/**
* Called when the next partition or EOF is encountered
* @return <= 0 if we should stop parsing, > 0 if we should keep going
*/
static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
{
return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
}
/**
* Figures out the proper offset and length of the essence container in each partition
*/
static void mxf_compute_essence_containers(MXFContext *mxf)
{
int x;
/* everything is already correct */
if (mxf->op == OPAtom)
return;
for (x = 0; x < mxf->partitions_count; x++) {
MXFPartition *p = &mxf->partitions[x];
if (!p->body_sid)
continue; /* BodySID == 0 -> no essence */
if (x >= mxf->partitions_count - 1)
break; /* FooterPartition - can't compute length (and we don't need to) */
/* essence container spans to the next partition */
p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
if (p->essence_length < 0) {
/* next ThisPartition < essence_offset */
p->essence_length = 0;
av_log(mxf->fc, AV_LOG_ERROR,
"partition %i: bad ThisPartition = %"PRIX64"\n",
x+1, mxf->partitions[x+1].this_partition);
}
}
}
static int64_t round_to_kag(int64_t position, int kag_size)
{
/* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
/* NOTE: kag_size may be any integer between 1 - 2^10 */
int64_t ret = (position / kag_size) * kag_size;
return ret == position ? ret : ret + kag_size;
}
static int is_pcm(enum AVCodecID codec_id)
{
/* we only care about "normal" PCM codecs until we get samples */
return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD;
}
static AVStream* mxf_get_opatom_stream(MXFContext *mxf)
{
int i;
if (mxf->op != OPAtom)
return NULL;
for (i = 0; i < mxf->fc->nb_streams; i++) {
if (mxf->fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA)
continue;
return mxf->fc->streams[i];
}
return NULL;
}
/**
* Deal with the case where for some audio atoms EditUnitByteCount is
* very small (2, 4..). In those cases we should read more than one
* sample per call to mxf_read_packet().
*/
static void mxf_handle_small_eubc(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
/* assuming non-OPAtom == frame wrapped
* no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */
AVStream *st = mxf_get_opatom_stream(mxf);
if (!st)
return;
/* expect PCM with exactly one index table segment and a small (< 32) EUBC */
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
!is_pcm(st->codecpar->codec_id) ||
mxf->nb_index_tables != 1 ||
mxf->index_tables[0].nb_segments != 1 ||
mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32)
return;
/* arbitrarily default to 48 kHz PAL audio frame size */
/* TODO: We could compute this from the ratio between the audio
* and video edit rates for 48 kHz NTSC we could use the
* 1802-1802-1802-1802-1801 pattern. */
mxf->edit_units_per_packet = 1920;
}
/**
* Deal with the case where OPAtom files does not have any IndexTableSegments.
*/
static int mxf_handle_missing_index_segment(MXFContext *mxf)
{
AVFormatContext *s = mxf->fc;
AVStream *st = NULL;
MXFIndexTableSegment *segment = NULL;
MXFPartition *p = NULL;
int essence_partition_count = 0;
int i, ret;
st = mxf_get_opatom_stream(mxf);
if (!st)
return 0;
/* TODO: support raw video without an index if they exist */
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || !is_pcm(st->codecpar->codec_id))
return 0;
/* check if file already has a IndexTableSegment */
for (i = 0; i < mxf->metadata_sets_count; i++) {
if (mxf->metadata_sets[i]->type == IndexTableSegment)
return 0;
}
/* find the essence partition */
for (i = 0; i < mxf->partitions_count; i++) {
/* BodySID == 0 -> no essence */
if (!mxf->partitions[i].body_sid)
continue;
p = &mxf->partitions[i];
essence_partition_count++;
}
/* only handle files with a single essence partition */
if (essence_partition_count != 1)
return 0;
if (!(segment = av_mallocz(sizeof(*segment))))
return AVERROR(ENOMEM);
if ((ret = mxf_add_metadata_set(mxf, segment))) {
mxf_free_metadataset((MXFMetadataSet**)&segment, 1);
return ret;
}
segment->type = IndexTableSegment;
/* stream will be treated as small EditUnitByteCount */
segment->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
segment->index_start_position = 0;
segment->index_duration = s->streams[0]->duration;
segment->index_sid = p->index_sid;
segment->body_sid = p->body_sid;
return 0;
}
static void mxf_read_random_index_pack(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
uint32_t length;
int64_t file_size, max_rip_length, min_rip_length;
KLVPacket klv;
if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
return;
file_size = avio_size(s->pb);
/* S377m says to check the RIP length for "silly" values, without defining "silly".
* The limit below assumes a file with nothing but partition packs and a RIP.
* Before changing this, consider that a muxer may place each sample in its own partition.
*
* 105 is the size of the smallest possible PartitionPack
* 12 is the size of each RIP entry
* 28 is the size of the RIP header and footer, assuming an 8-byte BER
*/
max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28;
max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly
/* We're only interested in RIPs with at least two entries.. */
min_rip_length = 16+1+24+4;
/* See S377m section 11 */
avio_seek(s->pb, file_size - 4, SEEK_SET);
length = avio_rb32(s->pb);
if (length < min_rip_length || length > max_rip_length)
goto end;
avio_seek(s->pb, file_size - length, SEEK_SET);
if (klv_read_packet(&klv, s->pb) < 0 ||
!IS_KLV_KEY(klv.key, mxf_random_index_pack_key) ||
klv.length != length - 20)
goto end;
avio_skip(s->pb, klv.length - 12);
mxf->footer_partition = avio_rb64(s->pb);
/* sanity check */
if (mxf->run_in + mxf->footer_partition >= file_size) {
av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n");
mxf->footer_partition = 0;
}
end:
avio_seek(s->pb, mxf->run_in, SEEK_SET);
}
static int mxf_read_header(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
KLVPacket klv;
int64_t essence_offset = 0;
int ret;
mxf->last_forward_tell = INT64_MAX;
mxf->edit_units_per_packet = 1;
if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
return AVERROR_INVALIDDATA;
}
avio_seek(s->pb, -14, SEEK_CUR);
mxf->fc = s;
mxf->run_in = avio_tell(s->pb);
mxf_read_random_index_pack(s);
while (!avio_feof(s->pb)) {
const MXFMetadataReadTableEntry *metadata;
if (klv_read_packet(&klv, s->pb) < 0) {
/* EOF - seek to previous partition or stop */
if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
break;
else
continue;
}
PRINT_KEY(s, "read header", klv.key);
av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_system_item_key)) {
if (!mxf->current_partition) {
av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
return AVERROR_INVALIDDATA;
}
if (!mxf->current_partition->essence_offset) {
/* for OP1a we compute essence_offset
* for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
* TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
* for OPAtom we still need the actual essence_offset though (the KL's length can vary)
*/
int64_t op1a_essence_offset =
round_to_kag(mxf->current_partition->this_partition +
mxf->current_partition->pack_length, mxf->current_partition->kag_size) +
round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size);
if (mxf->op == OPAtom) {
/* point essence_offset to the actual data
* OPAtom has all the essence in one big KLV
*/
mxf->current_partition->essence_offset = avio_tell(s->pb);
mxf->current_partition->essence_length = klv.length;
} else {
/* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
mxf->current_partition->essence_offset = op1a_essence_offset;
}
}
if (!essence_offset)
essence_offset = klv.offset;
/* seek to footer, previous partition or stop */
if (mxf_parse_handle_essence(mxf) <= 0)
break;
continue;
} else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) {
/* next partition pack - keep going, seek to previous partition or stop */
if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
break;
else if (mxf->parsing_backward)
continue;
/* we're still parsing forward. proceed to parsing this partition pack */
}
for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
if (IS_KLV_KEY(klv.key, metadata->key)) {
if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0)
goto fail;
break;
}
}
if (!metadata->read) {
av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
UID_ARG(klv.key));
avio_skip(s->pb, klv.length);
}
}
/* FIXME avoid seek */
if (!essence_offset) {
av_log(s, AV_LOG_ERROR, "no essence\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
avio_seek(s->pb, essence_offset, SEEK_SET);
mxf_compute_essence_containers(mxf);
/* we need to do this before computing the index tables
* to be able to fill in zero IndexDurations with st->duration */
if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
goto fail;
mxf_handle_missing_index_segment(mxf);
if ((ret = mxf_compute_index_tables(mxf)) < 0)
goto fail;
if (mxf->nb_index_tables > 1) {
/* TODO: look up which IndexSID to use via EssenceContainerData */
av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
mxf->nb_index_tables, mxf->index_tables[0].index_sid);
} else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
mxf_handle_small_eubc(s);
return 0;
fail:
mxf_read_close(s);
return ret;
}
/**
* Sets mxf->current_edit_unit based on what offset we're currently at.
* @return next_ofs if OK, <0 on error
*/
static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset)
{
int64_t last_ofs = -1, next_ofs = -1;
MXFIndexTable *t = &mxf->index_tables[0];
/* this is called from the OP1a demuxing logic, which means there
* may be no index tables */
if (mxf->nb_index_tables <= 0)
return -1;
/* find mxf->current_edit_unit so that the next edit unit starts ahead of current_offset */
while (mxf->current_edit_unit >= 0) {
if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0)
return -1;
if (next_ofs <= last_ofs) {
/* large next_ofs didn't change or current_edit_unit wrapped
* around this fixes the infinite loop on zzuf3.mxf */
av_log(mxf->fc, AV_LOG_ERROR,
"next_ofs didn't change. not deriving packet timestamps\n");
return -1;
}
if (next_ofs > current_offset)
break;
last_ofs = next_ofs;
mxf->current_edit_unit++;
}
/* not checking mxf->current_edit_unit >= t->nb_ptses here since CBR files may lack IndexEntryArrays */
if (mxf->current_edit_unit < 0)
return -1;
return next_ofs;
}
static int mxf_compute_sample_count(MXFContext *mxf, int stream_index,
uint64_t *sample_count)
{
int i, total = 0, size = 0;
AVStream *st = mxf->fc->streams[stream_index];
MXFTrack *track = st->priv_data;
AVRational time_base = av_inv_q(track->edit_rate);
AVRational sample_rate = av_inv_q(st->time_base);
const MXFSamplesPerFrame *spf = NULL;
if ((sample_rate.num / sample_rate.den) == 48000)
spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base);
if (!spf) {
int remainder = (sample_rate.num * time_base.num) %
(time_base.den * sample_rate.den);
*sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1},
av_mul_q(sample_rate, time_base)));
if (remainder)
av_log(mxf->fc, AV_LOG_WARNING,
"seeking detected on stream #%d with time base (%d/%d) and "
"sample rate (%d/%d), audio pts won't be accurate.\n",
stream_index, time_base.num, time_base.den,
sample_rate.num, sample_rate.den);
return 0;
}
while (spf->samples_per_frame[size]) {
total += spf->samples_per_frame[size];
size++;
}
av_assert2(size);
*sample_count = (mxf->current_edit_unit / size) * (uint64_t)total;
for (i = 0; i < mxf->current_edit_unit % size; i++) {
*sample_count += spf->samples_per_frame[i];
}
return 0;
}
static int mxf_set_audio_pts(MXFContext *mxf, AVCodecParameters *par,
AVPacket *pkt)
{
MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data;
int64_t bits_per_sample = par->bits_per_coded_sample;
if (!bits_per_sample)
bits_per_sample = av_get_bits_per_sample(par->codec_id);
pkt->pts = track->sample_count;
if ( par->channels <= 0
|| bits_per_sample <= 0
|| par->channels * (int64_t)bits_per_sample < 8)
return AVERROR(EINVAL);
track->sample_count += pkt->size / (par->channels * (int64_t)bits_per_sample / 8);
return 0;
}
static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
{
KLVPacket klv;
MXFContext *mxf = s->priv_data;
int ret;
while ((ret = klv_read_packet(&klv, s->pb)) == 0) {
PRINT_KEY(s, "read packet", klv.key);
av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
ret = mxf_decrypt_triplet(s, pkt, &klv);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
return ret;
}
return 0;
}
if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
int index = mxf_get_stream_index(s, &klv);
int64_t next_ofs, next_klv;
AVStream *st;
MXFTrack *track;
AVCodecParameters *par;
if (index < 0) {
av_log(s, AV_LOG_ERROR,
"error getting stream index %"PRIu32"\n",
AV_RB32(klv.key + 12));
goto skip;
}
st = s->streams[index];
track = st->priv_data;
if (s->streams[index]->discard == AVDISCARD_ALL)
goto skip;
next_klv = avio_tell(s->pb) + klv.length;
next_ofs = mxf_set_current_edit_unit(mxf, klv.offset);
if (next_ofs >= 0 && next_klv > next_ofs) {
/* if this check is hit then it's possible OPAtom was treated as OP1a
* truncate the packet since it's probably very large (>2 GiB is common) */
avpriv_request_sample(s,
"OPAtom misinterpreted as OP1a? "
"KLV for edit unit %i extending into "
"next edit unit",
mxf->current_edit_unit);
klv.length = next_ofs - avio_tell(s->pb);
}
/* check for 8 channels AES3 element */
if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
pkt, klv.length);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
return ret;
}
} else {
ret = av_get_packet(s->pb, pkt, klv.length);
if (ret < 0)
return ret;
}
pkt->stream_index = index;
pkt->pos = klv.offset;
par = st->codecpar;
if (par->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
/* mxf->current_edit_unit good - see if we have an
* index table to derive timestamps from */
MXFIndexTable *t = &mxf->index_tables[0];
if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) {
pkt->dts = mxf->current_edit_unit + t->first_dts;
pkt->pts = t->ptses[mxf->current_edit_unit];
} else if (track && track->intra_only) {
/* intra-only -> PTS = EditUnit.
* let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
pkt->pts = mxf->current_edit_unit;
}
} else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
ret = mxf_set_audio_pts(mxf, par, pkt);
if (ret < 0)
return ret;
}
/* seek for truncated packets */
avio_seek(s->pb, next_klv, SEEK_SET);
return 0;
} else
skip:
avio_skip(s->pb, klv.length);
}
return avio_feof(s->pb) ? AVERROR_EOF : ret;
}
static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
{
MXFContext *mxf = s->priv_data;
int ret, size;
int64_t ret64, pos, next_pos;
AVStream *st;
MXFIndexTable *t;
int edit_units;
if (mxf->op != OPAtom)
return mxf_read_packet_old(s, pkt);
// If we have no streams then we basically are at EOF
st = mxf_get_opatom_stream(mxf);
if (!st)
return AVERROR_EOF;
/* OPAtom - clip wrapped demuxing */
/* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */
t = &mxf->index_tables[0];
if (mxf->current_edit_unit >= st->duration)
return AVERROR_EOF;
edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit);
if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
return ret;
/* compute size by finding the next edit unit or the end of the essence container
* not pretty, but it works */
if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 &&
(next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
return AVERROR_INVALIDDATA;
}
if ((size = next_pos - pos) <= 0) {
av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
return AVERROR_INVALIDDATA;
}
if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
return ret64;
if ((size = av_get_packet(s->pb, pkt, size)) < 0)
return size;
pkt->stream_index = st->index;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
pkt->dts = mxf->current_edit_unit + t->first_dts;
pkt->pts = t->ptses[mxf->current_edit_unit];
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
int ret = mxf_set_audio_pts(mxf, st->codecpar, pkt);
if (ret < 0)
return ret;
}
mxf->current_edit_unit += edit_units;
return 0;
}
static int mxf_read_close(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
int i;
av_freep(&mxf->packages_refs);
for (i = 0; i < s->nb_streams; i++)
s->streams[i]->priv_data = NULL;
for (i = 0; i < mxf->metadata_sets_count; i++) {
mxf_free_metadataset(mxf->metadata_sets + i, 1);
}
av_freep(&mxf->partitions);
av_freep(&mxf->metadata_sets);
av_freep(&mxf->aesc);
av_freep(&mxf->local_tags);
if (mxf->index_tables) {
for (i = 0; i < mxf->nb_index_tables; i++) {
av_freep(&mxf->index_tables[i].segments);
av_freep(&mxf->index_tables[i].ptses);
av_freep(&mxf->index_tables[i].fake_index);
av_freep(&mxf->index_tables[i].offsets);
}
}
av_freep(&mxf->index_tables);
return 0;
}
static int mxf_probe(AVProbeData *p) {
const uint8_t *bufp = p->buf;
const uint8_t *end = p->buf + p->buf_size;
if (p->buf_size < sizeof(mxf_header_partition_pack_key))
return 0;
/* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
end -= sizeof(mxf_header_partition_pack_key);
for (; bufp < end;) {
if (!((bufp[13] - 1) & 0xF2)){
if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) &&
AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) &&
AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) &&
AV_RN16(bufp+12) == AV_RN16(mxf_header_partition_pack_key+12))
return AVPROBE_SCORE_MAX;
bufp ++;
} else
bufp += 10;
}
return 0;
}
/* rudimentary byte seek */
/* XXX: use MXF Index */
static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
{
AVStream *st = s->streams[stream_index];
int64_t seconds;
MXFContext* mxf = s->priv_data;
int64_t seekpos;
int i, ret;
MXFIndexTable *t;
MXFTrack *source_track = st->priv_data;
if(st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
return 0;
/* if audio then truncate sample_time to EditRate */
if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
sample_time = av_rescale_q(sample_time, st->time_base,
av_inv_q(source_track->edit_rate));
if (mxf->nb_index_tables <= 0) {
if (!s->bit_rate)
return AVERROR_INVALIDDATA;
if (sample_time < 0)
sample_time = 0;
seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
if (seekpos < 0)
return seekpos;
ff_update_cur_dts(s, st, sample_time);
mxf->current_edit_unit = sample_time;
} else {
t = &mxf->index_tables[0];
/* clamp above zero, else ff_index_search_timestamp() returns negative
* this also means we allow seeking before the start */
sample_time = FFMAX(sample_time, 0);
if (t->fake_index) {
/* The first frames may not be keyframes in presentation order, so
* we have to advance the target to be able to find the first
* keyframe backwards... */
if (!(flags & AVSEEK_FLAG_ANY) &&
(flags & AVSEEK_FLAG_BACKWARD) &&
t->ptses[0] != AV_NOPTS_VALUE &&
sample_time < t->ptses[0] &&
(t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME))
sample_time = t->ptses[0];
/* behave as if we have a proper index */
if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
return sample_time;
/* get the stored order index from the display order index */
sample_time += t->offsets[sample_time];
} else {
/* no IndexEntryArray (one or more CBR segments)
* make sure we don't seek past the end */
sample_time = FFMIN(sample_time, source_track->original_duration - 1);
}
if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) < 0)
return ret;
ff_update_cur_dts(s, st, sample_time);
mxf->current_edit_unit = sample_time;
avio_seek(s->pb, seekpos, SEEK_SET);
}
// Update all tracks sample count
for (i = 0; i < s->nb_streams; i++) {
AVStream *cur_st = s->streams[i];
MXFTrack *cur_track = cur_st->priv_data;
uint64_t current_sample_count = 0;
if (cur_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
ret = mxf_compute_sample_count(mxf, i, ¤t_sample_count);
if (ret < 0)
return ret;
cur_track->sample_count = current_sample_count;
}
}
return 0;
}
AVInputFormat ff_mxf_demuxer = {
.name = "mxf",
.long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
.flags = AVFMT_SEEK_TO_PTS,
.priv_data_size = sizeof(MXFContext),
.read_probe = mxf_probe,
.read_header = mxf_read_header,
.read_packet = mxf_read_packet,
.read_close = mxf_read_close,
.read_seek = mxf_read_seek,
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2778_0 |
crossvul-cpp_data_good_2802_5 | /* nautilus-mime-actions.c - uri-specific versions of mime action functions
*
* Copyright (C) 2000, 2001 Eazel, Inc.
*
* The Gnome Library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* The Gnome Library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with the Gnome Library; see the file COPYING.LIB. If not,
* see <http://www.gnu.org/licenses/>.
*
* Authors: Maciej Stachowiak <mjs@eazel.com>
*/
#include <config.h>
#include "nautilus-mime-actions.h"
#include "nautilus-window-slot.h"
#include "nautilus-application.h"
#include <eel/eel-glib-extensions.h>
#include <eel/eel-stock-dialogs.h>
#include <eel/eel-string.h>
#include <glib.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>
#include <string.h>
#include <gdk/gdkx.h>
#include "nautilus-file-attributes.h"
#include "nautilus-file.h"
#include "nautilus-file-operations.h"
#include "nautilus-metadata.h"
#include "nautilus-program-choosing.h"
#include "nautilus-global-preferences.h"
#include "nautilus-signaller.h"
#include "nautilus-metadata.h"
#define DEBUG_FLAG NAUTILUS_DEBUG_MIME
#include "nautilus-debug.h"
typedef enum
{
ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE,
ACTIVATION_ACTION_ASK,
ACTIVATION_ACTION_LAUNCH,
ACTIVATION_ACTION_LAUNCH_IN_TERMINAL,
ACTIVATION_ACTION_OPEN_IN_VIEW,
ACTIVATION_ACTION_OPEN_IN_APPLICATION,
ACTIVATION_ACTION_EXTRACT,
ACTIVATION_ACTION_DO_NOTHING,
} ActivationAction;
typedef struct
{
NautilusFile *file;
char *uri;
} LaunchLocation;
typedef struct
{
GAppInfo *application;
GList *uris;
} ApplicationLaunchParameters;
typedef struct
{
NautilusWindowSlot *slot;
gpointer window;
GtkWindow *parent_window;
GCancellable *cancellable;
GList *locations;
GList *mountables;
GList *start_mountables;
GList *not_mounted;
NautilusWindowOpenFlags flags;
char *timed_wait_prompt;
gboolean timed_wait_active;
NautilusFileListHandle *files_handle;
gboolean tried_mounting;
char *activation_directory;
gboolean user_confirmation;
} ActivateParameters;
struct
{
char *name;
char *mimetypes[20];
} mimetype_groups[] =
{
{
N_("Anything"),
{ NULL }
},
{
N_("Files"),
{ "application/octet-stream",
"text/plain",
NULL}
},
{
N_("Folders"),
{ "inode/directory",
NULL}
},
{ N_("Documents"),
{ "application/rtf",
"application/msword",
"application/vnd.sun.xml.writer",
"application/vnd.sun.xml.writer.global",
"application/vnd.sun.xml.writer.template",
"application/vnd.oasis.opendocument.text",
"application/vnd.oasis.opendocument.text-template",
"application/x-abiword",
"application/x-applix-word",
"application/x-mswrite",
"application/docbook+xml",
"application/x-kword",
"application/x-kword-crypt",
"application/x-lyx",
NULL}},
{ N_("Illustration"),
{ "application/illustrator",
"application/vnd.corel-draw",
"application/vnd.stardivision.draw",
"application/vnd.oasis.opendocument.graphics",
"application/x-dia-diagram",
"application/x-karbon",
"application/x-killustrator",
"application/x-kivio",
"application/x-kontour",
"application/x-wpg",
NULL}},
{ N_("Music"),
{ "application/ogg",
"audio/x-vorbis+ogg",
"audio/ac3",
"audio/basic",
"audio/midi",
"audio/x-flac",
"audio/mp4",
"audio/mpeg",
"audio/x-mpeg",
"audio/x-ms-asx",
"audio/x-pn-realaudio",
NULL}},
{ N_("PDF / PostScript"),
{ "application/pdf",
"application/postscript",
"application/x-dvi",
"image/x-eps",
NULL}},
{ N_("Picture"),
{ "application/vnd.oasis.opendocument.image",
"application/x-krita",
"image/bmp",
"image/cgm",
"image/gif",
"image/jpeg",
"image/jpeg2000",
"image/png",
"image/svg+xml",
"image/tiff",
"image/x-compressed-xcf",
"image/x-pcx",
"image/x-photo-cd",
"image/x-psd",
"image/x-tga",
"image/x-xcf",
NULL}},
{ N_("Presentation"),
{ "application/vnd.ms-powerpoint",
"application/vnd.sun.xml.impress",
"application/vnd.oasis.opendocument.presentation",
"application/x-magicpoint",
"application/x-kpresenter",
NULL}},
{ N_("Spreadsheet"),
{ "application/vnd.lotus-1-2-3",
"application/vnd.ms-excel",
"application/vnd.stardivision.calc",
"application/vnd.sun.xml.calc",
"application/vnd.oasis.opendocument.spreadsheet",
"application/x-applix-spreadsheet",
"application/x-gnumeric",
"application/x-kspread",
"application/x-kspread-crypt",
"application/x-quattropro",
"application/x-sc",
"application/x-siag",
NULL}},
{ N_("Text File"),
{ "text/plain",
NULL}},
{ N_("Video"),
{ "video/mp4",
"video/3gpp",
"video/mpeg",
"video/quicktime",
"video/vivo",
"video/x-avi",
"video/x-mng",
"video/x-ms-asf",
"video/x-ms-wmv",
"video/x-msvideo",
"video/x-nsv",
"video/x-real-video",
NULL}}
};
/* Number of seconds until cancel dialog shows up */
#define DELAY_UNTIL_CANCEL_MSECS 5000
#define RESPONSE_RUN 1000
#define RESPONSE_DISPLAY 1001
#define RESPONSE_RUN_IN_TERMINAL 1002
#define SILENT_WINDOW_OPEN_LIMIT 5
#define SILENT_OPEN_LIMIT 5
/* This number controls a maximum character count for a URL that is
* displayed as part of a dialog. It's fairly arbitrary -- big enough
* to allow most "normal" URIs to display in full, but small enough to
* prevent the dialog from getting insanely wide.
*/
#define MAX_URI_IN_DIALOG_LENGTH 60
static void cancel_activate_callback (gpointer callback_data);
static void activate_activation_uris_ready_callback (GList *files,
gpointer callback_data);
static void activation_mount_mountables (ActivateParameters *parameters);
static void activation_start_mountables (ActivateParameters *parameters);
static void activate_callback (GList *files,
gpointer callback_data);
static void activation_mount_not_mounted (ActivateParameters *parameters);
static void
launch_location_free (LaunchLocation *location)
{
nautilus_file_unref (location->file);
g_free (location->uri);
g_free (location);
}
static void
launch_location_list_free (GList *list)
{
g_list_foreach (list, (GFunc) launch_location_free, NULL);
g_list_free (list);
}
static GList *
get_file_list_for_launch_locations (GList *locations)
{
GList *files, *l;
LaunchLocation *location;
files = NULL;
for (l = locations; l != NULL; l = l->next)
{
location = l->data;
files = g_list_prepend (files,
nautilus_file_ref (location->file));
}
return g_list_reverse (files);
}
static LaunchLocation *
launch_location_from_file (NautilusFile *file)
{
LaunchLocation *location;
location = g_new (LaunchLocation, 1);
location->file = nautilus_file_ref (file);
location->uri = nautilus_file_get_uri (file);
return location;
}
static void
launch_location_update_from_file (LaunchLocation *location,
NautilusFile *file)
{
nautilus_file_unref (location->file);
g_free (location->uri);
location->file = nautilus_file_ref (file);
location->uri = nautilus_file_get_uri (file);
}
static void
launch_location_update_from_uri (LaunchLocation *location,
const char *uri)
{
nautilus_file_unref (location->file);
g_free (location->uri);
location->file = nautilus_file_get_by_uri (uri);
location->uri = g_strdup (uri);
}
static LaunchLocation *
find_launch_location_for_file (GList *list,
NautilusFile *file)
{
LaunchLocation *location;
GList *l;
for (l = list; l != NULL; l = l->next)
{
location = l->data;
if (location->file == file)
{
return location;
}
}
return NULL;
}
static GList *
launch_locations_from_file_list (GList *list)
{
GList *new;
new = NULL;
while (list)
{
new = g_list_prepend (new,
launch_location_from_file (list->data));
list = list->next;
}
new = g_list_reverse (new);
return new;
}
static ApplicationLaunchParameters *
application_launch_parameters_new (GAppInfo *application,
GList *uris)
{
ApplicationLaunchParameters *result;
result = g_new0 (ApplicationLaunchParameters, 1);
result->application = g_object_ref (application);
result->uris = g_list_copy_deep (uris, (GCopyFunc) g_strdup, NULL);
return result;
}
static void
application_launch_parameters_free (ApplicationLaunchParameters *parameters)
{
g_object_unref (parameters->application);
g_list_free_full (parameters->uris, g_free);
g_free (parameters);
}
static gboolean
nautilus_mime_actions_check_if_required_attributes_ready (NautilusFile *file)
{
NautilusFileAttributes attributes;
gboolean ready;
attributes = nautilus_mime_actions_get_required_file_attributes ();
ready = nautilus_file_check_if_ready (file, attributes);
return ready;
}
NautilusFileAttributes
nautilus_mime_actions_get_required_file_attributes (void)
{
return NAUTILUS_FILE_ATTRIBUTE_INFO |
NAUTILUS_FILE_ATTRIBUTE_LINK_INFO;
}
GAppInfo *
nautilus_mime_get_default_application_for_file (NautilusFile *file)
{
GAppInfo *app;
char *mime_type;
char *uri_scheme;
if (!nautilus_mime_actions_check_if_required_attributes_ready (file))
{
return NULL;
}
mime_type = nautilus_file_get_mime_type (file);
app = g_app_info_get_default_for_type (mime_type,
!nautilus_file_is_local_or_fuse (file));
g_free (mime_type);
if (app == NULL)
{
uri_scheme = nautilus_file_get_uri_scheme (file);
if (uri_scheme != NULL)
{
app = g_app_info_get_default_for_uri_scheme (uri_scheme);
g_free (uri_scheme);
}
}
return app;
}
static int
file_compare_by_mime_type (NautilusFile *file_a,
NautilusFile *file_b)
{
char *mime_type_a, *mime_type_b;
int ret;
mime_type_a = nautilus_file_get_mime_type (file_a);
mime_type_b = nautilus_file_get_mime_type (file_b);
ret = strcmp (mime_type_a, mime_type_b);
g_free (mime_type_a);
g_free (mime_type_b);
return ret;
}
static int
file_compare_by_parent_uri (NautilusFile *file_a,
NautilusFile *file_b)
{
char *parent_uri_a, *parent_uri_b;
int ret;
parent_uri_a = nautilus_file_get_parent_uri (file_a);
parent_uri_b = nautilus_file_get_parent_uri (file_b);
ret = strcmp (parent_uri_a, parent_uri_b);
g_free (parent_uri_a);
g_free (parent_uri_b);
return ret;
}
GAppInfo *
nautilus_mime_get_default_application_for_files (GList *files)
{
GList *l, *sorted_files;
NautilusFile *file;
GAppInfo *app, *one_app;
g_assert (files != NULL);
sorted_files = g_list_sort (g_list_copy (files), (GCompareFunc) file_compare_by_mime_type);
app = NULL;
for (l = sorted_files; l != NULL; l = l->next)
{
file = l->data;
if (l->prev &&
file_compare_by_mime_type (file, l->prev->data) == 0 &&
file_compare_by_parent_uri (file, l->prev->data) == 0)
{
continue;
}
one_app = nautilus_mime_get_default_application_for_file (file);
if (one_app == NULL || (app != NULL && !g_app_info_equal (app, one_app)))
{
if (app)
{
g_object_unref (app);
}
if (one_app)
{
g_object_unref (one_app);
}
app = NULL;
break;
}
if (app == NULL)
{
app = one_app;
}
else
{
g_object_unref (one_app);
}
}
g_list_free (sorted_files);
return app;
}
static void
trash_or_delete_files (GtkWindow *parent_window,
const GList *files,
gboolean delete_if_all_already_in_trash)
{
GList *locations;
const GList *node;
locations = NULL;
for (node = files; node != NULL; node = node->next)
{
locations = g_list_prepend (locations,
nautilus_file_get_location ((NautilusFile *) node->data));
}
locations = g_list_reverse (locations);
nautilus_file_operations_trash_or_delete (locations,
parent_window,
NULL, NULL);
g_list_free_full (locations, g_object_unref);
}
static void
report_broken_symbolic_link (GtkWindow *parent_window,
NautilusFile *file)
{
char *target_path;
char *display_name;
char *prompt;
char *detail;
GtkDialog *dialog;
GList file_as_list;
int response;
gboolean can_trash;
g_assert (nautilus_file_is_broken_symbolic_link (file));
display_name = nautilus_file_get_display_name (file);
can_trash = nautilus_file_can_trash (file) && !nautilus_file_is_in_trash (file);
if (can_trash)
{
prompt = g_strdup_printf (_("The link “%s” is broken. Move it to Trash?"), display_name);
}
else
{
prompt = g_strdup_printf (_("The link “%s” is broken."), display_name);
}
g_free (display_name);
target_path = nautilus_file_get_symbolic_link_target_path (file);
if (target_path == NULL)
{
detail = g_strdup (_("This link cannot be used because it has no target."));
}
else
{
detail = g_strdup_printf (_("This link cannot be used because its target "
"“%s” doesn’t exist."), target_path);
}
if (!can_trash)
{
eel_run_simple_dialog (GTK_WIDGET (parent_window), FALSE, GTK_MESSAGE_WARNING,
prompt, detail, _("_Cancel"), NULL);
goto out;
}
dialog = eel_show_yes_no_dialog (prompt, detail, _("Mo_ve to Trash"), _("_Cancel"),
parent_window);
gtk_dialog_set_default_response (dialog, GTK_RESPONSE_CANCEL);
/* Make this modal to avoid problems with reffing the view & file
* to keep them around in case the view changes, which would then
* cause the old view not to be destroyed, which would cause its
* merged Bonobo items not to be un-merged. Maybe we need to unmerge
* explicitly when disconnecting views instead of relying on the
* unmerge in Destroy. But since BonoboUIHandler is probably going
* to change wildly, I don't want to mess with this now.
*/
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
if (response == GTK_RESPONSE_YES)
{
file_as_list.data = file;
file_as_list.next = NULL;
file_as_list.prev = NULL;
trash_or_delete_files (parent_window, &file_as_list, TRUE);
}
out:
g_free (prompt);
g_free (target_path);
g_free (detail);
}
static ActivationAction
get_executable_text_file_action (GtkWindow *parent_window,
NautilusFile *file)
{
GtkDialog *dialog;
char *file_name;
char *prompt;
char *detail;
int preferences_value;
int response;
g_assert (nautilus_file_contains_text (file));
preferences_value = g_settings_get_enum (nautilus_preferences,
NAUTILUS_PREFERENCES_EXECUTABLE_TEXT_ACTIVATION);
switch (preferences_value)
{
case NAUTILUS_EXECUTABLE_TEXT_LAUNCH:
{
return ACTIVATION_ACTION_LAUNCH;
}
case NAUTILUS_EXECUTABLE_TEXT_DISPLAY:
{
return ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
case NAUTILUS_EXECUTABLE_TEXT_ASK:
{
}
break;
default:
/* Complain non-fatally, since preference data can't be trusted */
g_warning ("Unknown value %d for NAUTILUS_PREFERENCES_EXECUTABLE_TEXT_ACTIVATION",
preferences_value);
}
file_name = nautilus_file_get_display_name (file);
prompt = g_strdup_printf (_("Do you want to run “%s”, or display its contents?"),
file_name);
detail = g_strdup_printf (_("“%s” is an executable text file."),
file_name);
g_free (file_name);
dialog = eel_create_question_dialog (prompt,
detail,
_("Run in _Terminal"), RESPONSE_RUN_IN_TERMINAL,
_("_Display"), RESPONSE_DISPLAY,
parent_window);
gtk_dialog_add_button (dialog, _("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_add_button (dialog, _("_Run"), RESPONSE_RUN);
gtk_dialog_set_default_response (dialog, GTK_RESPONSE_CANCEL);
gtk_widget_show (GTK_WIDGET (dialog));
g_free (prompt);
g_free (detail);
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
switch (response)
{
case RESPONSE_RUN:
{
return ACTIVATION_ACTION_LAUNCH;
}
case RESPONSE_RUN_IN_TERMINAL:
{
return ACTIVATION_ACTION_LAUNCH_IN_TERMINAL;
}
case RESPONSE_DISPLAY:
{
return ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
default:
return ACTIVATION_ACTION_DO_NOTHING;
}
}
static ActivationAction
get_default_executable_text_file_action (void)
{
int preferences_value;
preferences_value = g_settings_get_enum (nautilus_preferences,
NAUTILUS_PREFERENCES_EXECUTABLE_TEXT_ACTIVATION);
switch (preferences_value)
{
case NAUTILUS_EXECUTABLE_TEXT_LAUNCH:
{
return ACTIVATION_ACTION_LAUNCH;
}
case NAUTILUS_EXECUTABLE_TEXT_DISPLAY:
{
return ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
case NAUTILUS_EXECUTABLE_TEXT_ASK:
default:
return ACTIVATION_ACTION_ASK;
}
}
static ActivationAction
get_activation_action (NautilusFile *file)
{
ActivationAction action;
char *activation_uri;
gboolean can_extract;
can_extract = g_settings_get_boolean (nautilus_preferences,
NAUTILUS_PREFERENCES_AUTOMATIC_DECOMPRESSION);
if (can_extract && nautilus_file_is_archive (file))
{
return ACTIVATION_ACTION_EXTRACT;
}
if (nautilus_file_is_nautilus_link (file))
{
return ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE;
}
activation_uri = nautilus_file_get_activation_uri (file);
if (activation_uri == NULL)
{
activation_uri = nautilus_file_get_uri (file);
}
action = ACTIVATION_ACTION_DO_NOTHING;
if (nautilus_file_is_launchable (file))
{
char *executable_path;
action = ACTIVATION_ACTION_LAUNCH;
executable_path = g_filename_from_uri (activation_uri, NULL, NULL);
if (!executable_path)
{
action = ACTIVATION_ACTION_DO_NOTHING;
}
else if (nautilus_file_contains_text (file))
{
action = get_default_executable_text_file_action ();
}
g_free (executable_path);
}
if (action == ACTIVATION_ACTION_DO_NOTHING)
{
if (nautilus_file_opens_in_view (file))
{
action = ACTIVATION_ACTION_OPEN_IN_VIEW;
}
else
{
action = ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
}
g_free (activation_uri);
return action;
}
gboolean
nautilus_mime_file_extracts (NautilusFile *file)
{
return get_activation_action (file) == ACTIVATION_ACTION_EXTRACT;
}
gboolean
nautilus_mime_file_launches (NautilusFile *file)
{
ActivationAction activation_action;
activation_action = get_activation_action (file);
return (activation_action == ACTIVATION_ACTION_LAUNCH);
}
gboolean
nautilus_mime_file_opens_in_external_app (NautilusFile *file)
{
ActivationAction activation_action;
activation_action = get_activation_action (file);
return (activation_action == ACTIVATION_ACTION_OPEN_IN_APPLICATION);
}
static unsigned int
mime_application_hash (GAppInfo *app)
{
const char *id;
id = g_app_info_get_id (app);
if (id == NULL)
{
return GPOINTER_TO_UINT (app);
}
return g_str_hash (id);
}
static void
list_to_parameters_foreach (GAppInfo *application,
GList *uris,
GList **ret)
{
ApplicationLaunchParameters *parameters;
uris = g_list_reverse (uris);
parameters = application_launch_parameters_new
(application, uris);
*ret = g_list_prepend (*ret, parameters);
}
/**
* make_activation_parameters
*
* Construct a list of ApplicationLaunchParameters from a list of NautilusFiles,
* where files that have the same default application are put into the same
* launch parameter, and others are put into the unhandled_files list.
*
* @files: Files to use for construction.
* @unhandled_files: Files without any default application will be put here.
*
* Return value: Newly allocated list of ApplicationLaunchParameters.
**/
static GList *
make_activation_parameters (GList *uris,
GList **unhandled_uris)
{
GList *ret, *l, *app_uris;
NautilusFile *file;
GAppInfo *app, *old_app;
GHashTable *app_table;
char *uri;
ret = NULL;
*unhandled_uris = NULL;
app_table = g_hash_table_new_full
((GHashFunc) mime_application_hash,
(GEqualFunc) g_app_info_equal,
(GDestroyNotify) g_object_unref,
(GDestroyNotify) g_list_free);
for (l = uris; l != NULL; l = l->next)
{
uri = l->data;
file = nautilus_file_get_by_uri (uri);
app = nautilus_mime_get_default_application_for_file (file);
if (app != NULL)
{
app_uris = NULL;
if (g_hash_table_lookup_extended (app_table, app,
(gpointer *) &old_app,
(gpointer *) &app_uris))
{
g_hash_table_steal (app_table, old_app);
app_uris = g_list_prepend (app_uris, uri);
g_object_unref (app);
app = old_app;
}
else
{
app_uris = g_list_prepend (NULL, uri);
}
g_hash_table_insert (app_table, app, app_uris);
}
else
{
*unhandled_uris = g_list_prepend (*unhandled_uris, uri);
}
nautilus_file_unref (file);
}
g_hash_table_foreach (app_table,
(GHFunc) list_to_parameters_foreach,
&ret);
g_hash_table_destroy (app_table);
*unhandled_uris = g_list_reverse (*unhandled_uris);
return g_list_reverse (ret);
}
static gboolean
file_was_cancelled (NautilusFile *file)
{
GError *error;
error = nautilus_file_get_file_info_error (file);
return
error != NULL &&
error->domain == G_IO_ERROR &&
error->code == G_IO_ERROR_CANCELLED;
}
static gboolean
file_was_not_mounted (NautilusFile *file)
{
GError *error;
error = nautilus_file_get_file_info_error (file);
return
error != NULL &&
error->domain == G_IO_ERROR &&
error->code == G_IO_ERROR_NOT_MOUNTED;
}
static void
activation_parameters_free (ActivateParameters *parameters)
{
if (parameters->timed_wait_active)
{
eel_timed_wait_stop (cancel_activate_callback, parameters);
}
if (parameters->slot)
{
g_object_remove_weak_pointer (G_OBJECT (parameters->slot), (gpointer *) ¶meters->slot);
}
if (parameters->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (parameters->parent_window), (gpointer *) ¶meters->parent_window);
}
g_object_unref (parameters->cancellable);
launch_location_list_free (parameters->locations);
nautilus_file_list_free (parameters->mountables);
nautilus_file_list_free (parameters->start_mountables);
nautilus_file_list_free (parameters->not_mounted);
g_free (parameters->activation_directory);
g_free (parameters->timed_wait_prompt);
g_assert (parameters->files_handle == NULL);
g_free (parameters);
}
static void
cancel_activate_callback (gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
parameters->timed_wait_active = FALSE;
g_cancellable_cancel (parameters->cancellable);
if (parameters->files_handle)
{
nautilus_file_list_cancel_call_when_ready (parameters->files_handle);
parameters->files_handle = NULL;
activation_parameters_free (parameters);
}
}
static void
activation_start_timed_cancel (ActivateParameters *parameters)
{
parameters->timed_wait_active = TRUE;
eel_timed_wait_start_with_duration
(DELAY_UNTIL_CANCEL_MSECS,
cancel_activate_callback,
parameters,
parameters->timed_wait_prompt,
parameters->parent_window);
}
static void
pause_activation_timed_cancel (ActivateParameters *parameters)
{
if (parameters->timed_wait_active)
{
eel_timed_wait_stop (cancel_activate_callback, parameters);
parameters->timed_wait_active = FALSE;
}
}
static void
unpause_activation_timed_cancel (ActivateParameters *parameters)
{
if (!parameters->timed_wait_active)
{
activation_start_timed_cancel (parameters);
}
}
static void
activate_mount_op_active (GtkMountOperation *operation,
GParamSpec *pspec,
ActivateParameters *parameters)
{
gboolean is_active;
g_object_get (operation, "is-showing", &is_active, NULL);
if (is_active)
{
pause_activation_timed_cancel (parameters);
}
else
{
unpause_activation_timed_cancel (parameters);
}
}
static gboolean
confirm_multiple_windows (GtkWindow *parent_window,
int count,
gboolean use_tabs)
{
GtkDialog *dialog;
char *prompt;
char *detail;
int response;
if (count <= SILENT_WINDOW_OPEN_LIMIT)
{
return TRUE;
}
prompt = _("Are you sure you want to open all files?");
if (use_tabs)
{
detail = g_strdup_printf (ngettext ("This will open %d separate tab.",
"This will open %d separate tabs.", count), count);
}
else
{
detail = g_strdup_printf (ngettext ("This will open %d separate window.",
"This will open %d separate windows.", count), count);
}
dialog = eel_show_yes_no_dialog (prompt, detail,
_("_OK"), _("_Cancel"),
parent_window);
g_free (detail);
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
return response == GTK_RESPONSE_YES;
}
typedef struct
{
NautilusWindowSlot *slot;
GtkWindow *parent_window;
NautilusFile *file;
GList *files;
NautilusWindowOpenFlags flags;
char *activation_directory;
gboolean user_confirmation;
char *uri;
GDBusProxy *proxy;
GtkWidget *dialog;
} ActivateParametersInstall;
static void
activate_parameters_install_free (ActivateParametersInstall *parameters_install)
{
if (parameters_install->slot)
{
g_object_remove_weak_pointer (G_OBJECT (parameters_install->slot), (gpointer *) ¶meters_install->slot);
}
if (parameters_install->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (parameters_install->parent_window), (gpointer *) ¶meters_install->parent_window);
}
if (parameters_install->proxy != NULL)
{
g_object_unref (parameters_install->proxy);
}
nautilus_file_unref (parameters_install->file);
nautilus_file_list_free (parameters_install->files);
g_free (parameters_install->activation_directory);
g_free (parameters_install->uri);
g_free (parameters_install);
}
static char *
get_application_no_mime_type_handler_message (NautilusFile *file,
char *uri)
{
char *uri_for_display;
char *name;
char *error_message;
name = nautilus_file_get_display_name (file);
/* Truncate the URI so it doesn't get insanely wide. Note that even
* though the dialog uses wrapped text, if the URI doesn't contain
* white space then the text-wrapping code is too stupid to wrap it.
*/
uri_for_display = eel_str_middle_truncate (name, MAX_URI_IN_DIALOG_LENGTH);
error_message = g_strdup_printf (_("Could not display “%s”."), uri_for_display);
g_free (uri_for_display);
g_free (name);
return error_message;
}
static void
open_with_response_cb (GtkDialog *dialog,
gint response_id,
gpointer user_data)
{
GtkWindow *parent_window;
NautilusFile *file;
GList files;
GAppInfo *info;
ActivateParametersInstall *parameters = user_data;
if (response_id != GTK_RESPONSE_OK)
{
gtk_widget_destroy (GTK_WIDGET (dialog));
return;
}
parent_window = parameters->parent_window;
file = g_object_get_data (G_OBJECT (dialog), "mime-action:file");
info = gtk_app_chooser_get_app_info (GTK_APP_CHOOSER (dialog));
gtk_widget_destroy (GTK_WIDGET (dialog));
g_signal_emit_by_name (nautilus_signaller_get_current (), "mime-data-changed");
files.next = NULL;
files.prev = NULL;
files.data = file;
nautilus_launch_application (info, &files, parent_window);
g_object_unref (info);
activate_parameters_install_free (parameters);
}
static void
choose_program (GtkDialog *message_dialog,
int response,
gpointer callback_data)
{
GtkWidget *dialog;
NautilusFile *file;
GFile *location;
ActivateParametersInstall *parameters = callback_data;
if (response != GTK_RESPONSE_ACCEPT)
{
gtk_widget_destroy (GTK_WIDGET (message_dialog));
activate_parameters_install_free (parameters);
return;
}
file = g_object_get_data (G_OBJECT (message_dialog), "mime-action:file");
g_assert (NAUTILUS_IS_FILE (file));
location = nautilus_file_get_location (file);
nautilus_file_ref (file);
/* Destroy the message dialog after ref:ing the file */
gtk_widget_destroy (GTK_WIDGET (message_dialog));
dialog = gtk_app_chooser_dialog_new (parameters->parent_window,
GTK_DIALOG_MODAL,
location);
g_object_set_data_full (G_OBJECT (dialog),
"mime-action:file",
nautilus_file_ref (file),
(GDestroyNotify) nautilus_file_unref);
gtk_widget_show (dialog);
g_signal_connect (dialog,
"response",
G_CALLBACK (open_with_response_cb),
parameters);
g_object_unref (location);
nautilus_file_unref (file);
}
static void
show_unhandled_type_error (ActivateParametersInstall *parameters)
{
GtkWidget *dialog;
char *mime_type = nautilus_file_get_mime_type (parameters->file);
char *error_message = get_application_no_mime_type_handler_message (parameters->file, parameters->uri);
if (g_content_type_is_unknown (mime_type))
{
dialog = gtk_message_dialog_new (parameters->parent_window,
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
0,
"%s", error_message);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("The file is of an unknown type"));
}
else
{
char *text;
text = g_strdup_printf (_("There is no application installed for “%s” files"), g_content_type_get_description (mime_type));
dialog = gtk_message_dialog_new (parameters->parent_window,
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
0,
"%s", error_message);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s", text);
g_free (text);
}
gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Select Application"), GTK_RESPONSE_ACCEPT);
gtk_dialog_add_button (GTK_DIALOG (dialog), _("_OK"), GTK_RESPONSE_OK);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK);
g_object_set_data_full (G_OBJECT (dialog),
"mime-action:file",
nautilus_file_ref (parameters->file),
(GDestroyNotify) nautilus_file_unref);
gtk_widget_show (GTK_WIDGET (dialog));
g_signal_connect (dialog, "response",
G_CALLBACK (choose_program), parameters);
g_free (error_message);
g_free (mime_type);
}
static void
search_for_application_dbus_call_notify_cb (GDBusProxy *proxy,
GAsyncResult *result,
gpointer user_data)
{
ActivateParametersInstall *parameters_install = user_data;
GVariant *variant;
GError *error = NULL;
variant = g_dbus_proxy_call_finish (proxy, result, &error);
if (variant == NULL)
{
if (!g_dbus_error_is_remote_error (error) ||
g_strcmp0 (g_dbus_error_get_remote_error (error), "org.freedesktop.PackageKit.Modify.Failed") == 0)
{
char *message;
message = g_strdup_printf ("%s\n%s",
_("There was an internal error trying to search for applications:"),
error->message);
eel_show_error_dialog (_("Unable to search for application"), message,
parameters_install->parent_window);
g_free (message);
}
else
{
g_warning ("Error while trying to search for applications: %s",
error->message);
}
g_error_free (error);
activate_parameters_install_free (parameters_install);
return;
}
g_variant_unref (variant);
/* activate the file again */
nautilus_mime_activate_files (parameters_install->parent_window,
parameters_install->slot,
parameters_install->files,
parameters_install->activation_directory,
parameters_install->flags,
parameters_install->user_confirmation);
activate_parameters_install_free (parameters_install);
}
static void
search_for_application_mime_type (ActivateParametersInstall *parameters_install,
const gchar *mime_type)
{
GdkWindow *window;
guint xid = 0;
const char *mime_types[2];
g_assert (parameters_install->proxy != NULL);
/* get XID from parent window */
window = gtk_widget_get_window (GTK_WIDGET (parameters_install->parent_window));
if (window != NULL)
{
xid = GDK_WINDOW_XID (window);
}
mime_types[0] = mime_type;
mime_types[1] = NULL;
g_dbus_proxy_call (parameters_install->proxy,
"InstallMimeTypes",
g_variant_new ("(u^ass)",
xid,
mime_types,
"hide-confirm-search"),
G_DBUS_CALL_FLAGS_NONE,
G_MAXINT /* no timeout */,
NULL /* cancellable */,
(GAsyncReadyCallback) search_for_application_dbus_call_notify_cb,
parameters_install);
DEBUG ("InstallMimeType method invoked for %s", mime_type);
}
static void
application_unhandled_file_install (GtkDialog *dialog,
gint response_id,
ActivateParametersInstall *parameters_install)
{
char *mime_type;
gtk_widget_destroy (GTK_WIDGET (dialog));
parameters_install->dialog = NULL;
if (response_id == GTK_RESPONSE_YES)
{
mime_type = nautilus_file_get_mime_type (parameters_install->file);
search_for_application_mime_type (parameters_install, mime_type);
g_free (mime_type);
}
else
{
/* free as we're not going to get the async dbus callback */
activate_parameters_install_free (parameters_install);
}
}
static gboolean
delete_cb (GtkDialog *dialog)
{
gtk_dialog_response (dialog, GTK_RESPONSE_DELETE_EVENT);
return TRUE;
}
static void
pk_proxy_appeared_cb (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
ActivateParametersInstall *parameters_install = user_data;
char *mime_type, *name_owner;
char *error_message;
GtkWidget *dialog;
GDBusProxy *proxy;
GError *error = NULL;
proxy = g_dbus_proxy_new_for_bus_finish (res, &error);
name_owner = g_dbus_proxy_get_name_owner (proxy);
if (error != NULL || name_owner == NULL)
{
g_warning ("Couldn't call Modify on the PackageKit interface: %s",
error != NULL ? error->message : "no owner for PackageKit");
g_clear_error (&error);
/* show an unhelpful dialog */
show_unhandled_type_error (parameters_install);
return;
}
g_free (name_owner);
mime_type = nautilus_file_get_mime_type (parameters_install->file);
error_message = get_application_no_mime_type_handler_message (parameters_install->file,
parameters_install->uri);
/* use a custom dialog to prompt the user to install new software */
dialog = gtk_message_dialog_new (parameters_install->parent_window, 0,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_YES_NO,
"%s", error_message);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("There is no application installed for “%s” files.\n"
"Do you want to search for an application to open this file?"),
g_content_type_get_description (mime_type));
gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
parameters_install->dialog = dialog;
parameters_install->proxy = proxy;
g_signal_connect (dialog, "response",
G_CALLBACK (application_unhandled_file_install),
parameters_install);
g_signal_connect (dialog, "delete-event",
G_CALLBACK (delete_cb), NULL);
gtk_widget_show_all (dialog);
g_free (mime_type);
}
static void
application_unhandled_uri (ActivateParameters *parameters,
char *uri)
{
gboolean show_install_mime;
char *mime_type;
NautilusFile *file;
ActivateParametersInstall *parameters_install;
file = nautilus_file_get_by_uri (uri);
mime_type = nautilus_file_get_mime_type (file);
/* copy the parts of parameters we are interested in as the orignal will be unref'd */
parameters_install = g_new0 (ActivateParametersInstall, 1);
parameters_install->slot = parameters->slot;
g_object_add_weak_pointer (G_OBJECT (parameters_install->slot), (gpointer *) ¶meters_install->slot);
if (parameters->parent_window)
{
parameters_install->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_install->parent_window), (gpointer *) ¶meters_install->parent_window);
}
parameters_install->activation_directory = g_strdup (parameters->activation_directory);
parameters_install->file = file;
parameters_install->files = get_file_list_for_launch_locations (parameters->locations);
parameters_install->flags = parameters->flags;
parameters_install->user_confirmation = parameters->user_confirmation;
parameters_install->uri = g_strdup (uri);
#ifdef ENABLE_PACKAGEKIT
/* allow an admin to disable the PackageKit search functionality */
show_install_mime = g_settings_get_boolean (nautilus_preferences, NAUTILUS_PREFERENCES_INSTALL_MIME_ACTIVATION);
#else
/* we have no install functionality */
show_install_mime = FALSE;
#endif
/* There is no use trying to look for handlers of application/octet-stream */
if (g_content_type_is_unknown (mime_type))
{
show_install_mime = FALSE;
}
g_free (mime_type);
if (!show_install_mime)
{
goto out;
}
g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.PackageKit",
"/org/freedesktop/PackageKit",
"org.freedesktop.PackageKit.Modify",
NULL,
pk_proxy_appeared_cb,
parameters_install);
return;
out:
/* show an unhelpful dialog */
show_unhandled_type_error (parameters_install);
}
typedef struct
{
GtkWindow *parent_window;
NautilusFile *file;
} ActivateParametersDesktop;
static void
activate_parameters_desktop_free (ActivateParametersDesktop *parameters_desktop)
{
if (parameters_desktop->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
nautilus_file_unref (parameters_desktop->file);
g_free (parameters_desktop);
}
static void
untrusted_launcher_response_callback (GtkDialog *dialog,
int response_id,
ActivateParametersDesktop *parameters)
{
GdkScreen *screen;
char *uri;
GFile *file;
switch (response_id)
{
case GTK_RESPONSE_OK:
{
file = nautilus_file_get_location (parameters->file);
/* We need to do this in order to prevent malicious desktop files
* with the executable bit already set.
* See https://bugzilla.gnome.org/show_bug.cgi?id=777991
*/
nautilus_file_set_metadata (parameters->file, NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED,
NULL,
"yes");
nautilus_file_mark_desktop_file_executable (file,
parameters->parent_window,
TRUE,
NULL, NULL);
/* Need to force a reload of the attributes so is_trusted is marked
* correctly. Not sure why the general monitor doesn't fire in this
* case when setting the metadata
*/
nautilus_file_invalidate_all_attributes (parameters->file);
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
uri = nautilus_file_get_uri (parameters->file);
DEBUG ("Launching untrusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
g_object_unref (file);
}
break;
default:
{
/* Just destroy dialog */
}
break;
}
gtk_widget_destroy (GTK_WIDGET (dialog));
activate_parameters_desktop_free (parameters);
}
static void
activate_desktop_file (ActivateParameters *parameters,
NautilusFile *file)
{
ActivateParametersDesktop *parameters_desktop;
char *primary, *secondary, *display_name;
GtkWidget *dialog;
GdkScreen *screen;
char *uri;
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
if (!nautilus_file_is_trusted_link (file))
{
/* copy the parts of parameters we are interested in as the orignal will be freed */
parameters_desktop = g_new0 (ActivateParametersDesktop, 1);
if (parameters->parent_window)
{
parameters_desktop->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
parameters_desktop->file = nautilus_file_ref (file);
primary = _("Untrusted application launcher");
display_name = nautilus_file_get_display_name (file);
secondary =
g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. "
"If you do not know the source of this file, launching it may be unsafe."
),
display_name);
dialog = gtk_message_dialog_new (parameters->parent_window,
0,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", primary,
"secondary-text", secondary,
NULL);
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);
if (nautilus_file_can_set_permissions (file))
{
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("Trust and _Launch"), GTK_RESPONSE_OK);
}
g_signal_connect (dialog, "response",
G_CALLBACK (untrusted_launcher_response_callback),
parameters_desktop);
gtk_widget_show (dialog);
g_free (display_name);
g_free (secondary);
return;
}
uri = nautilus_file_get_uri (file);
DEBUG ("Launching trusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
static void
activate_files (ActivateParameters *parameters)
{
NautilusFile *file;
NautilusWindow *window;
NautilusWindowOpenFlags flags;
g_autoptr (GList) open_in_app_parameters = NULL;
g_autoptr (GList) unhandled_open_in_app_uris = NULL;
ApplicationLaunchParameters *one_parameters;
int count;
g_autofree char *old_working_dir = NULL;
GdkScreen *screen;
gint num_apps;
gint num_unhandled;
gint num_files;
gboolean open_files;
gboolean closed_window;
g_autoptr (GQueue) launch_desktop_files = NULL;
g_autoptr (GQueue) launch_files = NULL;
g_autoptr (GQueue) launch_in_terminal_files = NULL;
g_autoptr (GQueue) open_in_app_uris = NULL;
g_autoptr (GQueue) open_in_view_files = NULL;
GList *l;
ActivationAction action;
LaunchLocation *location;
launch_desktop_files = g_queue_new ();
launch_files = g_queue_new ();
launch_in_terminal_files = g_queue_new ();
open_in_view_files = g_queue_new ();
open_in_app_uris = g_queue_new ();
for (l = parameters->locations; l != NULL; l = l->next)
{
location = l->data;
file = location->file;
if (file_was_cancelled (file))
{
continue;
}
action = get_activation_action (file);
if (action == ACTIVATION_ACTION_ASK)
{
/* Special case for executable text files, since it might be
* dangerous & unexpected to launch these.
*/
pause_activation_timed_cancel (parameters);
action = get_executable_text_file_action (parameters->parent_window, file);
unpause_activation_timed_cancel (parameters);
}
switch (action)
{
case ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE:
{
g_queue_push_tail (launch_desktop_files, file);
}
break;
case ACTIVATION_ACTION_LAUNCH:
{
g_queue_push_tail (launch_files, file);
}
break;
case ACTIVATION_ACTION_LAUNCH_IN_TERMINAL:
{
g_queue_push_tail (launch_in_terminal_files, file);
}
break;
case ACTIVATION_ACTION_OPEN_IN_VIEW:
{
g_queue_push_tail (open_in_view_files, file);
}
break;
case ACTIVATION_ACTION_OPEN_IN_APPLICATION:
{
g_queue_push_tail (open_in_app_uris, location->uri);
}
break;
case ACTIVATION_ACTION_DO_NOTHING:
{
}
break;
case ACTIVATION_ACTION_EXTRACT:
{
/* Extraction of files should be handled in the view */
g_assert_not_reached ();
}
break;
case ACTIVATION_ACTION_ASK:
{
g_assert_not_reached ();
}
break;
}
}
for (l = g_queue_peek_head_link (launch_desktop_files); l != NULL; l = l->next)
{
file = NAUTILUS_FILE (l->data);
activate_desktop_file (parameters, file);
}
if (parameters->activation_directory &&
(!g_queue_is_empty (launch_files) ||
!g_queue_is_empty (launch_in_terminal_files)))
{
old_working_dir = g_get_current_dir ();
g_chdir (parameters->activation_directory);
}
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
for (l = g_queue_peek_head_link (launch_files); l != NULL; l = l->next)
{
g_autofree char *uri = NULL;
g_autofree char *executable_path = NULL;
g_autofree char *quoted_path = NULL;
file = NAUTILUS_FILE (l->data);
uri = nautilus_file_get_activation_uri (file);
executable_path = g_filename_from_uri (uri, NULL, NULL);
quoted_path = g_shell_quote (executable_path);
DEBUG ("Launching file path %s", quoted_path);
nautilus_launch_application_from_command (screen, quoted_path, FALSE, NULL);
}
for (l = g_queue_peek_head_link (launch_in_terminal_files); l != NULL; l = l->next)
{
g_autofree char *uri = NULL;
g_autofree char *executable_path = NULL;
g_autofree char *quoted_path = NULL;
file = NAUTILUS_FILE (l->data);
uri = nautilus_file_get_activation_uri (file);
executable_path = g_filename_from_uri (uri, NULL, NULL);
quoted_path = g_shell_quote (executable_path);
DEBUG ("Launching in terminal file quoted path %s", quoted_path);
nautilus_launch_application_from_command (screen, quoted_path, TRUE, NULL);
}
if (old_working_dir != NULL)
{
g_chdir (old_working_dir);
}
count = g_queue_get_length (open_in_view_files);
flags = parameters->flags;
if (count > 1)
{
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0)
{
/* if CLOSE_BEHIND is set and we have a directory to be activated, we
* will first have to open a new window and after that we can open the
* rest of files in tabs */
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0)
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW;
}
else
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB;
}
}
else
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW;
}
}
else
{
/* if we want to close the window and activate a single directory, then we will need
* the NEW_WINDOW flag set */
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0)
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW;
}
}
if (parameters->slot != NULL &&
(!parameters->user_confirmation ||
confirm_multiple_windows (parameters->parent_window, count,
(flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0)))
{
if ((flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0 &&
g_settings_get_enum (nautilus_preferences, NAUTILUS_PREFERENCES_NEW_TAB_POSITION) ==
NAUTILUS_NEW_TAB_POSITION_AFTER_CURRENT_TAB)
{
/* When inserting N tabs after the current one,
* we first open tab N, then tab N-1, ..., then tab 0.
* Each of them is appended to the current tab, i.e.
* prepended to the list of tabs to open.
*/
g_queue_reverse (open_in_view_files);
}
closed_window = FALSE;
for (l = g_queue_peek_head_link (open_in_view_files); l != NULL; l = l->next)
{
g_autofree char *uri = NULL;
g_autoptr (GFile) location = NULL;
g_autoptr (GFile) location_with_permissions = NULL;
/* The ui should ask for navigation or object windows
* depending on what the current one is */
file = NAUTILUS_FILE (l->data);
uri = nautilus_file_get_activation_uri (file);
location = g_file_new_for_uri (uri);
if (g_file_is_native (location) &&
(nautilus_file_is_in_admin (file) ||
!nautilus_file_can_read (file) ||
!nautilus_file_can_execute (file)))
{
g_autofree gchar *file_path = NULL;
g_free (uri);
file_path = g_file_get_path (location);
uri = g_strconcat ("admin://", file_path, NULL);
}
location_with_permissions = g_file_new_for_uri (uri);
/* FIXME: we need to pass the parent_window, but we only use it for the current active window,
* which nautilus-application should take care of. However is not working and creating regressions
* in some cases. Until we figure out what's going on, continue to use the parameters->slot
* to make splicit the window we want to use for activating the files */
nautilus_application_open_location_full (NAUTILUS_APPLICATION (g_application_get_default ()),
location_with_permissions, flags, NULL, NULL, parameters->slot);
/* close only the window from which the action was launched and then open
* tabs/windows (depending on parameters->flags) */
if (!closed_window && (flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0)
{
flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND);
/* if NEW_WINDOW is set, we want all files in new windows, not in tabs */
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0)
{
flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW);
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB;
}
closed_window = TRUE;
}
}
}
if (open_in_app_uris != NULL)
{
open_in_app_parameters = make_activation_parameters (g_queue_peek_head_link (open_in_app_uris),
&unhandled_open_in_app_uris);
}
num_apps = g_list_length (open_in_app_parameters);
num_unhandled = g_list_length (unhandled_open_in_app_uris);
num_files = g_queue_get_length (open_in_app_uris);
open_files = TRUE;
if (g_queue_is_empty (open_in_app_uris) &&
(!parameters->user_confirmation ||
num_files + num_unhandled > SILENT_OPEN_LIMIT) &&
num_apps > 1)
{
GtkDialog *dialog;
char *prompt;
g_autofree char *detail = NULL;
int response;
pause_activation_timed_cancel (parameters);
prompt = _("Are you sure you want to open all files?");
detail = g_strdup_printf (ngettext ("This will open %d separate application.",
"This will open %d separate applications.", num_apps), num_apps);
dialog = eel_show_yes_no_dialog (prompt, detail,
_("_OK"), _("_Cancel"),
parameters->parent_window);
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
unpause_activation_timed_cancel (parameters);
if (response != GTK_RESPONSE_YES)
{
open_files = FALSE;
}
}
if (open_files)
{
for (l = open_in_app_parameters; l != NULL; l = l->next)
{
one_parameters = l->data;
nautilus_launch_application_by_uri (one_parameters->application,
one_parameters->uris,
parameters->parent_window);
application_launch_parameters_free (one_parameters);
}
for (l = unhandled_open_in_app_uris; l != NULL; l = l->next)
{
char *uri = l->data;
/* this does not block */
application_unhandled_uri (parameters, uri);
}
}
window = NULL;
if (parameters->slot != NULL)
{
window = nautilus_window_slot_get_window (parameters->slot);
}
if (open_in_app_parameters != NULL ||
unhandled_open_in_app_uris != NULL)
{
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0 &&
window != NULL)
{
nautilus_window_close (window);
}
}
activation_parameters_free (parameters);
}
static void
activation_mount_not_mounted_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
ActivateParameters *parameters = user_data;
GError *error;
NautilusFile *file;
LaunchLocation *loc;
file = parameters->not_mounted->data;
error = NULL;
if (!g_file_mount_enclosing_volume_finish (G_FILE (source_object), res, &error))
{
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_CANCELLED &&
error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED))
{
eel_show_error_dialog (_("Unable to access location"), error->message, parameters->parent_window);
}
if (error->domain != G_IO_ERROR ||
error->code != G_IO_ERROR_ALREADY_MOUNTED)
{
loc = find_launch_location_for_file (parameters->locations,
file);
if (loc)
{
parameters->locations =
g_list_remove (parameters->locations, loc);
launch_location_free (loc);
}
}
g_error_free (error);
}
parameters->not_mounted = g_list_delete_link (parameters->not_mounted,
parameters->not_mounted);
nautilus_file_unref (file);
activation_mount_not_mounted (parameters);
}
static void
activation_mount_not_mounted (ActivateParameters *parameters)
{
NautilusFile *file;
GFile *location;
LaunchLocation *loc;
GMountOperation *mount_op;
GList *l, *next, *files;
if (parameters->not_mounted != NULL)
{
file = parameters->not_mounted->data;
mount_op = gtk_mount_operation_new (parameters->parent_window);
g_mount_operation_set_password_save (mount_op, G_PASSWORD_SAVE_FOR_SESSION);
g_signal_connect (mount_op, "notify::is-showing",
G_CALLBACK (activate_mount_op_active), parameters);
location = nautilus_file_get_location (file);
g_file_mount_enclosing_volume (location, 0, mount_op, parameters->cancellable,
activation_mount_not_mounted_callback, parameters);
g_object_unref (location);
/* unref mount_op here - g_file_mount_enclosing_volume() does ref for itself */
g_object_unref (mount_op);
return;
}
parameters->tried_mounting = TRUE;
if (parameters->locations == NULL)
{
activation_parameters_free (parameters);
return;
}
/* once the mount is finished, refresh all attributes */
/* - fixes new windows not appearing after successful mount */
for (l = parameters->locations; l != NULL; l = next)
{
loc = l->data;
next = l->next;
nautilus_file_invalidate_all_attributes (loc->file);
}
files = get_file_list_for_launch_locations (parameters->locations);
nautilus_file_list_call_when_ready
(files,
nautilus_mime_actions_get_required_file_attributes (),
¶meters->files_handle,
activate_callback, parameters);
nautilus_file_list_free (files);
}
static void
activate_callback (GList *files,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
GList *l, *next;
NautilusFile *file;
LaunchLocation *location;
parameters->files_handle = NULL;
for (l = parameters->locations; l != NULL; l = next)
{
location = l->data;
file = location->file;
next = l->next;
if (file_was_cancelled (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
if (file_was_not_mounted (file))
{
if (parameters->tried_mounting)
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
}
else
{
parameters->not_mounted = g_list_prepend (parameters->not_mounted,
nautilus_file_ref (file));
}
continue;
}
}
if (parameters->not_mounted != NULL)
{
activation_mount_not_mounted (parameters);
}
else
{
activate_files (parameters);
}
}
static void
activate_activation_uris_ready_callback (GList *files_ignore,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
GList *l, *next, *files;
NautilusFile *file;
LaunchLocation *location;
parameters->files_handle = NULL;
for (l = parameters->locations; l != NULL; l = next)
{
location = l->data;
file = location->file;
next = l->next;
if (file_was_cancelled (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
if (nautilus_file_is_broken_symbolic_link (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
pause_activation_timed_cancel (parameters);
report_broken_symbolic_link (parameters->parent_window, file);
unpause_activation_timed_cancel (parameters);
continue;
}
if (nautilus_file_get_file_type (file) == G_FILE_TYPE_MOUNTABLE &&
!nautilus_file_has_activation_uri (file))
{
/* Don't launch these... There is nothing we
* can do */
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
}
if (parameters->locations == NULL)
{
activation_parameters_free (parameters);
return;
}
/* Convert the files to the actual activation uri files */
for (l = parameters->locations; l != NULL; l = l->next)
{
char *uri;
location = l->data;
/* We want the file for the activation URI since we care
* about the attributes for that, not for the original file.
*/
uri = nautilus_file_get_activation_uri (location->file);
if (uri != NULL)
{
launch_location_update_from_uri (location, uri);
}
g_free (uri);
}
/* get the parameters for the actual files */
files = get_file_list_for_launch_locations (parameters->locations);
nautilus_file_list_call_when_ready
(files,
nautilus_mime_actions_get_required_file_attributes (),
¶meters->files_handle,
activate_callback, parameters);
nautilus_file_list_free (files);
}
static void
activation_get_activation_uris (ActivateParameters *parameters)
{
GList *l, *files;
NautilusFile *file;
LaunchLocation *location;
/* link target info might be stale, re-read it */
for (l = parameters->locations; l != NULL; l = l->next)
{
location = l->data;
file = location->file;
if (file_was_cancelled (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
}
if (parameters->locations == NULL)
{
activation_parameters_free (parameters);
return;
}
files = get_file_list_for_launch_locations (parameters->locations);
nautilus_file_list_call_when_ready
(files, nautilus_mime_actions_get_required_file_attributes (),
¶meters->files_handle,
activate_activation_uris_ready_callback, parameters);
nautilus_file_list_free (files);
}
static void
activation_mountable_mounted (NautilusFile *file,
GFile *result_location,
GError *error,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
NautilusFile *target_file;
LaunchLocation *location;
/* Remove from list of files that have to be mounted */
parameters->mountables = g_list_remove (parameters->mountables, file);
nautilus_file_unref (file);
if (error == NULL)
{
/* Replace file with the result of the mount */
target_file = nautilus_file_get (result_location);
location = find_launch_location_for_file (parameters->locations,
file);
if (location)
{
launch_location_update_from_file (location, target_file);
}
nautilus_file_unref (target_file);
}
else
{
/* Remove failed file */
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED))
{
location = find_launch_location_for_file (parameters->locations,
file);
if (location)
{
parameters->locations =
g_list_remove (parameters->locations,
location);
launch_location_free (location);
}
}
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_CANCELLED &&
error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED))
{
eel_show_error_dialog (_("Unable to access location"),
error->message, parameters->parent_window);
}
if (error->code == G_IO_ERROR_CANCELLED)
{
activation_parameters_free (parameters);
return;
}
}
/* Mount more mountables */
activation_mount_mountables (parameters);
}
static void
activation_mount_mountables (ActivateParameters *parameters)
{
NautilusFile *file;
GMountOperation *mount_op;
if (parameters->mountables != NULL)
{
file = parameters->mountables->data;
mount_op = gtk_mount_operation_new (parameters->parent_window);
g_mount_operation_set_password_save (mount_op, G_PASSWORD_SAVE_FOR_SESSION);
g_signal_connect (mount_op, "notify::is-showing",
G_CALLBACK (activate_mount_op_active), parameters);
nautilus_file_mount (file,
mount_op,
parameters->cancellable,
activation_mountable_mounted,
parameters);
g_object_unref (mount_op);
return;
}
if (parameters->mountables == NULL && parameters->start_mountables == NULL)
{
activation_get_activation_uris (parameters);
}
}
static void
activation_mountable_started (NautilusFile *file,
GFile *gfile_of_file,
GError *error,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
LaunchLocation *location;
/* Remove from list of files that have to be mounted */
parameters->start_mountables = g_list_remove (parameters->start_mountables, file);
nautilus_file_unref (file);
if (error == NULL)
{
/* Remove file */
location = find_launch_location_for_file (parameters->locations, file);
if (location != NULL)
{
parameters->locations = g_list_remove (parameters->locations, location);
launch_location_free (location);
}
}
else
{
/* Remove failed file */
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_FAILED_HANDLED))
{
location = find_launch_location_for_file (parameters->locations,
file);
if (location)
{
parameters->locations =
g_list_remove (parameters->locations,
location);
launch_location_free (location);
}
}
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_CANCELLED &&
error->code != G_IO_ERROR_FAILED_HANDLED))
{
eel_show_error_dialog (_("Unable to start location"),
error->message, NULL);
}
if (error->code == G_IO_ERROR_CANCELLED)
{
activation_parameters_free (parameters);
return;
}
}
/* Start more mountables */
activation_start_mountables (parameters);
}
static void
activation_start_mountables (ActivateParameters *parameters)
{
NautilusFile *file;
GMountOperation *start_op;
if (parameters->start_mountables != NULL)
{
file = parameters->start_mountables->data;
start_op = gtk_mount_operation_new (parameters->parent_window);
g_signal_connect (start_op, "notify::is-showing",
G_CALLBACK (activate_mount_op_active), parameters);
nautilus_file_start (file,
start_op,
parameters->cancellable,
activation_mountable_started,
parameters);
g_object_unref (start_op);
return;
}
if (parameters->mountables == NULL && parameters->start_mountables == NULL)
{
activation_get_activation_uris (parameters);
}
}
/**
* nautilus_mime_activate_files:
*
* Activate a list of files. Each one might launch with an application or
* with a component. This is normally called only by subclasses.
* @view: FMDirectoryView in question.
* @files: A GList of NautilusFiles to activate.
*
**/
void
nautilus_mime_activate_files (GtkWindow *parent_window,
NautilusWindowSlot *slot,
GList *files,
const char *launch_directory,
NautilusWindowOpenFlags flags,
gboolean user_confirmation)
{
ActivateParameters *parameters;
char *file_name;
int file_count;
GList *l, *next;
NautilusFile *file;
LaunchLocation *location;
if (files == NULL)
{
return;
}
DEBUG_FILES (files, "Calling activate_files() with files:");
parameters = g_new0 (ActivateParameters, 1);
parameters->slot = slot;
g_object_add_weak_pointer (G_OBJECT (parameters->slot), (gpointer *) ¶meters->slot);
if (parent_window)
{
parameters->parent_window = parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters->parent_window), (gpointer *) ¶meters->parent_window);
}
parameters->cancellable = g_cancellable_new ();
parameters->activation_directory = g_strdup (launch_directory);
parameters->locations = launch_locations_from_file_list (files);
parameters->flags = flags;
parameters->user_confirmation = user_confirmation;
file_count = g_list_length (files);
if (file_count == 1)
{
file_name = nautilus_file_get_display_name (files->data);
parameters->timed_wait_prompt = g_strdup_printf (_("Opening “%s”."), file_name);
g_free (file_name);
}
else
{
parameters->timed_wait_prompt = g_strdup_printf (ngettext ("Opening %d item.",
"Opening %d items.",
file_count),
file_count);
}
for (l = parameters->locations; l != NULL; l = next)
{
location = l->data;
file = location->file;
next = l->next;
if (nautilus_file_can_mount (file))
{
parameters->mountables = g_list_prepend (parameters->mountables,
nautilus_file_ref (file));
}
if (nautilus_file_can_start (file))
{
parameters->start_mountables = g_list_prepend (parameters->start_mountables,
nautilus_file_ref (file));
}
}
activation_start_timed_cancel (parameters);
if (parameters->mountables != NULL)
{
activation_mount_mountables (parameters);
}
if (parameters->start_mountables != NULL)
{
activation_start_mountables (parameters);
}
if (parameters->mountables == NULL && parameters->start_mountables == NULL)
{
activation_get_activation_uris (parameters);
}
}
/**
* nautilus_mime_activate_file:
*
* Activate a file in this view. This might involve switching the displayed
* location for the current window, or launching an application.
* @view: FMDirectoryView in question.
* @file: A NautilusFile representing the file in this view to activate.
* @use_new_window: Should this item be opened in a new window?
*
**/
void
nautilus_mime_activate_file (GtkWindow *parent_window,
NautilusWindowSlot *slot,
NautilusFile *file,
const char *launch_directory,
NautilusWindowOpenFlags flags)
{
GList *files;
g_return_if_fail (NAUTILUS_IS_FILE (file));
files = g_list_prepend (NULL, file);
nautilus_mime_activate_files (parent_window, slot, files, launch_directory, flags, FALSE);
g_list_free (files);
}
gint
nautilus_mime_types_get_number_of_groups (void)
{
return G_N_ELEMENTS (mimetype_groups);
}
const gchar *
nautilus_mime_types_group_get_name (gint group_index)
{
g_return_val_if_fail (group_index < G_N_ELEMENTS (mimetype_groups), NULL);
return gettext (mimetype_groups[group_index].name);
}
GList *
nautilus_mime_types_group_get_mimetypes (gint group_index)
{
GList *mimetypes;
gint i;
g_return_val_if_fail (group_index < G_N_ELEMENTS (mimetype_groups), NULL);
mimetypes = NULL;
/* Setup the new mimetypes set */
for (i = 0; mimetype_groups[group_index].mimetypes[i]; i++)
{
mimetypes = g_list_append (mimetypes, mimetype_groups[group_index].mimetypes[i]);
}
return mimetypes;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2802_5 |
crossvul-cpp_data_bad_19_0 | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.memcached.org/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <mellon@pobox.com>
* Brad Fitzpatrick <brad@danga.com>
*/
#include "memcached.h"
#ifdef EXTSTORE
#include "storage.h"
#endif
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sysexits.h>
#include <stddef.h>
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#endif
/* FreeBSD 4.x doesn't have IOV_MAX exposed. */
#ifndef IOV_MAX
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__)
# define IOV_MAX 1024
/* GNU/Hurd don't set MAXPATHLEN
* http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */
#ifndef MAXPATHLEN
#define MAXPATHLEN 4096
#endif
#endif
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static int try_read_command(conn *c);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static void conn_set_state(conn *c, enum conn_states state);
static int start_conn_timeout_thread();
/* stats */
static void stats_init(void);
static void server_stats(ADD_STAT add_stats, conn *c);
static void process_stat_settings(ADD_STAT add_stats, void *c);
static void conn_to_str(const conn *c, char *buf);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void process_command(conn *c, char *command);
static void write_and_free(conn *c, char *buf, int bytes);
static int ensure_iov_space(conn *c);
static int add_iov(conn *c, const void *buf, int len);
static int add_chunked_item_iovs(conn *c, item *it, int len);
static int add_msghdr(conn *c);
static void write_bin_error(conn *c, protocol_binary_response_status err,
const char *errstr, int swallow);
static void write_bin_miss_response(conn *c, char *key, size_t nkey);
#ifdef EXTSTORE
static void _get_extstore_cb(void *e, obj_io *io, int ret);
static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt);
#endif
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct stats_state stats_state;
struct settings settings;
time_t process_started; /* when the process was started */
conn **conns;
struct slab_rebalance slab_rebal;
volatile int slab_rebalance_signal;
#ifdef EXTSTORE
/* hoping this is temporary; I'd prefer to cut globals, but will complete this
* battle another day.
*/
void *ext_storage;
#endif
/** file scope variables **/
static conn *listen_conn = NULL;
static int max_fds;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
static enum transmit_result transmit(conn *c);
/* This reduces the latency without adding lots of extra wiring to be able to
* notify the listener thread of when to listen again.
* Also, the clock timer could be broken out into its own thread and we
* can block the listener via a condition.
*/
static volatile bool allow_new_conns = true;
static struct event maxconnsevent;
static void maxconns_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 0, .tv_usec = 10000};
if (fd == -42 || allow_new_conns == false) {
/* reschedule in 10ms if we need to keep polling */
evtimer_set(&maxconnsevent, maxconns_handler, 0);
event_base_set(main_base, &maxconnsevent);
evtimer_add(&maxconnsevent, &t);
} else {
evtimer_del(&maxconnsevent);
accept_new_conns(true);
}
}
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
static rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
memset(&stats, 0, sizeof(struct stats));
memset(&stats_state, 0, sizeof(struct stats_state));
stats_state.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - ITEM_UPDATE_INTERVAL - 2;
stats_prefix_init();
}
static void stats_reset(void) {
STATS_LOCK();
memset(&stats, 0, sizeof(struct stats));
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 11211;
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.oldest_cas = 0; /* supplements accuracy of oldest_live */
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.num_threads_per_udp = 0;
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */
settings.slab_chunk_size_max = settings.slab_page_size / 2;
settings.sasl = false;
settings.maxconns_fast = true;
settings.lru_crawler = false;
settings.lru_crawler_sleep = 100;
settings.lru_crawler_tocrawl = 0;
settings.lru_maintainer_thread = false;
settings.lru_segmented = true;
settings.hot_lru_pct = 20;
settings.warm_lru_pct = 40;
settings.hot_max_factor = 0.2;
settings.warm_max_factor = 2.0;
settings.inline_ascii_response = false;
settings.temp_lru = false;
settings.temporary_ttl = 61;
settings.idle_timeout = 0; /* disabled */
settings.hashpower_init = 0;
settings.slab_reassign = true;
settings.slab_automove = 1;
settings.slab_automove_ratio = 0.8;
settings.slab_automove_window = 30;
settings.shutdown_command = false;
settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT;
settings.flush_enabled = true;
settings.dump_enabled = true;
settings.crawls_persleep = 1000;
settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE;
settings.logger_buf_size = LOGGER_BUF_SIZE;
settings.drop_privileges = true;
#ifdef MEMCACHED_DEBUG
settings.relaxed_privileges = false;
#endif
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_msghdr(conn *c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (! msg) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
if (IS_UDP(c->transport) && c->request_addr_size > 0) {
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
}
c->msgbytes = 0;
c->msgused++;
if (IS_UDP(c->transport)) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE);
}
return 0;
}
extern pthread_mutex_t conn_lock;
/* Connection timeout thread bits */
static pthread_t conn_timeout_tid;
#define CONNS_PER_SLICE 100
#define TIMEOUT_MSG_SIZE (1 + sizeof(int))
static void *conn_timeout_thread(void *arg) {
int i;
conn *c;
char buf[TIMEOUT_MSG_SIZE];
rel_time_t oldest_last_cmd;
int sleep_time;
useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE);
while(1) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread at top of connection list\n");
oldest_last_cmd = current_time;
for (i = 0; i < max_fds; i++) {
if ((i % CONNS_PER_SLICE) == 0) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread sleeping for %ulus\n",
(unsigned int)timeslice);
usleep(timeslice);
}
if (!conns[i])
continue;
c = conns[i];
if (!IS_TCP(c->transport))
continue;
if (c->state != conn_new_cmd && c->state != conn_read)
continue;
if ((current_time - c->last_cmd_time) > settings.idle_timeout) {
buf[0] = 't';
memcpy(&buf[1], &i, sizeof(int));
if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE)
!= TIMEOUT_MSG_SIZE)
perror("Failed to write timeout to notify pipe");
} else {
if (c->last_cmd_time < oldest_last_cmd)
oldest_last_cmd = c->last_cmd_time;
}
}
/* This is the soonest we could have another connection time out */
sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1;
if (sleep_time <= 0)
sleep_time = 1;
if (settings.verbose > 2)
fprintf(stderr,
"idle timeout thread finished pass, sleeping for %ds\n",
sleep_time);
usleep((useconds_t) sleep_time * 1000000);
}
return NULL;
}
static int start_conn_timeout_thread() {
int ret;
if (settings.idle_timeout == 0)
return -1;
if ((ret = pthread_create(&conn_timeout_tid, NULL,
conn_timeout_thread, NULL)) != 0) {
fprintf(stderr, "Can't create idle connection timeout thread: %s\n",
strerror(ret));
return -1;
}
return 0;
}
/*
* Initializes the connections array. We don't actually allocate connection
* structures until they're needed, so as to avoid wasting memory when the
* maximum connection count is much higher than the actual number of
* connections.
*
* This does end up wasting a few pointers' worth of memory for FDs that are
* used for things other than connections, but that's worth it in exchange for
* being able to directly index the conns array by FD.
*/
static void conn_init(void) {
/* We're unlikely to see an FD much higher than maxconns. */
int next_fd = dup(1);
int headroom = 10; /* account for extra unexpected open FDs */
struct rlimit rl;
max_fds = settings.maxconns + headroom + next_fd;
/* But if possible, get the actual highest FD we can possibly ever see. */
if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
max_fds = rl.rlim_max;
} else {
fprintf(stderr, "Failed to query maximum file descriptor; "
"falling back to maxconns\n");
}
close(next_fd);
if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
/* This is unrecoverable so bail out early. */
exit(1);
}
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
}
return rv;
}
void conn_close_idle(conn *c) {
if (settings.idle_timeout > 0 &&
(current_time - c->last_cmd_time) > settings.idle_timeout) {
if (c->state != conn_new_cmd && c->state != conn_read) {
if (settings.verbose > 1)
fprintf(stderr,
"fd %d wants to timeout, but isn't in read state", c->sfd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, "Closing idle fd %d\n", c->sfd);
c->thread->stats.idle_kicks++;
conn_set_state(c, conn_closing);
drive_machine(c);
}
}
/* bring conn back from a sidethread. could have had its event base moved. */
void conn_worker_readd(conn *c) {
c->ev_flags = EV_READ | EV_PERSIST;
event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c);
event_base_set(c->thread->base, &c->event);
c->state = conn_new_cmd;
// TODO: call conn_cleanup/fail/etc
if (event_add(&c->event, 0) == -1) {
perror("event_add");
}
#ifdef EXTSTORE
// If we had IO objects, process
if (c->io_wraplist) {
//assert(c->io_wrapleft == 0); // assert no more to process
conn_set_state(c, conn_mwrite);
drive_machine(c);
}
#endif
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base) {
conn *c;
assert(sfd >= 0 && sfd < max_fds);
c = conns[sfd];
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate connection object\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->rbuf = c->wbuf = 0;
c->ilist = 0;
c->suffixlist = 0;
c->iov = 0;
c->msglist = 0;
c->hdrbuf = 0;
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->suffixsize = SUFFIX_LIST_INITIAL;
c->iovsize = IOV_LIST_INITIAL;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize);
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 ||
c->msglist == 0 || c->suffixlist == 0) {
conn_free(c);
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate buffers for connection\n");
return NULL;
}
STATS_LOCK();
stats_state.conn_structs++;
STATS_UNLOCK();
c->sfd = sfd;
conns[sfd] = c;
}
c->transport = transport;
c->protocol = settings.binding_protocol;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (transport == tcp_transport && init_state == conn_new_cmd) {
if (getpeername(sfd, (struct sockaddr *) &c->request_addr,
&c->request_addr_size)) {
perror("getpeername");
memset(&c->request_addr, 0, sizeof(c->request_addr));
}
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = c->wbytes = 0;
c->wcurr = c->wbuf;
c->rcurr = c->rbuf;
c->ritem = 0;
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
c->ileft = 0;
c->suffixleft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->authenticated = false;
c->last_cmd_time = current_time; /* initialize for idle kicker */
#ifdef EXTSTORE
c->io_wraplist = NULL;
c->io_wrapleft = 0;
#endif
c->write_and_go = init_state;
c->write_and_free = 0;
c->item = 0;
c->noreply = false;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
perror("event_add");
return NULL;
}
STATS_LOCK();
stats_state.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
#ifdef EXTSTORE
static void recache_or_free(conn *c, io_wrap *wrap) {
item *it;
it = (item *)wrap->io.buf;
bool do_free = true;
// If request was ultimately a miss, unlink the header.
if (wrap->miss) {
do_free = false;
size_t ntotal = ITEM_ntotal(wrap->hdr_it);
item_unlink(wrap->hdr_it);
slabs_free(it, ntotal, slabs_clsid(ntotal));
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.miss_from_extstore++;
if (wrap->badcrc)
c->thread->stats.badcrc_from_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
} else if (settings.ext_recache_rate) {
// hashvalue is cuddled during store
uint32_t hv = (uint32_t)it->time;
// opt to throw away rather than wait on a lock.
void *hold_lock = item_trylock(hv);
if (hold_lock != NULL) {
item *h_it = wrap->hdr_it;
uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE;
// Item must be recently hit at least twice to recache.
if (((h_it->it_flags & flags) == flags) &&
h_it->time > current_time - ITEM_UPDATE_INTERVAL &&
c->recache_counter++ % settings.ext_recache_rate == 0) {
do_free = false;
// In case it's been updated.
it->exptime = h_it->exptime;
it->it_flags &= ~ITEM_LINKED;
it->refcount = 0;
it->h_next = NULL; // might not be necessary.
STORAGE_delete(c->thread->storage, h_it);
item_replace(h_it, it, hv);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.recache_from_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
if (hold_lock)
item_trylock_unlock(hold_lock);
}
if (do_free)
slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it));
wrap->io.buf = NULL; // sanity.
wrap->io.next = NULL;
wrap->next = NULL;
wrap->active = false;
// TODO: reuse lock and/or hv.
item_remove(wrap->hdr_it);
}
#endif
static void conn_release_items(conn *c) {
assert(c != NULL);
if (c->item) {
item_remove(c->item);
c->item = 0;
}
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
if (c->suffixleft != 0) {
for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) {
do_cache_free(c->thread->suffix_cache, *(c->suffixcurr));
}
}
#ifdef EXTSTORE
if (c->io_wraplist) {
io_wrap *tmp = c->io_wraplist;
while (tmp) {
io_wrap *next = tmp->next;
recache_or_free(c, tmp);
do_cache_free(c->thread->io_cache, tmp); // lockless
tmp = next;
}
c->io_wraplist = NULL;
}
#endif
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
conn_release_items(c);
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
if (IS_UDP(c->transport)) {
conn_set_state(c, conn_read);
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
assert(c != NULL);
assert(c->sfd >= 0 && c->sfd < max_fds);
MEMCACHED_CONN_DESTROY(c);
conns[c->sfd] = NULL;
if (c->hdrbuf)
free(c->hdrbuf);
if (c->msglist)
free(c->msglist);
if (c->rbuf)
free(c->rbuf);
if (c->wbuf)
free(c->wbuf);
if (c->ilist)
free(c->ilist);
if (c->suffixlist)
free(c->suffixlist);
if (c->iov)
free(c->iov);
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
conn_cleanup(c);
MEMCACHED_CONN_RELEASE(c->sfd);
conn_set_state(c, conn_closed);
close(c->sfd);
pthread_mutex_lock(&conn_lock);
allow_new_conns = true;
pthread_mutex_unlock(&conn_lock);
STATS_LOCK();
stats_state.curr_conns--;
STATS_UNLOCK();
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
static void conn_shrink(conn *c) {
assert(c != NULL);
if (IS_UDP(c->transport))
return;
if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) {
char *newbuf;
if (c->rcurr != c->rbuf)
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
if (newbuf) {
c->rbuf = newbuf;
c->rsize = DATA_BUFFER_SIZE;
}
/* TODO check other branch... */
c->rcurr = c->rbuf;
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]));
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0]));
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->iovsize > IOV_LIST_HIGHWAT) {
struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0]));
if (newbuf) {
c->iov = newbuf;
c->iovsize = IOV_LIST_INITIAL;
}
/* TODO check return value */
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite",
"conn_closed",
"conn_watch" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);
if (state != c->state) {
if (settings.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state),
state_text(state));
}
if (state == conn_write || state == conn_mwrite) {
MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes);
}
c->state = state;
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov = (struct iovec *)realloc(c->iov,
(c->iovsize * 2) * sizeof(struct iovec));
if (! new_iov) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->iov = new_iov;
c->iovsize *= 2;
/* Point all the msghdr structures at the new list. */
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* Returns 0 on success, -1 on out-of-memory.
* Note: This is a hot path for at least ASCII protocol. While there is
* redundant code in splitting TCP/UDP handling, any reduction in steps has a
* large impact for TCP connections.
*/
static int add_iov(conn *c, const void *buf, int len) {
struct msghdr *m;
int leftover;
assert(c != NULL);
if (IS_UDP(c->transport)) {
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes.
*/
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
} else {
/* Optimized path for TCP connections */
m = &c->msglist[c->msgused - 1];
if (m->msg_iovlen == IOV_MAX) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
}
return 0;
}
static int add_chunked_item_iovs(conn *c, item *it, int len) {
assert(it->it_flags & ITEM_CHUNKED);
item_chunk *ch = (item_chunk *) ITEM_data(it);
while (ch) {
int todo = (len > ch->used) ? ch->used : len;
if (add_iov(c, ch->data, todo) != 0) {
return -1;
}
ch = ch->next;
len -= todo;
}
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
static int build_udp_headers(conn *c) {
int i;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf) {
new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE);
} else {
new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE);
}
if (! new_hdrbuf) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = (void*)hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = 0;
*hdr++ = 0;
assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn *c, const char *str) {
size_t len;
assert(c != NULL);
if (c->noreply) {
if (settings.verbose > 1)
fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str);
c->noreply = false;
conn_set_state(c, conn_new_cmd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
/* Nuke a partial output... */
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
add_msghdr(c);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
return;
}
/*
* Outputs a protocol-specific "out of memory" error. For ASCII clients,
* this is equivalent to out_string().
*/
static void out_of_memory(conn *c, char *ascii_error) {
const static char error_prefix[] = "SERVER_ERROR ";
const static int error_prefix_len = sizeof(error_prefix) - 1;
if (c->protocol == binary_prot) {
/* Strip off the generic error prefix; it's irrelevant in binary */
if (!strncmp(ascii_error, error_prefix, error_prefix_len)) {
ascii_error += error_prefix_len;
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0);
} else {
out_string(c, ascii_error);
}
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->cmd, and the item is ready in c->item.
*/
static void complete_nread_ascii(conn *c) {
assert(c != NULL);
item *it = c->item;
int comm = c->cmd;
enum store_item_type ret;
bool is_valid = false;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if ((it->it_flags & ITEM_CHUNKED) == 0) {
if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) {
is_valid = true;
}
} else {
char buf[2];
/* should point to the final item chunk */
item_chunk *ch = (item_chunk *) c->ritem;
assert(ch->used != 0);
/* :( We need to look at the last two bytes. This could span two
* chunks.
*/
if (ch->used > 1) {
buf[0] = ch->data[ch->used - 2];
buf[1] = ch->data[ch->used - 1];
} else {
assert(ch->prev);
assert(ch->used == 1);
buf[0] = ch->prev->data[ch->prev->used - 1];
buf[1] = ch->data[ch->used - 1];
}
if (strncmp(buf, "\r\n", 2) == 0) {
is_valid = true;
} else {
assert(1 == 0);
}
}
if (!is_valid) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
ret = store_item(it, comm, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_CAS:
MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes,
cas);
break;
}
#endif
switch (ret) {
case STORED:
out_string(c, "STORED");
break;
case EXISTS:
out_string(c, "EXISTS");
break;
case NOT_FOUND:
out_string(c, "NOT_FOUND");
break;
case NOT_STORED:
out_string(c, "NOT_STORED");
break;
default:
out_string(c, "SERVER_ERROR Unhandled storage type.");
}
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
/**
* get a pointer to the start of the request struct for the current command
*/
static void* binary_get_request(conn *c) {
char *ret = c->rcurr;
ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen +
c->binary_header.request.extlen);
assert(ret >= c->rbuf);
return ret;
}
/**
* get a pointer to the key in this request
*/
static char* binary_get_key(conn *c) {
return c->rcurr - (c->binary_header.request.keylen);
}
static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) {
protocol_binary_response_header* header;
assert(c);
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
/* This should never run out of memory because iov and msg lists
* have minimum sizes big enough to hold an error response.
*/
out_of_memory(c, "SERVER_ERROR out of memory adding binary header");
return;
}
header = (protocol_binary_response_header *)c->wbuf;
header->response.magic = (uint8_t)PROTOCOL_BINARY_RES;
header->response.opcode = c->binary_header.request.opcode;
header->response.keylen = (uint16_t)htons(key_len);
header->response.extlen = (uint8_t)hdr_len;
header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
header->response.status = (uint16_t)htons(err);
header->response.bodylen = htonl(body_len);
header->response.opaque = c->opaque;
header->response.cas = htonll(c->cas);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d Writing bin response:", c->sfd);
for (ii = 0; ii < sizeof(header->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n>%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", header->bytes[ii]);
}
fprintf(stderr, "\n");
}
add_iov(c, c->wbuf, sizeof(header->response));
}
/**
* Writes a binary error response. If errstr is supplied, it is used as the
* error text; otherwise a generic description of the error status code is
* included.
*/
static void write_bin_error(conn *c, protocol_binary_response_status err,
const char *errstr, int swallow) {
size_t len;
if (!errstr) {
switch (err) {
case PROTOCOL_BINARY_RESPONSE_ENOMEM:
errstr = "Out of memory";
break;
case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
errstr = "Unknown command";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
errstr = "Not found";
break;
case PROTOCOL_BINARY_RESPONSE_EINVAL:
errstr = "Invalid arguments";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
errstr = "Data exists for key.";
break;
case PROTOCOL_BINARY_RESPONSE_E2BIG:
errstr = "Too large.";
break;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL:
errstr = "Non-numeric server-side value for incr or decr";
break;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
errstr = "Not stored.";
break;
case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR:
errstr = "Auth failure.";
break;
default:
assert(false);
errstr = "UNHANDLED ERROR";
fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err);
}
}
if (settings.verbose > 1) {
fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr);
}
len = strlen(errstr);
add_bin_header(c, err, 0, 0, len);
if (len > 0) {
add_iov(c, errstr, len);
}
conn_set_state(c, conn_mwrite);
if(swallow > 0) {
c->sbytes = swallow;
c->write_and_go = conn_swallow;
} else {
c->write_and_go = conn_new_cmd;
}
}
/* Form and send a response to a command over the binary protocol */
static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) {
if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET ||
c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_bin_header(c, 0, hlen, keylen, dlen);
if(dlen > 0) {
add_iov(c, d, dlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
conn_set_state(c, conn_new_cmd);
}
}
static void complete_incr_bin(conn *c) {
item *it;
char *key;
size_t nkey;
/* Weird magic in add_delta forces me to pad here */
char tmpbuf[INCR_MAX_STORAGE_LEN];
uint64_t cas = 0;
protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf;
protocol_binary_request_incr* req = binary_get_request(c);
assert(c != NULL);
assert(c->wsize >= sizeof(*rsp));
/* fix byteorder in the request */
req->message.body.delta = ntohll(req->message.body.delta);
req->message.body.initial = ntohll(req->message.body.initial);
req->message.body.expiration = ntohl(req->message.body.expiration);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int i;
fprintf(stderr, "incr ");
for (i = 0; i < nkey; i++) {
fprintf(stderr, "%c", key[i]);
}
fprintf(stderr, " %lld, %llu, %d\n",
(long long)req->message.body.delta,
(long long)req->message.body.initial,
req->message.body.expiration);
}
if (c->binary_header.request.cas != 0) {
cas = c->binary_header.request.cas;
}
switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT,
req->message.body.delta, tmpbuf,
&cas)) {
case OK:
rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10));
if (cas) {
c->cas = cas;
}
write_bin_response(c, &rsp->message.body, 0, 0,
sizeof(rsp->message.body.value));
break;
case NON_NUMERIC:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0);
break;
case EOM:
out_of_memory(c, "SERVER_ERROR Out of memory incrementing value");
break;
case DELTA_ITEM_NOT_FOUND:
if (req->message.body.expiration != 0xffffffff) {
/* Save some room for the response */
rsp->message.body.value = htonll(req->message.body.initial);
snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu",
(unsigned long long)req->message.body.initial);
int res = strlen(tmpbuf);
it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration),
res + 2);
if (it != NULL) {
memcpy(ITEM_data(it), tmpbuf, res);
memcpy(ITEM_data(it) + res, "\r\n", 2);
if (store_item(it, NREAD_ADD, c)) {
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value));
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED,
NULL, 0);
}
item_remove(it); /* release our reference */
} else {
out_of_memory(c,
"SERVER_ERROR Out of memory allocating new item");
}
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
}
break;
case DELTA_ITEM_CAS_MISMATCH:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
break;
}
}
static void complete_update_bin(conn *c) {
protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL;
enum store_item_type ret = NOT_STORED;
assert(c != NULL);
item *it = c->item;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We don't actually receive the trailing two characters in the bin
* protocol, so we're going to just set them here */
if ((it->it_flags & ITEM_CHUNKED) == 0) {
*(ITEM_data(it) + it->nbytes - 2) = '\r';
*(ITEM_data(it) + it->nbytes - 1) = '\n';
} else {
assert(c->ritem);
item_chunk *ch = (item_chunk *) c->ritem;
if (ch->size == ch->used)
ch = ch->next;
assert(ch->size - ch->used >= 2);
ch->data[ch->used] = '\r';
ch->data[ch->used + 1] = '\n';
ch->used += 2;
}
ret = store_item(it, c->cmd, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
}
#endif
switch (ret) {
case STORED:
/* Stored */
write_bin_response(c, NULL, 0, 0, 0);
break;
case EXISTS:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
break;
case NOT_FOUND:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
break;
case NOT_STORED:
case TOO_LARGE:
case NO_MEMORY:
if (c->cmd == NREAD_ADD) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;
} else if(c->cmd == NREAD_REPLACE) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED;
}
write_bin_error(c, eno, NULL, 0);
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
static void write_bin_miss_response(conn *c, char *key, size_t nkey) {
if (nkey) {
char *ofs = c->wbuf + sizeof(protocol_binary_response_header);
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, nkey, nkey);
memcpy(ofs, key, nkey);
add_iov(c, ofs, nkey);
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
NULL, 0);
}
}
static void process_bin_get_or_touch(conn *c) {
item *it;
protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf;
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH ||
c->cmd == PROTOCOL_BINARY_CMD_GAT ||
c->cmd == PROTOCOL_BINARY_CMD_GATK);
int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK ||
c->cmd == PROTOCOL_BINARY_CMD_GATK);
int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH);
bool failed = false;
if (settings.verbose > 1) {
fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET");
if (fwrite(key, 1, nkey, stderr)) {}
fputc('\n', stderr);
}
if (should_touch) {
protocol_binary_request_touch *t = binary_get_request(c);
time_t exptime = ntohl(t->message.body.expiration);
it = item_touch(key, nkey, realtime(exptime), c);
} else {
it = item_get(key, nkey, c, DO_UPDATE);
}
if (it) {
/* the length has two unnecessary bytes ("\r\n") */
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2);
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
} else {
c->thread->stats.get_cmds++;
c->thread->stats.lru_hits[it->slabs_clsid]++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
if (should_touch) {
MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
} else {
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
}
if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) {
bodylen -= it->nbytes - 2;
} else if (should_return_key) {
bodylen += nkey;
keylen = nkey;
}
add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen);
rsp->message.header.response.cas = htonll(ITEM_get_cas(it));
// add the flags
if (settings.inline_ascii_response) {
rsp->message.body.flags = htonl(strtoul(ITEM_suffix(it), NULL, 10));
} else if (it->nsuffix > 0) {
rsp->message.body.flags = htonl(*((uint32_t *)ITEM_suffix(it)));
} else {
rsp->message.body.flags = 0;
}
add_iov(c, &rsp->message.body, sizeof(rsp->message.body));
if (should_return_key) {
add_iov(c, ITEM_key(it), nkey);
}
if (should_return_value) {
/* Add the data minus the CRLF */
#ifdef EXTSTORE
if (it->it_flags & ITEM_HDR) {
int iovcnt = 4;
int iovst = c->iovused - 3;
if (!should_return_key) {
iovcnt = 3;
iovst = c->iovused - 2;
}
// FIXME: this can return an error, but code flow doesn't
// allow bailing here.
if (_get_extstore(c, it, iovst, iovcnt) != 0)
failed = true;
} else if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes - 2);
} else {
add_chunked_item_iovs(c, it, it->nbytes - 2);
}
#else
if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes - 2);
} else {
add_chunked_item_iovs(c, it, it->nbytes - 2);
}
#endif
}
if (!failed) {
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
/* Remember this command so we can garbage collect it later */
#ifdef EXTSTORE
if ((it->it_flags & ITEM_HDR) == 0) {
c->item = it;
} else {
c->item = NULL;
}
#else
c->item = it;
#endif
} else {
item_remove(it);
}
} else {
failed = true;
}
if (failed) {
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
} else {
c->thread->stats.get_cmds++;
c->thread->stats.get_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
if (should_touch) {
MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0);
} else {
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
if (c->noreply) {
conn_set_state(c, conn_new_cmd);
} else {
if (should_return_key) {
write_bin_miss_response(c, key, nkey);
} else {
write_bin_miss_response(c, NULL, 0);
}
}
}
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
}
static void append_bin_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *buf = c->stats.buffer + c->stats.offset;
uint32_t bodylen = klen + vlen;
protocol_binary_response_header header = {
.response.magic = (uint8_t)PROTOCOL_BINARY_RES,
.response.opcode = PROTOCOL_BINARY_CMD_STAT,
.response.keylen = (uint16_t)htons(klen),
.response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES,
.response.bodylen = htonl(bodylen),
.response.opaque = c->opaque
};
memcpy(buf, header.bytes, sizeof(header.response));
buf += sizeof(header.response);
if (klen > 0) {
memcpy(buf, key, klen);
buf += klen;
if (vlen > 0) {
memcpy(buf, val, vlen);
}
}
c->stats.offset += sizeof(header.response) + bodylen;
}
static void append_ascii_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *pos = c->stats.buffer + c->stats.offset;
uint32_t nbytes = 0;
int remaining = c->stats.size - c->stats.offset;
int room = remaining - 1;
if (klen == 0 && vlen == 0) {
nbytes = snprintf(pos, room, "END\r\n");
} else if (vlen == 0) {
nbytes = snprintf(pos, room, "STAT %s\r\n", key);
} else {
nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val);
}
c->stats.offset += nbytes;
}
static bool grow_stats_buf(conn *c, size_t needed) {
size_t nsize = c->stats.size;
size_t available = nsize - c->stats.offset;
bool rv = true;
/* Special case: No buffer -- need to allocate fresh */
if (c->stats.buffer == NULL) {
nsize = 1024;
available = c->stats.size = c->stats.offset = 0;
}
while (needed > available) {
assert(nsize > 0);
nsize = nsize << 1;
available = nsize - c->stats.offset;
}
if (nsize != c->stats.size) {
char *ptr = realloc(c->stats.buffer, nsize);
if (ptr) {
c->stats.buffer = ptr;
c->stats.size = nsize;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
rv = false;
}
}
return rv;
}
static void append_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
const void *cookie)
{
/* value without a key is invalid */
if (klen == 0 && vlen > 0) {
return ;
}
conn *c = (conn*)cookie;
if (c->protocol == binary_prot) {
size_t needed = vlen + klen + sizeof(protocol_binary_response_header);
if (!grow_stats_buf(c, needed)) {
return ;
}
append_bin_stats(key, klen, val, vlen, c);
} else {
size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n"
if (!grow_stats_buf(c, needed)) {
return ;
}
append_ascii_stats(key, klen, val, vlen, c);
}
assert(c->stats.offset <= c->stats.size);
}
static void process_bin_stat(conn *c) {
char *subcommand = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d STATS ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", subcommand[ii]);
}
fprintf(stderr, "\n");
}
if (nkey == 0) {
/* request all statistics */
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strncmp(subcommand, "reset", 5) == 0) {
stats_reset();
} else if (strncmp(subcommand, "settings", 8) == 0) {
process_stat_settings(&append_stats, c);
} else if (strncmp(subcommand, "detail", 6) == 0) {
char *subcmd_pos = subcommand + 6;
if (strncmp(subcmd_pos, " dump", 5) == 0) {
int len;
char *dump_buf = stats_prefix_dump(&len);
if (dump_buf == NULL || len <= 0) {
out_of_memory(c, "SERVER_ERROR Out of memory generating stats");
if (dump_buf != NULL)
free(dump_buf);
return;
} else {
append_stats("detailed", strlen("detailed"), dump_buf, len, c);
free(dump_buf);
}
} else if (strncmp(subcmd_pos, " on", 3) == 0) {
settings.detail_enabled = 1;
} else if (strncmp(subcmd_pos, " off", 4) == 0) {
settings.detail_enabled = 0;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
return;
}
} else {
if (get_stats(subcommand, nkey, &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR Out of memory generating stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
}
return;
}
/* Append termination package and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) {
assert(c);
c->substate = next_substate;
c->rlbytes = c->keylen + extra;
/* Ok... do we have room for the extras and the key in the input buffer? */
ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf;
if (c->rlbytes > c->rsize - offset) {
size_t nsize = c->rsize;
size_t size = c->rlbytes + sizeof(protocol_binary_request_header);
while (size > nsize) {
nsize *= 2;
}
if (nsize != c->rsize) {
if (settings.verbose > 1) {
fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n",
c->sfd, (unsigned long)c->rsize, (unsigned long)nsize);
}
char *newm = realloc(c->rbuf, nsize);
if (newm == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
if (settings.verbose) {
fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n",
c->sfd);
}
conn_set_state(c, conn_closing);
return;
}
c->rbuf= newm;
/* rcurr should point to the same offset in the packet */
c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header);
c->rsize = nsize;
}
if (c->rbuf != c->rcurr) {
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Repack input buffer\n", c->sfd);
}
}
}
/* preserve the header in the buffer.. */
c->ritem = c->rcurr + sizeof(protocol_binary_request_header);
conn_set_state(c, conn_nread);
}
/* Just write an error message and disconnect the client */
static void handle_binary_protocol_error(conn *c) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0);
if (settings.verbose) {
fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n",
c->binary_header.request.opcode, c->sfd);
}
c->write_and_go = conn_closing;
}
static void init_sasl_conn(conn *c) {
assert(c);
/* should something else be returned? */
if (!settings.sasl)
return;
c->authenticated = false;
if (!c->sasl_conn) {
int result=sasl_server_new("memcached",
NULL,
my_sasl_hostname[0] ? my_sasl_hostname : NULL,
NULL, NULL,
NULL, 0, &c->sasl_conn);
if (result != SASL_OK) {
if (settings.verbose) {
fprintf(stderr, "Failed to initialize SASL conn.\n");
}
c->sasl_conn = NULL;
}
}
}
static void bin_list_sasl_mechs(conn *c) {
// Guard against a disabled SASL.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
init_sasl_conn(c);
const char *result_string = NULL;
unsigned int string_length = 0;
int result=sasl_listmech(c->sasl_conn, NULL,
"", /* What to prepend the string with */
" ", /* What to separate mechanisms with */
"", /* What to append to the string */
&result_string, &string_length,
NULL);
if (result != SASL_OK) {
/* Perhaps there's a better error for this... */
if (settings.verbose) {
fprintf(stderr, "Failed to list SASL mechanisms.\n");
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
return;
}
write_bin_response(c, (char*)result_string, 0, 0, string_length);
}
static void process_bin_sasl_auth(conn *c) {
// Guard for handling disabled SASL on the server.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
assert(c->binary_header.request.extlen == 0);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > MAX_SASL_MECH_LEN) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
return;
}
char *key = binary_get_key(c);
assert(key);
item *it = item_alloc(key, nkey, 0, 0, vlen+2);
/* Can't use a chunked item for SASL authentication. */
if (it == 0 || (it->it_flags & ITEM_CHUNKED)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen);
c->write_and_go = conn_swallow;
return;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_reading_sasl_auth_data;
}
static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > ((item*) c->item)->nkey) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
item_unlink(c->item);
return;
}
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
if (vlen > ((item*) c->item)->nbytes) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
item_unlink(c->item);
return;
}
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
c->authenticated = true;
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.auth_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.auth_cmds++;
c->thread->stats.auth_errors++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
static bool authenticated(conn *c) {
assert(settings.sasl);
bool rv = false;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */
rv = true;
break;
default:
rv = c->authenticated;
}
if (settings.verbose > 1) {
fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n",
c->cmd, rv ? "true" : "false");
}
return rv;
}
static void dispatch_bin_command(conn *c) {
int protocol_error = 0;
uint8_t extlen = c->binary_header.request.extlen;
uint16_t keylen = c->binary_header.request.keylen;
uint32_t bodylen = c->binary_header.request.bodylen;
if (keylen > bodylen || keylen + extlen > bodylen) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0);
c->write_and_go = conn_closing;
return;
}
if (settings.sasl && !authenticated(c)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
c->write_and_go = conn_closing;
return;
}
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
c->noreply = true;
/* binprot supports 16bit keys, but internals are still 8bit */
if (keylen > KEY_MAX_LENGTH) {
handle_binary_protocol_error(c);
return;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SETQ:
c->cmd = PROTOCOL_BINARY_CMD_SET;
break;
case PROTOCOL_BINARY_CMD_ADDQ:
c->cmd = PROTOCOL_BINARY_CMD_ADD;
break;
case PROTOCOL_BINARY_CMD_REPLACEQ:
c->cmd = PROTOCOL_BINARY_CMD_REPLACE;
break;
case PROTOCOL_BINARY_CMD_DELETEQ:
c->cmd = PROTOCOL_BINARY_CMD_DELETE;
break;
case PROTOCOL_BINARY_CMD_INCREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_INCREMENT;
break;
case PROTOCOL_BINARY_CMD_DECREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_DECREMENT;
break;
case PROTOCOL_BINARY_CMD_QUITQ:
c->cmd = PROTOCOL_BINARY_CMD_QUIT;
break;
case PROTOCOL_BINARY_CMD_FLUSHQ:
c->cmd = PROTOCOL_BINARY_CMD_FLUSH;
break;
case PROTOCOL_BINARY_CMD_APPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_PREPEND;
break;
case PROTOCOL_BINARY_CMD_GETQ:
c->cmd = PROTOCOL_BINARY_CMD_GET;
break;
case PROTOCOL_BINARY_CMD_GETKQ:
c->cmd = PROTOCOL_BINARY_CMD_GETK;
break;
case PROTOCOL_BINARY_CMD_GATQ:
c->cmd = PROTOCOL_BINARY_CMD_GAT;
break;
case PROTOCOL_BINARY_CMD_GATKQ:
c->cmd = PROTOCOL_BINARY_CMD_GATK;
break;
default:
c->noreply = false;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_VERSION:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, VERSION, 0, 0, strlen(VERSION));
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_FLUSH:
if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) {
bin_read_key(c, bin_read_flush_exptime, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_NOOP:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_REPLACE:
if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) {
bin_read_key(c, bin_reading_set_header, 8);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETK:
if (extlen == 0 && bodylen == keylen && keylen > 0) {
bin_read_key(c, bin_reading_get_key, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_DELETE:
if (keylen > 0 && extlen == 0 && bodylen == keylen) {
bin_read_key(c, bin_reading_del_header, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_INCREMENT:
case PROTOCOL_BINARY_CMD_DECREMENT:
if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) {
bin_read_key(c, bin_reading_incr_header, 20);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_APPEND:
case PROTOCOL_BINARY_CMD_PREPEND:
if (keylen > 0 && extlen == 0) {
bin_read_key(c, bin_reading_set_header, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_STAT:
if (extlen == 0) {
bin_read_key(c, bin_reading_stat, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_QUIT:
if (keylen == 0 && extlen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
c->write_and_go = conn_closing;
if (c->noreply) {
conn_set_state(c, conn_closing);
}
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
bin_list_sasl_mechs(c);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_AUTH:
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (extlen == 0 && keylen != 0) {
bin_read_key(c, bin_reading_sasl_auth, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_TOUCH:
case PROTOCOL_BINARY_CMD_GAT:
case PROTOCOL_BINARY_CMD_GATQ:
case PROTOCOL_BINARY_CMD_GATK:
case PROTOCOL_BINARY_CMD_GATKQ:
if (extlen == 4 && keylen != 0) {
bin_read_key(c, bin_reading_touch_key, 4);
} else {
protocol_error = 1;
}
break;
default:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
bodylen);
}
if (protocol_error)
handle_binary_protocol_error(c);
}
static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* This error generating method eats the swallow value. Add here. */
c->sbytes = vlen;
status = NO_MEMORY;
}
/* FIXME: losing c->cmd since it's translated below. refactor? */
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, 0, key, nkey, req->message.body.expiration,
ITEM_clsid(it));
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_append_prepend(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
vlen = c->binary_header.request.bodylen - nkey;
if (settings.verbose > 1) {
fprintf(stderr, "Value len is %d\n", vlen);
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, 0, 0, vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, 0, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* OOM calls eat the swallow value. Add here. */
c->sbytes = vlen;
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_APPEND:
c->cmd = NREAD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPEND:
c->cmd = NREAD_PREPEND;
break;
default:
assert(0);
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_flush(conn *c) {
time_t exptime = 0;
protocol_binary_request_flush* req = binary_get_request(c);
rel_time_t new_oldest = 0;
if (!settings.flush_enabled) {
// flush_all is not allowed but we log it on stats
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
return;
}
if (c->binary_header.request.extlen == sizeof(req->message.body)) {
exptime = ntohl(req->message.body.expiration);
}
if (exptime > 0) {
new_oldest = realtime(exptime);
} else {
new_oldest = current_time;
}
if (settings.use_cas) {
settings.oldest_live = new_oldest - 1;
if (settings.oldest_live <= current_time)
settings.oldest_cas = get_cas_id();
} else {
settings.oldest_live = new_oldest;
}
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_response(c, NULL, 0, 0, 0);
}
static void process_bin_delete(conn *c) {
item *it;
protocol_binary_request_delete* req = binary_get_request(c);
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
assert(c != NULL);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "Deleting ");
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
uint64_t cas = ntohll(req->message.header.request.cas);
if (cas == 0 || cas == ITEM_get_cas(it)) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
write_bin_response(c, NULL, 0, 0, 0);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
static void complete_nread_binary(conn *c) {
assert(c != NULL);
assert(c->cmd >= 0);
switch(c->substate) {
case bin_reading_set_header:
if (c->cmd == PROTOCOL_BINARY_CMD_APPEND ||
c->cmd == PROTOCOL_BINARY_CMD_PREPEND) {
process_bin_append_prepend(c);
} else {
process_bin_update(c);
}
break;
case bin_read_set_value:
complete_update_bin(c);
break;
case bin_reading_get_key:
case bin_reading_touch_key:
process_bin_get_or_touch(c);
break;
case bin_reading_stat:
process_bin_stat(c);
break;
case bin_reading_del_header:
process_bin_delete(c);
break;
case bin_reading_incr_header:
complete_incr_bin(c);
break;
case bin_read_flush_exptime:
process_bin_flush(c);
break;
case bin_reading_sasl_auth:
process_bin_sasl_auth(c);
break;
case bin_reading_sasl_auth_data:
process_bin_complete_sasl_auth(c);
break;
default:
fprintf(stderr, "Not handling substate %d\n", c->substate);
assert(0);
}
}
static void reset_cmd_handler(conn *c) {
c->cmd = -1;
c->substate = bin_no_state;
if(c->item != NULL) {
item_remove(c->item);
c->item = NULL;
}
conn_shrink(c);
if (c->rbytes > 0) {
conn_set_state(c, conn_parse_cmd);
} else {
conn_set_state(c, conn_waiting);
}
}
static void complete_nread(conn *c) {
assert(c != NULL);
assert(c->protocol == ascii_prot
|| c->protocol == binary_prot);
if (c->protocol == ascii_prot) {
complete_nread_ascii(c);
} else if (c->protocol == binary_prot) {
complete_nread_binary(c);
}
}
/* Destination must always be chunked */
/* This should be part of item.c */
static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) {
item_chunk *dch = (item_chunk *) ITEM_data(d_it);
/* Advance dch until we find free space */
while (dch->size == dch->used) {
if (dch->next) {
dch = dch->next;
} else {
break;
}
}
if (s_it->it_flags & ITEM_CHUNKED) {
int remain = len;
item_chunk *sch = (item_chunk *) ITEM_data(s_it);
int copied = 0;
/* Fills dch's to capacity, not straight copy sch in case data is
* being added or removed (ie append/prepend)
*/
while (sch && dch && remain) {
assert(dch->used <= dch->size);
int todo = (dch->size - dch->used < sch->used - copied)
? dch->size - dch->used : sch->used - copied;
if (remain < todo)
todo = remain;
memcpy(dch->data + dch->used, sch->data + copied, todo);
dch->used += todo;
copied += todo;
remain -= todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, remain);
if (tch) {
dch = tch;
} else {
return -1;
}
}
assert(copied <= sch->used);
if (copied == sch->used) {
copied = 0;
sch = sch->next;
}
}
/* assert that the destination had enough space for the source */
assert(remain == 0);
} else {
int done = 0;
/* Fill dch's via a non-chunked item. */
while (len > done && dch) {
int todo = (dch->size - dch->used < len - done)
? dch->size - dch->used : len - done;
//assert(dch->size - dch->used != 0);
memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo);
done += todo;
dch->used += todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, len - done);
if (tch) {
dch = tch;
} else {
return -1;
}
}
}
assert(len == done);
}
return 0;
}
static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) {
if (comm == NREAD_APPEND) {
if (new_it->it_flags & ITEM_CHUNKED) {
if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 ||
_store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) {
return -1;
}
} else {
memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes);
memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes);
}
} else {
/* NREAD_PREPEND */
if (new_it->it_flags & ITEM_CHUNKED) {
if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 ||
_store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) {
return -1;
}
} else {
memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes);
memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes);
}
}
return 0;
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns the state of storage.
*/
enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) {
char *key = ITEM_key(it);
item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE);
enum store_item_type stored = NOT_STORED;
item *new_it = NULL;
uint32_t flags;
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && (comm == NREAD_REPLACE
|| comm == NREAD_APPEND || comm == NREAD_PREPEND))
{
/* replace only replaces an existing value; don't store */
} else if (comm == NREAD_CAS) {
/* validate cas operation */
if(old_it == NULL) {
// LRU expired
stored = NOT_FOUND;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.cas_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) {
// cas validates
// it and old_it may belong to different classes.
// I'm updating the stats for the one that's getting pushed out
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
STORAGE_delete(c->thread->storage, old_it);
item_replace(old_it, it, hv);
stored = STORED;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(settings.verbose > 1) {
fprintf(stderr, "CAS: failure: expected %llu, got %llu\n",
(unsigned long long)ITEM_get_cas(old_it),
(unsigned long long)ITEM_get_cas(it));
}
stored = EXISTS;
}
} else {
int failed_alloc = 0;
/*
* Append - combine new and old record into single one. Here it's
* atomic and thread-safe.
*/
if (comm == NREAD_APPEND || comm == NREAD_PREPEND) {
/*
* Validate CAS
*/
if (ITEM_get_cas(it) != 0) {
// CAS much be equal
if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) {
stored = EXISTS;
}
}
#ifdef EXTSTORE
if ((old_it->it_flags & ITEM_HDR) != 0) {
/* block append/prepend from working with extstore-d items.
* also don't replace the header with the append chunk
* accidentally, so mark as a failed_alloc.
*/
failed_alloc = 1;
} else
#endif
if (stored == NOT_STORED) {
/* we have it and old_it here - alloc memory to hold both */
/* flags was already lost - so recover them from ITEM_suffix(it) */
if (settings.inline_ascii_response) {
flags = (uint32_t) strtoul(ITEM_suffix(old_it), (char **) NULL, 10);
} else if (old_it->nsuffix > 0) {
flags = *((uint32_t *)ITEM_suffix(old_it));
} else {
flags = 0;
}
new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */);
/* copy data from it and old_it to new_it */
if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) {
failed_alloc = 1;
stored = NOT_STORED;
// failed data copy, free up.
if (new_it != NULL)
item_remove(new_it);
} else {
it = new_it;
}
}
}
if (stored == NOT_STORED && failed_alloc == 0) {
if (old_it != NULL) {
STORAGE_delete(c->thread->storage, old_it);
item_replace(old_it, it, hv);
} else {
do_item_link(it, hv);
}
c->cas = ITEM_get_cas(it);
stored = STORED;
}
}
if (old_it != NULL)
do_item_remove(old_it); /* release our reference */
if (new_it != NULL)
do_item_remove(new_it);
if (stored == STORED) {
c->cas = ITEM_get_cas(it);
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL,
stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it));
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 8
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
size_t len = strlen(command);
unsigned int i = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
s = e = command;
for (i = 0; i < len; i++) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
if (ntokens == max_tokens - 1) {
e++;
s = e; /* so we don't add an extra token */
break;
}
}
s = e + 1;
}
e++;
}
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
/* set up a connection to write a buffer then free it, used for stats */
static void write_and_free(conn *c, char *buf, int bytes) {
if (buf) {
c->write_and_free = buf;
c->wcurr = buf;
c->wbytes = bytes;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
} else {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
}
}
static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens)
{
int noreply_index = ntokens - 2;
/*
NOTE: this function is not the first place where we are going to
send the reply. We could send it instead from process_command()
if the request line has wrong number of tokens. However parsing
malformed line for "noreply" option is not reliable anyway, so
it can't be helped.
*/
if (tokens[noreply_index].value
&& strcmp(tokens[noreply_index].value, "noreply") == 0) {
c->noreply = true;
}
return c->noreply;
}
void append_stat(const char *name, ADD_STAT add_stats, conn *c,
const char *fmt, ...) {
char val_str[STAT_VAL_LEN];
int vlen;
va_list ap;
assert(name);
assert(add_stats);
assert(c);
assert(fmt);
va_start(ap, fmt);
vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap);
va_end(ap);
add_stats(name, strlen(name), val_str, vlen, c);
}
inline static void process_stats_detail(conn *c, const char *command) {
assert(c != NULL);
if (strcmp(command, "on") == 0) {
settings.detail_enabled = 1;
out_string(c, "OK");
}
else if (strcmp(command, "off") == 0) {
settings.detail_enabled = 0;
out_string(c, "OK");
}
else if (strcmp(command, "dump") == 0) {
int len;
char *stats = stats_prefix_dump(&len);
write_and_free(c, stats, len);
}
else {
out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump");
}
}
/* return server specific stats only */
static void server_stats(ADD_STAT add_stats, conn *c) {
pid_t pid = getpid();
rel_time_t now = current_time;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(&thread_stats);
struct slab_stats slab_stats;
slab_stats_aggregate(&thread_stats, &slab_stats);
#ifdef EXTSTORE
struct extstore_stats st;
#endif
#ifndef WIN32
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
#endif /* !WIN32 */
STATS_LOCK();
APPEND_STAT("pid", "%lu", (long)pid);
APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL);
APPEND_STAT("time", "%ld", now + (long)process_started);
APPEND_STAT("version", "%s", VERSION);
APPEND_STAT("libevent", "%s", event_get_version());
APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *)));
#ifndef WIN32
append_stat("rusage_user", add_stats, c, "%ld.%06ld",
(long)usage.ru_utime.tv_sec,
(long)usage.ru_utime.tv_usec);
append_stat("rusage_system", add_stats, c, "%ld.%06ld",
(long)usage.ru_stime.tv_sec,
(long)usage.ru_stime.tv_usec);
#endif /* !WIN32 */
APPEND_STAT("max_connections", "%d", settings.maxconns);
APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1);
APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns);
if (settings.maxconns_fast) {
APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns);
}
APPEND_STAT("connection_structures", "%u", stats_state.conn_structs);
APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds);
APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds);
APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds);
APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds);
APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds);
APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits);
APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses);
APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired);
APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed);
#ifdef EXTSTORE
if (c->thread->storage) {
APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore);
APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore);
APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore);
APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore);
}
#endif
APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses);
APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits);
APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses);
APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits);
APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses);
APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits);
APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses);
APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits);
APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval);
APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits);
APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses);
APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds);
APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors);
if (settings.idle_timeout) {
APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks);
}
APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read);
APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written);
APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns);
APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num);
APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us);
APPEND_STAT("threads", "%d", settings.num_threads);
APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields);
APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level);
APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes);
APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding);
if (settings.slab_reassign) {
APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues);
APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues);
APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem);
APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim);
APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items);
APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes);
APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running);
APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved);
}
if (settings.lru_crawler) {
APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running);
APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts);
}
if (settings.lru_maintainer_thread) {
APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles);
}
APPEND_STAT("malloc_fails", "%llu",
(unsigned long long)stats.malloc_fails);
APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped);
APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written);
APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped);
APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent);
STATS_UNLOCK();
#ifdef EXTSTORE
if (c->thread->storage) {
STATS_LOCK();
APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost);
APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues);
APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped);
STATS_UNLOCK();
extstore_get_stats(c->thread->storage, &st);
APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs);
APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions);
APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims);
APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free);
APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used);
APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted);
APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read);
APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written);
APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used);
APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted);
APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written);
APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read);
APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used);
APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented);
APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size));
}
#endif
}
static void process_stat_settings(ADD_STAT add_stats, void *c) {
assert(add_stats);
APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("maxconns", "%d", settings.maxconns);
APPEND_STAT("tcpport", "%d", settings.port);
APPEND_STAT("udpport", "%d", settings.udpport);
APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL");
APPEND_STAT("verbosity", "%d", settings.verbose);
APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live);
APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off");
APPEND_STAT("domain_socket", "%s",
settings.socketpath ? settings.socketpath : "NULL");
APPEND_STAT("umask", "%o", settings.access);
APPEND_STAT("growth_factor", "%.2f", settings.factor);
APPEND_STAT("chunk_size", "%d", settings.chunk_size);
APPEND_STAT("num_threads", "%d", settings.num_threads);
APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp);
APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter);
APPEND_STAT("detail_enabled", "%s",
settings.detail_enabled ? "yes" : "no");
APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event);
APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no");
APPEND_STAT("tcp_backlog", "%d", settings.backlog);
APPEND_STAT("binding_protocol", "%s",
prot_text(settings.binding_protocol));
APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no");
APPEND_STAT("item_size_max", "%d", settings.item_size_max);
APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no");
APPEND_STAT("hashpower_init", "%d", settings.hashpower_init);
APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no");
APPEND_STAT("slab_automove", "%d", settings.slab_automove);
APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio);
APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window);
APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max);
APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no");
APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep);
APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl);
APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time);
APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no");
APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no");
APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm);
APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no");
APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no");
APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct);
APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct);
APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor);
APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor);
APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no");
APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl);
APPEND_STAT("idle_timeout", "%d", settings.idle_timeout);
APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size);
APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size);
APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no");
APPEND_STAT("inline_ascii_response", "%s", settings.inline_ascii_response ? "yes" : "no");
#ifdef EXTSTORE
APPEND_STAT("ext_item_size", "%u", settings.ext_item_size);
APPEND_STAT("ext_item_age", "%u", settings.ext_item_age);
APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl);
APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate);
APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size);
APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under);
APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under);
APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag);
APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio);
APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no");
#endif
}
static void conn_to_str(const conn *c, char *buf) {
char addr_text[MAXPATHLEN];
if (!c) {
strcpy(buf, "<null>");
} else if (c->state == conn_closed) {
strcpy(buf, "<closed>");
} else {
const char *protoname = "?";
struct sockaddr_in6 local_addr;
struct sockaddr *addr = (void *)&c->request_addr;
int af;
unsigned short port = 0;
/* For listen ports and idle UDP ports, show listen address */
if (c->state == conn_listening ||
(IS_UDP(c->transport) &&
c->state == conn_read)) {
socklen_t local_addr_len = sizeof(local_addr);
if (getsockname(c->sfd,
(struct sockaddr *)&local_addr,
&local_addr_len) == 0) {
addr = (struct sockaddr *)&local_addr;
}
}
af = addr->sa_family;
addr_text[0] = '\0';
switch (af) {
case AF_INET:
(void) inet_ntop(af,
&((struct sockaddr_in *)addr)->sin_addr,
addr_text,
sizeof(addr_text) - 1);
port = ntohs(((struct sockaddr_in *)addr)->sin_port);
protoname = IS_UDP(c->transport) ? "udp" : "tcp";
break;
case AF_INET6:
addr_text[0] = '[';
addr_text[1] = '\0';
if (inet_ntop(af,
&((struct sockaddr_in6 *)addr)->sin6_addr,
addr_text + 1,
sizeof(addr_text) - 2)) {
strcat(addr_text, "]");
}
port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
protoname = IS_UDP(c->transport) ? "udp6" : "tcp6";
break;
case AF_UNIX:
strncpy(addr_text,
((struct sockaddr_un *)addr)->sun_path,
sizeof(addr_text) - 1);
addr_text[sizeof(addr_text)-1] = '\0';
protoname = "unix";
break;
}
if (strlen(addr_text) < 2) {
/* Most likely this is a connected UNIX-domain client which
* has no peer socket address, but there's no portable way
* to tell for sure.
*/
sprintf(addr_text, "<AF %d>", af);
}
if (port) {
sprintf(buf, "%s:%s:%u", protoname, addr_text, port);
} else {
sprintf(buf, "%s:%s", protoname, addr_text);
}
}
}
static void process_stats_conns(ADD_STAT add_stats, void *c) {
int i;
char key_str[STAT_KEY_LEN];
char val_str[STAT_VAL_LEN];
char conn_name[MAXPATHLEN + sizeof("unix:") + sizeof("65535")];
int klen = 0, vlen = 0;
assert(add_stats);
for (i = 0; i < max_fds; i++) {
if (conns[i]) {
/* This is safe to do unlocked because conns are never freed; the
* worst that'll happen will be a minor inconsistency in the
* output -- not worth the complexity of the locking that'd be
* required to prevent it.
*/
if (conns[i]->state != conn_closed) {
conn_to_str(conns[i], conn_name);
APPEND_NUM_STAT(i, "addr", "%s", conn_name);
APPEND_NUM_STAT(i, "state", "%s",
state_text(conns[i]->state));
APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d",
current_time - conns[i]->last_cmd_time);
}
}
}
}
#ifdef EXTSTORE
static void process_extstore_stats(ADD_STAT add_stats, conn *c) {
int i;
char key_str[STAT_KEY_LEN];
char val_str[STAT_VAL_LEN];
int klen = 0, vlen = 0;
struct extstore_stats st;
assert(add_stats);
void *storage = c->thread->storage;
extstore_get_stats(storage, &st);
st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data));
extstore_get_page_data(storage, &st);
for (i = 0; i < st.page_count; i++) {
APPEND_NUM_STAT(i, "version", "%llu",
(unsigned long long) st.page_data[i].version);
APPEND_NUM_STAT(i, "bytes", "%llu",
(unsigned long long) st.page_data[i].bytes_used);
APPEND_NUM_STAT(i, "bucket", "%u",
st.page_data[i].bucket);
}
}
#endif
static void process_stat(conn *c, token_t *tokens, const size_t ntokens) {
const char *subcommand = tokens[SUBCOMMAND_TOKEN].value;
assert(c != NULL);
if (ntokens < 2) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (ntokens == 2) {
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strcmp(subcommand, "reset") == 0) {
stats_reset();
out_string(c, "RESET");
return ;
} else if (strcmp(subcommand, "detail") == 0) {
/* NOTE: how to tackle detail with binary? */
if (ntokens < 4)
process_stats_detail(c, ""); /* outputs the error message */
else
process_stats_detail(c, tokens[2].value);
/* Output already generated */
return ;
} else if (strcmp(subcommand, "settings") == 0) {
process_stat_settings(&append_stats, c);
} else if (strcmp(subcommand, "cachedump") == 0) {
char *buf;
unsigned int bytes, id, limit = 0;
if (!settings.dump_enabled) {
out_string(c, "CLIENT_ERROR stats cachedump not allowed");
return;
}
if (ntokens < 5) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (!safe_strtoul(tokens[2].value, &id) ||
!safe_strtoul(tokens[3].value, &limit)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (id >= MAX_NUMBER_OF_SLAB_CLASSES) {
out_string(c, "CLIENT_ERROR Illegal slab id");
return;
}
buf = item_cachedump(id, limit, &bytes);
write_and_free(c, buf, bytes);
return ;
} else if (strcmp(subcommand, "conns") == 0) {
process_stats_conns(&append_stats, c);
#ifdef EXTSTORE
} else if (strcmp(subcommand, "extstore") == 0) {
process_extstore_stats(&append_stats, c);
#endif
} else {
/* getting here means that the subcommand is either engine specific or
is invalid. query the engine and see. */
if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
out_string(c, "ERROR");
}
return ;
}
/* append terminator and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
/* nsuffix == 0 means use no storage for client flags */
static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) {
char *p = suffix;
if (!settings.inline_ascii_response) {
*p = ' ';
p++;
if (it->nsuffix == 0) {
*p = '0';
p++;
} else {
p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p);
}
*p = ' ';
p = itoa_u32(nbytes-2, p+1);
} else {
p = suffix;
}
if (return_cas) {
*p = ' ';
p = itoa_u64(ITEM_get_cas(it), p+1);
}
*p = '\r';
*(p+1) = '\n';
*(p+2) = '\0';
return (p - suffix) + 2;
}
#define IT_REFCOUNT_LIMIT 60000
static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) {
item *it;
if (should_touch) {
it = item_touch(key, nkey, exptime, c);
} else {
it = item_get(key, nkey, c, DO_UPDATE);
}
if (it && it->refcount > IT_REFCOUNT_LIMIT) {
item_remove(it);
it = NULL;
}
return it;
}
static inline int _ascii_get_expand_ilist(conn *c, int i) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
}
return 0;
}
static inline char *_ascii_get_suffix_buf(conn *c, int i) {
char *suffix;
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return NULL;
}
}
suffix = do_cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix");
return NULL;
}
*(c->suffixlist + i) = suffix;
return suffix;
}
#ifdef EXTSTORE
// FIXME: This runs in the IO thread. to get better IO performance this should
// simply mark the io wrapper with the return value and decrement wrapleft, if
// zero redispatching. Still a bit of work being done in the side thread but
// minimized at least.
static void _get_extstore_cb(void *e, obj_io *io, int ret) {
// FIXME: assumes success
io_wrap *wrap = (io_wrap *)io->data;
conn *c = wrap->c;
assert(wrap->active == true);
item *read_it = (item *)io->buf;
bool miss = false;
// TODO: How to do counters for hit/misses?
if (ret < 1) {
miss = true;
} else {
uint32_t crc2;
uint32_t crc = (uint32_t) read_it->exptime;
int x;
// item is chunked, crc the iov's
if (io->iov != NULL) {
// first iov is the header, which we don't use beyond crc
crc2 = crc32c(0, (char *)io->iov[0].iov_base+32, io->iov[0].iov_len-32);
// make sure it's not sent. hack :(
io->iov[0].iov_len = 0;
for (x = 1; x < io->iovcnt; x++) {
crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len);
}
} else {
crc2 = crc32c(0, (char *)read_it+32, io->len-32);
}
if (crc != crc2) {
miss = true;
wrap->badcrc = true;
}
}
if (miss) {
int i;
struct iovec *v;
// TODO: This should be movable to the worker thread.
if (c->protocol == binary_prot) {
protocol_binary_response_header *header =
(protocol_binary_response_header *)c->wbuf;
// this zeroes out the iovecs since binprot never stacks them.
if (header->response.keylen) {
write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey);
} else {
write_bin_miss_response(c, 0, 0);
}
} else {
for (i = 0; i < wrap->iovec_count; i++) {
v = &c->iov[wrap->iovec_start + i];
v->iov_len = 0;
v->iov_base = NULL;
}
}
wrap->miss = true;
} else {
assert(read_it->slabs_clsid != 0);
// kill \r\n for binprot
if (io->iov == NULL) {
c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it);
if (c->protocol == binary_prot)
c->iov[wrap->iovec_data].iov_len -= 2;
} else {
// FIXME: Might need to go back and ensure chunked binprots don't
// ever span two chunks for the final \r\n
if (c->protocol == binary_prot) {
if (io->iov[io->iovcnt-1].iov_len >= 2) {
io->iov[io->iovcnt-1].iov_len -= 2;
} else {
io->iov[io->iovcnt-1].iov_len = 0;
io->iov[io->iovcnt-2].iov_len -= 1;
}
}
}
// iov_len is already set
// TODO: Should do that here instead and cuddle in the wrap object
}
c->io_wrapleft--;
wrap->active = false;
//assert(c->io_wrapleft >= 0);
// All IO's have returned, lets re-attach this connection to our original
// thread.
if (c->io_wrapleft == 0) {
assert(c->io_queued == true);
c->io_queued = false;
redispatch_conn(c);
}
}
// FIXME: This completely breaks UDP support.
static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) {
item_hdr *hdr = (item_hdr *)ITEM_data(it);
size_t ntotal = ITEM_ntotal(it);
unsigned int clsid = slabs_clsid(ntotal);
item *new_it;
bool chunked = false;
if (ntotal > settings.slab_chunk_size_max) {
// Pull a chunked item header.
// FIXME: make a func. used in several places.
uint32_t flags;
if (settings.inline_ascii_response) {
flags = (uint32_t) strtoul(ITEM_suffix(it), (char **) NULL, 10);
} else if (it->nsuffix > 0) {
flags = *((uint32_t *)ITEM_suffix(it));
} else {
flags = 0;
}
new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes);
assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED));
chunked = true;
} else {
new_it = do_item_alloc_pull(ntotal, clsid);
}
if (new_it == NULL)
return -1;
assert(!c->io_queued); // FIXME: debugging.
// so we can free the chunk on a miss
new_it->slabs_clsid = clsid;
io_wrap *io = do_cache_alloc(c->thread->io_cache);
io->active = true;
io->miss = false;
io->badcrc = false;
// io_wrap owns the reference for this object now.
io->hdr_it = it;
// FIXME: error handling.
// The offsets we'll wipe on a miss.
io->iovec_start = iovst;
io->iovec_count = iovcnt;
// This is probably super dangerous. keep it at 0 and fill into wrap
// object?
if (chunked) {
unsigned int ciovcnt = 1;
size_t remain = new_it->nbytes;
item_chunk *chunk = (item_chunk *) ITEM_data(new_it);
io->io.iov = &c->iov[c->iovused];
// fill the header so we can get the full data + crc back.
add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes);
while (remain > 0) {
chunk = do_item_alloc_chunk(chunk, remain);
// TODO: counter bump
if (chunk == NULL) {
item_remove(new_it);
do_cache_free(c->thread->io_cache, io);
return -1;
}
add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size);
chunk->used = (remain < chunk->size) ? remain : chunk->size;
remain -= chunk->size;
ciovcnt++;
}
io->io.iovcnt = ciovcnt;
// header object was already accounted for, remove one from total
io->iovec_count += ciovcnt-1;
} else {
io->io.iov = NULL;
io->iovec_data = c->iovused;
add_iov(c, "", it->nbytes);
}
io->io.buf = (void *)new_it;
// The offset we'll fill in on a hit.
io->c = c;
// We need to stack the sub-struct IO's together as well.
if (c->io_wraplist) {
io->io.next = &c->io_wraplist->io;
} else {
io->io.next = NULL;
}
// IO queue for this connection.
io->next = c->io_wraplist;
c->io_wraplist = io;
assert(c->io_wrapleft >= 0);
c->io_wrapleft++;
// reference ourselves for the callback.
io->io.data = (void *)io;
// Now, fill in io->io based on what was in our header.
io->io.page_version = hdr->page_version;
io->io.page_id = hdr->page_id;
io->io.offset = hdr->offset;
io->io.len = ntotal;
io->io.mode = OBJ_IO_READ;
io->io.cb = _get_extstore_cb;
//fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data);
// FIXME: This stat needs to move to reflect # of flash hits vs misses
// for now it's a good gauge on how often we request out to flash at
// least.
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
return 0;
}
#endif
// FIXME: the 'breaks' around memory malloc's should break all the way down,
// fill ileft/suffixleft, then run conn_releaseitems()
/* ntokens is overwritten here... shrug.. */
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) {
char *key;
size_t nkey;
int i = 0;
int si = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
int32_t exptime_int = 0;
rel_time_t exptime = 0;
assert(c != NULL);
if (should_touch) {
// For get and touch commands, use first token as exptime
if (!safe_strtol(tokens[1].value, &exptime_int)) {
out_string(c, "CLIENT_ERROR invalid exptime argument");
return;
}
key_token++;
exptime = realtime(exptime_int);
}
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if (nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
while (i-- > 0) {
item_remove(*(c->ilist + i));
if (return_cas || !settings.inline_ascii_response) {
do_cache_free(c->thread->suffix_cache, *(c->suffixlist + i));
}
}
return;
}
it = limited_get(key, nkey, c, exptime, should_touch);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (_ascii_get_expand_ilist(c, i) != 0) {
item_remove(it);
break; // FIXME: Should bail down to error.
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas || !settings.inline_ascii_response)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
int nbytes;
suffix = _ascii_get_suffix_buf(c, si);
if (suffix == NULL) {
item_remove(it);
break;
}
si++;
nbytes = it->nbytes;
int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes);
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
(settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) ||
add_iov(c, suffix, suffix_len) != 0)
{
item_remove(it);
break;
}
#ifdef EXTSTORE
if (it->it_flags & ITEM_HDR) {
if (_get_extstore(c, it, c->iovused-3, 4) != 0) {
item_remove(it);
break;
}
} else if ((it->it_flags & ITEM_CHUNKED) == 0) {
#else
if ((it->it_flags & ITEM_CHUNKED) == 0) {
#endif
add_iov(c, ITEM_data(it), it->nbytes);
} else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0)
{
item_remove(it);
break;
}
if ((it->it_flags & ITEM_CHUNKED) == 0)
{
if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
} else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 ||
add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
break;
}
}
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d sending key ", c->sfd);
for (ii = 0; ii < it->nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
} else {
c->thread->stats.lru_hits[it->slabs_clsid]++;
c->thread->stats.get_cmds++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
#ifdef EXTSTORE
/* If ITEM_HDR, an io_wrap owns the reference. */
if ((it->it_flags & ITEM_HDR) == 0) {
*(c->ilist + i) = it;
i++;
}
#else
*(c->ilist + i) = it;
i++;
#endif
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
} else {
c->thread->stats.get_misses++;
c->thread->stats.get_cmds++;
}
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
pthread_mutex_unlock(&c->thread->stats.mutex);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas || !settings.inline_ascii_response) {
c->suffixcurr = c->suffixlist;
c->suffixleft = si;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_of_memory(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
}
static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
/* Negative exptimes can underflow and end up immortal. realtime() will
immediately expire values that are greater than REALTIME_MAXDELTA, but less
than process_started, so lets aim for that. */
if (exptime < 0)
exptime = REALTIME_MAXDELTA + 1;
// does cas value exist?
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
if (vlen < 0 || vlen > (INT_MAX - 2)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
vlen += 2;
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, flags, vlen)) {
out_string(c, "SERVER_ERROR object too large for cache");
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR out of memory storing object");
status = NO_MEMORY;
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, comm, key, nkey, 0, 0);
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
int32_t exptime_int = 0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtol(tokens[2].value, &exptime_int)) {
out_string(c, "CLIENT_ERROR invalid exptime argument");
return;
}
it = item_touch(key, nkey, realtime(exptime_int), c);
if (it) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "TOUCHED");
item_remove(it);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) {
char temp[INCR_MAX_STORAGE_LEN];
uint64_t delta;
char *key;
size_t nkey;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtoull(tokens[2].value, &delta)) {
out_string(c, "CLIENT_ERROR invalid numeric delta argument");
return;
}
switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) {
case OK:
out_string(c, temp);
break;
case NON_NUMERIC:
out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value");
break;
case EOM:
out_of_memory(c, "SERVER_ERROR out of memory");
break;
case DELTA_ITEM_NOT_FOUND:
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
break;
case DELTA_ITEM_CAS_MISMATCH:
break; /* Should never get here */
}
}
/*
* adds a delta value to a numeric item.
*
* c connection requesting the operation
* it item to adjust
* incr true to increment value, false to decrement
* delta amount to adjust value by
* buf buffer for response string
*
* returns a response string to send back to the client.
*/
enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey,
const bool incr, const int64_t delta,
char *buf, uint64_t *cas,
const uint32_t hv) {
char *ptr;
uint64_t value;
int res;
item *it;
it = do_item_get(key, nkey, hv, c, DONT_UPDATE);
if (!it) {
return DELTA_ITEM_NOT_FOUND;
}
/* Can't delta zero byte values. 2-byte are the "\r\n" */
/* Also can't delta for chunked items. Too large to be a number */
#ifdef EXTSTORE
if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) {
#else
if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) {
#endif
return NON_NUMERIC;
}
if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) {
do_item_remove(it);
return DELTA_ITEM_CAS_MISMATCH;
}
ptr = ITEM_data(it);
if (!safe_strtoull(ptr, &value)) {
do_item_remove(it);
return NON_NUMERIC;
}
if (incr) {
value += delta;
MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value);
} else {
if(delta > value) {
value = 0;
} else {
value -= delta;
}
MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value);
}
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++;
} else {
c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value);
res = strlen(buf);
/* refcount == 2 means we are the only ones holding the item, and it is
* linked. We hold the item's lock in this function, so refcount cannot
* increase. */
if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */
/* When changing the value without replacing the item, we
need to update the CAS on the existing item. */
/* We also need to fiddle it in the sizes tracker in case the tracking
* was enabled at runtime, since it relies on the CAS value to know
* whether to remove an item or not. */
item_stats_sizes_remove(it);
ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
item_stats_sizes_add(it);
memcpy(ITEM_data(it), buf, res);
memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2);
do_item_update(it);
} else if (it->refcount > 1) {
item *new_it;
uint32_t flags;
if (settings.inline_ascii_response) {
flags = (uint32_t) strtoul(ITEM_suffix(it), (char **) NULL, 10);
} else if (it->nsuffix > 0) {
flags = *((uint32_t *)ITEM_suffix(it));
} else {
flags = 0;
}
new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2);
if (new_it == 0) {
do_item_remove(it);
return EOM;
}
memcpy(ITEM_data(new_it), buf, res);
memcpy(ITEM_data(new_it) + res, "\r\n", 2);
item_replace(it, new_it, hv);
// Overwrite the older item's CAS with our new CAS since we're
// returning the CAS of the old item below.
ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0);
do_item_remove(new_it); /* release our reference */
} else {
/* Should never get here. This means we somehow fetched an unlinked
* item. TODO: Add a counter? */
if (settings.verbose) {
fprintf(stderr, "Tried to do incr/decr on invalid item\n");
}
if (it->refcount == 1)
do_item_remove(it);
return DELTA_ITEM_NOT_FOUND;
}
if (cas) {
*cas = ITEM_get_cas(it); /* swap the incoming CAS value */
}
do_item_remove(it); /* release our reference */
return OK;
}
static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
item *it;
assert(c != NULL);
if (ntokens > 3) {
bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0;
bool sets_noreply = set_noreply_maybe(c, tokens, ntokens);
bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply))
|| (ntokens == 5 && hold_is_zero && sets_noreply);
if (!valid) {
out_string(c, "CLIENT_ERROR bad command line format. "
"Usage: delete <key> [noreply]");
return;
}
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it); /* release our reference */
out_string(c, "DELETED");
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
level = strtoul(tokens[1].value, NULL, 10);
settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level;
out_string(c, "OK");
return;
}
#ifdef MEMCACHED_DEBUG
static void process_misbehave_command(conn *c) {
int allowed = 0;
// try opening new TCP socket
int i = socket(AF_INET, SOCK_STREAM, 0);
if (i != -1) {
allowed++;
close(i);
}
// try executing new commands
i = system("sleep 0");
if (i != -1) {
allowed++;
}
if (allowed) {
out_string(c, "ERROR");
} else {
out_string(c, "OK");
}
}
#endif
static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
double ratio;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (strcmp(tokens[2].value, "ratio") == 0) {
if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) {
out_string(c, "ERROR");
return;
}
settings.slab_automove_ratio = ratio;
} else {
level = strtoul(tokens[2].value, NULL, 10);
if (level == 0) {
settings.slab_automove = 0;
} else if (level == 1 || level == 2) {
settings.slab_automove = level;
} else {
out_string(c, "ERROR");
return;
}
}
out_string(c, "OK");
return;
}
/* TODO: decide on syntax for sampling? */
static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) {
uint16_t f = 0;
int x;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (ntokens > 2) {
for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) {
if ((strcmp(tokens[x].value, "rawcmds") == 0)) {
f |= LOG_RAWCMDS;
} else if ((strcmp(tokens[x].value, "evictions") == 0)) {
f |= LOG_EVICTIONS;
} else if ((strcmp(tokens[x].value, "fetchers") == 0)) {
f |= LOG_FETCHERS;
} else if ((strcmp(tokens[x].value, "mutations") == 0)) {
f |= LOG_MUTATIONS;
} else if ((strcmp(tokens[x].value, "sysevents") == 0)) {
f |= LOG_SYSEVENTS;
} else {
out_string(c, "ERROR");
return;
}
}
} else {
f |= LOG_FETCHERS;
}
switch(logger_add_watcher(c, c->sfd, f)) {
case LOGGER_ADD_WATCHER_TOO_MANY:
out_string(c, "WATCHER_TOO_MANY log watcher limit reached");
break;
case LOGGER_ADD_WATCHER_FAILED:
out_string(c, "WATCHER_FAILED failed to add log watcher");
break;
case LOGGER_ADD_WATCHER_OK:
conn_set_state(c, conn_watch);
event_del(&c->event);
break;
}
}
static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t memlimit;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (!safe_strtoul(tokens[1].value, &memlimit)) {
out_string(c, "ERROR");
} else {
if (memlimit < 8) {
out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m");
} else {
if (memlimit > 1000000000) {
out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes");
} else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) {
if (settings.verbose > 0) {
fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit);
}
out_string(c, "OK");
} else {
out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust");
}
}
}
}
static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t pct_hot;
uint32_t pct_warm;
double hot_factor;
int32_t ttl;
double factor;
set_noreply_maybe(c, tokens, ntokens);
if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) {
if (!safe_strtoul(tokens[2].value, &pct_hot) ||
!safe_strtoul(tokens[3].value, &pct_warm) ||
!safe_strtod(tokens[4].value, &hot_factor) ||
!safe_strtod(tokens[5].value, &factor)) {
out_string(c, "ERROR");
} else {
if (pct_hot + pct_warm > 80) {
out_string(c, "ERROR hot and warm pcts must not exceed 80");
} else if (factor <= 0 || hot_factor <= 0) {
out_string(c, "ERROR hot/warm age factors must be greater than 0");
} else {
settings.hot_lru_pct = pct_hot;
settings.warm_lru_pct = pct_warm;
settings.hot_max_factor = hot_factor;
settings.warm_max_factor = factor;
out_string(c, "OK");
}
}
} else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 3 &&
settings.lru_maintainer_thread) {
if (strcmp(tokens[2].value, "flat") == 0) {
settings.lru_segmented = false;
out_string(c, "OK");
} else if (strcmp(tokens[2].value, "segmented") == 0) {
settings.lru_segmented = true;
out_string(c, "OK");
} else {
out_string(c, "ERROR");
}
} else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 3 &&
settings.lru_maintainer_thread) {
if (!safe_strtol(tokens[2].value, &ttl)) {
out_string(c, "ERROR");
} else {
if (ttl < 0) {
settings.temp_lru = false;
} else {
settings.temp_lru = true;
settings.temporary_ttl = ttl;
}
out_string(c, "OK");
}
} else {
out_string(c, "ERROR");
}
}
#ifdef EXTSTORE
static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) {
set_noreply_maybe(c, tokens, ntokens);
bool ok = true;
if (ntokens < 4) {
ok = false;
} else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) {
/* per-slab-class free chunk setting. */
unsigned int clsid = 0;
unsigned int limit = 0;
if (!safe_strtoul(tokens[2].value, &clsid) ||
!safe_strtoul(tokens[3].value, &limit)) {
ok = false;
} else {
if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) {
settings.ext_free_memchunks[clsid] = limit;
} else {
ok = false;
}
}
} else if (strcmp(tokens[1].value, "item_size") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_item_size))
ok = false;
} else if (strcmp(tokens[1].value, "item_age") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_item_age))
ok = false;
} else if (strcmp(tokens[1].value, "low_ttl") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl))
ok = false;
} else if (strcmp(tokens[1].value, "recache_rate") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate))
ok = false;
} else if (strcmp(tokens[1].value, "compact_under") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under))
ok = false;
} else if (strcmp(tokens[1].value, "drop_under") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under))
ok = false;
} else if (strcmp(tokens[1].value, "max_frag") == 0) {
if (!safe_strtod(tokens[2].value, &settings.ext_max_frag))
ok = false;
} else if (strcmp(tokens[1].value, "drop_unread") == 0) {
unsigned int v;
if (!safe_strtoul(tokens[2].value, &v)) {
ok = false;
} else {
settings.ext_drop_unread = v == 0 ? false : true;
}
} else {
ok = false;
}
if (!ok) {
out_string(c, "ERROR");
} else {
out_string(c, "OK");
}
}
#endif
static void process_command(conn *c, char *command) {
token_t tokens[MAX_TOKENS];
size_t ntokens;
int comm;
assert(c != NULL);
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
if (settings.verbose > 1)
fprintf(stderr, "<%d %s\n", c->sfd, command);
/*
* for commands set/add/replace, we build an item and read the data
* directly into it, then continue in nread_complete().
*/
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_of_memory(c, "SERVER_ERROR out of memory preparing response");
return;
}
ntokens = tokenize_command(command, tokens, MAX_TOKENS);
if (ntokens >= 3 &&
((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) ||
(strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) {
process_get_command(c, tokens, ntokens, false, false);
} else if ((ntokens == 6 || ntokens == 7) &&
((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) {
process_update_command(c, tokens, ntokens, comm, false);
} else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) {
process_update_command(c, tokens, ntokens, comm, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 1);
} else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) {
process_get_command(c, tokens, ntokens, true, false);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 0);
} else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) {
process_delete_command(c, tokens, ntokens);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) {
process_touch_command(c, tokens, ntokens);
} else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) {
process_get_command(c, tokens, ntokens, false, true);
} else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) {
process_get_command(c, tokens, ntokens, true, true);
} else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) {
process_stat(c, tokens, ntokens);
} else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) {
time_t exptime = 0;
rel_time_t new_oldest = 0;
set_noreply_maybe(c, tokens, ntokens);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (!settings.flush_enabled) {
// flush_all is not allowed but we log it on stats
out_string(c, "CLIENT_ERROR flush_all not allowed");
return;
}
if (ntokens != (c->noreply ? 3 : 2)) {
exptime = strtol(tokens[1].value, NULL, 10);
if(errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
/*
If exptime is zero realtime() would return zero too, and
realtime(exptime) - 1 would overflow to the max unsigned
value. So we process exptime == 0 the same way we do when
no delay is given at all.
*/
if (exptime > 0) {
new_oldest = realtime(exptime);
} else { /* exptime == 0 */
new_oldest = current_time;
}
if (settings.use_cas) {
settings.oldest_live = new_oldest - 1;
if (settings.oldest_live <= current_time)
settings.oldest_cas = get_cas_id();
} else {
settings.oldest_live = new_oldest;
}
out_string(c, "OK");
return;
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) {
out_string(c, "VERSION " VERSION);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) {
conn_set_state(c, conn_closing);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) {
if (settings.shutdown_command) {
conn_set_state(c, conn_closing);
raise(SIGINT);
} else {
out_string(c, "ERROR: shutdown not enabled");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) {
if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) {
int src, dst, rv;
if (settings.slab_reassign == false) {
out_string(c, "CLIENT_ERROR slab reassignment disabled");
return;
}
src = strtol(tokens[2].value, NULL, 10);
dst = strtol(tokens[3].value, NULL, 10);
if (errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
rv = slabs_reassign(src, dst);
switch (rv) {
case REASSIGN_OK:
out_string(c, "OK");
break;
case REASSIGN_RUNNING:
out_string(c, "BUSY currently processing reassign request");
break;
case REASSIGN_BADCLASS:
out_string(c, "BADCLASS invalid src or dst class id");
break;
case REASSIGN_NOSPARE:
out_string(c, "NOSPARE source class has no spare pages");
break;
case REASSIGN_SRC_DST_SAME:
out_string(c, "SAME src and dst class are identical");
break;
}
return;
} else if (ntokens >= 4 &&
(strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) {
process_slabs_automove_command(c, tokens, ntokens);
} else {
out_string(c, "ERROR");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) {
if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) {
int rv;
if (settings.lru_crawler == false) {
out_string(c, "CLIENT_ERROR lru crawler disabled");
return;
}
rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0,
settings.lru_crawler_tocrawl);
switch(rv) {
case CRAWLER_OK:
out_string(c, "OK");
break;
case CRAWLER_RUNNING:
out_string(c, "BUSY currently processing crawler request");
break;
case CRAWLER_BADCLASS:
out_string(c, "BADCLASS invalid class id");
break;
case CRAWLER_NOTSTARTED:
out_string(c, "NOTSTARTED no items to crawl");
break;
case CRAWLER_ERROR:
out_string(c, "ERROR an unknown error happened");
break;
}
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) {
if (settings.lru_crawler == false) {
out_string(c, "CLIENT_ERROR lru crawler disabled");
return;
}
if (!settings.dump_enabled) {
out_string(c, "ERROR metadump not allowed");
return;
}
int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP,
c, c->sfd, LRU_CRAWLER_CAP_REMAINING);
switch(rv) {
case CRAWLER_OK:
out_string(c, "OK");
// TODO: Don't reuse conn_watch here.
conn_set_state(c, conn_watch);
event_del(&c->event);
break;
case CRAWLER_RUNNING:
out_string(c, "BUSY currently processing crawler request");
break;
case CRAWLER_BADCLASS:
out_string(c, "BADCLASS invalid class id");
break;
case CRAWLER_NOTSTARTED:
out_string(c, "NOTSTARTED no items to crawl");
break;
case CRAWLER_ERROR:
out_string(c, "ERROR an unknown error happened");
break;
}
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) {
uint32_t tocrawl;
if (!safe_strtoul(tokens[2].value, &tocrawl)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
settings.lru_crawler_tocrawl = tocrawl;
out_string(c, "OK");
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) {
uint32_t tosleep;
if (!safe_strtoul(tokens[2].value, &tosleep)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (tosleep > 1000000) {
out_string(c, "CLIENT_ERROR sleep must be one second or less");
return;
}
settings.lru_crawler_sleep = tosleep;
out_string(c, "OK");
return;
} else if (ntokens == 3) {
if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) {
if (start_item_crawler_thread() == 0) {
out_string(c, "OK");
} else {
out_string(c, "ERROR failed to start lru crawler thread");
}
} else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) {
if (stop_item_crawler_thread() == 0) {
out_string(c, "OK");
} else {
out_string(c, "ERROR failed to stop lru crawler thread");
}
} else {
out_string(c, "ERROR");
}
return;
} else {
out_string(c, "ERROR");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) {
process_watch_command(c, tokens, ntokens);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) {
process_memlimit_command(c, tokens, ntokens);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) {
process_verbosity_command(c, tokens, ntokens);
} else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) {
process_lru_command(c, tokens, ntokens);
#ifdef MEMCACHED_DEBUG
// commands which exist only for testing the memcached's security protection
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) {
process_misbehave_command(c);
#endif
#ifdef EXTSTORE
} else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) {
process_extstore_command(c, tokens, ntokens);
#endif
} else {
if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) {
conn_set_state(c, conn_closing);
} else {
out_string(c, "ERROR");
}
}
return;
}
/*
* if we have a complete line in the buffer, process it.
*/
static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_of_memory(c,
"SERVER_ERROR Out of memory allocating headers");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (ptr - c->rcurr > 100 ||
(strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
c->last_cmd_time = current_time;
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
/*
* read a UDP request.
*/
static enum try_read_result try_read_udp(conn *c) {
int res;
assert(c != NULL);
c->request_addr_size = sizeof(c->request_addr);
res = recvfrom(c->sfd, c->rbuf, c->rsize,
0, (struct sockaddr *)&c->request_addr,
&c->request_addr_size);
if (res > 8) {
unsigned char *buf = (unsigned char *)c->rbuf;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* Beginning of UDP packet is the request ID; save it. */
c->request_id = buf[0] * 256 + buf[1];
/* If this is a multi-packet request, drop it. */
if (buf[4] != 0 || buf[5] != 1) {
out_string(c, "SERVER_ERROR multi-packet request not supported");
return READ_NO_DATA_RECEIVED;
}
/* Don't care about any of the rest of the header. */
res -= 8;
memmove(c->rbuf, c->rbuf + 8, res);
c->rbytes = res;
c->rcurr = c->rbuf;
return READ_DATA_RECEIVED;
}
return READ_NO_DATA_RECEIVED;
}
/*
* read from network as much as we can, handle buffer overflow and connection
* close.
* before reading, move the remaining incomplete fragment of a command
* (if any) to the beginning of the buffer.
*
* To protect us from someone flooding a connection with bogus data causing
* the connection to eat up all available memory, break out and start looking
* at the data I've got after a number of reallocs...
*
* @return enum try_read_result
*/
static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
int num_allocs = 0;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
if (num_allocs == 4) {
return gotdata;
}
++num_allocs;
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
if (settings.verbose > 0) {
fprintf(stderr, "Couldn't realloc input buffer\n");
}
c->rbytes = 0; /* ignore what we read */
out_of_memory(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = read(c->sfd, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
static bool update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags)
return true;
if (event_del(&c->event) == -1) return false;
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) return false;
return true;
}
/*
* Sets whether we are listening for new connections or not.
*/
void do_accept_new_conns(const bool do_accept) {
conn *next;
for (next = listen_conn; next; next = next->next) {
if (do_accept) {
update_event(next, EV_READ | EV_PERSIST);
if (listen(next->sfd, settings.backlog) != 0) {
perror("listen");
}
}
else {
update_event(next, 0);
if (listen(next->sfd, 0) != 0) {
perror("listen");
}
}
}
if (do_accept) {
struct timeval maxconns_exited;
uint64_t elapsed_us;
gettimeofday(&maxconns_exited,NULL);
STATS_LOCK();
elapsed_us =
(maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000
+ (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec);
stats.time_in_listen_disabled_us += elapsed_us;
stats_state.accepting_conns = true;
STATS_UNLOCK();
} else {
STATS_LOCK();
stats_state.accepting_conns = false;
gettimeofday(&stats.maxconns_entered,NULL);
stats.listen_disabled_num++;
STATS_UNLOCK();
allow_new_conns = false;
maxconns_handler(-42, 0, 0);
}
}
/*
* Transmit the next chunk of data from our list of msgbuf structures.
*
* Returns:
* TRANSMIT_COMPLETE All done writing.
* TRANSMIT_INCOMPLETE More data remaining to write.
* TRANSMIT_SOFT_ERROR Can't write any more right now.
* TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
*/
static enum transmit_result transmit(conn *c) {
assert(c != NULL);
if (c->msgcurr < c->msgused &&
c->msglist[c->msgcurr].msg_iovlen == 0) {
/* Finished writing the current msg; advance to the next. */
c->msgcurr++;
}
if (c->msgcurr < c->msgused) {
ssize_t res;
struct msghdr *m = &c->msglist[c->msgcurr];
res = sendmsg(c->sfd, m, 0);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_written += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We've written some of the data. Remove the completed
iovec entries from the list of pending writes. */
while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) {
res -= m->msg_iov->iov_len;
m->msg_iovlen--;
m->msg_iov++;
}
/* Might have written just part of the last iovec entry;
adjust it so the next write will do the rest. */
if (res > 0) {
m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res;
m->msg_iov->iov_len -= res;
}
return TRANSMIT_INCOMPLETE;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
}
return TRANSMIT_SOFT_ERROR;
}
/* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK,
we have a real error, on which we close the connection */
if (settings.verbose > 0)
perror("Failed to write, and not due to blocking");
if (IS_UDP(c->transport))
conn_set_state(c, conn_read);
else
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
} else {
return TRANSMIT_COMPLETE;
}
}
/* Does a looped read to fill data chunks */
/* TODO: restrict number of times this can loop.
* Also, benchmark using readv's.
*/
static int read_into_chunked_item(conn *c) {
int total = 0;
int res;
assert(c->rcurr != c->ritem);
while (c->rlbytes > 0) {
item_chunk *ch = (item_chunk *)c->ritem;
assert(ch->used <= ch->size);
if (ch->size == ch->used) {
// FIXME: ch->next is currently always 0. remove this?
if (ch->next) {
c->ritem = (char *) ch->next;
} else {
/* Allocate next chunk. Binary protocol needs 2b for \r\n */
c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes +
((c->protocol == binary_prot) ? 2 : 0));
if (!c->ritem) {
// We failed an allocation. Let caller handle cleanup.
total = -2;
break;
}
// ritem has new chunk, restart the loop.
continue;
//assert(c->rlbytes == 0);
}
}
int unused = ch->size - ch->used;
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
total = 0;
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
tocopy = tocopy > unused ? unused : tocopy;
if (c->ritem != c->rcurr) {
memmove(ch->data + ch->used, c->rcurr, tocopy);
}
total += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
ch->used += tocopy;
if (c->rlbytes == 0) {
break;
}
} else {
/* now try reading from the socket */
res = read(c->sfd, ch->data + ch->used,
(unused > c->rlbytes ? c->rlbytes : unused));
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
ch->used += res;
total += res;
c->rlbytes -= res;
} else {
/* Reset total to the latest result so caller can handle it */
total = res;
break;
}
}
}
/* At some point I will be able to ditch the \r\n from item storage and
remove all of these kludges.
The above binprot check ensures inline space for \r\n, but if we do
exactly enough allocs there will be no additional chunk for \r\n.
*/
if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) {
item_chunk *ch = (item_chunk *)c->ritem;
if (ch->size - ch->used < 2) {
c->ritem = (char *) do_item_alloc_chunk(ch, 2);
if (!c->ritem) {
total = -2;
}
}
}
return total;
}
static void drive_machine(conn *c) {
bool stop = false;
int sfd;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
const char *str;
#ifdef HAVE_ACCEPT4
static int use_accept4 = 1;
#else
static int use_accept4 = 0;
#endif
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
#ifdef HAVE_ACCEPT4
if (use_accept4) {
sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK);
} else {
sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen);
}
#else
sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen);
#endif
if (sfd == -1) {
if (use_accept4 && errno == ENOSYS) {
use_accept4 = 0;
continue;
}
perror(use_accept4 ? "accept4()" : "accept()");
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if (!use_accept4) {
if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
}
if (settings.maxconns_fast &&
stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) {
str = "ERROR Too many open connections\r\n";
res = write(sfd, str, strlen(str));
close(sfd);
STATS_LOCK();
stats.rejected_conns++;
STATS_UNLOCK();
} else {
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, c->transport);
}
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* Check if rbytes < 0, to prevent crash */
if (c->rlbytes < 0) {
if (settings.verbose) {
fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes);
}
conn_set_state(c, conn_closing);
break;
}
if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) {
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = read(c->sfd, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
} else {
res = read_into_chunked_item(c);
if (res > 0)
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* Memory allocation failure */
if (res == -2) {
out_of_memory(c, "SERVER_ERROR Out of memory during read");
c->sbytes = c->rlbytes;
c->write_and_go = conn_swallow;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes <= 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
#ifdef EXTSTORE
/* have side IO's that must process before transmit() can run.
* remove the connection from the worker thread and dispatch the
* IO queue
*/
if (c->io_wrapleft) {
assert(c->io_queued == false);
assert(c->io_wraplist != NULL);
// TODO: create proper state for this condition
conn_set_state(c, conn_watch);
event_del(&c->event);
c->io_queued = true;
extstore_submit(c->thread->storage, &c->io_wraplist->io);
stop = true;
break;
}
#endif
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
conn_release_items(c);
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_closed:
/* This only happens if dormando is an idiot. */
abort();
break;
case conn_watch:
/* We handed off our connection to the logger thread. */
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
}
void event_handler(const int fd, const short which, void *arg) {
conn *c;
c = (conn *)arg;
assert(c != NULL);
c->which = which;
/* sanity */
if (fd != c->sfd) {
if (settings.verbose > 0)
fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n");
conn_close(c);
return;
}
drive_machine(c);
/* wait for next event */
return;
}
static int new_socket(struct addrinfo *ai) {
int sfd;
int flags;
if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
/*
* Sets a socket's send buffer size to the maximum allowed by the system.
*/
static void maximize_sndbuf(const int sfd) {
socklen_t intsize = sizeof(int);
int last_good = 0;
int min, max, avg;
int old_size;
/* Start with the default size. */
if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) {
if (settings.verbose > 0)
perror("getsockopt(SO_SNDBUF)");
return;
}
/* Binary-search for the real maximum. */
min = old_size;
max = MAX_SENDBUF_SIZE;
while (min <= max) {
avg = ((unsigned int)(min + max)) / 2;
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) {
last_good = avg;
min = avg + 1;
} else {
max = avg - 1;
}
}
if (settings.verbose > 1)
fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good);
}
/**
* Create a socket and bind it to a specific port number
* @param interface the interface to bind to
* @param port the port number to bind to
* @param transport the transport protocol (TCP / UDP)
* @param portnumber_file A filepointer to write the port numbers to
* when they are successfully added to the list of ports we
* listen on.
*/
static int server_socket(const char *interface,
int port,
enum network_transport transport,
FILE *portnumber_file) {
int sfd;
struct linger ling = {0, 0};
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = { .ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC };
char port_buf[NI_MAXSERV];
int error;
int success = 0;
int flags =1;
hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM;
if (port == -1) {
port = 0;
}
snprintf(port_buf, sizeof(port_buf), "%d", port);
error= getaddrinfo(interface, port_buf, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM)
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
else
perror("getaddrinfo()");
return 1;
}
for (next= ai; next; next= next->ai_next) {
conn *listen_conn_add;
if ((sfd = new_socket(next)) == -1) {
/* getaddrinfo can return "junk" addresses,
* we make sure at least one works before erroring.
*/
if (errno == EMFILE) {
/* ...unless we're out of fds */
perror("server_socket");
exit(EX_OSERR);
}
continue;
}
#ifdef IPV6_V6ONLY
if (next->ai_family == AF_INET6) {
error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags));
if (error != 0) {
perror("setsockopt");
close(sfd);
continue;
}
}
#endif
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
if (IS_UDP(transport)) {
maximize_sndbuf(sfd);
} else {
error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
}
if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
if (errno != EADDRINUSE) {
perror("bind()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
close(sfd);
continue;
} else {
success++;
if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
if (portnumber_file != NULL &&
(next->ai_addr->sa_family == AF_INET ||
next->ai_addr->sa_family == AF_INET6)) {
union {
struct sockaddr_in in;
struct sockaddr_in6 in6;
} my_sockaddr;
socklen_t len = sizeof(my_sockaddr);
if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
if (next->ai_addr->sa_family == AF_INET) {
fprintf(portnumber_file, "%s INET: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in.sin_port));
} else {
fprintf(portnumber_file, "%s INET6: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in6.sin6_port));
}
}
}
}
if (IS_UDP(transport)) {
int c;
for (c = 0; c < settings.num_threads_per_udp; c++) {
/* Allocate one UDP file descriptor per worker thread;
* this allows "stats conns" to separately list multiple
* parallel UDP requests in progress.
*
* The dispatch code round-robins new connection requests
* among threads, so this is guaranteed to assign one
* FD to each thread.
*/
int per_thread_fd = c ? dup(sfd) : sfd;
dispatch_conn_new(per_thread_fd, conn_read,
EV_READ | EV_PERSIST,
UDP_READ_BUFFER_SIZE, transport);
}
} else {
if (!(listen_conn_add = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
listen_conn_add->next = listen_conn;
listen_conn = listen_conn_add;
}
}
freeaddrinfo(ai);
/* Return zero iff we detected no errors in starting up connections */
return success == 0;
}
static int server_sockets(int port, enum network_transport transport,
FILE *portnumber_file) {
if (settings.inter == NULL) {
return server_socket(settings.inter, port, transport, portnumber_file);
} else {
// tokenize them and bind to each one of them..
char *b;
int ret = 0;
char *list = strdup(settings.inter);
if (list == NULL) {
fprintf(stderr, "Failed to allocate memory for parsing server interface string\n");
return 1;
}
for (char *p = strtok_r(list, ";,", &b);
p != NULL;
p = strtok_r(NULL, ";,", &b)) {
int the_port = port;
char *h = NULL;
if (*p == '[') {
// expecting it to be an IPv6 address enclosed in []
// i.e. RFC3986 style recommended by RFC5952
char *e = strchr(p, ']');
if (e == NULL) {
fprintf(stderr, "Invalid IPV6 address: \"%s\"", p);
free(list);
return 1;
}
h = ++p; // skip the opening '['
*e = '\0';
p = ++e; // skip the closing ']'
}
char *s = strchr(p, ':');
if (s != NULL) {
// If no more semicolons - attempt to treat as port number.
// Otherwise the only valid option is an unenclosed IPv6 without port, until
// of course there was an RFC3986 IPv6 address previously specified -
// in such a case there is no good option, will just send it to fail as port number.
if (strchr(s + 1, ':') == NULL || h != NULL) {
*s = '\0';
++s;
if (!safe_strtol(s, &the_port)) {
fprintf(stderr, "Invalid port number: \"%s\"", s);
free(list);
return 1;
}
}
}
if (h != NULL)
p = h;
if (strcmp(p, "*") == 0) {
p = NULL;
}
ret |= server_socket(p, the_port, transport, portnumber_file);
}
free(list);
return ret;
}
}
static int new_socket_unix(void) {
int sfd;
int flags;
if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket()");
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
static int server_socket_unix(const char *path, int access_mask) {
int sfd;
struct linger ling = {0, 0};
struct sockaddr_un addr;
struct stat tstat;
int flags =1;
int old_umask;
if (!path) {
return 1;
}
if ((sfd = new_socket_unix()) == -1) {
return 1;
}
/*
* Clean up a previous socket file if we left it around
*/
if (lstat(path, &tstat) == 0) {
if (S_ISSOCK(tstat.st_mode))
unlink(path);
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/*
* the memset call clears nonstandard fields in some implementations
* that otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
assert(strcmp(addr.sun_path, path) == 0);
old_umask = umask( ~(access_mask&0777));
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind()");
close(sfd);
umask(old_umask);
return 1;
}
umask(old_umask);
if (listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
return 1;
}
if (!(listen_conn = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
local_transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*
* We keep the current time of day in a global variable that's updated by a
* timer event. This saves us a bunch of time() system calls (we really only
* need to get the time once a second, whereas there can be tens of thousands
* of requests a second) and allows us to use server-start-relative timestamps
* rather than absolute UNIX timestamps, a space savings on systems where
* sizeof(time_t) > sizeof(unsigned int).
*/
volatile rel_time_t current_time;
static struct event clockevent;
/* libevent uses a monotonic clock when available for event scheduling. Aside
* from jitter, simply ticking our internal timer here is accurate enough.
* Note that users who are setting explicit dates for expiration times *must*
* ensure their clocks are correct before starting memcached. */
static void clock_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
static bool initialized = false;
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
static bool monotonic = false;
static time_t monotonic_start;
#endif
if (initialized) {
/* only delete the event if it's actually there. */
evtimer_del(&clockevent);
} else {
initialized = true;
/* process_started is initialized to time() - 2. We initialize to 1 so
* flush_all won't underflow during tests. */
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
monotonic = true;
monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2;
}
#endif
}
// While we're here, check for hash table expansion.
// This function should be quick to avoid delaying the timer.
assoc_start_expand(stats_state.curr_items);
evtimer_set(&clockevent, clock_handler, 0);
event_base_set(main_base, &clockevent);
evtimer_add(&clockevent, &t);
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
if (monotonic) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
return;
current_time = (rel_time_t) (ts.tv_sec - monotonic_start);
return;
}
#endif
{
struct timeval tv;
gettimeofday(&tv, NULL);
current_time = (rel_time_t) (tv.tv_sec - process_started);
}
}
static void usage(void) {
printf(PACKAGE " " VERSION "\n");
printf("-p, --port=<num> TCP port to listen on (default: 11211)\n"
"-U, --udp-port=<num> UDP port to listen on (default: 11211, 0 is off)\n"
"-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n"
"-A, --enable-shutdown enable ascii \"shutdown\" command\n"
"-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n"
"-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n"
"-d, --daemon run as a daemon\n"
"-r, --enable-coredumps maximize core file limit\n"
"-u, --user=<user> assume identity of <username> (only when run as root)\n"
"-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n"
"-M, --disable-evictions return error on memory exhausted instead of evicting\n"
"-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n"
"-k, --lock-memory lock down all paged memory\n"
"-v, --verbose verbose (print errors/warnings while in event loop)\n"
"-vv very verbose (also print client commands/responses)\n"
"-vvv extremely verbose (internal state transitions)\n"
"-h, --help print this help and exit\n"
"-i, --license print memcached and libevent license\n"
"-V, --version print version and exit\n"
"-P, --pidfile=<file> save PID in <file>, only used with -d option\n"
"-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n"
"-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n");
printf("-L, --enable-largepages try to use large memory pages (if available)\n");
printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n"
" This is used for per-prefix stats reporting. The default is\n"
" \":\" (colon). If this option is specified, stats collection\n"
" is turned on automatically; if not, then it may be turned on\n"
" by sending the \"stats detail on\" command to the server.\n");
printf("-t, --threads=<num> number of threads to use (default: 4)\n");
printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n"
" requests processed per connection to prevent \n"
" starvation (default: 20)\n");
printf("-C, --disable-cas disable use of CAS\n");
printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n");
printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n");
printf("-I, --max-item-size=<num> adjusts max item size\n"
" (default: 1mb, min: 1k, max: 128m)\n");
#ifdef ENABLE_SASL
printf("-S, --enable-sasl turn on Sasl authentication\n");
#endif
printf("-F, --disable-flush-all disable flush_all command\n");
printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n");
printf("-o, --extended comma separated list of extended options\n"
" most options have a 'no_' prefix to disable\n"
" - maxconns_fast: immediately close new connections after limit\n"
" - hashpower: an integer multiplier for how large the hash\n"
" table should be. normally grows at runtime.\n"
" set based on \"STAT hash_power_level\"\n"
" - tail_repair_time: time in seconds for how long to wait before\n"
" forcefully killing LRU tail item.\n"
" disabled by default; very dangerous option.\n"
" - hash_algorithm: the hash table algorithm\n"
" default is murmur3 hash. options: jenkins, murmur3\n"
" - lru_crawler: enable LRU Crawler background thread\n"
" - lru_crawler_sleep: microseconds to sleep between items\n"
" default is 100.\n"
" - lru_crawler_tocrawl: max items to crawl per slab per run\n"
" default is 0 (unlimited)\n"
" - lru_maintainer: enable new LRU system + background thread\n"
" - hot_lru_pct: pct of slab memory to reserve for hot lru.\n"
" (requires lru_maintainer)\n"
" - warm_lru_pct: pct of slab memory to reserve for warm lru.\n"
" (requires lru_maintainer)\n"
" - hot_max_factor: items idle > cold lru age * drop from hot lru.\n"
" - warm_max_factor: items idle > cold lru age * this drop from warm.\n"
" - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n"
" (requires lru_maintainer)\n"
" - idle_timeout: timeout for idle connections\n"
" - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n"
" - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n"
" - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n"
" read by background thread, then written to watchers.\n"
" - track_sizes: enable dynamic reports for 'stats sizes' command.\n"
" - no_inline_ascii_resp: save up to 24 bytes per item.\n"
" small perf hit in ASCII, no perf difference in\n"
" binary protocol. speeds up all sets.\n"
" - no_hashexpand: disables hash table expansion (dangerous)\n"
" - modern: enables options which will be default in future.\n"
" currently: nothing\n"
" - no_modern: uses defaults of previous major version (1.4.x)\n"
#ifdef HAVE_DROP_PRIVILEGES
" - no_drop_privileges: Disable drop_privileges in case it causes issues with\n"
" some customisation.\n"
#ifdef MEMCACHED_DEBUG
" - relaxed_privileges: Running tests requires extra privileges.\n"
#endif
#endif
#ifdef EXTSTORE
" - ext_path: file to write to for external storage.\n"
" - ext_page_size: size in megabytes of storage pages.\n"
" - ext_wbuf_size: size in megabytes of page write buffers.\n"
" - ext_threads: number of IO threads to run.\n"
" - ext_item_size: store items larger than this (bytes)\n"
" - ext_item_age: store items idle at least this long\n"
" - ext_low_ttl: consider TTLs lower than this specially\n"
" - ext_drop_unread: don't re-write unread values during compaction\n"
" - ext_recache_rate: recache an item every N accesses\n"
" - ext_compact_under: compact when fewer than this many free pages\n"
" - ext_drop_under: drop COLD items when fewer than this many free pages\n"
" - ext_max_frag: max page fragmentation to tolerage\n"
" (see doc/storage.txt for more info)\n"
#endif
);
return;
}
static void usage_license(void) {
printf(PACKAGE " " VERSION "\n\n");
printf(
"Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are\n"
"met:\n"
"\n"
" * Redistributions of source code must retain the above copyright\n"
"notice, this list of conditions and the following disclaimer.\n"
"\n"
" * Redistributions in binary form must reproduce the above\n"
"copyright notice, this list of conditions and the following disclaimer\n"
"in the documentation and/or other materials provided with the\n"
"distribution.\n"
"\n"
" * Neither the name of the Danga Interactive nor the names of its\n"
"contributors may be used to endorse or promote products derived from\n"
"this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"\n"
"\n"
"This product includes software developed by Niels Provos.\n"
"\n"
"[ libevent ]\n"
"\n"
"Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions\n"
"are met:\n"
"1. Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
"3. All advertising materials mentioning features or use of this software\n"
" must display the following acknowledgement:\n"
" This product includes software developed by Niels Provos.\n"
"4. The name of the author may not be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n"
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
);
return;
}
static void save_pid(const char *pid_file) {
FILE *fp;
if (access(pid_file, F_OK) == 0) {
if ((fp = fopen(pid_file, "r")) != NULL) {
char buffer[1024];
if (fgets(buffer, sizeof(buffer), fp) != NULL) {
unsigned int pid;
if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) {
fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid);
}
}
fclose(fp);
}
}
/* Create the pid file first with a temporary name, then
* atomically move the file to the real name to avoid a race with
* another process opening the file to read the pid, but finding
* it empty.
*/
char tmp_pid_file[1024];
snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file);
if ((fp = fopen(tmp_pid_file, "w")) == NULL) {
vperror("Could not open the pid file %s for writing", tmp_pid_file);
return;
}
fprintf(fp,"%ld\n", (long)getpid());
if (fclose(fp) == -1) {
vperror("Could not close the pid file %s", tmp_pid_file);
}
if (rename(tmp_pid_file, pid_file) != 0) {
vperror("Could not rename the pid file from %s to %s",
tmp_pid_file, pid_file);
}
}
static void remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
vperror("Could not remove the pid file %s", pid_file);
}
}
static void sig_handler(const int sig) {
printf("Signal handled: %s.\n", strsignal(sig));
exit(EXIT_SUCCESS);
}
#ifndef HAVE_SIGIGNORE
static int sigignore(int sig) {
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 };
if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) {
return -1;
}
return 0;
}
#endif
/*
* On systems that supports multiple page sizes we may reduce the
* number of TLB-misses by using the biggest available page size
*/
static int enable_large_pages(void) {
#if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL)
int ret = -1;
size_t sizes[32];
int avail = getpagesizes(sizes, 32);
if (avail != -1) {
size_t max = sizes[0];
struct memcntl_mha arg = {0};
int ii;
for (ii = 1; ii < avail; ++ii) {
if (max < sizes[ii]) {
max = sizes[ii];
}
}
arg.mha_flags = 0;
arg.mha_pagesize = max;
arg.mha_cmd = MHA_MAPSIZE_BSSBRK;
if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) {
fprintf(stderr, "Failed to set large pages: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
} else {
ret = 0;
}
} else {
fprintf(stderr, "Failed to get supported pagesizes: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
}
return ret;
#else
return -1;
#endif
}
/**
* Do basic sanity check of the runtime environment
* @return true if no errors found, false if we can't use this env
*/
static bool sanitycheck(void) {
/* One of our biggest problems is old and bogus libevents */
const char *ever = event_get_version();
if (ever != NULL) {
if (strncmp(ever, "1.", 2) == 0) {
/* Require at least 1.3 (that's still a couple of years old) */
if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) {
fprintf(stderr, "You are using libevent %s.\nPlease upgrade to"
" a more recent version (1.3 or newer)\n",
event_get_version());
return false;
}
}
}
return true;
}
static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) {
char *b = NULL;
uint32_t size = 0;
int i = 0;
uint32_t last_size = 0;
if (strlen(s) < 1)
return false;
for (char *p = strtok_r(s, "-", &b);
p != NULL;
p = strtok_r(NULL, "-", &b)) {
if (!safe_strtoul(p, &size) || size < settings.chunk_size
|| size > settings.slab_chunk_size_max) {
fprintf(stderr, "slab size %u is out of valid range\n", size);
return false;
}
if (last_size >= size) {
fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size);
return false;
}
if (size <= last_size + CHUNK_ALIGN_BYTES) {
fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n",
size, CHUNK_ALIGN_BYTES);
return false;
}
slab_sizes[i++] = size;
last_size = size;
if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) {
fprintf(stderr, "too many slab classes specified\n");
return false;
}
}
slab_sizes[i] = 0;
return true;
}
int main (int argc, char **argv) {
int c;
bool lock_memory = false;
bool do_daemonize = false;
bool preallocate = false;
int maxcore = 0;
char *username = NULL;
char *pid_file = NULL;
struct passwd *pw;
struct rlimit rlim;
char *buf;
char unit = '\0';
int size_max = 0;
int retval = EXIT_SUCCESS;
/* listening sockets */
static int *l_socket = NULL;
/* udp socket */
static int *u_socket = NULL;
bool protocol_specified = false;
bool tcp_specified = false;
bool udp_specified = false;
bool start_lru_maintainer = true;
bool start_lru_crawler = true;
bool start_assoc_maint = true;
enum hashfunc_type hash_type = MURMUR3_HASH;
uint32_t tocrawl;
uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES];
bool use_slab_sizes = false;
char *slab_sizes_unparsed = NULL;
bool slab_chunk_size_changed = false;
#ifdef EXTSTORE
void *storage = NULL;
char *storage_file = NULL;
struct extstore_conf ext_cf;
#endif
char *subopts, *subopts_orig;
char *subopts_value;
enum {
MAXCONNS_FAST = 0,
HASHPOWER_INIT,
NO_HASHEXPAND,
SLAB_REASSIGN,
SLAB_AUTOMOVE,
SLAB_AUTOMOVE_RATIO,
SLAB_AUTOMOVE_WINDOW,
TAIL_REPAIR_TIME,
HASH_ALGORITHM,
LRU_CRAWLER,
LRU_CRAWLER_SLEEP,
LRU_CRAWLER_TOCRAWL,
LRU_MAINTAINER,
HOT_LRU_PCT,
WARM_LRU_PCT,
HOT_MAX_FACTOR,
WARM_MAX_FACTOR,
TEMPORARY_TTL,
IDLE_TIMEOUT,
WATCHER_LOGBUF_SIZE,
WORKER_LOGBUF_SIZE,
SLAB_SIZES,
SLAB_CHUNK_MAX,
TRACK_SIZES,
NO_INLINE_ASCII_RESP,
MODERN,
NO_MODERN,
NO_CHUNKED_ITEMS,
NO_SLAB_REASSIGN,
NO_SLAB_AUTOMOVE,
NO_MAXCONNS_FAST,
INLINE_ASCII_RESP,
NO_LRU_CRAWLER,
NO_LRU_MAINTAINER,
NO_DROP_PRIVILEGES,
#ifdef MEMCACHED_DEBUG
RELAXED_PRIVILEGES,
#endif
#ifdef EXTSTORE
EXT_PAGE_SIZE,
EXT_PAGE_COUNT,
EXT_WBUF_SIZE,
EXT_THREADS,
EXT_IO_DEPTH,
EXT_PATH,
EXT_ITEM_SIZE,
EXT_ITEM_AGE,
EXT_LOW_TTL,
EXT_RECACHE_RATE,
EXT_COMPACT_UNDER,
EXT_DROP_UNDER,
EXT_MAX_FRAG,
EXT_DROP_UNREAD,
SLAB_AUTOMOVE_FREERATIO,
#endif
};
char *const subopts_tokens[] = {
[MAXCONNS_FAST] = "maxconns_fast",
[HASHPOWER_INIT] = "hashpower",
[NO_HASHEXPAND] = "no_hashexpand",
[SLAB_REASSIGN] = "slab_reassign",
[SLAB_AUTOMOVE] = "slab_automove",
[SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio",
[SLAB_AUTOMOVE_WINDOW] = "slab_automove_window",
[TAIL_REPAIR_TIME] = "tail_repair_time",
[HASH_ALGORITHM] = "hash_algorithm",
[LRU_CRAWLER] = "lru_crawler",
[LRU_CRAWLER_SLEEP] = "lru_crawler_sleep",
[LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl",
[LRU_MAINTAINER] = "lru_maintainer",
[HOT_LRU_PCT] = "hot_lru_pct",
[WARM_LRU_PCT] = "warm_lru_pct",
[HOT_MAX_FACTOR] = "hot_max_factor",
[WARM_MAX_FACTOR] = "warm_max_factor",
[TEMPORARY_TTL] = "temporary_ttl",
[IDLE_TIMEOUT] = "idle_timeout",
[WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size",
[WORKER_LOGBUF_SIZE] = "worker_logbuf_size",
[SLAB_SIZES] = "slab_sizes",
[SLAB_CHUNK_MAX] = "slab_chunk_max",
[TRACK_SIZES] = "track_sizes",
[NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp",
[MODERN] = "modern",
[NO_MODERN] = "no_modern",
[NO_CHUNKED_ITEMS] = "no_chunked_items",
[NO_SLAB_REASSIGN] = "no_slab_reassign",
[NO_SLAB_AUTOMOVE] = "no_slab_automove",
[NO_MAXCONNS_FAST] = "no_maxconns_fast",
[INLINE_ASCII_RESP] = "inline_ascii_resp",
[NO_LRU_CRAWLER] = "no_lru_crawler",
[NO_LRU_MAINTAINER] = "no_lru_maintainer",
[NO_DROP_PRIVILEGES] = "no_drop_privileges",
#ifdef MEMCACHED_DEBUG
[RELAXED_PRIVILEGES] = "relaxed_privileges",
#endif
#ifdef EXTSTORE
[EXT_PAGE_SIZE] = "ext_page_size",
[EXT_PAGE_COUNT] = "ext_page_count",
[EXT_WBUF_SIZE] = "ext_wbuf_size",
[EXT_THREADS] = "ext_threads",
[EXT_IO_DEPTH] = "ext_io_depth",
[EXT_PATH] = "ext_path",
[EXT_ITEM_SIZE] = "ext_item_size",
[EXT_ITEM_AGE] = "ext_item_age",
[EXT_LOW_TTL] = "ext_low_ttl",
[EXT_RECACHE_RATE] = "ext_recache_rate",
[EXT_COMPACT_UNDER] = "ext_compact_under",
[EXT_DROP_UNDER] = "ext_drop_under",
[EXT_MAX_FRAG] = "ext_max_frag",
[EXT_DROP_UNREAD] = "ext_drop_unread",
[SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio",
#endif
NULL
};
if (!sanitycheck()) {
return EX_OSERR;
}
/* handle SIGINT and SIGTERM */
signal(SIGINT, sig_handler);
signal(SIGTERM, sig_handler);
/* init settings */
settings_init();
#ifdef EXTSTORE
settings.ext_item_size = 512;
settings.ext_item_age = UINT_MAX;
settings.ext_low_ttl = 0;
settings.ext_recache_rate = 2000;
settings.ext_max_frag = 0.8;
settings.ext_drop_unread = false;
settings.ext_wbuf_size = 1024 * 1024 * 4;
settings.ext_compact_under = 0;
settings.ext_drop_under = 0;
settings.slab_automove_freeratio = 0.01;
ext_cf.page_size = 1024 * 1024 * 64;
ext_cf.page_count = 64;
ext_cf.wbuf_size = settings.ext_wbuf_size;
ext_cf.io_threadcount = 1;
ext_cf.io_depth = 1;
ext_cf.page_buckets = 4;
ext_cf.wbuf_count = ext_cf.page_buckets;
#endif
/* Run regardless of initializing it later */
init_lru_maintainer();
/* set stderr non-buffering (for running under, say, daemontools) */
setbuf(stderr, NULL);
char *shortopts =
"a:" /* access mask for unix socket */
"A" /* enable admin shutdown command */
"p:" /* TCP port number to listen on */
"s:" /* unix socket path to listen on */
"U:" /* UDP port number to listen on */
"m:" /* max memory to use for items in megabytes */
"M" /* return error on memory exhausted */
"c:" /* max simultaneous connections */
"k" /* lock down all paged memory */
"hiV" /* help, licence info, version */
"r" /* maximize core file limit */
"v" /* verbose */
"d" /* daemon mode */
"l:" /* interface to listen on */
"u:" /* user identity to run as */
"P:" /* save PID in file */
"f:" /* factor? */
"n:" /* minimum space allocated for key+value+flags */
"t:" /* threads */
"D:" /* prefix delimiter? */
"L" /* Large memory pages */
"R:" /* max requests per event */
"C" /* Disable use of CAS */
"b:" /* backlog queue limit */
"B:" /* Binding protocol */
"I:" /* Max item size */
"S" /* Sasl ON */
"F" /* Disable flush_all */
"X" /* Disable dump commands */
"o:" /* Extended generic options */
;
/* process arguments */
#ifdef HAVE_GETOPT_LONG
const struct option longopts[] = {
{"unix-mask", required_argument, 0, 'a'},
{"enable-shutdown", no_argument, 0, 'A'},
{"port", required_argument, 0, 'p'},
{"unix-socket", required_argument, 0, 's'},
{"udp-port", required_argument, 0, 'U'},
{"memory-limit", required_argument, 0, 'm'},
{"disable-evictions", no_argument, 0, 'M'},
{"conn-limit", required_argument, 0, 'c'},
{"lock-memory", no_argument, 0, 'k'},
{"help", no_argument, 0, 'h'},
{"license", no_argument, 0, 'i'},
{"version", no_argument, 0, 'V'},
{"enable-coredumps", no_argument, 0, 'r'},
{"verbose", optional_argument, 0, 'v'},
{"daemon", no_argument, 0, 'd'},
{"listen", required_argument, 0, 'l'},
{"user", required_argument, 0, 'u'},
{"pidfile", required_argument, 0, 'P'},
{"slab-growth-factor", required_argument, 0, 'f'},
{"slab-min-size", required_argument, 0, 'n'},
{"threads", required_argument, 0, 't'},
{"enable-largepages", no_argument, 0, 'L'},
{"max-reqs-per-event", required_argument, 0, 'R'},
{"disable-cas", no_argument, 0, 'C'},
{"listen-backlog", required_argument, 0, 'b'},
{"protocol", required_argument, 0, 'B'},
{"max-item-size", required_argument, 0, 'I'},
{"enable-sasl", no_argument, 0, 'S'},
{"disable-flush-all", no_argument, 0, 'F'},
{"disable-dumping", no_argument, 0, 'X'},
{"extended", required_argument, 0, 'o'},
{0, 0, 0, 0}
};
int optindex;
while (-1 != (c = getopt_long(argc, argv, shortopts,
longopts, &optindex))) {
#else
while (-1 != (c = getopt(argc, argv, shortopts))) {
#endif
switch (c) {
case 'A':
/* enables "shutdown" command */
settings.shutdown_command = true;
break;
case 'a':
/* access for unix domain socket, as octal mask (like chmod)*/
settings.access= strtol(optarg,NULL,8);
break;
case 'U':
settings.udpport = atoi(optarg);
udp_specified = true;
break;
case 'p':
settings.port = atoi(optarg);
tcp_specified = true;
break;
case 's':
settings.socketpath = optarg;
break;
case 'm':
settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
break;
case 'M':
settings.evict_to_free = 0;
break;
case 'c':
settings.maxconns = atoi(optarg);
if (settings.maxconns <= 0) {
fprintf(stderr, "Maximum connections must be greater than 0\n");
return 1;
}
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'i':
usage_license();
exit(EXIT_SUCCESS);
case 'V':
printf(PACKAGE " " VERSION "\n");
exit(EXIT_SUCCESS);
case 'k':
lock_memory = true;
break;
case 'v':
settings.verbose++;
break;
case 'l':
if (settings.inter != NULL) {
if (strstr(settings.inter, optarg) != NULL) {
break;
}
size_t len = strlen(settings.inter) + strlen(optarg) + 2;
char *p = malloc(len);
if (p == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
return 1;
}
snprintf(p, len, "%s,%s", settings.inter, optarg);
free(settings.inter);
settings.inter = p;
} else {
settings.inter= strdup(optarg);
}
break;
case 'd':
do_daemonize = true;
break;
case 'r':
maxcore = 1;
break;
case 'R':
settings.reqs_per_event = atoi(optarg);
if (settings.reqs_per_event == 0) {
fprintf(stderr, "Number of requests per event must be greater than 0\n");
return 1;
}
break;
case 'u':
username = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'f':
settings.factor = atof(optarg);
if (settings.factor <= 1.0) {
fprintf(stderr, "Factor must be greater than 1\n");
return 1;
}
break;
case 'n':
settings.chunk_size = atoi(optarg);
if (settings.chunk_size == 0) {
fprintf(stderr, "Chunk size must be greater than 0\n");
return 1;
}
break;
case 't':
settings.num_threads = atoi(optarg);
if (settings.num_threads <= 0) {
fprintf(stderr, "Number of threads must be greater than 0\n");
return 1;
}
/* There're other problems when you get above 64 threads.
* In the future we should portably detect # of cores for the
* default.
*/
if (settings.num_threads > 64) {
fprintf(stderr, "WARNING: Setting a high number of worker"
"threads is not recommended.\n"
" Set this value to the number of cores in"
" your machine or less.\n");
}
break;
case 'D':
if (! optarg || ! optarg[0]) {
fprintf(stderr, "No delimiter specified\n");
return 1;
}
settings.prefix_delimiter = optarg[0];
settings.detail_enabled = 1;
break;
case 'L' :
if (enable_large_pages() == 0) {
preallocate = true;
} else {
fprintf(stderr, "Cannot enable large pages on this system\n"
"(There is no Linux support as of this version)\n");
return 1;
}
break;
case 'C' :
settings.use_cas = false;
break;
case 'b' :
settings.backlog = atoi(optarg);
break;
case 'B':
protocol_specified = true;
if (strcmp(optarg, "auto") == 0) {
settings.binding_protocol = negotiating_prot;
} else if (strcmp(optarg, "binary") == 0) {
settings.binding_protocol = binary_prot;
} else if (strcmp(optarg, "ascii") == 0) {
settings.binding_protocol = ascii_prot;
} else {
fprintf(stderr, "Invalid value for binding protocol: %s\n"
" -- should be one of auto, binary, or ascii\n", optarg);
exit(EX_USAGE);
}
break;
case 'I':
buf = strdup(optarg);
unit = buf[strlen(buf)-1];
if (unit == 'k' || unit == 'm' ||
unit == 'K' || unit == 'M') {
buf[strlen(buf)-1] = '\0';
size_max = atoi(buf);
if (unit == 'k' || unit == 'K')
size_max *= 1024;
if (unit == 'm' || unit == 'M')
size_max *= 1024 * 1024;
settings.item_size_max = size_max;
} else {
settings.item_size_max = atoi(buf);
}
free(buf);
break;
case 'S': /* set Sasl authentication to true. Default is false */
#ifndef ENABLE_SASL
fprintf(stderr, "This server is not built with SASL support.\n");
exit(EX_USAGE);
#endif
settings.sasl = true;
break;
case 'F' :
settings.flush_enabled = false;
break;
case 'X' :
settings.dump_enabled = false;
break;
case 'o': /* It's sub-opts time! */
subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */
while (*subopts != '\0') {
switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) {
case MAXCONNS_FAST:
settings.maxconns_fast = true;
break;
case HASHPOWER_INIT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for hashpower\n");
return 1;
}
settings.hashpower_init = atoi(subopts_value);
if (settings.hashpower_init < 12) {
fprintf(stderr, "Initial hashtable multiplier of %d is too low\n",
settings.hashpower_init);
return 1;
} else if (settings.hashpower_init > 32) {
fprintf(stderr, "Initial hashtable multiplier of %d is too high\n"
"Choose a value based on \"STAT hash_power_level\" from a running instance\n",
settings.hashpower_init);
return 1;
}
break;
case NO_HASHEXPAND:
start_assoc_maint = false;
break;
case SLAB_REASSIGN:
settings.slab_reassign = true;
break;
case SLAB_AUTOMOVE:
if (subopts_value == NULL) {
settings.slab_automove = 1;
break;
}
settings.slab_automove = atoi(subopts_value);
if (settings.slab_automove < 0 || settings.slab_automove > 2) {
fprintf(stderr, "slab_automove must be between 0 and 2\n");
return 1;
}
break;
case SLAB_AUTOMOVE_RATIO:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_ratio argument\n");
return 1;
}
settings.slab_automove_ratio = atof(subopts_value);
if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) {
fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n");
return 1;
}
break;
case SLAB_AUTOMOVE_WINDOW:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_window argument\n");
return 1;
}
settings.slab_automove_window = atoi(subopts_value);
if (settings.slab_automove_window < 3) {
fprintf(stderr, "slab_automove_window must be > 2\n");
return 1;
}
break;
case TAIL_REPAIR_TIME:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for tail_repair_time\n");
return 1;
}
settings.tail_repair_time = atoi(subopts_value);
if (settings.tail_repair_time < 10) {
fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n");
return 1;
}
break;
case HASH_ALGORITHM:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hash_algorithm argument\n");
return 1;
};
if (strcmp(subopts_value, "jenkins") == 0) {
hash_type = JENKINS_HASH;
} else if (strcmp(subopts_value, "murmur3") == 0) {
hash_type = MURMUR3_HASH;
} else {
fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n");
return 1;
}
break;
case LRU_CRAWLER:
start_lru_crawler = true;
break;
case LRU_CRAWLER_SLEEP:
if (subopts_value == NULL) {
fprintf(stderr, "Missing lru_crawler_sleep value\n");
return 1;
}
settings.lru_crawler_sleep = atoi(subopts_value);
if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) {
fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n");
return 1;
}
break;
case LRU_CRAWLER_TOCRAWL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing lru_crawler_tocrawl value\n");
return 1;
}
if (!safe_strtoul(subopts_value, &tocrawl)) {
fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n");
return 1;
}
settings.lru_crawler_tocrawl = tocrawl;
break;
case LRU_MAINTAINER:
start_lru_maintainer = true;
settings.lru_segmented = true;
break;
case HOT_LRU_PCT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hot_lru_pct argument\n");
return 1;
}
settings.hot_lru_pct = atoi(subopts_value);
if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) {
fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n");
return 1;
}
break;
case WARM_LRU_PCT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing warm_lru_pct argument\n");
return 1;
}
settings.warm_lru_pct = atoi(subopts_value);
if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) {
fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n");
return 1;
}
break;
case HOT_MAX_FACTOR:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hot_max_factor argument\n");
return 1;
}
settings.hot_max_factor = atof(subopts_value);
if (settings.hot_max_factor <= 0) {
fprintf(stderr, "hot_max_factor must be > 0\n");
return 1;
}
break;
case WARM_MAX_FACTOR:
if (subopts_value == NULL) {
fprintf(stderr, "Missing warm_max_factor argument\n");
return 1;
}
settings.warm_max_factor = atof(subopts_value);
if (settings.warm_max_factor <= 0) {
fprintf(stderr, "warm_max_factor must be > 0\n");
return 1;
}
break;
case TEMPORARY_TTL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing temporary_ttl argument\n");
return 1;
}
settings.temp_lru = true;
settings.temporary_ttl = atoi(subopts_value);
break;
case IDLE_TIMEOUT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for idle_timeout\n");
return 1;
}
settings.idle_timeout = atoi(subopts_value);
break;
case WATCHER_LOGBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing watcher_logbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) {
fprintf(stderr, "could not parse argument to watcher_logbuf_size\n");
return 1;
}
settings.logger_watcher_buf_size *= 1024; /* kilobytes */
break;
case WORKER_LOGBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing worker_logbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) {
fprintf(stderr, "could not parse argument to worker_logbuf_size\n");
return 1;
}
settings.logger_buf_size *= 1024; /* kilobytes */
case SLAB_SIZES:
slab_sizes_unparsed = subopts_value;
break;
case SLAB_CHUNK_MAX:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_chunk_max argument\n");
}
if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) {
fprintf(stderr, "could not parse argument to slab_chunk_max\n");
}
slab_chunk_size_changed = true;
break;
case TRACK_SIZES:
item_stats_sizes_init();
break;
case NO_INLINE_ASCII_RESP:
settings.inline_ascii_response = false;
break;
case INLINE_ASCII_RESP:
settings.inline_ascii_response = true;
break;
case NO_CHUNKED_ITEMS:
settings.slab_chunk_size_max = settings.slab_page_size;
break;
case NO_SLAB_REASSIGN:
settings.slab_reassign = false;
break;
case NO_SLAB_AUTOMOVE:
settings.slab_automove = 0;
break;
case NO_MAXCONNS_FAST:
settings.maxconns_fast = false;
break;
case NO_LRU_CRAWLER:
settings.lru_crawler = false;
start_lru_crawler = false;
break;
case NO_LRU_MAINTAINER:
start_lru_maintainer = false;
settings.lru_segmented = false;
break;
#ifdef EXTSTORE
case EXT_PAGE_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_page_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.page_size)) {
fprintf(stderr, "could not parse argument to ext_page_size\n");
return 1;
}
ext_cf.page_size *= 1024 * 1024; /* megabytes */
break;
case EXT_PAGE_COUNT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_page_count argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.page_count)) {
fprintf(stderr, "could not parse argument to ext_page_count\n");
return 1;
}
break;
case EXT_WBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_wbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) {
fprintf(stderr, "could not parse argument to ext_wbuf_size\n");
return 1;
}
ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */
settings.ext_wbuf_size = ext_cf.wbuf_size;
break;
case EXT_THREADS:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_threads argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) {
fprintf(stderr, "could not parse argument to ext_threads\n");
return 1;
}
break;
case EXT_IO_DEPTH:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_io_depth argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) {
fprintf(stderr, "could not parse argument to ext_io_depth\n");
return 1;
}
break;
case EXT_ITEM_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_item_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_item_size)) {
fprintf(stderr, "could not parse argument to ext_item_size\n");
return 1;
}
break;
case EXT_ITEM_AGE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_item_age argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_item_age)) {
fprintf(stderr, "could not parse argument to ext_item_age\n");
return 1;
}
break;
case EXT_LOW_TTL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_low_ttl argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) {
fprintf(stderr, "could not parse argument to ext_low_ttl\n");
return 1;
}
break;
case EXT_RECACHE_RATE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_recache_rate argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) {
fprintf(stderr, "could not parse argument to ext_recache_rate\n");
return 1;
}
break;
case EXT_COMPACT_UNDER:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_compact_under argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) {
fprintf(stderr, "could not parse argument to ext_compact_under\n");
return 1;
}
break;
case EXT_DROP_UNDER:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_drop_under argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) {
fprintf(stderr, "could not parse argument to ext_drop_under\n");
return 1;
}
break;
case EXT_MAX_FRAG:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_max_frag argument\n");
return 1;
}
if (!safe_strtod(subopts_value, &settings.ext_max_frag)) {
fprintf(stderr, "could not parse argument to ext_max_frag\n");
return 1;
}
break;
case SLAB_AUTOMOVE_FREERATIO:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_freeratio argument\n");
return 1;
}
if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) {
fprintf(stderr, "could not parse argument to slab_automove_freeratio\n");
return 1;
}
break;
case EXT_DROP_UNREAD:
settings.ext_drop_unread = true;
break;
case EXT_PATH:
storage_file = strdup(subopts_value);
break;
#endif
case MODERN:
/* currently no new defaults */
break;
case NO_MODERN:
if (!slab_chunk_size_changed) {
settings.slab_chunk_size_max = settings.slab_page_size;
}
settings.slab_reassign = false;
settings.slab_automove = 0;
settings.maxconns_fast = false;
settings.inline_ascii_response = true;
settings.lru_segmented = false;
hash_type = JENKINS_HASH;
start_lru_crawler = false;
start_lru_maintainer = false;
break;
case NO_DROP_PRIVILEGES:
settings.drop_privileges = false;
break;
#ifdef MEMCACHED_DEBUG
case RELAXED_PRIVILEGES:
settings.relaxed_privileges = true;
break;
#endif
default:
printf("Illegal suboption \"%s\"\n", subopts_value);
return 1;
}
}
free(subopts_orig);
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
return 1;
}
}
if (settings.item_size_max < 1024) {
fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > (settings.maxbytes / 2)) {
fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > (1024 * 1024 * 1024)) {
fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > 1024 * 1024) {
if (!slab_chunk_size_changed) {
// Ideal new default is 16k, but needs stitching.
settings.slab_chunk_size_max = settings.slab_page_size / 2;
}
}
if (settings.slab_chunk_size_max > settings.item_size_max) {
fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n",
settings.slab_chunk_size_max, settings.item_size_max);
exit(EX_USAGE);
}
if (settings.item_size_max % settings.slab_chunk_size_max != 0) {
fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n",
settings.item_size_max, settings.slab_chunk_size_max);
exit(EX_USAGE);
}
if (settings.slab_page_size % settings.slab_chunk_size_max != 0) {
fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n",
settings.slab_chunk_size_max, settings.slab_page_size);
exit(EX_USAGE);
}
#ifdef EXTSTORE
if (storage_file) {
if (settings.item_size_max > ext_cf.wbuf_size) {
fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n",
settings.item_size_max, ext_cf.wbuf_size);
exit(EX_USAGE);
}
/* This is due to the suffix header being generated with the wrong length
* value for the ITEM_HDR replacement. The cuddled nbytes no longer
* matches, so we end up losing a few bytes on readback.
*/
if (settings.inline_ascii_response) {
fprintf(stderr, "Cannot use inline_ascii_response with extstore enabled\n");
exit(EX_USAGE);
}
if (settings.udpport) {
fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n");
exit(EX_USAGE);
}
}
#endif
// Reserve this for the new default. If factor size hasn't changed, use
// new default.
/*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) {
settings.factor = 1.08;
}*/
if (slab_sizes_unparsed != NULL) {
if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) {
use_slab_sizes = true;
} else {
exit(EX_USAGE);
}
}
if (settings.hot_lru_pct + settings.warm_lru_pct > 80) {
fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n");
exit(EX_USAGE);
}
if (settings.temp_lru && !start_lru_maintainer) {
fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n");
exit(EX_USAGE);
}
if (hash_init(hash_type) != 0) {
fprintf(stderr, "Failed to initialize hash_algorithm!\n");
exit(EX_USAGE);
}
/*
* Use one workerthread to serve each UDP port if the user specified
* multiple ports
*/
if (settings.inter != NULL && strchr(settings.inter, ',')) {
settings.num_threads_per_udp = 1;
} else {
settings.num_threads_per_udp = settings.num_threads;
}
if (settings.sasl) {
if (!protocol_specified) {
settings.binding_protocol = binary_prot;
} else {
if (settings.binding_protocol != binary_prot) {
fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n");
exit(EX_USAGE);
}
}
}
if (tcp_specified && settings.port != 0 && !udp_specified) {
settings.udpport = settings.port;
} else if (udp_specified && settings.udpport != 0 && !tcp_specified) {
settings.port = settings.udpport;
}
if (maxcore != 0) {
struct rlimit rlim_new;
/*
* First try raising to infinity; if that fails, try bringing
* the soft limit to the hard.
*/
if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) {
/* failed. try raising just to the old max */
rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
(void)setrlimit(RLIMIT_CORE, &rlim_new);
}
}
/*
* getrlimit again to see what we ended up with. Only fail if
* the soft limit ends up 0, because then no core files will be
* created at all.
*/
if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) {
fprintf(stderr, "failed to ensure corefile creation\n");
exit(EX_OSERR);
}
}
/*
* If needed, increase rlimits to allow as many connections
* as needed.
*/
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to getrlimit number of files\n");
exit(EX_OSERR);
} else {
rlim.rlim_cur = settings.maxconns;
rlim.rlim_max = settings.maxconns;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n");
exit(EX_OSERR);
}
}
/* lose root privileges if we have them */
if (getuid() == 0 || geteuid() == 0) {
if (username == 0 || *username == '\0') {
fprintf(stderr, "can't run as root without the -u switch\n");
exit(EX_USAGE);
}
if ((pw = getpwnam(username)) == 0) {
fprintf(stderr, "can't find the user %s to switch to\n", username);
exit(EX_NOUSER);
}
if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
fprintf(stderr, "failed to assume identity of user %s\n", username);
exit(EX_OSERR);
}
}
/* Initialize Sasl if -S was specified */
if (settings.sasl) {
init_sasl();
}
/* daemonize if requested */
/* if we want to ensure our ability to dump core, don't chdir to / */
if (do_daemonize) {
if (sigignore(SIGHUP) == -1) {
perror("Failed to ignore SIGHUP");
}
if (daemonize(maxcore, settings.verbose) == -1) {
fprintf(stderr, "failed to daemon() in order to daemonize\n");
exit(EXIT_FAILURE);
}
}
/* lock paged memory if needed */
if (lock_memory) {
#ifdef HAVE_MLOCKALL
int res = mlockall(MCL_CURRENT | MCL_FUTURE);
if (res != 0) {
fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n",
strerror(errno));
}
#else
fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n");
#endif
}
/* initialize main thread libevent instance */
#if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101
/* If libevent version is larger/equal to 2.0.2-alpha, use newer version */
struct event_config *ev_config;
ev_config = event_config_new();
event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK);
main_base = event_base_new_with_config(ev_config);
event_config_free(ev_config);
#else
/* Otherwise, use older API */
main_base = event_init();
#endif
/* initialize other stuff */
logger_init();
stats_init();
assoc_init(settings.hashpower_init);
conn_init();
slabs_init(settings.maxbytes, settings.factor, preallocate,
use_slab_sizes ? slab_sizes : NULL);
#ifdef EXTSTORE
if (storage_file) {
enum extstore_res eres;
if (settings.ext_compact_under == 0) {
settings.ext_compact_under = ext_cf.page_count / 4;
/* Only rescues non-COLD items if below this threshold */
settings.ext_drop_under = ext_cf.page_count / 4;
}
crc32c_init();
/* Init free chunks to zero. */
for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) {
settings.ext_free_memchunks[x] = 0;
}
storage = extstore_init(storage_file, &ext_cf, &eres);
if (storage == NULL) {
fprintf(stderr, "Failed to initialize external storage: %s\n",
extstore_err(eres));
if (eres == EXTSTORE_INIT_OPEN_FAIL) {
perror("extstore open");
}
exit(EXIT_FAILURE);
}
ext_storage = storage;
/* page mover algorithm for extstore needs memory prefilled */
slabs_prefill_global();
}
#endif
/*
* ignore SIGPIPE signals; we can use errno == EPIPE if we
* need that information
*/
if (sigignore(SIGPIPE) == -1) {
perror("failed to ignore SIGPIPE; sigaction");
exit(EX_OSERR);
}
/* start up worker threads if MT mode */
#ifdef EXTSTORE
slabs_set_storage(storage);
memcached_thread_init(settings.num_threads, storage);
init_lru_crawler(storage);
#else
memcached_thread_init(settings.num_threads, NULL);
init_lru_crawler(NULL);
#endif
if (start_assoc_maint && start_assoc_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (start_lru_crawler && start_item_crawler_thread() != 0) {
fprintf(stderr, "Failed to enable LRU crawler thread\n");
exit(EXIT_FAILURE);
}
#ifdef EXTSTORE
if (storage && start_storage_compact_thread(storage) != 0) {
fprintf(stderr, "Failed to start storage compaction thread\n");
exit(EXIT_FAILURE);
}
if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) {
#else
if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) {
#endif
fprintf(stderr, "Failed to enable LRU maintainer thread\n");
return 1;
}
if (settings.slab_reassign &&
start_slab_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (settings.idle_timeout && start_conn_timeout_thread() == -1) {
exit(EXIT_FAILURE);
}
/* initialise clock event */
clock_handler(0, 0, 0);
/* create unix mode sockets after dropping privileges */
if (settings.socketpath != NULL) {
errno = 0;
if (server_socket_unix(settings.socketpath,settings.access)) {
vperror("failed to listen on UNIX socket: %s", settings.socketpath);
exit(EX_OSERR);
}
}
/* create the listening socket, bind it, and init */
if (settings.socketpath == NULL) {
const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME");
char *temp_portnumber_filename = NULL;
size_t len;
FILE *portnumber_file = NULL;
if (portnumber_filename != NULL) {
len = strlen(portnumber_filename)+4+1;
temp_portnumber_filename = malloc(len);
snprintf(temp_portnumber_filename,
len,
"%s.lck", portnumber_filename);
portnumber_file = fopen(temp_portnumber_filename, "a");
if (portnumber_file == NULL) {
fprintf(stderr, "Failed to open \"%s\": %s\n",
temp_portnumber_filename, strerror(errno));
}
}
errno = 0;
if (settings.port && server_sockets(settings.port, tcp_transport,
portnumber_file)) {
vperror("failed to listen on TCP port %d", settings.port);
exit(EX_OSERR);
}
/*
* initialization order: first create the listening sockets
* (may need root on low ports), then drop root if needed,
* then daemonize if needed, then init libevent (in some cases
* descriptors created by libevent wouldn't survive forking).
*/
/* create the UDP listening socket and bind it */
errno = 0;
if (settings.udpport && server_sockets(settings.udpport, udp_transport,
portnumber_file)) {
vperror("failed to listen on UDP port %d", settings.udpport);
exit(EX_OSERR);
}
if (portnumber_file) {
fclose(portnumber_file);
rename(temp_portnumber_filename, portnumber_filename);
}
if (temp_portnumber_filename)
free(temp_portnumber_filename);
}
/* Give the sockets a moment to open. I know this is dumb, but the error
* is only an advisory.
*/
usleep(1000);
if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) {
fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n");
exit(EXIT_FAILURE);
}
if (pid_file != NULL) {
save_pid(pid_file);
}
/* Drop privileges no longer needed */
if (settings.drop_privileges) {
drop_privileges();
}
/* Initialize the uriencode lookup table. */
uriencode_init();
/* enter the event loop */
if (event_base_loop(main_base, 0) != 0) {
retval = EXIT_FAILURE;
}
stop_assoc_maintenance_thread();
/* remove the PID file if we're a daemon */
if (do_daemonize)
remove_pidfile(pid_file);
/* Clean up strdup() call for bind() address */
if (settings.inter)
free(settings.inter);
if (l_socket)
free(l_socket);
if (u_socket)
free(u_socket);
/* cleanup base */
event_base_free(main_base);
return retval;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_19_0 |
crossvul-cpp_data_good_2253_2 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Monkey HTTP Server
* ==================
* Copyright 2001-2014 Monkey Software LLC <eduardo@monkey.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <monkey/mk_list.h>
#include <monkey/mk_vhost.h>
#include <monkey/mk_utils.h>
#include <monkey/mk_macros.h>
#include <monkey/mk_config.h>
#include <monkey/mk_string.h>
#include <monkey/mk_http_status.h>
#include <monkey/mk_memory.h>
#include <monkey/mk_request.h>
#include <monkey/mk_info.h>
#include <monkey/mk_file.h>
/* Initialize Virtual Host FDT mutex */
pthread_mutex_t mk_vhost_fdt_mutex = PTHREAD_MUTEX_INITIALIZER;
static __thread struct mk_list *mk_vhost_fdt_key;
/*
* This function is triggered upon thread creation (inside the thread
* context), here we configure per-thread data.
*/
int mk_vhost_fdt_worker_init()
{
int i;
int j;
struct host *h;
struct mk_list *list;
struct mk_list *head;
struct vhost_fdt_host *fdt;
struct vhost_fdt_hash_table *ht;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return -1;
}
/*
* We are under a thread context and the main configuration is
* already in place. Now for every existent virtual host we are
* going to create the File Descriptor Table (FDT) which aims to
* hold references of 'open and shared' file descriptors under
* the Virtual Host context.
*/
/*
* Under an initialization context we need to protect this critical
* section
*/
pthread_mutex_lock(&mk_vhost_fdt_mutex);
/*
* Initialize the thread FDT/Hosts list and create an entry per
* existent virtual host
*/
list = mk_mem_malloc_z(sizeof(struct mk_list));
mk_list_init(list);
mk_list_foreach(head, &config->hosts) {
h = mk_list_entry(head, struct host, _head);
fdt = mk_mem_malloc(sizeof(struct vhost_fdt_host));
fdt->host = h;
/* Initialize hash table */
for (i = 0; i < VHOST_FDT_HASHTABLE_SIZE; i++) {
ht = &fdt->hash_table[i];
ht->av_slots = VHOST_FDT_HASHTABLE_CHAINS;
/* for each chain under the hash table, set the fd */
for (j = 0; j < VHOST_FDT_HASHTABLE_CHAINS; j++) {
hc = &ht->chain[j];
hc->fd = -1;
hc->hash = 0;
hc->readers = 0;
}
}
mk_list_add(&fdt->_head, list);
}
mk_vhost_fdt_key = list;
pthread_mutex_unlock(&mk_vhost_fdt_mutex);
return 0;
}
int mk_vhost_fdt_worker_exit()
{
struct mk_list *head;
struct mk_list *tmp;
struct vhost_fdt_host *fdt;
if (config->fdt == MK_FALSE) {
return -1;
}
mk_list_foreach_safe(head, tmp, mk_vhost_fdt_key) {
fdt = mk_list_entry(head, struct vhost_fdt_host, _head);
mk_list_del(&fdt->_head);
mk_mem_free(fdt);
}
mk_mem_free(mk_vhost_fdt_key);
return 0;
}
static inline
struct vhost_fdt_hash_table *mk_vhost_fdt_table_lookup(int id, struct host *host)
{
struct mk_list *head;
struct mk_list *vhost_list;
struct vhost_fdt_host *fdt_host;
struct vhost_fdt_hash_table *ht = NULL;
vhost_list = mk_vhost_fdt_key;
mk_list_foreach(head, vhost_list) {
fdt_host = mk_list_entry(head, struct vhost_fdt_host, _head);
if (fdt_host->host == host) {
ht = &fdt_host->hash_table[id];
return ht;
}
}
return ht;
}
static inline
struct vhost_fdt_hash_chain
*mk_vhost_fdt_chain_lookup(unsigned int hash, struct vhost_fdt_hash_table *ht)
{
int i;
struct vhost_fdt_hash_chain *hc = NULL;
for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) {
hc = &ht->chain[i];
if (hc->hash == hash) {
return hc;
}
}
return NULL;
}
static inline int mk_vhost_fdt_open(int id, unsigned int hash,
struct session_request *sr)
{
int i;
int fd;
struct vhost_fdt_hash_table *ht = NULL;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return open(sr->real_path.data, sr->file_info.flags_read_only);
}
ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);
if (mk_unlikely(!ht)) {
return open(sr->real_path.data, sr->file_info.flags_read_only);
}
/* We got the hash table, now look around the chains array */
hc = mk_vhost_fdt_chain_lookup(hash, ht);
if (hc) {
/* Increment the readers and return the shared FD */
hc->readers++;
return hc->fd;
}
/*
* Get here means that no entry exists in the hash table for the
* requested file descriptor and hash, we must try to open the file
* and register the entry in the table.
*/
fd = open(sr->real_path.data, sr->file_info.flags_read_only);
if (fd == -1) {
return -1;
}
/* If chains are full, just return the new FD, bad luck... */
if (ht->av_slots <= 0) {
return fd;
}
/* Register the new entry in an available slot */
for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) {
hc = &ht->chain[i];
if (hc->fd == -1) {
hc->fd = fd;
hc->hash = hash;
hc->readers++;
ht->av_slots--;
sr->vhost_fdt_id = id;
sr->vhost_fdt_hash = hash;
sr->fd_is_fdt = MK_TRUE;
return fd;
}
}
return -1;
}
static inline int mk_vhost_fdt_close(struct session_request *sr)
{
int id;
unsigned int hash;
struct vhost_fdt_hash_table *ht = NULL;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return close(sr->fd_file);
}
id = sr->vhost_fdt_id;
hash = sr->vhost_fdt_hash;
ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);
if (mk_unlikely(!ht)) {
return close(sr->fd_file);
}
/* We got the hash table, now look around the chains array */
hc = mk_vhost_fdt_chain_lookup(hash, ht);
if (hc) {
/* Increment the readers and check if we should close */
hc->readers--;
if (hc->readers == 0) {
hc->fd = -1;
hc->hash = 0;
ht->av_slots++;
return close(sr->fd_file);
}
else {
return 0;
}
}
return close(sr->fd_file);
}
int mk_vhost_open(struct session_request *sr)
{
int id;
int off;
unsigned int hash;
off = sr->host_conf->documentroot.len;
hash = mk_utils_gen_hash(sr->real_path.data + off,
sr->real_path.len - off);
id = (hash % VHOST_FDT_HASHTABLE_SIZE);
return mk_vhost_fdt_open(id, hash, sr);
}
int mk_vhost_close(struct session_request *sr)
{
return mk_vhost_fdt_close(sr);
}
/*
* Open a virtual host configuration file and return a structure with
* definitions.
*/
struct host *mk_vhost_read(char *path)
{
unsigned long len = 0;
char *tmp;
char *host_low;
struct stat checkdir;
struct host *host;
struct host_alias *new_alias;
struct error_page *err_page;
struct mk_config *cnf;
struct mk_config_section *section_host;
struct mk_config_section *section_ep;
struct mk_config_entry *entry_ep;
struct mk_string_line *entry;
struct mk_list *head, *list;
/* Read configuration file */
cnf = mk_config_create(path);
if (!cnf) {
mk_err("Configuration error, aborting.");
exit(EXIT_FAILURE);
}
/* Read tag 'HOST' */
section_host = mk_config_section_get(cnf, "HOST");
if (!section_host) {
mk_err("Invalid config file %s", path);
return NULL;
}
/* Alloc configuration node */
host = mk_mem_malloc_z(sizeof(struct host));
host->config = cnf;
host->file = mk_string_dup(path);
/* Init list for custom error pages */
mk_list_init(&host->error_pages);
/* Init list for host name aliases */
mk_list_init(&host->server_names);
/* Lookup Servername */
list = mk_config_section_getval(section_host, "Servername", MK_CONFIG_VAL_LIST);
if (!list) {
mk_err("Hostname does not contain a Servername");
exit(EXIT_FAILURE);
}
mk_list_foreach(head, list) {
entry = mk_list_entry(head, struct mk_string_line, _head);
if (entry->len > MK_HOSTNAME_LEN - 1) {
continue;
}
/* Hostname to lowercase */
host_low = mk_string_tolower(entry->val);
/* Alloc node */
new_alias = mk_mem_malloc_z(sizeof(struct host_alias));
new_alias->name = mk_mem_malloc_z(entry->len + 1);
strncpy(new_alias->name, host_low, entry->len);
mk_mem_free(host_low);
new_alias->len = entry->len;
mk_list_add(&new_alias->_head, &host->server_names);
}
mk_string_split_free(list);
/* Lookup document root handled by a mk_ptr_t */
host->documentroot.data = mk_config_section_getval(section_host,
"DocumentRoot",
MK_CONFIG_VAL_STR);
if (!host->documentroot.data) {
mk_err("Missing DocumentRoot entry on %s file", path);
mk_config_free(cnf);
return NULL;
}
host->documentroot.len = strlen(host->documentroot.data);
/* Validate document root configured */
if (stat(host->documentroot.data, &checkdir) == -1) {
mk_err("Invalid path to DocumentRoot in %s", path);
}
else if (!(checkdir.st_mode & S_IFDIR)) {
mk_err("DocumentRoot variable in %s has an invalid directory path", path);
}
if (mk_list_is_empty(&host->server_names) == 0) {
mk_config_free(cnf);
return NULL;
}
/* Check Virtual Host redirection */
host->header_redirect.data = NULL;
host->header_redirect.len = 0;
tmp = mk_config_section_getval(section_host,
"Redirect",
MK_CONFIG_VAL_STR);
if (tmp) {
host->header_redirect.data = mk_string_dup(tmp);
host->header_redirect.len = strlen(tmp);
mk_mem_free(tmp);
}
/* Error Pages */
section_ep = mk_config_section_get(cnf, "ERROR_PAGES");
if (section_ep) {
mk_list_foreach(head, §ion_ep->entries) {
entry_ep = mk_list_entry(head, struct mk_config_entry, _head);
int ep_status = -1;
char *ep_file = NULL;
unsigned long len;
ep_status = atoi(entry_ep->key);
ep_file = entry_ep->val;
/* Validate input values */
if (ep_status < MK_CLIENT_BAD_REQUEST ||
ep_status > MK_SERVER_HTTP_VERSION_UNSUP ||
ep_file == NULL) {
continue;
}
/* Alloc error page node */
err_page = mk_mem_malloc_z(sizeof(struct error_page));
err_page->status = ep_status;
err_page->file = mk_string_dup(ep_file);
err_page->real_path = NULL;
mk_string_build(&err_page->real_path, &len, "%s/%s",
host->documentroot.data, err_page->file);
MK_TRACE("Map error page: status %i -> %s", err_page->status, err_page->file);
/* Link page to the error page list */
mk_list_add(&err_page->_head, &host->error_pages);
}
}
/* Server Signature */
if (config->hideversion == MK_FALSE) {
mk_string_build(&host->host_signature, &len,
"Monkey/%s", VERSION);
}
else {
mk_string_build(&host->host_signature, &len, "Monkey");
}
mk_string_build(&host->header_host_signature.data,
&host->header_host_signature.len,
"Server: %s", host->host_signature);
return host;
}
void mk_vhost_set_single(char *path)
{
struct host *host;
struct host_alias *halias;
struct stat checkdir;
unsigned long len = 0;
/* Set the default host */
host = mk_mem_malloc_z(sizeof(struct host));
mk_list_init(&host->error_pages);
mk_list_init(&host->server_names);
/* Prepare the unique alias */
halias = mk_mem_malloc_z(sizeof(struct host_alias));
halias->name = mk_string_dup("127.0.0.1");
mk_list_add(&halias->_head, &host->server_names);
host->documentroot.data = mk_string_dup(path);
host->documentroot.len = strlen(path);
host->header_redirect.data = NULL;
/* Validate document root configured */
if (stat(host->documentroot.data, &checkdir) == -1) {
mk_err("Invalid path to DocumentRoot in %s", path);
exit(EXIT_FAILURE);
}
else if (!(checkdir.st_mode & S_IFDIR)) {
mk_err("DocumentRoot variable in %s has an invalid directory path", path);
exit(EXIT_FAILURE);
}
/* Server Signature */
if (config->hideversion == MK_FALSE) {
mk_string_build(&host->host_signature, &len,
"Monkey/%s", VERSION);
}
else {
mk_string_build(&host->host_signature, &len, "Monkey");
}
mk_string_build(&host->header_host_signature.data,
&host->header_host_signature.len,
"Server: %s", host->host_signature);
mk_list_add(&host->_head, &config->hosts);
}
/* Given a configuration directory, start reading the virtual host entries */
void mk_vhost_init(char *path)
{
DIR *dir;
unsigned long len;
char *buf = 0;
char *sites = 0;
char *file;
struct host *p_host; /* debug */
struct dirent *ent;
struct file_info f_info;
int ret;
/* Read default virtual host file */
mk_string_build(&sites, &len, "%s/%s/", path, config->sites_conf_dir);
ret = mk_file_get_info(sites, &f_info);
if (ret == -1 || f_info.is_directory == MK_FALSE) {
mk_mem_free(sites);
sites = config->sites_conf_dir;
}
mk_string_build(&buf, &len, "%s/default", sites);
p_host = mk_vhost_read(buf);
if (!p_host) {
mk_err("Error parsing main configuration file 'default'");
}
mk_list_add(&p_host->_head, &config->hosts);
config->nhosts++;
mk_mem_free(buf);
buf = NULL;
/* Read all virtual hosts defined in sites/ */
if (!(dir = opendir(sites))) {
mk_mem_free(sites);
mk_err("Could not open %s", sites);
exit(EXIT_FAILURE);
}
/* Reading content */
while ((ent = readdir(dir)) != NULL) {
if (ent->d_name[0] == '.') {
continue;
}
if (strcmp((char *) ent->d_name, "..") == 0) {
continue;
}
if (ent->d_name[strlen(ent->d_name) - 1] == '~') {
continue;
}
if (strcasecmp((char *) ent->d_name, "default") == 0) {
continue;
}
file = NULL;
mk_string_build(&file, &len, "%s/%s", sites, ent->d_name);
p_host = mk_vhost_read(file);
mk_mem_free(file);
if (!p_host) {
continue;
}
else {
mk_list_add(&p_host->_head, &config->hosts);
config->nhosts++;
}
}
closedir(dir);
mk_mem_free(sites);
}
/* Lookup a registered virtual host based on the given 'host' input */
int mk_vhost_get(mk_ptr_t host, struct host **vhost, struct host_alias **alias)
{
struct host *entry_host;
struct host_alias *entry_alias;
struct mk_list *head_vhost, *head_alias;
mk_list_foreach(head_vhost, &config->hosts) {
entry_host = mk_list_entry(head_vhost, struct host, _head);
mk_list_foreach(head_alias, &entry_host->server_names) {
entry_alias = mk_list_entry(head_alias, struct host_alias, _head);
if (entry_alias->len == host.len &&
strncmp(entry_alias->name, host.data, host.len) == 0) {
*vhost = entry_host;
*alias = entry_alias;
return 0;
}
}
}
return -1;
}
void mk_vhost_free_all()
{
struct host *host;
struct host_alias *host_alias;
struct error_page *ep;
struct mk_list *head_host;
struct mk_list *head_alias;
struct mk_list *head_error;
struct mk_list *tmp1, *tmp2;
mk_list_foreach_safe(head_host, tmp1, &config->hosts) {
host = mk_list_entry(head_host, struct host, _head);
mk_list_del(&host->_head);
mk_mem_free(host->file);
/* Free aliases or servernames */
mk_list_foreach_safe(head_alias, tmp2, &host->server_names) {
host_alias = mk_list_entry(head_alias, struct host_alias, _head);
mk_list_del(&host_alias->_head);
mk_mem_free(host_alias->name);
mk_mem_free(host_alias);
}
/* Free error pages */
mk_list_foreach_safe(head_error, tmp2, &host->error_pages) {
ep = mk_list_entry(head_error, struct error_page, _head);
mk_list_del(&ep->_head);
mk_mem_free(ep->file);
mk_mem_free(ep->real_path);
mk_mem_free(ep);
}
mk_ptr_free(&host->documentroot);
mk_mem_free(host->host_signature);
mk_ptr_free(&host->header_host_signature);
/* Free source configuration */
if (host->config) mk_config_free(host->config);
mk_mem_free(host);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2253_2 |
crossvul-cpp_data_bad_3978_0 | /* $OpenBSD: scp.c,v 1.209 2020/05/01 06:31:42 djm Exp $ */
/*
* scp - secure remote copy. This is basically patched BSD rcp which
* uses ssh to do the data transfer (instead of using rcmd).
*
* NOTE: This version should NOT be suid root. (This uses ssh to
* do the transfer and ssh has the necessary privileges.)
*
* 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*/
/*
* Copyright (c) 1999 Theo de Raadt. All rights reserved.
* Copyright (c) 1999 Aaron Campbell. 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.
*/
/*
* Parts from:
*
* Copyright (c) 1983, 1990, 1992, 1993, 1995
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "includes.h"
#include <sys/types.h>
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_POLL_H
#include <poll.h>
#else
# ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
# endif
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <sys/wait.h>
#include <sys/uio.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_FNMATCH_H
#include <fnmatch.h>
#endif
#include <limits.h>
#include <locale.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
#include <vis.h>
#endif
#include "xmalloc.h"
#include "ssh.h"
#include "atomicio.h"
#include "pathnames.h"
#include "log.h"
#include "misc.h"
#include "progressmeter.h"
#include "utf8.h"
extern char *__progname;
#define COPY_BUFLEN 16384
int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
/* Struct for addargs */
arglist args;
arglist remote_remote_args;
/* Bandwidth limit */
long long limit_kbps = 0;
struct bwlimit bwlimit;
/* Name of current file being transferred. */
char *curfile;
/* This is set to non-zero to enable verbose mode. */
int verbose_mode = 0;
/* This is set to zero if the progressmeter is not desired. */
int showprogress = 1;
/*
* This is set to non-zero if remote-remote copy should be piped
* through this process.
*/
int throughlocal = 0;
/* Non-standard port to use for the ssh connection or -1. */
int sshport = -1;
/* This is the program to execute for the secured connection. ("ssh" or -S) */
char *ssh_program = _PATH_SSH_PROGRAM;
/* This is used to store the pid of ssh_program */
pid_t do_cmd_pid = -1;
static void
killchild(int signo)
{
if (do_cmd_pid > 1) {
kill(do_cmd_pid, signo ? signo : SIGTERM);
waitpid(do_cmd_pid, NULL, 0);
}
if (signo)
_exit(1);
exit(1);
}
static void
suspchild(int signo)
{
int status;
if (do_cmd_pid > 1) {
kill(do_cmd_pid, signo);
while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
errno == EINTR)
;
kill(getpid(), SIGSTOP);
}
}
static int
do_local_cmd(arglist *a)
{
u_int i;
int status;
pid_t pid;
if (a->num == 0)
fatal("do_local_cmd: no arguments");
if (verbose_mode) {
fprintf(stderr, "Executing:");
for (i = 0; i < a->num; i++)
fmprintf(stderr, " %s", a->list[i]);
fprintf(stderr, "\n");
}
if ((pid = fork()) == -1)
fatal("do_local_cmd: fork: %s", strerror(errno));
if (pid == 0) {
execvp(a->list[0], a->list);
perror(a->list[0]);
exit(1);
}
do_cmd_pid = pid;
ssh_signal(SIGTERM, killchild);
ssh_signal(SIGINT, killchild);
ssh_signal(SIGHUP, killchild);
while (waitpid(pid, &status, 0) == -1)
if (errno != EINTR)
fatal("do_local_cmd: waitpid: %s", strerror(errno));
do_cmd_pid = -1;
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
return (-1);
return (0);
}
/*
* This function executes the given command as the specified user on the
* given host. This returns < 0 if execution fails, and >= 0 otherwise. This
* assigns the input and output file descriptors on success.
*/
int
do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
{
int pin[2], pout[2], reserved[2];
if (verbose_mode)
fmprintf(stderr,
"Executing: program %s host %s, user %s, command %s\n",
ssh_program, host,
remuser ? remuser : "(unspecified)", cmd);
if (port == -1)
port = sshport;
/*
* Reserve two descriptors so that the real pipes won't get
* descriptors 0 and 1 because that will screw up dup2 below.
*/
if (pipe(reserved) == -1)
fatal("pipe: %s", strerror(errno));
/* Create a socket pair for communicating with ssh. */
if (pipe(pin) == -1)
fatal("pipe: %s", strerror(errno));
if (pipe(pout) == -1)
fatal("pipe: %s", strerror(errno));
/* Free the reserved descriptors. */
close(reserved[0]);
close(reserved[1]);
ssh_signal(SIGTSTP, suspchild);
ssh_signal(SIGTTIN, suspchild);
ssh_signal(SIGTTOU, suspchild);
/* Fork a child to execute the command on the remote host using ssh. */
do_cmd_pid = fork();
if (do_cmd_pid == 0) {
/* Child. */
close(pin[1]);
close(pout[0]);
dup2(pin[0], 0);
dup2(pout[1], 1);
close(pin[0]);
close(pout[1]);
replacearg(&args, 0, "%s", ssh_program);
if (port != -1) {
addargs(&args, "-p");
addargs(&args, "%d", port);
}
if (remuser != NULL) {
addargs(&args, "-l");
addargs(&args, "%s", remuser);
}
addargs(&args, "--");
addargs(&args, "%s", host);
addargs(&args, "%s", cmd);
execvp(ssh_program, args.list);
perror(ssh_program);
exit(1);
} else if (do_cmd_pid == -1) {
fatal("fork: %s", strerror(errno));
}
/* Parent. Close the other side, and return the local side. */
close(pin[0]);
*fdout = pin[1];
close(pout[1]);
*fdin = pout[0];
ssh_signal(SIGTERM, killchild);
ssh_signal(SIGINT, killchild);
ssh_signal(SIGHUP, killchild);
return 0;
}
/*
* This function executes a command similar to do_cmd(), but expects the
* input and output descriptors to be setup by a previous call to do_cmd().
* This way the input and output of two commands can be connected.
*/
int
do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
{
pid_t pid;
int status;
if (verbose_mode)
fmprintf(stderr,
"Executing: 2nd program %s host %s, user %s, command %s\n",
ssh_program, host,
remuser ? remuser : "(unspecified)", cmd);
if (port == -1)
port = sshport;
/* Fork a child to execute the command on the remote host using ssh. */
pid = fork();
if (pid == 0) {
dup2(fdin, 0);
dup2(fdout, 1);
replacearg(&args, 0, "%s", ssh_program);
if (port != -1) {
addargs(&args, "-p");
addargs(&args, "%d", port);
}
if (remuser != NULL) {
addargs(&args, "-l");
addargs(&args, "%s", remuser);
}
addargs(&args, "-oBatchMode=yes");
addargs(&args, "--");
addargs(&args, "%s", host);
addargs(&args, "%s", cmd);
execvp(ssh_program, args.list);
perror(ssh_program);
exit(1);
} else if (pid == -1) {
fatal("fork: %s", strerror(errno));
}
while (waitpid(pid, &status, 0) == -1)
if (errno != EINTR)
fatal("do_cmd2: waitpid: %s", strerror(errno));
return 0;
}
typedef struct {
size_t cnt;
char *buf;
} BUF;
BUF *allocbuf(BUF *, int, int);
void lostconn(int);
int okname(char *);
void run_err(const char *,...);
int note_err(const char *,...);
void verifydir(char *);
struct passwd *pwd;
uid_t userid;
int errs, remin, remout;
int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
#define CMDNEEDS 64
char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
int response(void);
void rsource(char *, struct stat *);
void sink(int, char *[], const char *);
void source(int, char *[]);
void tolocal(int, char *[]);
void toremote(int, char *[]);
void usage(void);
int
main(int argc, char **argv)
{
int ch, fflag, tflag, status, n;
char **newargv;
const char *errstr;
extern char *optarg;
extern int optind;
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
seed_rng();
msetlocale();
/* Copy argv, because we modify it */
newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
for (n = 0; n < argc; n++)
newargv[n] = xstrdup(argv[n]);
argv = newargv;
__progname = ssh_get_progname(argv[0]);
memset(&args, '\0', sizeof(args));
memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
args.list = remote_remote_args.list = NULL;
addargs(&args, "%s", ssh_program);
addargs(&args, "-x");
addargs(&args, "-oForwardAgent=no");
addargs(&args, "-oPermitLocalCommand=no");
addargs(&args, "-oClearAllForwardings=yes");
addargs(&args, "-oRemoteCommand=none");
addargs(&args, "-oRequestTTY=no");
fflag = Tflag = tflag = 0;
while ((ch = getopt(argc, argv,
"dfl:prtTvBCc:i:P:q12346S:o:F:J:")) != -1) {
switch (ch) {
/* User-visible flags. */
case '1':
fatal("SSH protocol v.1 is no longer supported");
break;
case '2':
/* Ignored */
break;
case '4':
case '6':
case 'C':
addargs(&args, "-%c", ch);
addargs(&remote_remote_args, "-%c", ch);
break;
case '3':
throughlocal = 1;
break;
case 'o':
case 'c':
case 'i':
case 'F':
case 'J':
addargs(&remote_remote_args, "-%c", ch);
addargs(&remote_remote_args, "%s", optarg);
addargs(&args, "-%c", ch);
addargs(&args, "%s", optarg);
break;
case 'P':
sshport = a2port(optarg);
if (sshport <= 0)
fatal("bad port \"%s\"\n", optarg);
break;
case 'B':
addargs(&remote_remote_args, "-oBatchmode=yes");
addargs(&args, "-oBatchmode=yes");
break;
case 'l':
limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
&errstr);
if (errstr != NULL)
usage();
limit_kbps *= 1024; /* kbps */
bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
break;
case 'p':
pflag = 1;
break;
case 'r':
iamrecursive = 1;
break;
case 'S':
ssh_program = xstrdup(optarg);
break;
case 'v':
addargs(&args, "-v");
addargs(&remote_remote_args, "-v");
verbose_mode = 1;
break;
case 'q':
addargs(&args, "-q");
addargs(&remote_remote_args, "-q");
showprogress = 0;
break;
/* Server options. */
case 'd':
targetshouldbedirectory = 1;
break;
case 'f': /* "from" */
iamremote = 1;
fflag = 1;
break;
case 't': /* "to" */
iamremote = 1;
tflag = 1;
#ifdef HAVE_CYGWIN
setmode(0, O_BINARY);
#endif
break;
case 'T':
Tflag = 1;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if ((pwd = getpwuid(userid = getuid())) == NULL)
fatal("unknown user %u", (u_int) userid);
if (!isatty(STDOUT_FILENO))
showprogress = 0;
if (pflag) {
/* Cannot pledge: -p allows setuid/setgid files... */
} else {
if (pledge("stdio rpath wpath cpath fattr tty proc exec",
NULL) == -1) {
perror("pledge");
exit(1);
}
}
remin = STDIN_FILENO;
remout = STDOUT_FILENO;
if (fflag) {
/* Follow "protocol", send data. */
(void) response();
source(argc, argv);
exit(errs != 0);
}
if (tflag) {
/* Receive data. */
sink(argc, argv, NULL);
exit(errs != 0);
}
if (argc < 2)
usage();
if (argc > 2)
targetshouldbedirectory = 1;
remin = remout = -1;
do_cmd_pid = -1;
/* Command to be executed on remote system using "ssh". */
(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
verbose_mode ? " -v" : "",
iamrecursive ? " -r" : "", pflag ? " -p" : "",
targetshouldbedirectory ? " -d" : "");
(void) ssh_signal(SIGPIPE, lostconn);
if (colon(argv[argc - 1])) /* Dest is remote host. */
toremote(argc, argv);
else {
if (targetshouldbedirectory)
verifydir(argv[argc - 1]);
tolocal(argc, argv); /* Dest is local host. */
}
/*
* Finally check the exit status of the ssh process, if one was forked
* and no error has occurred yet
*/
if (do_cmd_pid != -1 && errs == 0) {
if (remin != -1)
(void) close(remin);
if (remout != -1)
(void) close(remout);
if (waitpid(do_cmd_pid, &status, 0) == -1)
errs = 1;
else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
errs = 1;
}
}
exit(errs != 0);
}
/* Callback from atomicio6 to update progress meter and limit bandwidth */
static int
scpio(void *_cnt, size_t s)
{
off_t *cnt = (off_t *)_cnt;
*cnt += s;
refresh_progress_meter(0);
if (limit_kbps > 0)
bandwidth_limit(&bwlimit, s);
return 0;
}
static int
do_times(int fd, int verb, const struct stat *sb)
{
/* strlen(2^64) == 20; strlen(10^6) == 7 */
char buf[(20 + 7 + 2) * 2 + 2];
(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
(unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
(unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
if (verb) {
fprintf(stderr, "File mtime %lld atime %lld\n",
(long long)sb->st_mtime, (long long)sb->st_atime);
fprintf(stderr, "Sending file timestamps: %s", buf);
}
(void) atomicio(vwrite, fd, buf, strlen(buf));
return (response());
}
static int
parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
char **pathp)
{
int r;
r = parse_uri("scp", uri, userp, hostp, portp, pathp);
if (r == 0 && *pathp == NULL)
*pathp = xstrdup(".");
return r;
}
/* Appends a string to an array; returns 0 on success, -1 on alloc failure */
static int
append(char *cp, char ***ap, size_t *np)
{
char **tmp;
if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
return -1;
tmp[(*np)] = cp;
(*np)++;
*ap = tmp;
return 0;
}
/*
* Finds the start and end of the first brace pair in the pattern.
* returns 0 on success or -1 for invalid patterns.
*/
static int
find_brace(const char *pattern, int *startp, int *endp)
{
int i;
int in_bracket, brace_level;
*startp = *endp = -1;
in_bracket = brace_level = 0;
for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
switch (pattern[i]) {
case '\\':
/* skip next character */
if (pattern[i + 1] != '\0')
i++;
break;
case '[':
in_bracket = 1;
break;
case ']':
in_bracket = 0;
break;
case '{':
if (in_bracket)
break;
if (pattern[i + 1] == '}') {
/* Protect a single {}, for find(1), like csh */
i++; /* skip */
break;
}
if (*startp == -1)
*startp = i;
brace_level++;
break;
case '}':
if (in_bracket)
break;
if (*startp < 0) {
/* Unbalanced brace */
return -1;
}
if (--brace_level <= 0)
*endp = i;
break;
}
}
/* unbalanced brackets/braces */
if (*endp < 0 && (*startp >= 0 || in_bracket))
return -1;
return 0;
}
/*
* Assembles and records a successfully-expanded pattern, returns -1 on
* alloc failure.
*/
static int
emit_expansion(const char *pattern, int brace_start, int brace_end,
int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
{
char *cp;
int o = 0, tail_len = strlen(pattern + brace_end + 1);
if ((cp = malloc(brace_start + (sel_end - sel_start) +
tail_len + 1)) == NULL)
return -1;
/* Pattern before initial brace */
if (brace_start > 0) {
memcpy(cp, pattern, brace_start);
o = brace_start;
}
/* Current braced selection */
if (sel_end - sel_start > 0) {
memcpy(cp + o, pattern + sel_start,
sel_end - sel_start);
o += sel_end - sel_start;
}
/* Remainder of pattern after closing brace */
if (tail_len > 0) {
memcpy(cp + o, pattern + brace_end + 1, tail_len);
o += tail_len;
}
cp[o] = '\0';
if (append(cp, patternsp, npatternsp) != 0) {
free(cp);
return -1;
}
return 0;
}
/*
* Expand the first encountered brace in pattern, appending the expanded
* patterns it yielded to the *patternsp array.
*
* Returns 0 on success or -1 on allocation failure.
*
* Signals whether expansion was performed via *expanded and whether
* pattern was invalid via *invalid.
*/
static int
brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
int *expanded, int *invalid)
{
int i;
int in_bracket, brace_start, brace_end, brace_level;
int sel_start, sel_end;
*invalid = *expanded = 0;
if (find_brace(pattern, &brace_start, &brace_end) != 0) {
*invalid = 1;
return 0;
} else if (brace_start == -1)
return 0;
in_bracket = brace_level = 0;
for (i = sel_start = brace_start + 1; i < brace_end; i++) {
switch (pattern[i]) {
case '{':
if (in_bracket)
break;
brace_level++;
break;
case '}':
if (in_bracket)
break;
brace_level--;
break;
case '[':
in_bracket = 1;
break;
case ']':
in_bracket = 0;
break;
case '\\':
if (i < brace_end - 1)
i++; /* skip */
break;
}
if (pattern[i] == ',' || i == brace_end - 1) {
if (in_bracket || brace_level > 0)
continue;
/* End of a selection, emit an expanded pattern */
/* Adjust end index for last selection */
sel_end = (i == brace_end - 1) ? brace_end : i;
if (emit_expansion(pattern, brace_start, brace_end,
sel_start, sel_end, patternsp, npatternsp) != 0)
return -1;
/* move on to the next selection */
sel_start = i + 1;
continue;
}
}
if (in_bracket || brace_level > 0) {
*invalid = 1;
return 0;
}
/* success */
*expanded = 1;
return 0;
}
/* Expand braces from pattern. Returns 0 on success, -1 on failure */
static int
brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
{
char *cp, *cp2, **active = NULL, **done = NULL;
size_t i, nactive = 0, ndone = 0;
int ret = -1, invalid = 0, expanded = 0;
*patternsp = NULL;
*npatternsp = 0;
/* Start the worklist with the original pattern */
if ((cp = strdup(pattern)) == NULL)
return -1;
if (append(cp, &active, &nactive) != 0) {
free(cp);
return -1;
}
while (nactive > 0) {
cp = active[nactive - 1];
nactive--;
if (brace_expand_one(cp, &active, &nactive,
&expanded, &invalid) == -1) {
free(cp);
goto fail;
}
if (invalid)
fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
if (expanded) {
/*
* Current entry expanded to new entries on the
* active list; discard the progenitor pattern.
*/
free(cp);
continue;
}
/*
* Pattern did not expand; append the finename component to
* the completed list
*/
if ((cp2 = strrchr(cp, '/')) != NULL)
*cp2++ = '\0';
else
cp2 = cp;
if (append(xstrdup(cp2), &done, &ndone) != 0) {
free(cp);
goto fail;
}
free(cp);
}
/* success */
*patternsp = done;
*npatternsp = ndone;
done = NULL;
ndone = 0;
ret = 0;
fail:
for (i = 0; i < nactive; i++)
free(active[i]);
free(active);
for (i = 0; i < ndone; i++)
free(done[i]);
free(done);
return ret;
}
void
toremote(int argc, char **argv)
{
char *suser = NULL, *host = NULL, *src = NULL;
char *bp, *tuser, *thost, *targ;
int sport = -1, tport = -1;
arglist alist;
int i, r;
u_int j;
memset(&alist, '\0', sizeof(alist));
alist.list = NULL;
/* Parse target */
r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
++errs;
goto out;
}
if (r != 0) {
if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
&targ) == -1) {
fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
++errs;
goto out;
}
}
if (tuser != NULL && !okname(tuser)) {
++errs;
goto out;
}
/* Parse source files */
for (i = 0; i < argc - 1; i++) {
free(suser);
free(host);
free(src);
r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[i]);
++errs;
continue;
}
if (r != 0) {
parse_user_host_path(argv[i], &suser, &host, &src);
}
if (suser != NULL && !okname(suser)) {
++errs;
continue;
}
if (host && throughlocal) { /* extended remote to remote */
xasprintf(&bp, "%s -f %s%s", cmd,
*src == '-' ? "-- " : "", src);
if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
exit(1);
free(bp);
xasprintf(&bp, "%s -t %s%s", cmd,
*targ == '-' ? "-- " : "", targ);
if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
exit(1);
free(bp);
(void) close(remin);
(void) close(remout);
remin = remout = -1;
} else if (host) { /* standard remote to remote */
if (tport != -1 && tport != SSH_DEFAULT_PORT) {
/* This would require the remote support URIs */
fatal("target port not supported with two "
"remote hosts without the -3 option");
}
freeargs(&alist);
addargs(&alist, "%s", ssh_program);
addargs(&alist, "-x");
addargs(&alist, "-oClearAllForwardings=yes");
addargs(&alist, "-n");
for (j = 0; j < remote_remote_args.num; j++) {
addargs(&alist, "%s",
remote_remote_args.list[j]);
}
if (sport != -1) {
addargs(&alist, "-p");
addargs(&alist, "%d", sport);
}
if (suser) {
addargs(&alist, "-l");
addargs(&alist, "%s", suser);
}
addargs(&alist, "--");
addargs(&alist, "%s", host);
addargs(&alist, "%s", cmd);
addargs(&alist, "%s", src);
addargs(&alist, "%s%s%s:%s",
tuser ? tuser : "", tuser ? "@" : "",
thost, targ);
if (do_local_cmd(&alist) != 0)
errs = 1;
} else { /* local to remote */
if (remin == -1) {
xasprintf(&bp, "%s -t %s%s", cmd,
*targ == '-' ? "-- " : "", targ);
if (do_cmd(thost, tuser, tport, bp, &remin,
&remout) < 0)
exit(1);
if (response() < 0)
exit(1);
free(bp);
}
source(1, argv + i);
}
}
out:
free(tuser);
free(thost);
free(targ);
free(suser);
free(host);
free(src);
}
void
tolocal(int argc, char **argv)
{
char *bp, *host = NULL, *src = NULL, *suser = NULL;
arglist alist;
int i, r, sport = -1;
memset(&alist, '\0', sizeof(alist));
alist.list = NULL;
for (i = 0; i < argc - 1; i++) {
free(suser);
free(host);
free(src);
r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[i]);
++errs;
continue;
}
if (r != 0)
parse_user_host_path(argv[i], &suser, &host, &src);
if (suser != NULL && !okname(suser)) {
++errs;
continue;
}
if (!host) { /* Local to local. */
freeargs(&alist);
addargs(&alist, "%s", _PATH_CP);
if (iamrecursive)
addargs(&alist, "-r");
if (pflag)
addargs(&alist, "-p");
addargs(&alist, "--");
addargs(&alist, "%s", argv[i]);
addargs(&alist, "%s", argv[argc-1]);
if (do_local_cmd(&alist))
++errs;
continue;
}
/* Remote to local. */
xasprintf(&bp, "%s -f %s%s",
cmd, *src == '-' ? "-- " : "", src);
if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
free(bp);
++errs;
continue;
}
free(bp);
sink(1, argv + argc - 1, src);
(void) close(remin);
remin = remout = -1;
}
free(suser);
free(host);
free(src);
}
void
source(int argc, char **argv)
{
struct stat stb;
static BUF buffer;
BUF *bp;
off_t i, statbytes;
size_t amt, nr;
int fd = -1, haderr, indx;
char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
int len;
for (indx = 0; indx < argc; ++indx) {
name = argv[indx];
statbytes = 0;
len = strlen(name);
while (len > 1 && name[len-1] == '/')
name[--len] = '\0';
if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1)
goto syserr;
if (strchr(name, '\n') != NULL) {
strnvis(encname, name, sizeof(encname), VIS_NL);
name = encname;
}
if (fstat(fd, &stb) == -1) {
syserr: run_err("%s: %s", name, strerror(errno));
goto next;
}
if (stb.st_size < 0) {
run_err("%s: %s", name, "Negative file size");
goto next;
}
unset_nonblock(fd);
switch (stb.st_mode & S_IFMT) {
case S_IFREG:
break;
case S_IFDIR:
if (iamrecursive) {
rsource(name, &stb);
goto next;
}
/* FALLTHROUGH */
default:
run_err("%s: not a regular file", name);
goto next;
}
if ((last = strrchr(name, '/')) == NULL)
last = name;
else
++last;
curfile = last;
if (pflag) {
if (do_times(remout, verbose_mode, &stb) < 0)
goto next;
}
#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
snprintf(buf, sizeof buf, "C%04o %lld %s\n",
(u_int) (stb.st_mode & FILEMODEMASK),
(long long)stb.st_size, last);
if (verbose_mode)
fmprintf(stderr, "Sending file modes: %s", buf);
(void) atomicio(vwrite, remout, buf, strlen(buf));
if (response() < 0)
goto next;
if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
next: if (fd != -1) {
(void) close(fd);
fd = -1;
}
continue;
}
if (showprogress)
start_progress_meter(curfile, stb.st_size, &statbytes);
set_nonblock(remout);
for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
amt = bp->cnt;
if (i + (off_t)amt > stb.st_size)
amt = stb.st_size - i;
if (!haderr) {
if ((nr = atomicio(read, fd,
bp->buf, amt)) != amt) {
haderr = errno;
memset(bp->buf + nr, 0, amt - nr);
}
}
/* Keep writing after error to retain sync */
if (haderr) {
(void)atomicio(vwrite, remout, bp->buf, amt);
memset(bp->buf, 0, amt);
continue;
}
if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
&statbytes) != amt)
haderr = errno;
}
unset_nonblock(remout);
if (fd != -1) {
if (close(fd) == -1 && !haderr)
haderr = errno;
fd = -1;
}
if (!haderr)
(void) atomicio(vwrite, remout, "", 1);
else
run_err("%s: %s", name, strerror(haderr));
(void) response();
if (showprogress)
stop_progress_meter();
}
}
void
rsource(char *name, struct stat *statp)
{
DIR *dirp;
struct dirent *dp;
char *last, *vect[1], path[PATH_MAX];
if (!(dirp = opendir(name))) {
run_err("%s: %s", name, strerror(errno));
return;
}
last = strrchr(name, '/');
if (last == NULL)
last = name;
else
last++;
if (pflag) {
if (do_times(remout, verbose_mode, statp) < 0) {
closedir(dirp);
return;
}
}
(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
(u_int) (statp->st_mode & FILEMODEMASK), 0, last);
if (verbose_mode)
fmprintf(stderr, "Entering directory: %s", path);
(void) atomicio(vwrite, remout, path, strlen(path));
if (response() < 0) {
closedir(dirp);
return;
}
while ((dp = readdir(dirp)) != NULL) {
if (dp->d_ino == 0)
continue;
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
run_err("%s/%s: name too long", name, dp->d_name);
continue;
}
(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
vect[0] = path;
source(1, vect);
}
(void) closedir(dirp);
(void) atomicio(vwrite, remout, "E\n", 2);
(void) response();
}
#define TYPE_OVERFLOW(type, val) \
((sizeof(type) == 4 && (val) > INT32_MAX) || \
(sizeof(type) == 8 && (val) > INT64_MAX) || \
(sizeof(type) != 4 && sizeof(type) != 8))
void
sink(int argc, char **argv, const char *src)
{
static BUF buffer;
struct stat stb;
BUF *bp;
off_t i;
size_t j, count;
int amt, exists, first, ofd;
mode_t mode, omode, mask;
off_t size, statbytes;
unsigned long long ull;
int setimes, targisdir, wrerr;
char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
char **patterns = NULL;
size_t n, npatterns = 0;
struct timeval tv[2];
#define atime tv[0]
#define mtime tv[1]
#define SCREWUP(str) { why = str; goto screwup; }
if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
SCREWUP("Unexpected off_t/time_t size");
setimes = targisdir = 0;
mask = umask(0);
if (!pflag)
(void) umask(mask);
if (argc != 1) {
run_err("ambiguous target");
exit(1);
}
targ = *argv;
if (targetshouldbedirectory)
verifydir(targ);
(void) atomicio(vwrite, remout, "", 1);
if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
targisdir = 1;
if (src != NULL && !iamrecursive && !Tflag) {
/*
* Prepare to try to restrict incoming filenames to match
* the requested destination file glob.
*/
if (brace_expand(src, &patterns, &npatterns) != 0)
fatal("%s: could not expand pattern", __func__);
}
for (first = 1;; first = 0) {
cp = buf;
if (atomicio(read, remin, cp, 1) != 1)
goto done;
if (*cp++ == '\n')
SCREWUP("unexpected <newline>");
do {
if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
SCREWUP("lost connection");
*cp++ = ch;
} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
*cp = 0;
if (verbose_mode)
fmprintf(stderr, "Sink: %s", buf);
if (buf[0] == '\01' || buf[0] == '\02') {
if (iamremote == 0) {
(void) snmprintf(visbuf, sizeof(visbuf),
NULL, "%s", buf + 1);
(void) atomicio(vwrite, STDERR_FILENO,
visbuf, strlen(visbuf));
}
if (buf[0] == '\02')
exit(1);
++errs;
continue;
}
if (buf[0] == 'E') {
(void) atomicio(vwrite, remout, "", 1);
goto done;
}
if (ch == '\n')
*--cp = 0;
cp = buf;
if (*cp == 'T') {
setimes++;
cp++;
if (!isdigit((unsigned char)*cp))
SCREWUP("mtime.sec not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("mtime.sec not delimited");
if (TYPE_OVERFLOW(time_t, ull))
setimes = 0; /* out of range */
mtime.tv_sec = ull;
mtime.tv_usec = strtol(cp, &cp, 10);
if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
mtime.tv_usec > 999999)
SCREWUP("mtime.usec not delimited");
if (!isdigit((unsigned char)*cp))
SCREWUP("atime.sec not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("atime.sec not delimited");
if (TYPE_OVERFLOW(time_t, ull))
setimes = 0; /* out of range */
atime.tv_sec = ull;
atime.tv_usec = strtol(cp, &cp, 10);
if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
atime.tv_usec > 999999)
SCREWUP("atime.usec not delimited");
(void) atomicio(vwrite, remout, "", 1);
continue;
}
if (*cp != 'C' && *cp != 'D') {
/*
* Check for the case "rcp remote:foo\* local:bar".
* In this case, the line "No match." can be returned
* by the shell before the rcp command on the remote is
* executed so the ^Aerror_message convention isn't
* followed.
*/
if (first) {
run_err("%s", cp);
exit(1);
}
SCREWUP("expected control record");
}
mode = 0;
for (++cp; cp < buf + 5; cp++) {
if (*cp < '0' || *cp > '7')
SCREWUP("bad mode");
mode = (mode << 3) | (*cp - '0');
}
if (!pflag)
mode &= ~mask;
if (*cp++ != ' ')
SCREWUP("mode not delimited");
if (!isdigit((unsigned char)*cp))
SCREWUP("size not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("size not delimited");
if (TYPE_OVERFLOW(off_t, ull))
SCREWUP("size out of range");
size = (off_t)ull;
if (*cp == '\0' || strchr(cp, '/') != NULL ||
strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
run_err("error: unexpected filename: %s", cp);
exit(1);
}
if (npatterns > 0) {
for (n = 0; n < npatterns; n++) {
if (fnmatch(patterns[n], cp, 0) == 0)
break;
}
if (n >= npatterns)
SCREWUP("filename does not match request");
}
if (targisdir) {
static char *namebuf;
static size_t cursize;
size_t need;
need = strlen(targ) + strlen(cp) + 250;
if (need > cursize) {
free(namebuf);
namebuf = xmalloc(need);
cursize = need;
}
(void) snprintf(namebuf, need, "%s%s%s", targ,
strcmp(targ, "/") ? "/" : "", cp);
np = namebuf;
} else
np = targ;
curfile = cp;
exists = stat(np, &stb) == 0;
if (buf[0] == 'D') {
int mod_flag = pflag;
if (!iamrecursive)
SCREWUP("received directory without -r");
if (exists) {
if (!S_ISDIR(stb.st_mode)) {
errno = ENOTDIR;
goto bad;
}
if (pflag)
(void) chmod(np, mode);
} else {
/* Handle copying from a read-only
directory */
mod_flag = 1;
if (mkdir(np, mode | S_IRWXU) == -1)
goto bad;
}
vect[0] = xstrdup(np);
sink(1, vect, src);
if (setimes) {
setimes = 0;
if (utimes(vect[0], tv) == -1)
run_err("%s: set times: %s",
vect[0], strerror(errno));
}
if (mod_flag)
(void) chmod(vect[0], mode);
free(vect[0]);
continue;
}
omode = mode;
mode |= S_IWUSR;
if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
bad: run_err("%s: %s", np, strerror(errno));
continue;
}
(void) atomicio(vwrite, remout, "", 1);
if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
(void) close(ofd);
continue;
}
cp = bp->buf;
wrerr = 0;
/*
* NB. do not use run_err() unless immediately followed by
* exit() below as it may send a spurious reply that might
* desyncronise us from the peer. Use note_err() instead.
*/
statbytes = 0;
if (showprogress)
start_progress_meter(curfile, size, &statbytes);
set_nonblock(remin);
for (count = i = 0; i < size; i += bp->cnt) {
amt = bp->cnt;
if (i + amt > size)
amt = size - i;
count += amt;
do {
j = atomicio6(read, remin, cp, amt,
scpio, &statbytes);
if (j == 0) {
run_err("%s", j != EPIPE ?
strerror(errno) :
"dropped connection");
exit(1);
}
amt -= j;
cp += j;
} while (amt > 0);
if (count == bp->cnt) {
/* Keep reading so we stay sync'd up. */
if (!wrerr) {
if (atomicio(vwrite, ofd, bp->buf,
count) != count) {
note_err("%s: %s", np,
strerror(errno));
wrerr = 1;
}
}
count = 0;
cp = bp->buf;
}
}
unset_nonblock(remin);
if (count != 0 && !wrerr &&
atomicio(vwrite, ofd, bp->buf, count) != count) {
note_err("%s: %s", np, strerror(errno));
wrerr = 1;
}
if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
ftruncate(ofd, size) != 0)
note_err("%s: truncate: %s", np, strerror(errno));
if (pflag) {
if (exists || omode != mode)
#ifdef HAVE_FCHMOD
if (fchmod(ofd, omode)) {
#else /* HAVE_FCHMOD */
if (chmod(np, omode)) {
#endif /* HAVE_FCHMOD */
note_err("%s: set mode: %s",
np, strerror(errno));
}
} else {
if (!exists && omode != mode)
#ifdef HAVE_FCHMOD
if (fchmod(ofd, omode & ~mask)) {
#else /* HAVE_FCHMOD */
if (chmod(np, omode & ~mask)) {
#endif /* HAVE_FCHMOD */
note_err("%s: set mode: %s",
np, strerror(errno));
}
}
if (close(ofd) == -1)
note_err(np, "%s: close: %s", np, strerror(errno));
(void) response();
if (showprogress)
stop_progress_meter();
if (setimes && !wrerr) {
setimes = 0;
if (utimes(np, tv) == -1) {
note_err("%s: set times: %s",
np, strerror(errno));
}
}
/* If no error was noted then signal success for this file */
if (note_err(NULL) == 0)
(void) atomicio(vwrite, remout, "", 1);
}
done:
for (n = 0; n < npatterns; n++)
free(patterns[n]);
free(patterns);
return;
screwup:
for (n = 0; n < npatterns; n++)
free(patterns[n]);
free(patterns);
run_err("protocol error: %s", why);
exit(1);
}
int
response(void)
{
char ch, *cp, resp, rbuf[2048], visbuf[2048];
if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
lostconn(0);
cp = rbuf;
switch (resp) {
case 0: /* ok */
return (0);
default:
*cp++ = resp;
/* FALLTHROUGH */
case 1: /* error, followed by error msg */
case 2: /* fatal error, "" */
do {
if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
lostconn(0);
*cp++ = ch;
} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
if (!iamremote) {
cp[-1] = '\0';
(void) snmprintf(visbuf, sizeof(visbuf),
NULL, "%s\n", rbuf);
(void) atomicio(vwrite, STDERR_FILENO,
visbuf, strlen(visbuf));
}
++errs;
if (resp == 1)
return (-1);
exit(1);
}
/* NOTREACHED */
}
void
usage(void)
{
(void) fprintf(stderr,
"usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
" [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
" [-S program] source ... target\n");
exit(1);
}
void
run_err(const char *fmt,...)
{
static FILE *fp;
va_list ap;
++errs;
if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
(void) fprintf(fp, "%c", 0x01);
(void) fprintf(fp, "scp: ");
va_start(ap, fmt);
(void) vfprintf(fp, fmt, ap);
va_end(ap);
(void) fprintf(fp, "\n");
(void) fflush(fp);
}
if (!iamremote) {
va_start(ap, fmt);
vfmprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
}
/*
* Notes a sink error for sending at the end of a file transfer. Returns 0 if
* no error has been noted or -1 otherwise. Use note_err(NULL) to flush
* any active error at the end of the transfer.
*/
int
note_err(const char *fmt, ...)
{
static char *emsg;
va_list ap;
/* Replay any previously-noted error */
if (fmt == NULL) {
if (emsg == NULL)
return 0;
run_err("%s", emsg);
free(emsg);
emsg = NULL;
return -1;
}
errs++;
/* Prefer first-noted error */
if (emsg != NULL)
return -1;
va_start(ap, fmt);
vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
va_end(ap);
return -1;
}
void
verifydir(char *cp)
{
struct stat stb;
if (!stat(cp, &stb)) {
if (S_ISDIR(stb.st_mode))
return;
errno = ENOTDIR;
}
run_err("%s: %s", cp, strerror(errno));
killchild(0);
}
int
okname(char *cp0)
{
int c;
char *cp;
cp = cp0;
do {
c = (int)*cp;
if (c & 0200)
goto bad;
if (!isalpha(c) && !isdigit((unsigned char)c)) {
switch (c) {
case '\'':
case '"':
case '`':
case ' ':
case '#':
goto bad;
default:
break;
}
}
} while (*++cp);
return (1);
bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
return (0);
}
BUF *
allocbuf(BUF *bp, int fd, int blksize)
{
size_t size;
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
struct stat stb;
if (fstat(fd, &stb) == -1) {
run_err("fstat: %s", strerror(errno));
return (0);
}
size = ROUNDUP(stb.st_blksize, blksize);
if (size == 0)
size = blksize;
#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
size = blksize;
#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
if (bp->cnt >= size)
return (bp);
bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
bp->cnt = size;
return (bp);
}
void
lostconn(int signo)
{
if (!iamremote)
(void)write(STDERR_FILENO, "lost connection\n", 16);
if (signo)
_exit(1);
else
exit(1);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3978_0 |
crossvul-cpp_data_good_2401_0 | /*
* Copyright (c) Christos Zoulas 2003.
* 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 immediately at the beginning of the file, without modification,
* 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 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 AUTHOR 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 "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: readelf.c,v 1.114 2014/12/11 14:19:36 christos Exp $")
#endif
#ifdef BUILTIN_ELF
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "readelf.h"
#include "magic.h"
#ifdef ELFCORE
private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *);
#endif
private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *, int);
private int doshn(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *, int, int);
private size_t donote(struct magic_set *, void *, size_t, size_t, int,
int, size_t, int *);
#define ELF_ALIGN(a) ((((a) + align - 1) / align) * align)
#define isquote(c) (strchr("'\"`", (c)) != NULL)
private uint16_t getu16(int, uint16_t);
private uint32_t getu32(int, uint32_t);
private uint64_t getu64(int, uint64_t);
#define MAX_PHNUM 128
#define MAX_SHNUM 32768
#define SIZE_UNKNOWN ((off_t)-1)
private int
toomany(struct magic_set *ms, const char *name, uint16_t num)
{
if (file_printf(ms, ", too many %s header sections (%u)", name, num
) == -1)
return -1;
return 0;
}
private uint16_t
getu16(int swap, uint16_t value)
{
union {
uint16_t ui;
char c[2];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[1];
retval.c[1] = tmpval.c[0];
return retval.ui;
} else
return value;
}
private uint32_t
getu32(int swap, uint32_t value)
{
union {
uint32_t ui;
char c[4];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[3];
retval.c[1] = tmpval.c[2];
retval.c[2] = tmpval.c[1];
retval.c[3] = tmpval.c[0];
return retval.ui;
} else
return value;
}
private uint64_t
getu64(int swap, uint64_t value)
{
union {
uint64_t ui;
char c[8];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[7];
retval.c[1] = tmpval.c[6];
retval.c[2] = tmpval.c[5];
retval.c[3] = tmpval.c[4];
retval.c[4] = tmpval.c[3];
retval.c[5] = tmpval.c[2];
retval.c[6] = tmpval.c[1];
retval.c[7] = tmpval.c[0];
return retval.ui;
} else
return value;
}
#define elf_getu16(swap, value) getu16(swap, value)
#define elf_getu32(swap, value) getu32(swap, value)
#define elf_getu64(swap, value) getu64(swap, value)
#define xsh_addr (clazz == ELFCLASS32 \
? (void *)&sh32 \
: (void *)&sh64)
#define xsh_sizeof (clazz == ELFCLASS32 \
? sizeof(sh32) \
: sizeof(sh64))
#define xsh_size (size_t)(clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_size) \
: elf_getu64(swap, sh64.sh_size))
#define xsh_offset (off_t)(clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_offset) \
: elf_getu64(swap, sh64.sh_offset))
#define xsh_type (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_type) \
: elf_getu32(swap, sh64.sh_type))
#define xsh_name (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_name) \
: elf_getu32(swap, sh64.sh_name))
#define xph_addr (clazz == ELFCLASS32 \
? (void *) &ph32 \
: (void *) &ph64)
#define xph_sizeof (clazz == ELFCLASS32 \
? sizeof(ph32) \
: sizeof(ph64))
#define xph_type (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_type) \
: elf_getu32(swap, ph64.p_type))
#define xph_offset (off_t)(clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_offset) \
: elf_getu64(swap, ph64.p_offset))
#define xph_align (size_t)((clazz == ELFCLASS32 \
? (off_t) (ph32.p_align ? \
elf_getu32(swap, ph32.p_align) : 4) \
: (off_t) (ph64.p_align ? \
elf_getu64(swap, ph64.p_align) : 4)))
#define xph_filesz (size_t)((clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_filesz) \
: elf_getu64(swap, ph64.p_filesz)))
#define xnh_addr (clazz == ELFCLASS32 \
? (void *)&nh32 \
: (void *)&nh64)
#define xph_memsz (size_t)((clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_memsz) \
: elf_getu64(swap, ph64.p_memsz)))
#define xnh_sizeof (clazz == ELFCLASS32 \
? sizeof nh32 \
: sizeof nh64)
#define xnh_type (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_type) \
: elf_getu32(swap, nh64.n_type))
#define xnh_namesz (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_namesz) \
: elf_getu32(swap, nh64.n_namesz))
#define xnh_descsz (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_descsz) \
: elf_getu32(swap, nh64.n_descsz))
#define prpsoffsets(i) (clazz == ELFCLASS32 \
? prpsoffsets32[i] \
: prpsoffsets64[i])
#define xcap_addr (clazz == ELFCLASS32 \
? (void *)&cap32 \
: (void *)&cap64)
#define xcap_sizeof (clazz == ELFCLASS32 \
? sizeof cap32 \
: sizeof cap64)
#define xcap_tag (clazz == ELFCLASS32 \
? elf_getu32(swap, cap32.c_tag) \
: elf_getu64(swap, cap64.c_tag))
#define xcap_val (clazz == ELFCLASS32 \
? elf_getu32(swap, cap32.c_un.c_val) \
: elf_getu64(swap, cap64.c_un.c_val))
#ifdef ELFCORE
/*
* Try larger offsets first to avoid false matches
* from earlier data that happen to look like strings.
*/
static const size_t prpsoffsets32[] = {
#ifdef USE_NT_PSINFO
104, /* SunOS 5.x (command line) */
88, /* SunOS 5.x (short name) */
#endif /* USE_NT_PSINFO */
100, /* SunOS 5.x (command line) */
84, /* SunOS 5.x (short name) */
44, /* Linux (command line) */
28, /* Linux 2.0.36 (short name) */
8, /* FreeBSD */
};
static const size_t prpsoffsets64[] = {
#ifdef USE_NT_PSINFO
152, /* SunOS 5.x (command line) */
136, /* SunOS 5.x (short name) */
#endif /* USE_NT_PSINFO */
136, /* SunOS 5.x, 64-bit (command line) */
120, /* SunOS 5.x, 64-bit (short name) */
56, /* Linux (command line) */
40, /* Linux (tested on core from 2.4.x, short name) */
16, /* FreeBSD, 64-bit */
};
#define NOFFSETS32 (sizeof prpsoffsets32 / sizeof prpsoffsets32[0])
#define NOFFSETS64 (sizeof prpsoffsets64 / sizeof prpsoffsets64[0])
#define NOFFSETS (clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64)
/*
* Look through the program headers of an executable image, searching
* for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or
* "FreeBSD"; if one is found, try looking in various places in its
* contents for a 16-character string containing only printable
* characters - if found, that string should be the name of the program
* that dropped core. Note: right after that 16-character string is,
* at least in SunOS 5.x (and possibly other SVR4-flavored systems) and
* Linux, a longer string (80 characters, in 5.x, probably other
* SVR4-flavored systems, and Linux) containing the start of the
* command line for that program.
*
* SunOS 5.x core files contain two PT_NOTE sections, with the types
* NT_PRPSINFO (old) and NT_PSINFO (new). These structs contain the
* same info about the command name and command line, so it probably
* isn't worthwhile to look for NT_PSINFO, but the offsets are provided
* above (see USE_NT_PSINFO), in case we ever decide to do so. The
* NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent;
* the SunOS 5.x file command relies on this (and prefers the latter).
*
* The signal number probably appears in a section of type NT_PRSTATUS,
* but that's also rather OS-dependent, in ways that are harder to
* dissect with heuristics, so I'm not bothering with the signal number.
* (I suppose the signal number could be of interest in situations where
* you don't have the binary of the program that dropped core; if you
* *do* have that binary, the debugger will probably tell you what
* signal it was.)
*/
#define OS_STYLE_SVR4 0
#define OS_STYLE_FREEBSD 1
#define OS_STYLE_NETBSD 2
private const char os_style_names[][8] = {
"SVR4",
"FreeBSD",
"NetBSD",
};
#define FLAGS_DID_CORE 0x01
#define FLAGS_DID_NOTE 0x02
#define FLAGS_DID_BUILD_ID 0x04
#define FLAGS_DID_CORE_STYLE 0x08
#define FLAGS_IS_CORE 0x10
private int
dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags);
if (offset == 0)
break;
}
}
return 0;
}
#endif
static void
do_note_netbsd_version(struct magic_set *ms, int swap, void *v)
{
uint32_t desc;
(void)memcpy(&desc, v, sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, ", for NetBSD") == -1)
return;
/*
* The version number used to be stuck as 199905, and was thus
* basically content-free. Newer versions of NetBSD have fixed
* this and now use the encoding of __NetBSD_Version__:
*
* MMmmrrpp00
*
* M = major version
* m = minor version
* r = release ["",A-Z,Z[A-Z] but numeric]
* p = patchlevel
*/
if (desc > 100000000U) {
uint32_t ver_patch = (desc / 100) % 100;
uint32_t ver_rel = (desc / 10000) % 100;
uint32_t ver_min = (desc / 1000000) % 100;
uint32_t ver_maj = desc / 100000000;
if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1)
return;
if (ver_rel == 0 && ver_patch != 0) {
if (file_printf(ms, ".%u", ver_patch) == -1)
return;
} else if (ver_rel != 0) {
while (ver_rel > 26) {
if (file_printf(ms, "Z") == -1)
return;
ver_rel -= 26;
}
if (file_printf(ms, "%c", 'A' + ver_rel - 1)
== -1)
return;
}
}
}
static void
do_note_freebsd_version(struct magic_set *ms, int swap, void *v)
{
uint32_t desc;
(void)memcpy(&desc, v, sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, ", for FreeBSD") == -1)
return;
/*
* Contents is __FreeBSD_version, whose relation to OS
* versions is defined by a huge table in the Porter's
* Handbook. This is the general scheme:
*
* Releases:
* Mmp000 (before 4.10)
* Mmi0p0 (before 5.0)
* Mmm0p0
*
* Development branches:
* Mmpxxx (before 4.6)
* Mmp1xx (before 4.10)
* Mmi1xx (before 5.0)
* M000xx (pre-M.0)
* Mmm1xx
*
* M = major version
* m = minor version
* i = minor version increment (491000 -> 4.10)
* p = patchlevel
* x = revision
*
* The first release of FreeBSD to use ELF by default
* was version 3.0.
*/
if (desc == 460002) {
if (file_printf(ms, " 4.6.2") == -1)
return;
} else if (desc < 460100) {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 10000 % 10) == -1)
return;
if (desc / 1000 % 10 > 0)
if (file_printf(ms, ".%d", desc / 1000 % 10) == -1)
return;
if ((desc % 1000 > 0) || (desc % 100000 == 0))
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc < 500000) {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 10000 % 10 + desc / 1000 % 10) == -1)
return;
if (desc / 100 % 10 > 0) {
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc / 10 % 10 > 0) {
if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
return;
}
} else {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 1000 % 100) == -1)
return;
if ((desc / 100 % 10 > 0) ||
(desc % 100000 / 100 == 0)) {
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc / 10 % 10 > 0) {
if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
return;
}
}
}
private size_t
donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
char sbuf[512];
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
file_printable(sbuf, sizeof(sbuf),
(const char *)&nbuf[doff + 0x7c])) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
/* SunOS 5.x hardware capability descriptions */
typedef struct cap_desc {
uint64_t cd_mask;
const char *cd_name;
} cap_desc_t;
static const cap_desc_t cap_desc_sparc[] = {
{ AV_SPARC_MUL32, "MUL32" },
{ AV_SPARC_DIV32, "DIV32" },
{ AV_SPARC_FSMULD, "FSMULD" },
{ AV_SPARC_V8PLUS, "V8PLUS" },
{ AV_SPARC_POPC, "POPC" },
{ AV_SPARC_VIS, "VIS" },
{ AV_SPARC_VIS2, "VIS2" },
{ AV_SPARC_ASI_BLK_INIT, "ASI_BLK_INIT" },
{ AV_SPARC_FMAF, "FMAF" },
{ AV_SPARC_FJFMAU, "FJFMAU" },
{ AV_SPARC_IMA, "IMA" },
{ 0, NULL }
};
static const cap_desc_t cap_desc_386[] = {
{ AV_386_FPU, "FPU" },
{ AV_386_TSC, "TSC" },
{ AV_386_CX8, "CX8" },
{ AV_386_SEP, "SEP" },
{ AV_386_AMD_SYSC, "AMD_SYSC" },
{ AV_386_CMOV, "CMOV" },
{ AV_386_MMX, "MMX" },
{ AV_386_AMD_MMX, "AMD_MMX" },
{ AV_386_AMD_3DNow, "AMD_3DNow" },
{ AV_386_AMD_3DNowx, "AMD_3DNowx" },
{ AV_386_FXSR, "FXSR" },
{ AV_386_SSE, "SSE" },
{ AV_386_SSE2, "SSE2" },
{ AV_386_PAUSE, "PAUSE" },
{ AV_386_SSE3, "SSE3" },
{ AV_386_MON, "MON" },
{ AV_386_CX16, "CX16" },
{ AV_386_AHF, "AHF" },
{ AV_386_TSCP, "TSCP" },
{ AV_386_AMD_SSE4A, "AMD_SSE4A" },
{ AV_386_POPCNT, "POPCNT" },
{ AV_386_AMD_LZCNT, "AMD_LZCNT" },
{ AV_386_SSSE3, "SSSE3" },
{ AV_386_SSE4_1, "SSE4.1" },
{ AV_386_SSE4_2, "SSE4.2" },
{ 0, NULL }
};
private int
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,
size_t size, off_t fsize, int *flags, int mach, int strtab)
{
Elf32_Shdr sh32;
Elf64_Shdr sh64;
int stripped = 1;
size_t nbadcap = 0;
void *nbuf;
off_t noff, coff, name_off;
uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */
uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */
char name[50];
ssize_t namesize;
if (size != xsh_sizeof) {
if (file_printf(ms, ", corrupted section header size") == -1)
return -1;
return 0;
}
/* Read offset of name section to be able to read section names later */
if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) < (ssize_t)xsh_sizeof) {
file_badread(ms);
return -1;
}
name_off = xsh_offset;
for ( ; num; num--) {
/* Read the name of this section. */
if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) {
file_badread(ms);
return -1;
}
name[namesize] = '\0';
if (strcmp(name, ".debug_info") == 0)
stripped = 0;
if (pread(fd, xsh_addr, xsh_sizeof, off) < (ssize_t)xsh_sizeof) {
file_badread(ms);
return -1;
}
off += size;
/* Things we can determine before we seek */
switch (xsh_type) {
case SHT_SYMTAB:
#if 0
case SHT_DYNSYM:
#endif
stripped = 0;
break;
default:
if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) {
/* Perhaps warn here */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xsh_type) {
case SHT_NOTE:
if ((nbuf = malloc(xsh_size)) == NULL) {
file_error(ms, errno, "Cannot allocate memory"
" for note");
return -1;
}
if (pread(fd, nbuf, xsh_size, xsh_offset) < (ssize_t)xsh_size) {
file_badread(ms);
free(nbuf);
return -1;
}
noff = 0;
for (;;) {
if (noff >= (off_t)xsh_size)
break;
noff = donote(ms, nbuf, (size_t)noff,
xsh_size, clazz, swap, 4, flags);
if (noff == 0)
break;
}
free(nbuf);
break;
case SHT_SUNW_cap:
switch (mach) {
case EM_SPARC:
case EM_SPARCV9:
case EM_IA_64:
case EM_386:
case EM_AMD64:
break;
default:
goto skip;
}
if (nbadcap > 5)
break;
if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) {
file_badseek(ms);
return -1;
}
coff = 0;
for (;;) {
Elf32_Cap cap32;
Elf64_Cap cap64;
char cbuf[/*CONSTCOND*/
MAX(sizeof cap32, sizeof cap64)];
if ((coff += xcap_sizeof) > (off_t)xsh_size)
break;
if (read(fd, cbuf, (size_t)xcap_sizeof) !=
(ssize_t)xcap_sizeof) {
file_badread(ms);
return -1;
}
if (cbuf[0] == 'A') {
#ifdef notyet
char *p = cbuf + 1;
uint32_t len, tag;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (memcmp("gnu", p, 3) != 0) {
if (file_printf(ms,
", unknown capability %.3s", p)
== -1)
return -1;
break;
}
p += strlen(p) + 1;
tag = *p++;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (tag != 1) {
if (file_printf(ms, ", unknown gnu"
" capability tag %d", tag)
== -1)
return -1;
break;
}
// gnu attributes
#endif
break;
}
(void)memcpy(xcap_addr, cbuf, xcap_sizeof);
switch (xcap_tag) {
case CA_SUNW_NULL:
break;
case CA_SUNW_HW_1:
cap_hw1 |= xcap_val;
break;
case CA_SUNW_SF_1:
cap_sf1 |= xcap_val;
break;
default:
if (file_printf(ms,
", with unknown capability "
"0x%" INT64_T_FORMAT "x = 0x%"
INT64_T_FORMAT "x",
(unsigned long long)xcap_tag,
(unsigned long long)xcap_val) == -1)
return -1;
if (nbadcap++ > 2)
coff = xsh_size;
break;
}
}
/*FALLTHROUGH*/
skip:
default:
break;
}
}
if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1)
return -1;
if (cap_hw1) {
const cap_desc_t *cdp;
switch (mach) {
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
cdp = cap_desc_sparc;
break;
case EM_386:
case EM_IA_64:
case EM_AMD64:
cdp = cap_desc_386;
break;
default:
cdp = NULL;
break;
}
if (file_printf(ms, ", uses") == -1)
return -1;
if (cdp) {
while (cdp->cd_name) {
if (cap_hw1 & cdp->cd_mask) {
if (file_printf(ms,
" %s", cdp->cd_name) == -1)
return -1;
cap_hw1 &= ~cdp->cd_mask;
}
++cdp;
}
if (cap_hw1)
if (file_printf(ms,
" unknown hardware capability 0x%"
INT64_T_FORMAT "x",
(unsigned long long)cap_hw1) == -1)
return -1;
} else {
if (file_printf(ms,
" hardware capability 0x%" INT64_T_FORMAT "x",
(unsigned long long)cap_hw1) == -1)
return -1;
}
}
if (cap_sf1) {
if (cap_sf1 & SF1_SUNW_FPUSED) {
if (file_printf(ms,
(cap_sf1 & SF1_SUNW_FPKNWN)
? ", uses frame pointer"
: ", not known to use frame pointer") == -1)
return -1;
}
cap_sf1 &= ~SF1_SUNW_MASK;
if (cap_sf1)
if (file_printf(ms,
", with unknown software capability 0x%"
INT64_T_FORMAT "x",
(unsigned long long)cap_sf1) == -1)
return -1;
}
return 0;
}
/*
* Look through the program headers of an executable image, searching
* for a PT_INTERP section; if one is found, it's dynamically linked,
* otherwise it's statically linked.
*/
private int
dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
protected int
file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type, phnum, shnum;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
if (S_ISREG(st.st_mode) || st.st_size != 0)
fsize = st.st_size;
else
fsize = SIZE_UNKNOWN;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2401_0 |
crossvul-cpp_data_bad_3988_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "path.h"
#include "posix.h"
#include "repository.h"
#ifdef GIT_WIN32
#include "win32/posix.h"
#include "win32/w32_buffer.h"
#include "win32/w32_util.h"
#include "win32/version.h"
#include <aclapi.h>
#else
#include <dirent.h>
#endif
#include <stdio.h>
#include <ctype.h>
#define LOOKS_LIKE_DRIVE_PREFIX(S) (git__isalpha((S)[0]) && (S)[1] == ':')
#ifdef GIT_WIN32
static bool looks_like_network_computer_name(const char *path, int pos)
{
if (pos < 3)
return false;
if (path[0] != '/' || path[1] != '/')
return false;
while (pos-- > 2) {
if (path[pos] == '/')
return false;
}
return true;
}
#endif
/*
* Based on the Android implementation, BSD licensed.
* http://android.git.kernel.org/
*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git_path_basename_r(git_buf *buffer, const char *path)
{
const char *endp, *startp;
int len, result;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
startp = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
/* All slashes becomes "/" */
if (endp == path && *endp == '/') {
startp = "/";
len = 1;
goto Exit;
}
/* Find the start of the base */
startp = endp;
while (startp > path && *(startp - 1) != '/')
startp--;
/* Cast is safe because max path < max int */
len = (int)(endp - startp + 1);
Exit:
result = len;
if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
return -1;
return result;
}
/*
* Determine if the path is a Windows prefix and, if so, returns
* its actual lentgh. If it is not a prefix, returns -1.
*/
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
GIT_UNUSED(len);
#else
/*
* Mimic unix behavior where '/.git' returns '/': 'C:/.git' will return
* 'C:/' here
*/
if (len == 2 && LOOKS_LIKE_DRIVE_PREFIX(path))
return 2;
/*
* Similarly checks if we're dealing with a network computer name
* '//computername/.git' will return '//computername/'
*/
if (looks_like_network_computer_name(path, len))
return len;
#endif
return -1;
}
/*
* Based on the Android implementation, BSD licensed.
* Check http://android.git.kernel.org/
*/
int git_path_dirname_r(git_buf *buffer, const char *path)
{
const char *endp;
int is_prefix = 0, len;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
path = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Find the start of the dir */
while (endp > path && *endp != '/')
endp--;
/* Either the dir is "/" or there are no slashes */
if (endp == path) {
path = (*endp == '/') ? "/" : ".";
len = 1;
goto Exit;
}
do {
endp--;
} while (endp > path && *endp == '/');
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Cast is safe because max path < max int */
len = (int)(endp - path + 1);
Exit:
if (buffer) {
if (git_buf_set(buffer, path, len) < 0)
return -1;
if (is_prefix && git_buf_putc(buffer, '/') < 0)
return -1;
}
return len;
}
char *git_path_dirname(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *dirname;
git_path_dirname_r(&buf, path);
dirname = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return dirname;
}
char *git_path_basename(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *basename;
git_path_basename_r(&buf, path);
basename = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return basename;
}
size_t git_path_basename_offset(git_buf *buffer)
{
ssize_t slash;
if (!buffer || buffer->size <= 0)
return 0;
slash = git_buf_rfind_next(buffer, '/');
if (slash >= 0 && buffer->ptr[slash] == '/')
return (size_t)(slash + 1);
return 0;
}
const char *git_path_topdir(const char *path)
{
size_t len;
ssize_t i;
assert(path);
len = strlen(path);
if (!len || path[len - 1] != '/')
return NULL;
for (i = (ssize_t)len - 2; i >= 0; --i)
if (path[i] == '/')
break;
return &path[i + 1];
}
int git_path_root(const char *path)
{
int offset = 0;
/* Does the root of the path look like a windows drive ? */
if (LOOKS_LIKE_DRIVE_PREFIX(path))
offset += 2;
#ifdef GIT_WIN32
/* Are we dealing with a windows network path? */
else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
{
offset += 2;
/* Skip the computer name segment */
while (path[offset] && path[offset] != '/' && path[offset] != '\\')
offset++;
}
if (path[offset] == '\\')
return offset;
#endif
if (path[offset] == '/')
return offset;
return -1; /* Not a real error - signals that path is not rooted */
}
void git_path_trim_slashes(git_buf *path)
{
int ceiling = git_path_root(path->ptr) + 1;
assert(ceiling >= 0);
while (path->size > (size_t)ceiling) {
if (path->ptr[path->size-1] != '/')
break;
path->ptr[path->size-1] = '\0';
path->size--;
}
}
int git_path_join_unrooted(
git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
{
ssize_t root;
assert(path && path_out);
root = (ssize_t)git_path_root(path);
if (base != NULL && root < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
root = (ssize_t)strlen(base);
} else {
if (git_buf_sets(path_out, path) < 0)
return -1;
if (root < 0)
root = 0;
else if (base)
git_path_equal_or_prefixed(base, path, &root);
}
if (root_at)
*root_at = root;
return 0;
}
void git_path_squash_slashes(git_buf *path)
{
char *p, *q;
if (path->size == 0)
return;
for (p = path->ptr, q = path->ptr; *q; p++, q++) {
*p = *q;
while (*q == '/' && *(q+1) == '/') {
path->size--;
q++;
}
}
*p = '\0';
}
int git_path_prettify(git_buf *path_out, const char *path, const char *base)
{
char buf[GIT_PATH_MAX];
assert(path && path_out);
/* construct path if needed */
if (base != NULL && git_path_root(path) < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
path = path_out->ptr;
}
if (p_realpath(path, buf) == NULL) {
/* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
git_buf_clear(path_out);
return error;
}
return git_buf_sets(path_out, buf);
}
int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
{
int error = git_path_prettify(path_out, path, base);
return (error < 0) ? error : git_path_to_dir(path_out);
}
int git_path_to_dir(git_buf *path)
{
if (path->asize > 0 &&
git_buf_len(path) > 0 &&
path->ptr[git_buf_len(path) - 1] != '/')
git_buf_putc(path, '/');
return git_buf_oom(path) ? -1 : 0;
}
void git_path_string_to_dir(char* path, size_t size)
{
size_t end = strlen(path);
if (end && path[end - 1] != '/' && end < size) {
path[end] = '/';
path[end + 1] = '\0';
}
}
int git__percent_decode(git_buf *decoded_out, const char *input)
{
int len, hi, lo, i;
assert(decoded_out && input);
len = (int)strlen(input);
git_buf_clear(decoded_out);
for(i = 0; i < len; i++)
{
char c = input[i];
if (c != '%')
goto append;
if (i >= len - 2)
goto append;
hi = git__fromhex(input[i + 1]);
lo = git__fromhex(input[i + 2]);
if (hi < 0 || lo < 0)
goto append;
c = (char)(hi << 4 | lo);
i += 2;
append:
if (git_buf_putc(decoded_out, c) < 0)
return -1;
}
return 0;
}
static int error_invalid_local_file_uri(const char *uri)
{
git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
return -1;
}
static int local_file_url_prefixlen(const char *file_url)
{
int len = -1;
if (git__prefixcmp(file_url, "file://") == 0) {
if (file_url[7] == '/')
len = 8;
else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
len = 17;
}
return len;
}
bool git_path_is_local_file_url(const char *file_url)
{
return (local_file_url_prefixlen(file_url) > 0);
}
int git_path_fromurl(git_buf *local_path_out, const char *file_url)
{
int offset;
assert(local_path_out && file_url);
if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
file_url[offset] == '\0' || file_url[offset] == '/')
return error_invalid_local_file_uri(file_url);
#ifndef GIT_WIN32
offset--; /* A *nix absolute path starts with a forward slash */
#endif
git_buf_clear(local_path_out);
return git__percent_decode(local_path_out, file_url + offset);
}
int git_path_walk_up(
git_buf *path,
const char *ceiling,
int (*cb)(void *data, const char *),
void *data)
{
int error = 0;
git_buf iter;
ssize_t stop = 0, scan;
char oldc = '\0';
assert(path && cb);
if (ceiling != NULL) {
if (git__prefixcmp(path->ptr, ceiling) == 0)
stop = (ssize_t)strlen(ceiling);
else
stop = git_buf_len(path);
}
scan = git_buf_len(path);
/* empty path: yield only once */
if (!scan) {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
return error;
}
iter.ptr = path->ptr;
iter.size = git_buf_len(path);
iter.asize = path->asize;
while (scan >= stop) {
error = cb(data, iter.ptr);
iter.ptr[scan] = oldc;
if (error) {
git_error_set_after_callback(error);
break;
}
scan = git_buf_rfind_next(&iter, '/');
if (scan >= 0) {
scan++;
oldc = iter.ptr[scan];
iter.size = scan;
iter.ptr[scan] = '\0';
}
}
if (scan >= 0)
iter.ptr[scan] = oldc;
/* relative path: yield for the last component */
if (!error && stop == 0 && iter.ptr[0] != '/') {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
}
return error;
}
bool git_path_exists(const char *path)
{
assert(path);
return p_access(path, F_OK) == 0;
}
bool git_path_isdir(const char *path)
{
struct stat st;
if (p_stat(path, &st) < 0)
return false;
return S_ISDIR(st.st_mode) != 0;
}
bool git_path_isfile(const char *path)
{
struct stat st;
assert(path);
if (p_stat(path, &st) < 0)
return false;
return S_ISREG(st.st_mode) != 0;
}
bool git_path_islink(const char *path)
{
struct stat st;
assert(path);
if (p_lstat(path, &st) < 0)
return false;
return S_ISLNK(st.st_mode) != 0;
}
#ifdef GIT_WIN32
bool git_path_is_empty_dir(const char *path)
{
git_win32_path filter_w;
bool empty = false;
if (git_win32__findfirstfile_filter(filter_w, path)) {
WIN32_FIND_DATAW findData;
HANDLE hFind = FindFirstFileW(filter_w, &findData);
/* FindFirstFile will fail if there are no children to the given
* path, which can happen if the given path is a file (and obviously
* has no children) or if the given path is an empty mount point.
* (Most directories have at least directory entries '.' and '..',
* but ridiculously another volume mounted in another drive letter's
* path space do not, and thus have nothing to enumerate.) If
* FindFirstFile fails, check if this is a directory-like thing
* (a mount point).
*/
if (hFind == INVALID_HANDLE_VALUE)
return git_path_isdir(path);
/* If the find handle was created successfully, then it's a directory */
empty = true;
do {
/* Allow the enumeration to return . and .. and still be considered
* empty. In the special case of drive roots (i.e. C:\) where . and
* .. do not occur, we can still consider the path to be an empty
* directory if there's nothing there. */
if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
empty = false;
break;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
return empty;
}
#else
static int path_found_entry(void *payload, git_buf *path)
{
GIT_UNUSED(payload);
return !git_path_is_dot_or_dotdot(path->ptr);
}
bool git_path_is_empty_dir(const char *path)
{
int error;
git_buf dir = GIT_BUF_INIT;
if (!git_path_isdir(path))
return false;
if ((error = git_buf_sets(&dir, path)) != 0)
git_error_clear();
else
error = git_path_direach(&dir, 0, path_found_entry, NULL);
git_buf_dispose(&dir);
return !error;
}
#endif
int git_path_set_error(int errno_value, const char *path, const char *action)
{
switch (errno_value) {
case ENOENT:
case ENOTDIR:
git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
return GIT_ENOTFOUND;
case EINVAL:
case ENAMETOOLONG:
git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
return GIT_EINVALIDSPEC;
case EEXIST:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
return GIT_EEXISTS;
case EACCES:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
return GIT_ELOCKED;
default:
git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
return -1;
}
}
int git_path_lstat(const char *path, struct stat *st)
{
if (p_lstat(path, st) == 0)
return 0;
return git_path_set_error(errno, path, "stat");
}
static bool _check_dir_contents(
git_buf *dir,
const char *sub,
bool (*predicate)(const char *))
{
bool result;
size_t dir_size = git_buf_len(dir);
size_t sub_size = strlen(sub);
size_t alloc_size;
/* leave base valid even if we could not make space for subdir */
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
git_buf_try_grow(dir, alloc_size, false) < 0)
return false;
/* save excursion */
if (git_buf_joinpath(dir, dir->ptr, sub) < 0)
return false;
result = predicate(dir->ptr);
/* restore path */
git_buf_truncate(dir, dir_size);
return result;
}
bool git_path_contains(git_buf *dir, const char *item)
{
return _check_dir_contents(dir, item, &git_path_exists);
}
bool git_path_contains_dir(git_buf *base, const char *subdir)
{
return _check_dir_contents(base, subdir, &git_path_isdir);
}
bool git_path_contains_file(git_buf *base, const char *file)
{
return _check_dir_contents(base, file, &git_path_isfile);
}
int git_path_find_dir(git_buf *dir, const char *path, const char *base)
{
int error = git_path_join_unrooted(dir, path, base, NULL);
if (!error) {
char buf[GIT_PATH_MAX];
if (p_realpath(dir->ptr, buf) != NULL)
error = git_buf_sets(dir, buf);
}
/* call dirname if this is not a directory */
if (!error) /* && git_path_isdir(dir->ptr) == false) */
error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
if (!error)
error = git_path_to_dir(dir);
return error;
}
int git_path_resolve_relative(git_buf *path, size_t ceiling)
{
char *base, *to, *from, *next;
size_t len;
GIT_ERROR_CHECK_ALLOC_BUF(path);
if (ceiling > path->size)
ceiling = path->size;
/* recognize drive prefixes, etc. that should not be backed over */
if (ceiling == 0)
ceiling = git_path_root(path->ptr) + 1;
/* recognize URL prefixes that should not be backed over */
if (ceiling == 0) {
for (next = path->ptr; *next && git__isalpha(*next); ++next);
if (next[0] == ':' && next[1] == '/' && next[2] == '/')
ceiling = (next + 3) - path->ptr;
}
base = to = from = path->ptr + ceiling;
while (*from) {
for (next = from; *next && *next != '/'; ++next);
len = next - from;
if (len == 1 && from[0] == '.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == '.' && from[1] == '.') {
/* error out if trying to up one from a hard base */
if (to == base && ceiling != 0) {
git_error_set(GIT_ERROR_INVALID,
"cannot strip root component off url");
return -1;
}
/* no more path segments to strip,
* use '../' as a new base path */
if (to == base) {
if (*next == '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
/* this is now the base, can't back up from a
* relative prefix */
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == '/') to--;
while (to > base && to[-1] != '/') to--;
}
} else {
if (*next == '/' && *from != '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
}
from += len;
while (*from == '/') from++;
}
*to = '\0';
path->size = to - path->ptr;
return 0;
}
int git_path_apply_relative(git_buf *target, const char *relpath)
{
return git_buf_joinpath(target, git_buf_cstr(target), relpath) ||
git_path_resolve_relative(target, 0);
}
int git_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t))
{
unsigned char c1, c2;
size_t len = len1 < len2 ? len1 : len2;
int cmp;
cmp = compare(name1, name2, len);
if (cmp)
return cmp;
c1 = name1[len];
c2 = name2[len];
if (c1 == '\0' && isdir1)
c1 = '/';
if (c2 == '\0' && isdir2)
c2 = '/';
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
size_t git_path_common_dirlen(const char *one, const char *two)
{
const char *p, *q, *dirsep = NULL;
for (p = one, q = two; *p && *q; p++, q++) {
if (*p == '/' && *q == '/')
dirsep = p;
else if (*p != *q)
break;
}
return dirsep ? (dirsep - one) + 1 : 0;
}
int git_path_make_relative(git_buf *path, const char *parent)
{
const char *p, *q, *p_dirsep, *q_dirsep;
size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
if (*p == '/' && *q == '/') {
p_dirsep = p;
q_dirsep = q;
}
else if (*p != *q)
break;
}
/* need at least 1 common path segment */
if ((p_dirsep == path->ptr || q_dirsep == parent) &&
(*p_dirsep != '/' || *q_dirsep != '/')) {
git_error_set(GIT_ERROR_INVALID,
"%s is not a parent of %s", parent, path->ptr);
return GIT_ENOTFOUND;
}
if (*p == '/' && !*q)
p++;
else if (!*p && *q == '/')
q++;
else if (!*p && !*q)
return git_buf_clear(path), 0;
else {
p = p_dirsep + 1;
q = q_dirsep + 1;
}
plen -= (p - path->ptr);
if (!*q)
return git_buf_set(path, p, plen);
for (; (q = strchr(q, '/')) && *(q + 1); q++)
depth++;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
/* save the offset as we might realllocate the pointer */
offset = p - path->ptr;
if (git_buf_try_grow(path, alloclen, 1) < 0)
return -1;
p = path->ptr + offset;
memmove(path->ptr + (depth * 3), p, plen + 1);
for (i = 0; i < depth; i++)
memcpy(path->ptr + (i * 3), "../", 3);
path->size = newlen;
return 0;
}
bool git_path_has_non_ascii(const char *path, size_t pathlen)
{
const uint8_t *scan = (const uint8_t *)path, *end;
for (end = scan + pathlen; scan < end; ++scan)
if (*scan & 0x80)
return true;
return false;
}
#ifdef GIT_USE_ICONV
int git_path_iconv_init_precompose(git_path_iconv_t *ic)
{
git_buf_init(&ic->buf, 0);
ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
return 0;
}
void git_path_iconv_clear(git_path_iconv_t *ic)
{
if (ic) {
if (ic->map != (iconv_t)-1)
iconv_close(ic->map);
git_buf_dispose(&ic->buf);
}
}
int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
{
char *nfd = (char*)*in, *nfc;
size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
int retry = 1;
if (!ic || ic->map == (iconv_t)-1 ||
!git_path_has_non_ascii(*in, *inlen))
return 0;
git_buf_clear(&ic->buf);
while (1) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
if (git_buf_grow(&ic->buf, alloclen) < 0)
return -1;
nfc = ic->buf.ptr + ic->buf.size;
nfclen = ic->buf.asize - ic->buf.size;
rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
ic->buf.size = (nfc - ic->buf.ptr);
if (rv != (size_t)-1)
break;
/* if we cannot convert the data (probably because iconv thinks
* it is not valid UTF-8 source data), then use original data
*/
if (errno != E2BIG)
return 0;
/* make space for 2x the remaining data to be converted
* (with per retry overhead to avoid infinite loops)
*/
wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
if (retry++ > 4)
goto fail;
}
ic->buf.ptr[ic->buf.size] = '\0';
*in = ic->buf.ptr;
*inlen = ic->buf.size;
return 0;
fail:
git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
return -1;
}
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";
/* Check if the platform is decomposing unicode data for us. We will
* emulate core Git and prefer to use precomposed unicode data internally
* on these platforms, composing the decomposed unicode on the fly.
*
* This mainly happens on the Mac where HDFS stores filenames as
* decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
* return decomposed unicode from readdir() even when the actual
* filesystem is storing precomposed unicode.
*/
bool git_path_does_fs_decompose_unicode(const char *root)
{
git_buf path = GIT_BUF_INIT;
int fd;
bool found_decomposed = false;
char tmp[6];
/* Create a file using a precomposed path and then try to find it
* using the decomposed name. If the lookup fails, then we will mark
* that we should precompose unicode for this repository.
*/
if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
(fd = p_mkstemp(path.ptr)) < 0)
goto done;
p_close(fd);
/* record trailing digits generated by mkstemp */
memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));
/* try to look up as NFD path */
if (git_buf_joinpath(&path, root, nfd_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
found_decomposed = git_path_exists(path.ptr);
/* remove temporary file (using original precomposed path) */
if (git_buf_joinpath(&path, root, nfc_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
(void)p_unlink(path.ptr);
done:
git_buf_dispose(&path);
return found_decomposed;
}
#else
bool git_path_does_fs_decompose_unicode(const char *root)
{
GIT_UNUSED(root);
return false;
}
#endif
#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif
int git_path_direach(
git_buf *path,
uint32_t flags,
int (*fn)(void *, git_buf *),
void *arg)
{
int error = 0;
ssize_t wd_len;
DIR *dir;
struct dirent *de;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_UNUSED(flags);
if (git_path_to_dir(path) < 0)
return -1;
wd_len = git_buf_len(path);
if ((dir = opendir(path->ptr)) == NULL) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
if (errno == ENOENT)
return GIT_ENOTFOUND;
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&ic);
#endif
while ((de = readdir(dir)) != NULL) {
const char *de_path = de->d_name;
size_t de_len = strlen(de_path);
if (git_path_is_dot_or_dotdot(de_path))
continue;
#ifdef GIT_USE_ICONV
if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
break;
#endif
if ((error = git_buf_put(path, de_path, de_len)) < 0)
break;
git_error_clear();
error = fn(arg, path);
git_buf_truncate(path, wd_len); /* restore path */
/* Only set our own error if the callback did not set one already */
if (error != 0) {
if (!git_error_last())
git_error_set_after_callback(error);
break;
}
}
closedir(dir);
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&ic);
#endif
return error;
}
#if defined(GIT_WIN32) && !defined(__MINGW32__)
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
* and better.
*/
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
git_win32_path path_filter;
static int is_win7_or_later = -1;
if (is_win7_or_later < 0)
is_win7_or_later = git_has_win32_version(6, 1, 0);
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
diriter->handle = INVALID_HANDLE_VALUE;
if (git_buf_puts(&diriter->path_utf8, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path_utf8);
if (diriter->path_utf8.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
return -1;
}
diriter->handle = FindFirstFileExW(
path_filter,
is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
&diriter->current,
FindExSearchNameMatch,
NULL,
is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
if (diriter->handle == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
return -1;
}
diriter->parent_utf8_len = diriter->path_utf8.size;
diriter->flags = flags;
return 0;
}
static int diriter_update_paths(git_path_diriter *diriter)
{
size_t filename_len, path_len;
filename_len = wcslen(diriter->current.cFileName);
if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
return -1;
if (path_len > GIT_WIN_PATH_UTF16) {
git_error_set(GIT_ERROR_FILESYSTEM,
"invalid path '%.*ls\\%ls' (path too long)",
diriter->parent_len, diriter->path, diriter->current.cFileName);
return -1;
}
diriter->path[diriter->parent_len] = L'\\';
memcpy(&diriter->path[diriter->parent_len+1],
diriter->current.cFileName, filename_len * sizeof(wchar_t));
diriter->path[path_len-1] = L'\0';
git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
if (diriter->parent_utf8_len > 0 &&
diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
git_buf_putc(&diriter->path_utf8, '/');
git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
if (git_buf_oom(&diriter->path_utf8))
return -1;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
do {
/* Our first time through, we already have the data from
* FindFirstFileW. Use it, otherwise get the next file.
*/
if (!diriter->needs_next)
diriter->needs_next = 1;
else if (!FindNextFileW(diriter->handle, &diriter->current))
return GIT_ITEROVER;
} while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));
if (diriter_update_paths(diriter) < 0)
return -1;
return 0;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path_utf8.size > diriter->parent_utf8_len);
*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path_utf8.ptr;
*out_len = diriter->path_utf8.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_win32__file_attribute_to_stat(out,
(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
diriter->path);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
git_buf_dispose(&diriter->path_utf8);
if (diriter->handle != INVALID_HANDLE_VALUE) {
FindClose(diriter->handle);
diriter->handle = INVALID_HANDLE_VALUE;
}
}
#else
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
if (git_buf_puts(&diriter->path, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path);
if (diriter->path.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
git_buf_dispose(&diriter->path);
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&diriter->ic);
#endif
diriter->parent_len = diriter->path.size;
diriter->flags = flags;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
struct dirent *de;
const char *filename;
size_t filename_len;
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
int error = 0;
assert(diriter);
errno = 0;
do {
if ((de = readdir(diriter->dir)) == NULL) {
if (!errno)
return GIT_ITEROVER;
git_error_set(GIT_ERROR_OS,
"could not read directory '%s'", diriter->path.ptr);
return -1;
}
} while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));
filename = de->d_name;
filename_len = strlen(filename);
#ifdef GIT_USE_ICONV
if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
(error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
return error;
#endif
git_buf_truncate(&diriter->path, diriter->parent_len);
if (diriter->parent_len > 0 &&
diriter->path.ptr[diriter->parent_len-1] != '/')
git_buf_putc(&diriter->path, '/');
git_buf_put(&diriter->path, filename, filename_len);
if (git_buf_oom(&diriter->path))
return -1;
return error;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path.size > diriter->parent_len);
*out = &diriter->path.ptr[diriter->parent_len+1];
*out_len = diriter->path.size - diriter->parent_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path.ptr;
*out_len = diriter->path.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_path_lstat(diriter->path.ptr, out);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
if (diriter->dir) {
closedir(diriter->dir);
diriter->dir = NULL;
}
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&diriter->ic);
#endif
git_buf_dispose(&diriter->path);
}
#endif
int git_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags)
{
git_path_diriter iter = GIT_PATH_DIRITER_INIT;
const char *name;
size_t name_len;
char *dup;
int error;
assert(contents && path);
if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
return error;
while ((error = git_path_diriter_next(&iter)) == 0) {
if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
break;
assert(name_len > prefix_len);
dup = git__strndup(name + prefix_len, name_len - prefix_len);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(contents, dup)) < 0)
break;
}
if (error == GIT_ITEROVER)
error = 0;
git_path_diriter_free(&iter);
return error;
}
int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
{
if (git_path_is_local_file_url(url_or_path))
return git_path_fromurl(local_path_out, url_or_path);
else
return git_buf_sets(local_path_out, url_or_path);
}
/* Reject paths like AUX or COM1, or those versions that end in a dot or
* colon. ("AUX." or "AUX:")
*/
GIT_INLINE(bool) verify_dospath(
const char *component,
size_t len,
const char dospath[3],
bool trailing_num)
{
size_t last = trailing_num ? 4 : 3;
if (len < last || git__strncasecmp(component, dospath, 3) != 0)
return true;
if (trailing_num && (component[3] < '1' || component[3] > '9'))
return true;
return (len > last &&
component[last] != '.' &&
component[last] != ':');
}
static int32_t next_hfs_char(const char **in, size_t *len)
{
while (*len) {
int32_t codepoint;
int cp_len = git__utf8_iterate((const uint8_t *)(*in), (int)(*len), &codepoint);
if (cp_len < 0)
return -1;
(*in) += cp_len;
(*len) -= cp_len;
/* these code points are ignored completely */
switch (codepoint) {
case 0x200c: /* ZERO WIDTH NON-JOINER */
case 0x200d: /* ZERO WIDTH JOINER */
case 0x200e: /* LEFT-TO-RIGHT MARK */
case 0x200f: /* RIGHT-TO-LEFT MARK */
case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
case 0x202c: /* POP DIRECTIONAL FORMATTING */
case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
case 0x206e: /* NATIONAL DIGIT SHAPES */
case 0x206f: /* NOMINAL DIGIT SHAPES */
case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
continue;
}
/* fold into lowercase -- this will only fold characters in
* the ASCII range, which is perfectly fine, because the
* git folder name can only be composed of ascii characters
*/
return git__tolower(codepoint);
}
return 0; /* NULL byte -- end of string */
}
static bool verify_dotgit_hfs_generic(const char *path, size_t len, const char *needle, size_t needle_len)
{
size_t i;
char c;
if (next_hfs_char(&path, &len) != '.')
return true;
for (i = 0; i < needle_len; i++) {
c = next_hfs_char(&path, &len);
if (c != needle[i])
return true;
}
if (next_hfs_char(&path, &len) != '\0')
return true;
return false;
}
static bool verify_dotgit_hfs(const char *path, size_t len)
{
return verify_dotgit_hfs_generic(path, len, "git", CONST_STRLEN("git"));
}
GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
{
git_buf *reserved = git_repository__reserved_names_win32;
size_t reserved_len = git_repository__reserved_names_win32_len;
size_t start = 0, i;
if (repo)
git_repository__reserved_names(&reserved, &reserved_len, repo, true);
for (i = 0; i < reserved_len; i++) {
git_buf *r = &reserved[i];
if (len >= r->size &&
strncasecmp(path, r->ptr, r->size) == 0) {
start = r->size;
break;
}
}
if (!start)
return true;
/*
* Reject paths that start with Windows-style directory separators
* (".git\") or NTFS alternate streams (".git:") and could be used
* to write to the ".git" directory on Windows platforms.
*/
if (path[start] == '\\' || path[start] == ':')
return false;
/* Reject paths like '.git ' or '.git.' */
for (i = start; i < len; i++) {
if (path[i] != ' ' && path[i] != '.')
return true;
}
return false;
}
GIT_INLINE(bool) only_spaces_and_dots(const char *path)
{
const char *c = path;
for (;; c++) {
if (*c == '\0')
return true;
if (*c != ' ' && *c != '.')
return false;
}
return true;
}
GIT_INLINE(bool) verify_dotgit_ntfs_generic(const char *name, size_t len, const char *dotgit_name, size_t dotgit_len, const char *shortname_pfix)
{
int i, saw_tilde;
if (name[0] == '.' && len >= dotgit_len &&
!strncasecmp(name + 1, dotgit_name, dotgit_len)) {
return !only_spaces_and_dots(name + dotgit_len + 1);
}
/* Detect the basic NTFS shortname with the first six chars */
if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
name[7] >= '1' && name[7] <= '4')
return !only_spaces_and_dots(name + 8);
/* Catch fallback names */
for (i = 0, saw_tilde = 0; i < 8; i++) {
if (name[i] == '\0') {
return true;
} else if (saw_tilde) {
if (name[i] < '0' || name[i] > '9')
return true;
} else if (name[i] == '~') {
if (name[i+1] < '1' || name[i+1] > '9')
return true;
saw_tilde = 1;
} else if (i >= 6) {
return true;
} else if ((unsigned char)name[i] > 127) {
return true;
} else if (git__tolower(name[i]) != shortname_pfix[i]) {
return true;
}
}
return !only_spaces_and_dots(name + i);
}
GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
{
if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
return false;
if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
return false;
if (flags & GIT_PATH_REJECT_NT_CHARS) {
if (c < 32)
return false;
switch (c) {
case '<':
case '>':
case ':':
case '"':
case '|':
case '?':
case '*':
return false;
}
}
return true;
}
/*
* Return the length of the common prefix between str and prefix, comparing them
* case-insensitively (must be ASCII to match).
*/
GIT_INLINE(size_t) common_prefix_icase(const char *str, size_t len, const char *prefix)
{
size_t count = 0;
while (len >0 && tolower(*str) == tolower(*prefix)) {
count++;
str++;
prefix++;
len--;
}
return count;
}
/*
* We fundamentally don't like some paths when dealing with user-inputted
* strings (in checkout or ref names): we don't want dot or dot-dot
* anywhere, we want to avoid writing weird paths on Windows that can't
* be handled by tools that use the non-\\?\ APIs, we don't want slashes
* or double slashes at the end of paths that can make them ambiguous.
*
* For checkout, we don't want to recurse into ".git" either.
*/
static bool verify_component(
git_repository *repo,
const char *component,
size_t len,
uint16_t mode,
unsigned int flags)
{
if (len == 0)
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 1 && component[0] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 2 && component[0] == '.' && component[1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
return false;
if (flags & GIT_PATH_REJECT_DOS_PATHS) {
if (!verify_dospath(component, len, "CON", false) ||
!verify_dospath(component, len, "PRN", false) ||
!verify_dospath(component, len, "AUX", false) ||
!verify_dospath(component, len, "NUL", false) ||
!verify_dospath(component, len, "COM", true) ||
!verify_dospath(component, len, "LPT", true))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_HFS) {
if (!verify_dotgit_hfs(component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_HFS))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS) {
if (!verify_dotgit_ntfs(repo, component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_NTFS))
return false;
}
/* don't bother rerunning the `.git` test if we ran the HFS or NTFS
* specific tests, they would have already rejected `.git`.
*/
if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_LITERAL)) {
if (len >= 4 &&
component[0] == '.' &&
(component[1] == 'g' || component[1] == 'G') &&
(component[2] == 'i' || component[2] == 'I') &&
(component[3] == 't' || component[3] == 'T')) {
if (len == 4)
return false;
if (S_ISLNK(mode) && common_prefix_icase(component, len, ".gitmodules") == len)
return false;
}
}
return true;
}
GIT_INLINE(unsigned int) dotgit_flags(
git_repository *repo,
unsigned int flags)
{
int protectHFS = 0, protectNTFS = 0;
int error = 0;
flags |= GIT_PATH_REJECT_DOT_GIT_LITERAL;
#ifdef __APPLE__
protectHFS = 1;
#endif
#ifdef GIT_WIN32
protectNTFS = 1;
#endif
if (repo && !protectHFS)
error = git_repository__configmap_lookup(&protectHFS, repo, GIT_CONFIGMAP_PROTECTHFS);
if (!error && protectHFS)
flags |= GIT_PATH_REJECT_DOT_GIT_HFS;
if (repo && !protectNTFS)
error = git_repository__configmap_lookup(&protectNTFS, repo, GIT_CONFIGMAP_PROTECTNTFS);
if (!error && protectNTFS)
flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;
return flags;
}
bool git_path_isvalid(
git_repository *repo,
const char *path,
uint16_t mode,
unsigned int flags)
{
const char *start, *c;
/* Upgrade the ".git" checks based on platform */
if ((flags & GIT_PATH_REJECT_DOT_GIT))
flags = dotgit_flags(repo, flags);
for (start = c = path; *c; c++) {
if (!verify_char(*c, flags))
return false;
if (*c == '/') {
if (!verify_component(repo, start, (c - start), mode, flags))
return false;
start = c+1;
}
}
return verify_component(repo, start, (c - start), mode, flags);
}
int git_path_normalize_slashes(git_buf *out, const char *path)
{
int error;
char *p;
if ((error = git_buf_puts(out, path)) < 0)
return error;
for (p = out->ptr; *p; p++) {
if (*p == '\\')
*p = '/';
}
return 0;
}
static const struct {
const char *file;
const char *hash;
size_t filelen;
} gitfiles[] = {
{ "gitignore", "gi250a", CONST_STRLEN("gitignore") },
{ "gitmodules", "gi7eba", CONST_STRLEN("gitmodules") },
{ "gitattributes", "gi7d29", CONST_STRLEN("gitattributes") }
};
extern int git_path_is_gitfile(const char *path, size_t pathlen, git_path_gitfile gitfile, git_path_fs fs)
{
const char *file, *hash;
size_t filelen;
if (!(gitfile >= GIT_PATH_GITFILE_GITIGNORE && gitfile < ARRAY_SIZE(gitfiles))) {
git_error_set(GIT_ERROR_OS, "invalid gitfile for path validation");
return -1;
}
file = gitfiles[gitfile].file;
filelen = gitfiles[gitfile].filelen;
hash = gitfiles[gitfile].hash;
switch (fs) {
case GIT_PATH_FS_GENERIC:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash) ||
!verify_dotgit_hfs_generic(path, pathlen, file, filelen);
case GIT_PATH_FS_NTFS:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash);
case GIT_PATH_FS_HFS:
return !verify_dotgit_hfs_generic(path, pathlen, file, filelen);
default:
git_error_set(GIT_ERROR_OS, "invalid filesystem for path validation");
return -1;
}
}
bool git_path_supports_symlinks(const char *dir)
{
git_buf path = GIT_BUF_INIT;
bool supported = false;
struct stat st;
int fd;
if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
p_close(fd) < 0 ||
p_unlink(path.ptr) < 0 ||
p_symlink("testing", path.ptr) < 0 ||
p_lstat(path.ptr, &st) < 0)
goto done;
supported = (S_ISLNK(st.st_mode) != 0);
done:
if (path.size)
(void)p_unlink(path.ptr);
git_buf_dispose(&path);
return supported;
}
int git_path_validate_system_file_ownership(const char *path)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
return GIT_OK;
#else
git_win32_path buf;
PSID owner_sid;
PSECURITY_DESCRIPTOR descriptor = NULL;
HANDLE token;
TOKEN_USER *info = NULL;
DWORD err, len;
int ret;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
err = GetNamedSecurityInfoW(buf, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION,
&owner_sid, NULL, NULL, NULL, &descriptor);
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
ret = GIT_ENOTFOUND;
goto cleanup;
}
if (err != ERROR_SUCCESS) {
git_error_set(GIT_ERROR_OS, "failed to get security information");
ret = GIT_ERROR;
goto cleanup;
}
if (!IsValidSid(owner_sid)) {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is unknown");
ret = GIT_ERROR;
goto cleanup;
}
if (IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
IsWellKnownSid(owner_sid, WinLocalSystemSid)) {
ret = GIT_OK;
goto cleanup;
}
/* Obtain current user's SID */
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
info = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(info);
if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
git__free(info);
info = NULL;
}
}
/*
* If the file is owned by the same account that is running the current
* process, it's okay to read from that file.
*/
if (info && EqualSid(owner_sid, info->User.Sid))
ret = GIT_OK;
else {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is not valid");
ret = GIT_ERROR;
}
free(info);
cleanup:
if (descriptor)
LocalFree(descriptor);
return ret;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3988_0 |
crossvul-cpp_data_good_1752_1 | #include <ruby.h>
#include <fiddle.h>
#define SafeStringValueCStr(v) (rb_check_safe_obj(rb_string_value(&v)), StringValueCStr(v))
VALUE rb_cHandle;
struct dl_handle {
void *ptr;
int open;
int enable_close;
};
#ifdef _WIN32
# ifndef _WIN32_WCE
static void *
w32_coredll(void)
{
MEMORY_BASIC_INFORMATION m;
memset(&m, 0, sizeof(m));
if( !VirtualQuery(_errno, &m, sizeof(m)) ) return NULL;
return m.AllocationBase;
}
# endif
static int
w32_dlclose(void *ptr)
{
# ifndef _WIN32_WCE
if( ptr == w32_coredll() ) return 0;
# endif
if( FreeLibrary((HMODULE)ptr) ) return 0;
return errno = rb_w32_map_errno(GetLastError());
}
#define dlclose(ptr) w32_dlclose(ptr)
#endif
static void
fiddle_handle_free(void *ptr)
{
struct dl_handle *fiddle_handle = ptr;
if( fiddle_handle->ptr && fiddle_handle->open && fiddle_handle->enable_close ){
dlclose(fiddle_handle->ptr);
}
xfree(ptr);
}
static size_t
fiddle_handle_memsize(const void *ptr)
{
return ptr ? sizeof(struct dl_handle) : 0;
}
static const rb_data_type_t fiddle_handle_data_type = {
"fiddle/handle",
{0, fiddle_handle_free, fiddle_handle_memsize,},
};
/*
* call-seq: close
*
* Close this handle.
*
* Calling close more than once will raise a Fiddle::DLError exception.
*/
static VALUE
rb_fiddle_handle_close(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if(fiddle_handle->open) {
int ret = dlclose(fiddle_handle->ptr);
fiddle_handle->open = 0;
/* Check dlclose for successful return value */
if(ret) {
#if defined(HAVE_DLERROR)
rb_raise(rb_eFiddleError, "%s", dlerror());
#else
rb_raise(rb_eFiddleError, "could not close handle");
#endif
}
return INT2NUM(ret);
}
rb_raise(rb_eFiddleError, "dlclose() called too many times");
UNREACHABLE;
}
static VALUE
rb_fiddle_handle_s_allocate(VALUE klass)
{
VALUE obj;
struct dl_handle *fiddle_handle;
obj = TypedData_Make_Struct(rb_cHandle, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
fiddle_handle->ptr = 0;
fiddle_handle->open = 0;
fiddle_handle->enable_close = 0;
return obj;
}
static VALUE
predefined_fiddle_handle(void *handle)
{
VALUE obj = rb_fiddle_handle_s_allocate(rb_cHandle);
struct dl_handle *fiddle_handle = DATA_PTR(obj);
fiddle_handle->ptr = handle;
fiddle_handle->open = 1;
OBJ_FREEZE(obj);
return obj;
}
/*
* call-seq:
* new(library = nil, flags = Fiddle::RTLD_LAZY | Fiddle::RTLD_GLOBAL)
*
* Create a new handler that opens +library+ with +flags+.
*
* If no +library+ is specified or +nil+ is given, DEFAULT is used, which is
* the equivalent to RTLD_DEFAULT. See <code>man 3 dlopen</code> for more.
*
* lib = Fiddle::Handle.new
*
* The default is dependent on OS, and provide a handle for all libraries
* already loaded. For example, in most cases you can use this to access +libc+
* functions, or ruby functions like +rb_str_new+.
*/
static VALUE
rb_fiddle_handle_initialize(int argc, VALUE argv[], VALUE self)
{
void *ptr;
struct dl_handle *fiddle_handle;
VALUE lib, flag;
char *clib;
int cflag;
const char *err;
switch( rb_scan_args(argc, argv, "02", &lib, &flag) ){
case 0:
clib = NULL;
cflag = RTLD_LAZY | RTLD_GLOBAL;
break;
case 1:
clib = NIL_P(lib) ? NULL : SafeStringValueCStr(lib);
cflag = RTLD_LAZY | RTLD_GLOBAL;
break;
case 2:
clib = NIL_P(lib) ? NULL : SafeStringValueCStr(lib);
cflag = NUM2INT(flag);
break;
default:
rb_bug("rb_fiddle_handle_new");
}
rb_secure(2);
#if defined(_WIN32)
if( !clib ){
HANDLE rb_libruby_handle(void);
ptr = rb_libruby_handle();
}
else if( STRCASECMP(clib, "libc") == 0
# ifdef RUBY_COREDLL
|| STRCASECMP(clib, RUBY_COREDLL) == 0
|| STRCASECMP(clib, RUBY_COREDLL".dll") == 0
# endif
){
# ifdef _WIN32_WCE
ptr = dlopen("coredll.dll", cflag);
# else
ptr = w32_coredll();
# endif
}
else
#endif
ptr = dlopen(clib, cflag);
#if defined(HAVE_DLERROR)
if( !ptr && (err = dlerror()) ){
rb_raise(rb_eFiddleError, "%s", err);
}
#else
if( !ptr ){
err = dlerror();
rb_raise(rb_eFiddleError, "%s", err);
}
#endif
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if( fiddle_handle->ptr && fiddle_handle->open && fiddle_handle->enable_close ){
dlclose(fiddle_handle->ptr);
}
fiddle_handle->ptr = ptr;
fiddle_handle->open = 1;
fiddle_handle->enable_close = 0;
if( rb_block_given_p() ){
rb_ensure(rb_yield, self, rb_fiddle_handle_close, self);
}
return Qnil;
}
/*
* call-seq: enable_close
*
* Enable a call to dlclose() when this handle is garbage collected.
*/
static VALUE
rb_fiddle_handle_enable_close(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
fiddle_handle->enable_close = 1;
return Qnil;
}
/*
* call-seq: disable_close
*
* Disable a call to dlclose() when this handle is garbage collected.
*/
static VALUE
rb_fiddle_handle_disable_close(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
fiddle_handle->enable_close = 0;
return Qnil;
}
/*
* call-seq: close_enabled?
*
* Returns +true+ if dlclose() will be called when this handle is garbage collected.
*
* See man(3) dlclose() for more info.
*/
static VALUE
rb_fiddle_handle_close_enabled_p(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if(fiddle_handle->enable_close) return Qtrue;
return Qfalse;
}
/*
* call-seq: to_i
*
* Returns the memory address for this handle.
*/
static VALUE
rb_fiddle_handle_to_i(VALUE self)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
return PTR2NUM(fiddle_handle);
}
static VALUE fiddle_handle_sym(void *handle, VALUE symbol);
/*
* Document-method: sym
*
* call-seq: sym(name)
*
* Get the address as an Integer for the function named +name+.
*/
static VALUE
rb_fiddle_handle_sym(VALUE self, VALUE sym)
{
struct dl_handle *fiddle_handle;
TypedData_Get_Struct(self, struct dl_handle, &fiddle_handle_data_type, fiddle_handle);
if( ! fiddle_handle->open ){
rb_raise(rb_eFiddleError, "closed handle");
}
return fiddle_handle_sym(fiddle_handle->ptr, sym);
}
#ifndef RTLD_NEXT
#define RTLD_NEXT NULL
#endif
#ifndef RTLD_DEFAULT
#define RTLD_DEFAULT NULL
#endif
/*
* Document-method: sym
*
* call-seq: sym(name)
*
* Get the address as an Integer for the function named +name+. The function
* is searched via dlsym on RTLD_NEXT.
*
* See man(3) dlsym() for more info.
*/
static VALUE
rb_fiddle_handle_s_sym(VALUE self, VALUE sym)
{
return fiddle_handle_sym(RTLD_NEXT, sym);
}
static VALUE
fiddle_handle_sym(void *handle, VALUE symbol)
{
#if defined(HAVE_DLERROR)
const char *err;
# define CHECK_DLERROR if( err = dlerror() ){ func = 0; }
#else
# define CHECK_DLERROR
#endif
void (*func)();
const char *name = SafeStringValueCStr(symbol);
rb_secure(2);
#ifdef HAVE_DLERROR
dlerror();
#endif
func = (void (*)())(VALUE)dlsym(handle, name);
CHECK_DLERROR;
#if defined(FUNC_STDCALL)
if( !func ){
int i;
int len = (int)strlen(name);
char *name_n;
#if defined(__CYGWIN__) || defined(_WIN32) || defined(__MINGW32__)
{
char *name_a = (char*)xmalloc(len+2);
strcpy(name_a, name);
name_n = name_a;
name_a[len] = 'A';
name_a[len+1] = '\0';
func = dlsym(handle, name_a);
CHECK_DLERROR;
if( func ) goto found;
name_n = xrealloc(name_a, len+6);
}
#else
name_n = (char*)xmalloc(len+6);
#endif
memcpy(name_n, name, len);
name_n[len++] = '@';
for( i = 0; i < 256; i += 4 ){
sprintf(name_n + len, "%d", i);
func = dlsym(handle, name_n);
CHECK_DLERROR;
if( func ) break;
}
if( func ) goto found;
name_n[len-1] = 'A';
name_n[len++] = '@';
for( i = 0; i < 256; i += 4 ){
sprintf(name_n + len, "%d", i);
func = dlsym(handle, name_n);
CHECK_DLERROR;
if( func ) break;
}
found:
xfree(name_n);
}
#endif
if( !func ){
rb_raise(rb_eFiddleError, "unknown symbol \"%"PRIsVALUE"\"", symbol);
}
return PTR2NUM(func);
}
void
Init_fiddle_handle(void)
{
/*
* Document-class: Fiddle::Handle
*
* The Fiddle::Handle is the manner to access the dynamic library
*
* == Example
*
* === Setup
*
* libc_so = "/lib64/libc.so.6"
* => "/lib64/libc.so.6"
* @handle = Fiddle::Handle.new(libc_so)
* => #<Fiddle::Handle:0x00000000d69ef8>
*
* === Setup, with flags
*
* libc_so = "/lib64/libc.so.6"
* => "/lib64/libc.so.6"
* @handle = Fiddle::Handle.new(libc_so, Fiddle::RTLD_LAZY | Fiddle::RTLD_GLOBAL)
* => #<Fiddle::Handle:0x00000000d69ef8>
*
* See RTLD_LAZY and RTLD_GLOBAL
*
* === Addresses to symbols
*
* strcpy_addr = @handle['strcpy']
* => 140062278451968
*
* or
*
* strcpy_addr = @handle.sym('strcpy')
* => 140062278451968
*
*/
rb_cHandle = rb_define_class_under(mFiddle, "Handle", rb_cObject);
rb_define_alloc_func(rb_cHandle, rb_fiddle_handle_s_allocate);
rb_define_singleton_method(rb_cHandle, "sym", rb_fiddle_handle_s_sym, 1);
rb_define_singleton_method(rb_cHandle, "[]", rb_fiddle_handle_s_sym, 1);
/* Document-const: NEXT
*
* A predefined pseudo-handle of RTLD_NEXT
*
* Which will find the next occurrence of a function in the search order
* after the current library.
*/
rb_define_const(rb_cHandle, "NEXT", predefined_fiddle_handle(RTLD_NEXT));
/* Document-const: DEFAULT
*
* A predefined pseudo-handle of RTLD_DEFAULT
*
* Which will find the first occurrence of the desired symbol using the
* default library search order
*/
rb_define_const(rb_cHandle, "DEFAULT", predefined_fiddle_handle(RTLD_DEFAULT));
/* Document-const: RTLD_GLOBAL
*
* rtld Fiddle::Handle flag.
*
* The symbols defined by this library will be made available for symbol
* resolution of subsequently loaded libraries.
*/
rb_define_const(rb_cHandle, "RTLD_GLOBAL", INT2NUM(RTLD_GLOBAL));
/* Document-const: RTLD_LAZY
*
* rtld Fiddle::Handle flag.
*
* Perform lazy binding. Only resolve symbols as the code that references
* them is executed. If the symbol is never referenced, then it is never
* resolved. (Lazy binding is only performed for function references;
* references to variables are always immediately bound when the library
* is loaded.)
*/
rb_define_const(rb_cHandle, "RTLD_LAZY", INT2NUM(RTLD_LAZY));
/* Document-const: RTLD_NOW
*
* rtld Fiddle::Handle flag.
*
* If this value is specified or the environment variable LD_BIND_NOW is
* set to a nonempty string, all undefined symbols in the library are
* resolved before Fiddle.dlopen returns. If this cannot be done an error
* is returned.
*/
rb_define_const(rb_cHandle, "RTLD_NOW", INT2NUM(RTLD_NOW));
rb_define_method(rb_cHandle, "initialize", rb_fiddle_handle_initialize, -1);
rb_define_method(rb_cHandle, "to_i", rb_fiddle_handle_to_i, 0);
rb_define_method(rb_cHandle, "close", rb_fiddle_handle_close, 0);
rb_define_method(rb_cHandle, "sym", rb_fiddle_handle_sym, 1);
rb_define_method(rb_cHandle, "[]", rb_fiddle_handle_sym, 1);
rb_define_method(rb_cHandle, "disable_close", rb_fiddle_handle_disable_close, 0);
rb_define_method(rb_cHandle, "enable_close", rb_fiddle_handle_enable_close, 0);
rb_define_method(rb_cHandle, "close_enabled?", rb_fiddle_handle_close_enabled_p, 0);
}
/* vim: set noet sws=4 sw=4: */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1752_1 |
crossvul-cpp_data_bad_4829_4 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4829_4 |
crossvul-cpp_data_good_3070_1 | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <limits.h>
#include <errno.h>
#define USE_SOCKETS
#include "../ssl_locl.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include "record_locl.h"
#if defined(OPENSSL_SMALL_FOOTPRINT) || \
!( defined(AES_ASM) && ( \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64) ) \
)
# undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
#endif
void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s)
{
rl->s = s;
RECORD_LAYER_set_first_record(&s->rlayer);
SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
}
void RECORD_LAYER_clear(RECORD_LAYER *rl)
{
rl->rstate = SSL_ST_READ_HEADER;
/*
* Do I need to clear read_ahead? As far as I can tell read_ahead did not
* previously get reset by SSL_clear...so I'll keep it that way..but is
* that right?
*/
rl->packet = NULL;
rl->packet_length = 0;
rl->wnum = 0;
memset(rl->alert_fragment, 0, sizeof(rl->alert_fragment));
rl->alert_fragment_len = 0;
memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
rl->handshake_fragment_len = 0;
rl->wpend_tot = 0;
rl->wpend_type = 0;
rl->wpend_ret = 0;
rl->wpend_buf = NULL;
SSL3_BUFFER_clear(&rl->rbuf);
ssl3_release_write_buffer(rl->s);
rl->numrpipes = 0;
SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
RECORD_LAYER_reset_read_sequence(rl);
RECORD_LAYER_reset_write_sequence(rl);
if (rl->d)
DTLS_RECORD_LAYER_clear(rl);
}
void RECORD_LAYER_release(RECORD_LAYER *rl)
{
if (SSL3_BUFFER_is_initialised(&rl->rbuf))
ssl3_release_read_buffer(rl->s);
if (rl->numwpipes > 0)
ssl3_release_write_buffer(rl->s);
SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
}
int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
{
return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
}
int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
{
return (rl->numwpipes > 0)
&& SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
}
int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len)
{
rl->packet_length = len;
if (len != 0) {
rl->rstate = SSL_ST_READ_HEADER;
if (!SSL3_BUFFER_is_initialised(&rl->rbuf))
if (!ssl3_setup_read_buffer(rl->s))
return 0;
}
rl->packet = SSL3_BUFFER_get_buf(&rl->rbuf);
SSL3_BUFFER_set_data(&rl->rbuf, buf, len);
return 1;
}
void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
{
memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
}
void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
{
memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
}
int ssl3_pending(const SSL *s)
{
unsigned int i;
int num = 0;
if (s->rlayer.rstate == SSL_ST_READ_BODY)
return 0;
for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) {
if (SSL3_RECORD_get_type(&s->rlayer.rrec[i])
!= SSL3_RT_APPLICATION_DATA)
return 0;
num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]);
}
return num;
}
void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
{
ctx->default_read_buf_len = len;
}
void SSL_set_default_read_buffer_len(SSL *s, size_t len)
{
SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len);
}
const char *SSL_rstate_string_long(const SSL *s)
{
switch (s->rlayer.rstate) {
case SSL_ST_READ_HEADER:
return "read header";
case SSL_ST_READ_BODY:
return "read body";
case SSL_ST_READ_DONE:
return "read done";
default:
return "unknown";
}
}
const char *SSL_rstate_string(const SSL *s)
{
switch (s->rlayer.rstate) {
case SSL_ST_READ_HEADER:
return "RH";
case SSL_ST_READ_BODY:
return "RB";
case SSL_ST_READ_DONE:
return "RD";
default:
return "unknown";
}
}
/*
* Return values are as per SSL_read()
*/
int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
{
/*
* If extend == 0, obtain new n-byte packet; if extend == 1, increase
* packet by another n bytes. The packet will be in the sub-array of
* s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
* s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus
* s->packet_length bytes if extend == 1].)
* if clearold == 1, move the packet to the start of the buffer; if
* clearold == 0 then leave any old packets where they were
*/
int i, len, left;
size_t align = 0;
unsigned char *pkt;
SSL3_BUFFER *rb;
if (n <= 0)
return n;
rb = &s->rlayer.rbuf;
if (rb->buf == NULL)
if (!ssl3_setup_read_buffer(s))
return -1;
left = rb->left;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
if (!extend) {
/* start with empty packet ... */
if (left == 0)
rb->offset = align;
else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
/*
* check if next packet length is large enough to justify payload
* alignment...
*/
pkt = rb->buf + rb->offset;
if (pkt[0] == SSL3_RT_APPLICATION_DATA
&& (pkt[3] << 8 | pkt[4]) >= 128) {
/*
* Note that even if packet is corrupted and its length field
* is insane, we can only be led to wrong decision about
* whether memmove will occur or not. Header values has no
* effect on memmove arguments and therefore no buffer
* overrun can be triggered.
*/
memmove(rb->buf + align, pkt, left);
rb->offset = align;
}
}
s->rlayer.packet = rb->buf + rb->offset;
s->rlayer.packet_length = 0;
/* ... now we can act as if 'extend' was set */
}
len = s->rlayer.packet_length;
pkt = rb->buf + align;
/*
* Move any available bytes to front of buffer: 'len' bytes already
* pointed to by 'packet', 'left' extra ones at the end
*/
if (s->rlayer.packet != pkt && clearold == 1) {
memmove(pkt, s->rlayer.packet, len + left);
s->rlayer.packet = pkt;
rb->offset = len + align;
}
/*
* For DTLS/UDP reads should not span multiple packets because the read
* operation returns the whole packet at once (as long as it fits into
* the buffer).
*/
if (SSL_IS_DTLS(s)) {
if (left == 0 && extend)
return 0;
if (left > 0 && n > left)
n = left;
}
/* if there is enough in the buffer from a previous read, take some */
if (left >= n) {
s->rlayer.packet_length += n;
rb->left = left - n;
rb->offset += n;
return (n);
}
/* else we need to read more data */
if (n > (int)(rb->len - rb->offset)) { /* does not happen */
SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
return -1;
}
/* We always act like read_ahead is set for DTLS */
if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s))
/* ignore max parameter */
max = n;
else {
if (max < n)
max = n;
if (max > (int)(rb->len - rb->offset))
max = rb->len - rb->offset;
}
while (left < n) {
/*
* Now we have len+left bytes at the front of s->s3->rbuf.buf and
* need to read in more until we have len+n (up to len+max if
* possible)
*/
clear_sys_error();
if (s->rbio != NULL) {
s->rwstate = SSL_READING;
i = BIO_read(s->rbio, pkt + len + left, max - left);
} else {
SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
i = -1;
}
if (i <= 0) {
rb->left = left;
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
if (len + left == 0)
ssl3_release_read_buffer(s);
return i;
}
left += i;
/*
* reads should *never* span multiple packets for DTLS because the
* underlying transport protocol is message oriented as opposed to
* byte oriented as in the TLS case.
*/
if (SSL_IS_DTLS(s)) {
if (n > left)
n = left; /* makes the while condition false */
}
}
/* done reading, now the book-keeping */
rb->offset += n;
rb->left = left - n;
s->rlayer.packet_length += n;
s->rwstate = SSL_NOTHING;
return (n);
}
/*
* Call this to write data in records of type 'type' It will return <= 0 if
* not all data has been sent or non-blocking IO.
*/
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
{
const unsigned char *buf = buf_;
int tot;
unsigned int n, split_send_fragment, maxpipes;
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
unsigned int max_send_fragment, nw;
unsigned int u_len = (unsigned int)len;
#endif
SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
int i;
if (len < 0) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);
return -1;
}
s->rwstate = SSL_NOTHING;
tot = s->rlayer.wnum;
/*
* ensure that if we end up with a smaller value of data to write out
* than the the original len from a write which didn't complete for
* non-blocking I/O and also somehow ended up avoiding the check for
* this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
* possible to end up with (len-tot) as a large number that will then
* promptly send beyond the end of the users buffer ... so we trap and
* report the error in a way the user will notice
*/
if ((unsigned int)len < s->rlayer.wnum) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
return -1;
}
s->rlayer.wnum = 0;
if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return -1;
}
}
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (wb->left != 0) {
i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->rlayer.wnum = tot;
return i;
}
tot += i; /* this might be last fragment */
}
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
/*
* Depending on platform multi-block can deliver several *times*
* better performance. Downside is that it has to allocate
* jumbo buffer to accommodate up to 8 records, but the
* compromise is considered worthy.
*/
if (type == SSL3_RT_APPLICATION_DATA &&
u_len >= 4 * (max_send_fragment = s->max_send_fragment) &&
s->compress == NULL && s->msg_callback == NULL &&
!SSL_WRITE_ETM(s) && SSL_USE_EXPLICIT_IV(s) &&
EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) &
EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
unsigned char aad[13];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
int packlen;
/* minimize address aliasing conflicts */
if ((max_send_fragment & 0xfff) == 0)
max_send_fragment -= 512;
if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
ssl3_release_write_buffer(s);
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
max_send_fragment, NULL);
if (u_len >= 8 * max_send_fragment)
packlen *= 8;
else
packlen *= 4;
if (!ssl3_setup_write_buffer(s, 1, packlen)) {
SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
return -1;
}
} else if (tot == len) { /* done? */
/* free jumbo buffer */
ssl3_release_write_buffer(s);
return tot;
}
n = (len - tot);
for (;;) {
if (n < 4 * max_send_fragment) {
/* free jumbo buffer */
ssl3_release_write_buffer(s);
break;
}
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0) {
s->rlayer.wnum = tot;
return i;
}
}
if (n >= 8 * max_send_fragment)
nw = max_send_fragment * (mb_param.interleave = 8);
else
nw = max_send_fragment * (mb_param.interleave = 4);
memcpy(aad, s->rlayer.write_sequence, 8);
aad[8] = type;
aad[9] = (unsigned char)(s->version >> 8);
aad[10] = (unsigned char)(s->version);
aad[11] = 0;
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = nw;
packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
/* free jumbo buffer */
ssl3_release_write_buffer(s);
break;
}
mb_param.out = wb->buf;
mb_param.inp = &buf[tot];
mb_param.len = nw;
if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param) <= 0)
return -1;
s->rlayer.write_sequence[7] += mb_param.interleave;
if (s->rlayer.write_sequence[7] < mb_param.interleave) {
int j = 6;
while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
}
wb->offset = 0;
wb->left = packlen;
s->rlayer.wpend_tot = nw;
s->rlayer.wpend_buf = &buf[tot];
s->rlayer.wpend_type = type;
s->rlayer.wpend_ret = nw;
i = ssl3_write_pending(s, type, &buf[tot], nw);
if (i <= 0) {
if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
/* free jumbo buffer */
ssl3_release_write_buffer(s);
}
s->rlayer.wnum = tot;
return i;
}
if (i == (int)n) {
/* free jumbo buffer */
ssl3_release_write_buffer(s);
return tot + i;
}
n -= i;
tot += i;
}
} else
#endif
if (tot == len) { /* done? */
if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot;
}
n = (len - tot);
split_send_fragment = s->split_send_fragment;
/*
* If max_pipelines is 0 then this means "undefined" and we default to
* 1 pipeline. Similarly if the cipher does not support pipelined
* processing then we also only use 1 pipeline, or if we're not using
* explicit IVs
*/
maxpipes = s->max_pipelines;
if (maxpipes > SSL_MAX_PIPELINES) {
/*
* We should have prevented this when we set max_pipelines so we
* shouldn't get here
*/
SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
if (maxpipes == 0
|| s->enc_write_ctx == NULL
|| !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))
& EVP_CIPH_FLAG_PIPELINE)
|| !SSL_USE_EXPLICIT_IV(s))
maxpipes = 1;
if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment
|| split_send_fragment == 0) {
/*
* We should have prevented this when we set the split and max send
* fragments so we shouldn't get here
*/
SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
for (;;) {
unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
unsigned int numpipes, j;
if (n == 0)
numpipes = 1;
else
numpipes = ((n - 1) / split_send_fragment) + 1;
if (numpipes > maxpipes)
numpipes = maxpipes;
if (n / numpipes >= s->max_send_fragment) {
/*
* We have enough data to completely fill all available
* pipelines
*/
for (j = 0; j < numpipes; j++) {
pipelens[j] = s->max_send_fragment;
}
} else {
/* We can partially fill all available pipelines */
tmppipelen = n / numpipes;
remain = n % numpipes;
for (j = 0; j < numpipes; j++) {
pipelens[j] = tmppipelen;
if (j < remain)
pipelens[j]++;
}
}
i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
if (i <= 0) {
/* XXX should we ssl3_release_write_buffer if i<0? */
s->rlayer.wnum = tot;
return i;
}
if ((i == (int)n) ||
(type == SSL3_RT_APPLICATION_DATA &&
(s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
/*
* next chunk of data should get another prepended empty fragment
* in ciphersuites with known-IV weakness:
*/
s->s3->empty_fragment_done = 0;
if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
!SSL_IS_DTLS(s))
ssl3_release_write_buffer(s);
return tot + i;
}
n -= i;
tot += i;
}
}
int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
unsigned int *pipelens, unsigned int numpipes,
int create_empty_fragment)
{
unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
SSL3_RECORD wr[SSL_MAX_PIPELINES];
int i, mac_size, clear = 0;
int prefix_len = 0;
int eivlen;
size_t align = 0;
SSL3_BUFFER *wb;
SSL_SESSION *sess;
unsigned int totlen = 0;
unsigned int j;
for (j = 0; j < numpipes; j++)
totlen += pipelens[j];
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (RECORD_LAYER_write_pending(&s->rlayer))
return (ssl3_write_pending(s, type, buf, totlen));
/* If we have an alert to send, lets send it */
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0)
return (i);
/* if it went, fall through and send more stuff */
}
if (s->rlayer.numwpipes < numpipes)
if (!ssl3_setup_write_buffer(s, numpipes, 0))
return -1;
if (totlen == 0 && !create_empty_fragment)
return 0;
sess = s->session;
if ((sess == NULL) ||
(s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL)) {
clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
mac_size = 0;
} else {
mac_size = EVP_MD_CTX_size(s->write_hash);
if (mac_size < 0)
goto err;
}
/*
* 'create_empty_fragment' is true only when this function calls itself
*/
if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
/*
* countermeasure against known-IV weakness in CBC ciphersuites (see
* http://www.openssl.org/~bodo/tls-cbc.txt)
*/
if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
/*
* recursive function call with 'create_empty_fragment' set; this
* prepares and buffers the data for an empty fragment (these
* 'prefix_len' bytes are sent out later together with the actual
* payload)
*/
unsigned int tmppipelen = 0;
prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
if (prefix_len <= 0)
goto err;
if (prefix_len >
(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
/* insufficient space */
SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
}
s->s3->empty_fragment_done = 1;
}
if (create_empty_fragment) {
wb = &s->rlayer.wbuf[0];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
/*
* extra fragment would be couple of cipher blocks, which would be
* multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
* payload, then we can just pretend we simply have two headers.
*/
align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
SSL3_BUFFER_set_offset(wb, align);
} else if (prefix_len) {
wb = &s->rlayer.wbuf[0];
outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
+ prefix_len;
} else {
for (j = 0; j < numpipes; j++) {
wb = &s->rlayer.wbuf[j];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
SSL3_BUFFER_set_offset(wb, align);
}
}
/* Explicit IV length, block ciphers appropriate version flag */
if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
if (mode == EVP_CIPH_CBC_MODE) {
eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
if (eivlen <= 1)
eivlen = 0;
}
/* Need explicit part of IV for GCM mode */
else if (mode == EVP_CIPH_GCM_MODE)
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
else if (mode == EVP_CIPH_CCM_MODE)
eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
else
eivlen = 0;
} else
eivlen = 0;
totlen = 0;
/* Clear our SSL3_RECORD structures */
memset(wr, 0, sizeof wr);
for (j = 0; j < numpipes; j++) {
/* write the header */
*(outbuf[j]++) = type & 0xff;
SSL3_RECORD_set_type(&wr[j], type);
*(outbuf[j]++) = (s->version >> 8);
/*
* Some servers hang if initial client hello is larger than 256 bytes
* and record version number > TLS 1.0
*/
if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
&& !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
*(outbuf[j]++) = 0x1;
else
*(outbuf[j]++) = s->version & 0xff;
/* field where we are to write out packet length */
plen[j] = outbuf[j];
outbuf[j] += 2;
/* lets setup the record stuff. */
SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
totlen += pipelens[j];
/*
* we now 'read' from wr->input, wr->length bytes into wr->data
*/
/* first we compress */
if (s->compress != NULL) {
if (!ssl3_do_compress(s, &wr[j])) {
SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
goto err;
}
} else {
memcpy(wr[j].data, wr[j].input, wr[j].length);
SSL3_RECORD_reset_input(&wr[j]);
}
/*
* we should still have the output to wr->data and the input from
* wr->input. Length should be wr->length. wr->data still points in the
* wb->buf
*/
if (!SSL_WRITE_ETM(s) && mac_size != 0) {
if (s->method->ssl3_enc->mac(s, &wr[j],
&(outbuf[j][wr[j].length + eivlen]),
1) < 0)
goto err;
SSL3_RECORD_add_length(&wr[j], mac_size);
}
SSL3_RECORD_set_data(&wr[j], outbuf[j]);
SSL3_RECORD_reset_input(&wr[j]);
if (eivlen) {
/*
* if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
*/
SSL3_RECORD_add_length(&wr[j], eivlen);
}
}
if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
goto err;
for (j = 0; j < numpipes; j++) {
if (SSL_WRITE_ETM(s) && mac_size != 0) {
if (s->method->ssl3_enc->mac(s, &wr[j],
outbuf[j] + wr[j].length, 1) < 0)
goto err;
SSL3_RECORD_add_length(&wr[j], mac_size);
}
/* record length after mac and block padding */
s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
if (s->msg_callback)
s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
s->msg_callback_arg);
/*
* we should now have wr->data pointing to the encrypted data, which is
* wr->length long
*/
SSL3_RECORD_set_type(&wr[j], type); /* not needed but helps for
* debugging */
SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
if (create_empty_fragment) {
/*
* we are in a recursive call; just return the length, don't write
* out anything here
*/
if (j > 0) {
/* We should never be pipelining an empty fragment!! */
SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
return SSL3_RECORD_get_length(wr);
}
/* now let's set up wb */
SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
prefix_len + SSL3_RECORD_get_length(&wr[j]));
}
/*
* memorize arguments so that ssl3_write_pending can detect bad write
* retries later
*/
s->rlayer.wpend_tot = totlen;
s->rlayer.wpend_buf = buf;
s->rlayer.wpend_type = type;
s->rlayer.wpend_ret = totlen;
/* we now just need to write the buffer */
return ssl3_write_pending(s, type, buf, totlen);
err:
return -1;
}
/* if s->s3->wbuf.left != 0, we need to call this
*
* Return values are as per SSL_write()
*/
int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
unsigned int len)
{
int i;
SSL3_BUFFER *wb = s->rlayer.wbuf;
unsigned int currbuf = 0;
/* XXXX */
if ((s->rlayer.wpend_tot > (int)len)
|| ((s->rlayer.wpend_buf != buf) &&
!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
|| (s->rlayer.wpend_type != type)) {
SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
return (-1);
}
for (;;) {
/* Loop until we find a buffer we haven't written out yet */
if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
&& currbuf < s->rlayer.numwpipes - 1) {
currbuf++;
continue;
}
clear_sys_error();
if (s->wbio != NULL) {
s->rwstate = SSL_WRITING;
i = BIO_write(s->wbio, (char *)
&(SSL3_BUFFER_get_buf(&wb[currbuf])
[SSL3_BUFFER_get_offset(&wb[currbuf])]),
(unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
} else {
SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
i = -1;
}
if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
SSL3_BUFFER_set_left(&wb[currbuf], 0);
SSL3_BUFFER_add_offset(&wb[currbuf], i);
if (currbuf + 1 < s->rlayer.numwpipes)
continue;
s->rwstate = SSL_NOTHING;
return (s->rlayer.wpend_ret);
} else if (i <= 0) {
if (SSL_IS_DTLS(s)) {
/*
* For DTLS, just drop it. That's kind of the whole point in
* using a datagram service
*/
SSL3_BUFFER_set_left(&wb[currbuf], 0);
}
return i;
}
SSL3_BUFFER_add_offset(&wb[currbuf], i);
SSL3_BUFFER_add_left(&wb[currbuf], -i);
}
}
/*-
* Return up to 'len' payload bytes received in 'type' records.
* 'type' is one of the following:
*
* - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
* - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
* - 0 (during a shutdown, no data has to be returned)
*
* If we don't have stored data to work from, read a SSL/TLS record first
* (possibly multiple records if we still don't have anything to return).
*
* This function must handle any surprises the peer may have for us, such as
* Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
* messages are treated as if they were handshake messages *if* the |recd_type|
* argument is non NULL.
* Also if record payloads contain fragments too small to process, we store
* them until there is enough for the respective protocol (the record protocol
* may use arbitrary fragmentation and even interleaving):
* Change cipher spec protocol
* just 1 byte needed, no need for keeping anything stored
* Alert protocol
* 2 bytes needed (AlertLevel, AlertDescription)
* Handshake protocol
* 4 bytes needed (HandshakeType, uint24 length) -- we just have
* to detect unexpected Client Hello and Hello Request messages
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
int len, int peek)
{
int al, i, j, ret;
unsigned int n, curr_rec, num_recs, read_bytes;
SSL3_RECORD *rr;
SSL3_BUFFER *rbuf;
void (*cb) (const SSL *ssl, int type2, int val) = NULL;
rbuf = &s->rlayer.rbuf;
if (!SSL3_BUFFER_is_initialised(rbuf)) {
/* Not initialized yet */
if (!ssl3_setup_read_buffer(s))
return (-1);
}
if ((type && (type != SSL3_RT_APPLICATION_DATA)
&& (type != SSL3_RT_HANDSHAKE)) || (peek
&& (type !=
SSL3_RT_APPLICATION_DATA))) {
SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
return -1;
}
if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
/* (partially) satisfy request from storage */
{
unsigned char *src = s->rlayer.handshake_fragment;
unsigned char *dst = buf;
unsigned int k;
/* peek == 0 */
n = 0;
while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
*dst++ = *src++;
len--;
s->rlayer.handshake_fragment_len--;
n++;
}
/* move any remaining fragment bytes: */
for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
s->rlayer.handshake_fragment[k] = *src++;
if (recvd_type != NULL)
*recvd_type = SSL3_RT_HANDSHAKE;
return n;
}
/*
* Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
*/
if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
/* type == SSL3_RT_APPLICATION_DATA */
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
}
start:
s->rwstate = SSL_NOTHING;
/*-
* For each record 'i' up to |num_recs]
* rr[i].type - is the type of record
* rr[i].data, - data
* rr[i].off, - offset into 'data' for next read
* rr[i].length, - number of bytes.
*/
rr = s->rlayer.rrec;
num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
do {
/* get new records if necessary */
if (num_recs == 0) {
ret = ssl3_get_record(s);
if (ret <= 0)
return (ret);
num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
if (num_recs == 0) {
/* Shouldn't happen */
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
goto f_err;
}
}
/* Skip over any records we have already read */
for (curr_rec = 0;
curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
curr_rec++) ;
if (curr_rec == num_recs) {
RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
num_recs = 0;
curr_rec = 0;
}
} while (num_recs == 0);
rr = &rr[curr_rec];
/*
* Reset the count of consecutive warning alerts if we've got a non-empty
* record that isn't an alert.
*/
if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT
&& SSL3_RECORD_get_length(rr) != 0)
s->rlayer.alert_count = 0;
/* we now have a packet which can be read and processed */
if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
* reset by ssl3_get_finished */
&& (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
goto f_err;
}
/*
* If the other end has shut down, throw anything we read away (even in
* 'peek' mode)
*/
if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
SSL3_RECORD_set_length(rr, 0);
s->rwstate = SSL_NOTHING;
return (0);
}
if (type == SSL3_RECORD_get_type(rr)
|| (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
&& type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
/*
* SSL3_RT_APPLICATION_DATA or
* SSL3_RT_HANDSHAKE or
* SSL3_RT_CHANGE_CIPHER_SPEC
*/
/*
* make sure that we are not getting application data when we are
* doing a handshake for the first time
*/
if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
(s->enc_read_ctx == NULL)) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
goto f_err;
}
if (type == SSL3_RT_HANDSHAKE
&& SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
&& s->rlayer.handshake_fragment_len > 0) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
goto f_err;
}
if (recvd_type != NULL)
*recvd_type = SSL3_RECORD_get_type(rr);
if (len <= 0)
return (len);
read_bytes = 0;
do {
if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
n = SSL3_RECORD_get_length(rr);
else
n = (unsigned int)len - read_bytes;
memcpy(buf, &(rr->data[rr->off]), n);
buf += n;
if (peek) {
/* Mark any zero length record as consumed CVE-2016-6305 */
if (SSL3_RECORD_get_length(rr) == 0)
SSL3_RECORD_set_read(rr);
} else {
SSL3_RECORD_sub_length(rr, n);
SSL3_RECORD_add_off(rr, n);
if (SSL3_RECORD_get_length(rr) == 0) {
s->rlayer.rstate = SSL_ST_READ_HEADER;
SSL3_RECORD_set_off(rr, 0);
SSL3_RECORD_set_read(rr);
}
}
if (SSL3_RECORD_get_length(rr) == 0
|| (peek && n == SSL3_RECORD_get_length(rr))) {
curr_rec++;
rr++;
}
read_bytes += n;
} while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
&& read_bytes < (unsigned int)len);
if (read_bytes == 0) {
/* We must have read empty records. Get more data */
goto start;
}
if (!peek && curr_rec == num_recs
&& (s->mode & SSL_MODE_RELEASE_BUFFERS)
&& SSL3_BUFFER_get_left(rbuf) == 0)
ssl3_release_read_buffer(s);
return read_bytes;
}
/*
* If we get here, then type != rr->type; if we have a handshake message,
* then it was unexpected (Hello Request or Client Hello) or invalid (we
* were actually expecting a CCS).
*/
/*
* Lets just double check that we've not got an SSLv2 record
*/
if (rr->rec_version == SSL2_VERSION) {
/*
* Should never happen. ssl3_get_record() should only give us an SSLv2
* record back if this is the first packet and we are looking for an
* initial ClientHello. Therefore |type| should always be equal to
* |rr->type|. If not then something has gone horribly wrong
*/
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
goto f_err;
}
if (s->method->version == TLS_ANY_VERSION
&& (s->server || rr->type != SSL3_RT_ALERT)) {
/*
* If we've got this far and still haven't decided on what version
* we're using then this must be a client side alert we're dealing with
* (we don't allow heartbeats yet). We shouldn't be receiving anything
* other than a ClientHello if we are a server.
*/
s->version = rr->rec_version;
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
goto f_err;
}
/*
* In case of record types for which we have 'fragment' storage, fill
* that so that we can process the data at a fixed place.
*/
{
unsigned int dest_maxlen = 0;
unsigned char *dest = NULL;
unsigned int *dest_len = NULL;
if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
dest_maxlen = sizeof s->rlayer.handshake_fragment;
dest = s->rlayer.handshake_fragment;
dest_len = &s->rlayer.handshake_fragment_len;
} else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
dest_maxlen = sizeof s->rlayer.alert_fragment;
dest = s->rlayer.alert_fragment;
dest_len = &s->rlayer.alert_fragment_len;
}
if (dest_maxlen > 0) {
n = dest_maxlen - *dest_len; /* available space in 'dest' */
if (SSL3_RECORD_get_length(rr) < n)
n = SSL3_RECORD_get_length(rr); /* available bytes */
/* now move 'n' bytes: */
while (n-- > 0) {
dest[(*dest_len)++] =
SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
SSL3_RECORD_add_off(rr, 1);
SSL3_RECORD_add_length(rr, -1);
}
if (*dest_len < dest_maxlen) {
SSL3_RECORD_set_read(rr);
goto start; /* fragment was too small */
}
}
}
/*-
* s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
* s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
* (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
*/
/* If we are a client, check for an incoming 'Hello Request': */
if ((!s->server) &&
(s->rlayer.handshake_fragment_len >= 4) &&
(s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
(s->session != NULL) && (s->session->cipher != NULL)) {
s->rlayer.handshake_fragment_len = 0;
if ((s->rlayer.handshake_fragment[1] != 0) ||
(s->rlayer.handshake_fragment[2] != 0) ||
(s->rlayer.handshake_fragment[3] != 0)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
goto f_err;
}
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
s->rlayer.handshake_fragment, 4, s,
s->msg_callback_arg);
if (SSL_is_init_finished(s) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
!s->s3->renegotiate) {
ssl3_renegotiate(s);
if (ssl3_renegotiate_check(s)) {
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (SSL3_BUFFER_get_left(rbuf) == 0) {
/* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data,
* but we trigger an SSL handshake, we return -1 with
* the retry option set. Otherwise renegotiation may
* cause nasty problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
}
} else {
SSL3_RECORD_set_read(rr);
}
} else {
/* Does this ever happen? */
SSL3_RECORD_set_read(rr);
}
/*
* we either finished a handshake or ignored the request, now try
* again to obtain the (application) data we were asked for
*/
goto start;
}
/*
* If we are a server and get a client hello when renegotiation isn't
* allowed send back a no renegotiation alert and carry on. WARNING:
* experimental code, needs reviewing (steve)
*/
if (s->server &&
SSL_is_init_finished(s) &&
!s->s3->send_connection_binding &&
(s->version > SSL3_VERSION) &&
(s->rlayer.handshake_fragment_len >= 4) &&
(s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
(s->session != NULL) && (s->session->cipher != NULL) &&
!(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
SSL3_RECORD_set_length(rr, 0);
SSL3_RECORD_set_read(rr);
ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
goto start;
}
if (s->rlayer.alert_fragment_len >= 2) {
int alert_level = s->rlayer.alert_fragment[0];
int alert_descr = s->rlayer.alert_fragment[1];
s->rlayer.alert_fragment_len = 0;
if (s->msg_callback)
s->msg_callback(0, s->version, SSL3_RT_ALERT,
s->rlayer.alert_fragment, 2, s,
s->msg_callback_arg);
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL) {
j = (alert_level << 8) | alert_descr;
cb(s, SSL_CB_READ_ALERT, j);
}
if (alert_level == SSL3_AL_WARNING) {
s->s3->warn_alert = alert_descr;
SSL3_RECORD_set_read(rr);
s->rlayer.alert_count++;
if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
goto f_err;
}
if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
return (0);
}
/*
* This is a warning but we receive it if we requested
* renegotiation and the peer denied it. Terminate with a fatal
* alert because if application tried to renegotiate it
* presumably had a good reason and expects it to succeed. In
* future we might have a renegotiation where we don't care if
* the peer refused it where we carry on.
*/
else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
goto f_err;
}
#ifdef SSL_AD_MISSING_SRP_USERNAME
else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
return (0);
#endif
} else if (alert_level == SSL3_AL_FATAL) {
char tmp[16];
s->rwstate = SSL_NOTHING;
s->s3->fatal_alert = alert_descr;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
ERR_add_error_data(2, "SSL alert number ", tmp);
s->shutdown |= SSL_RECEIVED_SHUTDOWN;
SSL3_RECORD_set_read(rr);
SSL_CTX_remove_session(s->session_ctx, s->session);
return (0);
} else {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
goto f_err;
}
goto start;
}
if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
* shutdown */
s->rwstate = SSL_NOTHING;
SSL3_RECORD_set_length(rr, 0);
SSL3_RECORD_set_read(rr);
return (0);
}
if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
goto f_err;
}
/*
* Unexpected handshake message (Client Hello, or protocol violation)
*/
if ((s->rlayer.handshake_fragment_len >= 4)
&& !ossl_statem_get_in_handshake(s)) {
if (SSL_is_init_finished(s) &&
!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
ossl_statem_set_in_init(s, 1);
s->renegotiate = 1;
s->new_session = 1;
}
i = s->handshake_func(s);
if (i < 0)
return (i);
if (i == 0) {
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
return (-1);
}
if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
if (SSL3_BUFFER_get_left(rbuf) == 0) {
/* no read-ahead left? */
BIO *bio;
/*
* In the case where we try to read application data, but we
* trigger an SSL handshake, we return -1 with the retry
* option set. Otherwise renegotiation may cause nasty
* problems in the blocking world
*/
s->rwstate = SSL_READING;
bio = SSL_get_rbio(s);
BIO_clear_retry_flags(bio);
BIO_set_retry_read(bio);
return (-1);
}
}
goto start;
}
switch (SSL3_RECORD_get_type(rr)) {
default:
/*
* TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
* TLS 1.2 says you MUST send an unexpected message alert. We use the
* TLS 1.2 behaviour for all protocol versions to prevent issues where
* no progress is being made and the peer continually sends unrecognised
* record types, using up resources processing them.
*/
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
case SSL3_RT_CHANGE_CIPHER_SPEC:
case SSL3_RT_ALERT:
case SSL3_RT_HANDSHAKE:
/*
* we already handled all of these, with the possible exception of
* SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
* that should not happen when type != rr->type
*/
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
goto f_err;
case SSL3_RT_APPLICATION_DATA:
/*
* At this point, we were expecting handshake data, but have
* application data. If the library was running inside ssl3_read()
* (i.e. in_read_app_data is set) and it makes sense to read
* application data at this point (session renegotiation not yet
* started), we will indulge it.
*/
if (ossl_statem_app_data_allowed(s)) {
s->s3->in_read_app_data = 2;
return (-1);
} else {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
goto f_err;
}
}
/* not reached */
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return (-1);
}
void ssl3_record_sequence_update(unsigned char *seq)
{
int i;
for (i = 7; i >= 0; i--) {
++seq[i];
if (seq[i] != 0)
break;
}
}
/*
* Returns true if the current rrec was sent in SSLv2 backwards compatible
* format and false otherwise.
*/
int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
{
return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
}
/*
* Returns the length in bytes of the current rrec
*/
unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
{
return SSL3_RECORD_get_length(&rl->rrec[0]);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3070_1 |
crossvul-cpp_data_good_332_0 | // SPDX-License-Identifier: GPL-2.0
/*
* Driver for Meywa-Denki & KAYAC YUREX
*
* Copyright (C) 2010 Tomoki Sekiyama (tomoki.sekiyama@gmail.com)
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kref.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/hid.h>
#define DRIVER_AUTHOR "Tomoki Sekiyama"
#define DRIVER_DESC "Driver for Meywa-Denki & KAYAC YUREX"
#define YUREX_VENDOR_ID 0x0c45
#define YUREX_PRODUCT_ID 0x1010
#define CMD_ACK '!'
#define CMD_ANIMATE 'A'
#define CMD_COUNT 'C'
#define CMD_LED 'L'
#define CMD_READ 'R'
#define CMD_SET 'S'
#define CMD_VERSION 'V'
#define CMD_EOF 0x0d
#define CMD_PADDING 0xff
#define YUREX_BUF_SIZE 8
#define YUREX_WRITE_TIMEOUT (HZ*2)
/* table of devices that work with this driver */
static struct usb_device_id yurex_table[] = {
{ USB_DEVICE(YUREX_VENDOR_ID, YUREX_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, yurex_table);
#ifdef CONFIG_USB_DYNAMIC_MINORS
#define YUREX_MINOR_BASE 0
#else
#define YUREX_MINOR_BASE 192
#endif
/* Structure to hold all of our device specific stuff */
struct usb_yurex {
struct usb_device *udev;
struct usb_interface *interface;
__u8 int_in_endpointAddr;
struct urb *urb; /* URB for interrupt in */
unsigned char *int_buffer; /* buffer for intterupt in */
struct urb *cntl_urb; /* URB for control msg */
struct usb_ctrlrequest *cntl_req; /* req for control msg */
unsigned char *cntl_buffer; /* buffer for control msg */
struct kref kref;
struct mutex io_mutex;
struct fasync_struct *async_queue;
wait_queue_head_t waitq;
spinlock_t lock;
__s64 bbu; /* BBU from device */
};
#define to_yurex_dev(d) container_of(d, struct usb_yurex, kref)
static struct usb_driver yurex_driver;
static const struct file_operations yurex_fops;
static void yurex_control_callback(struct urb *urb)
{
struct usb_yurex *dev = urb->context;
int status = urb->status;
if (status) {
dev_err(&urb->dev->dev, "%s - control failed: %d\n",
__func__, status);
wake_up_interruptible(&dev->waitq);
return;
}
/* on success, sender woken up by CMD_ACK int in, or timeout */
}
static void yurex_delete(struct kref *kref)
{
struct usb_yurex *dev = to_yurex_dev(kref);
dev_dbg(&dev->interface->dev, "%s\n", __func__);
usb_put_dev(dev->udev);
if (dev->cntl_urb) {
usb_kill_urb(dev->cntl_urb);
kfree(dev->cntl_req);
if (dev->cntl_buffer)
usb_free_coherent(dev->udev, YUREX_BUF_SIZE,
dev->cntl_buffer, dev->cntl_urb->transfer_dma);
usb_free_urb(dev->cntl_urb);
}
if (dev->urb) {
usb_kill_urb(dev->urb);
if (dev->int_buffer)
usb_free_coherent(dev->udev, YUREX_BUF_SIZE,
dev->int_buffer, dev->urb->transfer_dma);
usb_free_urb(dev->urb);
}
kfree(dev);
}
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with the driver core
*/
static struct usb_class_driver yurex_class = {
.name = "yurex%d",
.fops = &yurex_fops,
.minor_base = YUREX_MINOR_BASE,
};
static void yurex_interrupt(struct urb *urb)
{
struct usb_yurex *dev = urb->context;
unsigned char *buf = dev->int_buffer;
int status = urb->status;
unsigned long flags;
int retval, i;
switch (status) {
case 0: /*success*/
break;
case -EOVERFLOW:
dev_err(&dev->interface->dev,
"%s - overflow with length %d, actual length is %d\n",
__func__, YUREX_BUF_SIZE, dev->urb->actual_length);
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
case -EILSEQ:
/* The device is terminated, clean up */
return;
default:
dev_err(&dev->interface->dev,
"%s - unknown status received: %d\n", __func__, status);
goto exit;
}
/* handle received message */
switch (buf[0]) {
case CMD_COUNT:
case CMD_READ:
if (buf[6] == CMD_EOF) {
spin_lock_irqsave(&dev->lock, flags);
dev->bbu = 0;
for (i = 1; i < 6; i++) {
dev->bbu += buf[i];
if (i != 5)
dev->bbu <<= 8;
}
dev_dbg(&dev->interface->dev, "%s count: %lld\n",
__func__, dev->bbu);
spin_unlock_irqrestore(&dev->lock, flags);
kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
}
else
dev_dbg(&dev->interface->dev,
"data format error - no EOF\n");
break;
case CMD_ACK:
dev_dbg(&dev->interface->dev, "%s ack: %c\n",
__func__, buf[1]);
wake_up_interruptible(&dev->waitq);
break;
}
exit:
retval = usb_submit_urb(dev->urb, GFP_ATOMIC);
if (retval) {
dev_err(&dev->interface->dev, "%s - usb_submit_urb failed: %d\n",
__func__, retval);
}
}
static int yurex_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
struct usb_yurex *dev;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int retval = -ENOMEM;
DEFINE_WAIT(wait);
int res;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
goto error;
kref_init(&dev->kref);
mutex_init(&dev->io_mutex);
spin_lock_init(&dev->lock);
init_waitqueue_head(&dev->waitq);
dev->udev = usb_get_dev(interface_to_usbdev(interface));
dev->interface = interface;
/* set up the endpoint information */
iface_desc = interface->cur_altsetting;
res = usb_find_int_in_endpoint(iface_desc, &endpoint);
if (res) {
dev_err(&interface->dev, "Could not find endpoints\n");
retval = res;
goto error;
}
dev->int_in_endpointAddr = endpoint->bEndpointAddress;
/* allocate control URB */
dev->cntl_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->cntl_urb)
goto error;
/* allocate buffer for control req */
dev->cntl_req = kmalloc(YUREX_BUF_SIZE, GFP_KERNEL);
if (!dev->cntl_req)
goto error;
/* allocate buffer for control msg */
dev->cntl_buffer = usb_alloc_coherent(dev->udev, YUREX_BUF_SIZE,
GFP_KERNEL,
&dev->cntl_urb->transfer_dma);
if (!dev->cntl_buffer) {
dev_err(&interface->dev, "Could not allocate cntl_buffer\n");
goto error;
}
/* configure control URB */
dev->cntl_req->bRequestType = USB_DIR_OUT | USB_TYPE_CLASS |
USB_RECIP_INTERFACE;
dev->cntl_req->bRequest = HID_REQ_SET_REPORT;
dev->cntl_req->wValue = cpu_to_le16((HID_OUTPUT_REPORT + 1) << 8);
dev->cntl_req->wIndex = cpu_to_le16(iface_desc->desc.bInterfaceNumber);
dev->cntl_req->wLength = cpu_to_le16(YUREX_BUF_SIZE);
usb_fill_control_urb(dev->cntl_urb, dev->udev,
usb_sndctrlpipe(dev->udev, 0),
(void *)dev->cntl_req, dev->cntl_buffer,
YUREX_BUF_SIZE, yurex_control_callback, dev);
dev->cntl_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* allocate interrupt URB */
dev->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->urb)
goto error;
/* allocate buffer for interrupt in */
dev->int_buffer = usb_alloc_coherent(dev->udev, YUREX_BUF_SIZE,
GFP_KERNEL, &dev->urb->transfer_dma);
if (!dev->int_buffer) {
dev_err(&interface->dev, "Could not allocate int_buffer\n");
goto error;
}
/* configure interrupt URB */
usb_fill_int_urb(dev->urb, dev->udev,
usb_rcvintpipe(dev->udev, dev->int_in_endpointAddr),
dev->int_buffer, YUREX_BUF_SIZE, yurex_interrupt,
dev, 1);
dev->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
if (usb_submit_urb(dev->urb, GFP_KERNEL)) {
retval = -EIO;
dev_err(&interface->dev, "Could not submitting URB\n");
goto error;
}
/* save our data pointer in this interface device */
usb_set_intfdata(interface, dev);
dev->bbu = -1;
/* we can register the device now, as it is ready */
retval = usb_register_dev(interface, &yurex_class);
if (retval) {
dev_err(&interface->dev,
"Not able to get a minor for this device.\n");
usb_set_intfdata(interface, NULL);
goto error;
}
dev_info(&interface->dev,
"USB YUREX device now attached to Yurex #%d\n",
interface->minor);
return 0;
error:
if (dev)
/* this frees allocated memory */
kref_put(&dev->kref, yurex_delete);
return retval;
}
static void yurex_disconnect(struct usb_interface *interface)
{
struct usb_yurex *dev;
int minor = interface->minor;
dev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
/* give back our minor */
usb_deregister_dev(interface, &yurex_class);
/* prevent more I/O from starting */
mutex_lock(&dev->io_mutex);
dev->interface = NULL;
mutex_unlock(&dev->io_mutex);
/* wakeup waiters */
kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
wake_up_interruptible(&dev->waitq);
/* decrement our usage count */
kref_put(&dev->kref, yurex_delete);
dev_info(&interface->dev, "USB YUREX #%d now disconnected\n", minor);
}
static struct usb_driver yurex_driver = {
.name = "yurex",
.probe = yurex_probe,
.disconnect = yurex_disconnect,
.id_table = yurex_table,
};
static int yurex_fasync(int fd, struct file *file, int on)
{
struct usb_yurex *dev;
dev = file->private_data;
return fasync_helper(fd, file, on, &dev->async_queue);
}
static int yurex_open(struct inode *inode, struct file *file)
{
struct usb_yurex *dev;
struct usb_interface *interface;
int subminor;
int retval = 0;
subminor = iminor(inode);
interface = usb_find_interface(&yurex_driver, subminor);
if (!interface) {
printk(KERN_ERR "%s - error, can't find device for minor %d",
__func__, subminor);
retval = -ENODEV;
goto exit;
}
dev = usb_get_intfdata(interface);
if (!dev) {
retval = -ENODEV;
goto exit;
}
/* increment our usage count for the device */
kref_get(&dev->kref);
/* save our object in the file's private structure */
mutex_lock(&dev->io_mutex);
file->private_data = dev;
mutex_unlock(&dev->io_mutex);
exit:
return retval;
}
static int yurex_release(struct inode *inode, struct file *file)
{
struct usb_yurex *dev;
dev = file->private_data;
if (dev == NULL)
return -ENODEV;
/* decrement the count on our device */
kref_put(&dev->kref, yurex_delete);
return 0;
}
static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count,
loff_t *ppos)
{
struct usb_yurex *dev;
int len = 0;
char in_buffer[20];
unsigned long flags;
dev = file->private_data;
mutex_lock(&dev->io_mutex);
if (!dev->interface) { /* already disconnected */
mutex_unlock(&dev->io_mutex);
return -ENODEV;
}
spin_lock_irqsave(&dev->lock, flags);
len = snprintf(in_buffer, 20, "%lld\n", dev->bbu);
spin_unlock_irqrestore(&dev->lock, flags);
mutex_unlock(&dev->io_mutex);
return simple_read_from_buffer(buffer, count, ppos, in_buffer, len);
}
static ssize_t yurex_write(struct file *file, const char __user *user_buffer,
size_t count, loff_t *ppos)
{
struct usb_yurex *dev;
int i, set = 0, retval = 0;
char buffer[16];
char *data = buffer;
unsigned long long c, c2 = 0;
signed long timeout = 0;
DEFINE_WAIT(wait);
count = min(sizeof(buffer), count);
dev = file->private_data;
/* verify that we actually have some data to write */
if (count == 0)
goto error;
mutex_lock(&dev->io_mutex);
if (!dev->interface) { /* already disconnected */
mutex_unlock(&dev->io_mutex);
retval = -ENODEV;
goto error;
}
if (copy_from_user(buffer, user_buffer, count)) {
mutex_unlock(&dev->io_mutex);
retval = -EFAULT;
goto error;
}
memset(dev->cntl_buffer, CMD_PADDING, YUREX_BUF_SIZE);
switch (buffer[0]) {
case CMD_ANIMATE:
case CMD_LED:
dev->cntl_buffer[0] = buffer[0];
dev->cntl_buffer[1] = buffer[1];
dev->cntl_buffer[2] = CMD_EOF;
break;
case CMD_READ:
case CMD_VERSION:
dev->cntl_buffer[0] = buffer[0];
dev->cntl_buffer[1] = 0x00;
dev->cntl_buffer[2] = CMD_EOF;
break;
case CMD_SET:
data++;
/* FALL THROUGH */
case '0' ... '9':
set = 1;
c = c2 = simple_strtoull(data, NULL, 0);
dev->cntl_buffer[0] = CMD_SET;
for (i = 1; i < 6; i++) {
dev->cntl_buffer[i] = (c>>32) & 0xff;
c <<= 8;
}
buffer[6] = CMD_EOF;
break;
default:
mutex_unlock(&dev->io_mutex);
return -EINVAL;
}
/* send the data as the control msg */
prepare_to_wait(&dev->waitq, &wait, TASK_INTERRUPTIBLE);
dev_dbg(&dev->interface->dev, "%s - submit %c\n", __func__,
dev->cntl_buffer[0]);
retval = usb_submit_urb(dev->cntl_urb, GFP_KERNEL);
if (retval >= 0)
timeout = schedule_timeout(YUREX_WRITE_TIMEOUT);
finish_wait(&dev->waitq, &wait);
mutex_unlock(&dev->io_mutex);
if (retval < 0) {
dev_err(&dev->interface->dev,
"%s - failed to send bulk msg, error %d\n",
__func__, retval);
goto error;
}
if (set && timeout)
dev->bbu = c2;
return timeout ? count : -EIO;
error:
return retval;
}
static const struct file_operations yurex_fops = {
.owner = THIS_MODULE,
.read = yurex_read,
.write = yurex_write,
.open = yurex_open,
.release = yurex_release,
.fasync = yurex_fasync,
.llseek = default_llseek,
};
module_usb_driver(yurex_driver);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_332_0 |
crossvul-cpp_data_good_5718_1 | /*
* Bridge multicast support.
*
* 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 <linux/err.h>
#include <linux/if_ether.h>
#include <linux/igmp.h>
#include <linux/jhash.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/netdevice.h>
#include <linux/netfilter_bridge.h>
#include <linux/random.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/inetdevice.h>
#include <net/ip.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <net/ipv6.h>
#include <net/mld.h>
#include <net/ip6_checksum.h>
#endif
#include "br_private.h"
static void br_multicast_start_querier(struct net_bridge *br);
unsigned int br_mdb_rehash_seq;
static inline int br_ip_equal(const struct br_ip *a, const struct br_ip *b)
{
if (a->proto != b->proto)
return 0;
if (a->vid != b->vid)
return 0;
switch (a->proto) {
case htons(ETH_P_IP):
return a->u.ip4 == b->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return ipv6_addr_equal(&a->u.ip6, &b->u.ip6);
#endif
}
return 0;
}
static inline int __br_ip4_hash(struct net_bridge_mdb_htable *mdb, __be32 ip,
__u16 vid)
{
return jhash_2words((__force u32)ip, vid, mdb->secret) & (mdb->max - 1);
}
#if IS_ENABLED(CONFIG_IPV6)
static inline int __br_ip6_hash(struct net_bridge_mdb_htable *mdb,
const struct in6_addr *ip,
__u16 vid)
{
return jhash_2words(ipv6_addr_hash(ip), vid,
mdb->secret) & (mdb->max - 1);
}
#endif
static inline int br_ip_hash(struct net_bridge_mdb_htable *mdb,
struct br_ip *ip)
{
switch (ip->proto) {
case htons(ETH_P_IP):
return __br_ip4_hash(mdb, ip->u.ip4, ip->vid);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return __br_ip6_hash(mdb, &ip->u.ip6, ip->vid);
#endif
}
return 0;
}
static struct net_bridge_mdb_entry *__br_mdb_ip_get(
struct net_bridge_mdb_htable *mdb, struct br_ip *dst, int hash)
{
struct net_bridge_mdb_entry *mp;
hlist_for_each_entry_rcu(mp, &mdb->mhash[hash], hlist[mdb->ver]) {
if (br_ip_equal(&mp->addr, dst))
return mp;
}
return NULL;
}
struct net_bridge_mdb_entry *br_mdb_ip_get(struct net_bridge_mdb_htable *mdb,
struct br_ip *dst)
{
if (!mdb)
return NULL;
return __br_mdb_ip_get(mdb, dst, br_ip_hash(mdb, dst));
}
static struct net_bridge_mdb_entry *br_mdb_ip4_get(
struct net_bridge_mdb_htable *mdb, __be32 dst, __u16 vid)
{
struct br_ip br_dst;
br_dst.u.ip4 = dst;
br_dst.proto = htons(ETH_P_IP);
br_dst.vid = vid;
return br_mdb_ip_get(mdb, &br_dst);
}
#if IS_ENABLED(CONFIG_IPV6)
static struct net_bridge_mdb_entry *br_mdb_ip6_get(
struct net_bridge_mdb_htable *mdb, const struct in6_addr *dst,
__u16 vid)
{
struct br_ip br_dst;
br_dst.u.ip6 = *dst;
br_dst.proto = htons(ETH_P_IPV6);
br_dst.vid = vid;
return br_mdb_ip_get(mdb, &br_dst);
}
#endif
struct net_bridge_mdb_entry *br_mdb_get(struct net_bridge *br,
struct sk_buff *skb, u16 vid)
{
struct net_bridge_mdb_htable *mdb = rcu_dereference(br->mdb);
struct br_ip ip;
if (br->multicast_disabled)
return NULL;
if (BR_INPUT_SKB_CB(skb)->igmp)
return NULL;
ip.proto = skb->protocol;
ip.vid = vid;
switch (skb->protocol) {
case htons(ETH_P_IP):
ip.u.ip4 = ip_hdr(skb)->daddr;
break;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
ip.u.ip6 = ipv6_hdr(skb)->daddr;
break;
#endif
default:
return NULL;
}
return br_mdb_ip_get(mdb, &ip);
}
static void br_mdb_free(struct rcu_head *head)
{
struct net_bridge_mdb_htable *mdb =
container_of(head, struct net_bridge_mdb_htable, rcu);
struct net_bridge_mdb_htable *old = mdb->old;
mdb->old = NULL;
kfree(old->mhash);
kfree(old);
}
static int br_mdb_copy(struct net_bridge_mdb_htable *new,
struct net_bridge_mdb_htable *old,
int elasticity)
{
struct net_bridge_mdb_entry *mp;
int maxlen;
int len;
int i;
for (i = 0; i < old->max; i++)
hlist_for_each_entry(mp, &old->mhash[i], hlist[old->ver])
hlist_add_head(&mp->hlist[new->ver],
&new->mhash[br_ip_hash(new, &mp->addr)]);
if (!elasticity)
return 0;
maxlen = 0;
for (i = 0; i < new->max; i++) {
len = 0;
hlist_for_each_entry(mp, &new->mhash[i], hlist[new->ver])
len++;
if (len > maxlen)
maxlen = len;
}
return maxlen > elasticity ? -EINVAL : 0;
}
void br_multicast_free_pg(struct rcu_head *head)
{
struct net_bridge_port_group *p =
container_of(head, struct net_bridge_port_group, rcu);
kfree(p);
}
static void br_multicast_free_group(struct rcu_head *head)
{
struct net_bridge_mdb_entry *mp =
container_of(head, struct net_bridge_mdb_entry, rcu);
kfree(mp);
}
static void br_multicast_group_expired(unsigned long data)
{
struct net_bridge_mdb_entry *mp = (void *)data;
struct net_bridge *br = mp->br;
struct net_bridge_mdb_htable *mdb;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || timer_pending(&mp->timer))
goto out;
mp->mglist = false;
if (mp->ports)
goto out;
mdb = mlock_dereference(br->mdb, br);
hlist_del_rcu(&mp->hlist[mdb->ver]);
mdb->size--;
call_rcu_bh(&mp->rcu, br_multicast_free_group);
out:
spin_unlock(&br->multicast_lock);
}
static void br_multicast_del_pg(struct net_bridge *br,
struct net_bridge_port_group *pg)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &pg->addr);
if (WARN_ON(!mp))
return;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p != pg)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
if (!mp->ports && !mp->mglist && mp->timer_armed &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
return;
}
WARN_ON(1);
}
static void br_multicast_port_group_expired(unsigned long data)
{
struct net_bridge_port_group *pg = (void *)data;
struct net_bridge *br = pg->port->br;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || timer_pending(&pg->timer) ||
hlist_unhashed(&pg->mglist) || pg->state & MDB_PERMANENT)
goto out;
br_multicast_del_pg(br, pg);
out:
spin_unlock(&br->multicast_lock);
}
static int br_mdb_rehash(struct net_bridge_mdb_htable __rcu **mdbp, int max,
int elasticity)
{
struct net_bridge_mdb_htable *old = rcu_dereference_protected(*mdbp, 1);
struct net_bridge_mdb_htable *mdb;
int err;
mdb = kmalloc(sizeof(*mdb), GFP_ATOMIC);
if (!mdb)
return -ENOMEM;
mdb->max = max;
mdb->old = old;
mdb->mhash = kzalloc(max * sizeof(*mdb->mhash), GFP_ATOMIC);
if (!mdb->mhash) {
kfree(mdb);
return -ENOMEM;
}
mdb->size = old ? old->size : 0;
mdb->ver = old ? old->ver ^ 1 : 0;
if (!old || elasticity)
get_random_bytes(&mdb->secret, sizeof(mdb->secret));
else
mdb->secret = old->secret;
if (!old)
goto out;
err = br_mdb_copy(mdb, old, elasticity);
if (err) {
kfree(mdb->mhash);
kfree(mdb);
return err;
}
br_mdb_rehash_seq++;
call_rcu_bh(&mdb->rcu, br_mdb_free);
out:
rcu_assign_pointer(*mdbp, mdb);
return 0;
}
static struct sk_buff *br_ip4_multicast_alloc_query(struct net_bridge *br,
__be32 group)
{
struct sk_buff *skb;
struct igmphdr *ih;
struct ethhdr *eth;
struct iphdr *iph;
skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*iph) +
sizeof(*ih) + 4);
if (!skb)
goto out;
skb->protocol = htons(ETH_P_IP);
skb_reset_mac_header(skb);
eth = eth_hdr(skb);
memcpy(eth->h_source, br->dev->dev_addr, 6);
eth->h_dest[0] = 1;
eth->h_dest[1] = 0;
eth->h_dest[2] = 0x5e;
eth->h_dest[3] = 0;
eth->h_dest[4] = 0;
eth->h_dest[5] = 1;
eth->h_proto = htons(ETH_P_IP);
skb_put(skb, sizeof(*eth));
skb_set_network_header(skb, skb->len);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = 6;
iph->tos = 0xc0;
iph->tot_len = htons(sizeof(*iph) + sizeof(*ih) + 4);
iph->id = 0;
iph->frag_off = htons(IP_DF);
iph->ttl = 1;
iph->protocol = IPPROTO_IGMP;
iph->saddr = br->multicast_query_use_ifaddr ?
inet_select_addr(br->dev, 0, RT_SCOPE_LINK) : 0;
iph->daddr = htonl(INADDR_ALLHOSTS_GROUP);
((u8 *)&iph[1])[0] = IPOPT_RA;
((u8 *)&iph[1])[1] = 4;
((u8 *)&iph[1])[2] = 0;
((u8 *)&iph[1])[3] = 0;
ip_send_check(iph);
skb_put(skb, 24);
skb_set_transport_header(skb, skb->len);
ih = igmp_hdr(skb);
ih->type = IGMP_HOST_MEMBERSHIP_QUERY;
ih->code = (group ? br->multicast_last_member_interval :
br->multicast_query_response_interval) /
(HZ / IGMP_TIMER_SCALE);
ih->group = group;
ih->csum = 0;
ih->csum = ip_compute_csum((void *)ih, sizeof(struct igmphdr));
skb_put(skb, sizeof(*ih));
__skb_pull(skb, sizeof(*eth));
out:
return skb;
}
#if IS_ENABLED(CONFIG_IPV6)
static struct sk_buff *br_ip6_multicast_alloc_query(struct net_bridge *br,
const struct in6_addr *group)
{
struct sk_buff *skb;
struct ipv6hdr *ip6h;
struct mld_msg *mldq;
struct ethhdr *eth;
u8 *hopopt;
unsigned long interval;
skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*ip6h) +
8 + sizeof(*mldq));
if (!skb)
goto out;
skb->protocol = htons(ETH_P_IPV6);
/* Ethernet header */
skb_reset_mac_header(skb);
eth = eth_hdr(skb);
memcpy(eth->h_source, br->dev->dev_addr, 6);
eth->h_proto = htons(ETH_P_IPV6);
skb_put(skb, sizeof(*eth));
/* IPv6 header + HbH option */
skb_set_network_header(skb, skb->len);
ip6h = ipv6_hdr(skb);
*(__force __be32 *)ip6h = htonl(0x60000000);
ip6h->payload_len = htons(8 + sizeof(*mldq));
ip6h->nexthdr = IPPROTO_HOPOPTS;
ip6h->hop_limit = 1;
ipv6_addr_set(&ip6h->daddr, htonl(0xff020000), 0, 0, htonl(1));
if (ipv6_dev_get_saddr(dev_net(br->dev), br->dev, &ip6h->daddr, 0,
&ip6h->saddr)) {
kfree_skb(skb);
return NULL;
}
ipv6_eth_mc_map(&ip6h->daddr, eth->h_dest);
hopopt = (u8 *)(ip6h + 1);
hopopt[0] = IPPROTO_ICMPV6; /* next hdr */
hopopt[1] = 0; /* length of HbH */
hopopt[2] = IPV6_TLV_ROUTERALERT; /* Router Alert */
hopopt[3] = 2; /* Length of RA Option */
hopopt[4] = 0; /* Type = 0x0000 (MLD) */
hopopt[5] = 0;
hopopt[6] = IPV6_TLV_PAD1; /* Pad1 */
hopopt[7] = IPV6_TLV_PAD1; /* Pad1 */
skb_put(skb, sizeof(*ip6h) + 8);
/* ICMPv6 */
skb_set_transport_header(skb, skb->len);
mldq = (struct mld_msg *) icmp6_hdr(skb);
interval = ipv6_addr_any(group) ?
br->multicast_query_response_interval :
br->multicast_last_member_interval;
mldq->mld_type = ICMPV6_MGM_QUERY;
mldq->mld_code = 0;
mldq->mld_cksum = 0;
mldq->mld_maxdelay = htons((u16)jiffies_to_msecs(interval));
mldq->mld_reserved = 0;
mldq->mld_mca = *group;
/* checksum */
mldq->mld_cksum = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
sizeof(*mldq), IPPROTO_ICMPV6,
csum_partial(mldq,
sizeof(*mldq), 0));
skb_put(skb, sizeof(*mldq));
__skb_pull(skb, sizeof(*eth));
out:
return skb;
}
#endif
static struct sk_buff *br_multicast_alloc_query(struct net_bridge *br,
struct br_ip *addr)
{
switch (addr->proto) {
case htons(ETH_P_IP):
return br_ip4_multicast_alloc_query(br, addr->u.ip4);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return br_ip6_multicast_alloc_query(br, &addr->u.ip6);
#endif
}
return NULL;
}
static struct net_bridge_mdb_entry *br_multicast_get_group(
struct net_bridge *br, struct net_bridge_port *port,
struct br_ip *group, int hash)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
unsigned int count = 0;
unsigned int max;
int elasticity;
int err;
mdb = rcu_dereference_protected(br->mdb, 1);
hlist_for_each_entry(mp, &mdb->mhash[hash], hlist[mdb->ver]) {
count++;
if (unlikely(br_ip_equal(group, &mp->addr)))
return mp;
}
elasticity = 0;
max = mdb->max;
if (unlikely(count > br->hash_elasticity && count)) {
if (net_ratelimit())
br_info(br, "Multicast hash table "
"chain limit reached: %s\n",
port ? port->dev->name : br->dev->name);
elasticity = br->hash_elasticity;
}
if (mdb->size >= max) {
max *= 2;
if (unlikely(max > br->hash_max)) {
br_warn(br, "Multicast hash table maximum of %d "
"reached, disabling snooping: %s\n",
br->hash_max,
port ? port->dev->name : br->dev->name);
err = -E2BIG;
disable:
br->multicast_disabled = 1;
goto err;
}
}
if (max > mdb->max || elasticity) {
if (mdb->old) {
if (net_ratelimit())
br_info(br, "Multicast hash table "
"on fire: %s\n",
port ? port->dev->name : br->dev->name);
err = -EEXIST;
goto err;
}
err = br_mdb_rehash(&br->mdb, max, elasticity);
if (err) {
br_warn(br, "Cannot rehash multicast "
"hash table, disabling snooping: %s, %d, %d\n",
port ? port->dev->name : br->dev->name,
mdb->size, err);
goto disable;
}
err = -EAGAIN;
goto err;
}
return NULL;
err:
mp = ERR_PTR(err);
return mp;
}
struct net_bridge_mdb_entry *br_multicast_new_group(struct net_bridge *br,
struct net_bridge_port *port, struct br_ip *group)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
int hash;
int err;
mdb = rcu_dereference_protected(br->mdb, 1);
if (!mdb) {
err = br_mdb_rehash(&br->mdb, BR_HASH_SIZE, 0);
if (err)
return ERR_PTR(err);
goto rehash;
}
hash = br_ip_hash(mdb, group);
mp = br_multicast_get_group(br, port, group, hash);
switch (PTR_ERR(mp)) {
case 0:
break;
case -EAGAIN:
rehash:
mdb = rcu_dereference_protected(br->mdb, 1);
hash = br_ip_hash(mdb, group);
break;
default:
goto out;
}
mp = kzalloc(sizeof(*mp), GFP_ATOMIC);
if (unlikely(!mp))
return ERR_PTR(-ENOMEM);
mp->br = br;
mp->addr = *group;
hlist_add_head_rcu(&mp->hlist[mdb->ver], &mdb->mhash[hash]);
mdb->size++;
out:
return mp;
}
struct net_bridge_port_group *br_multicast_new_port_group(
struct net_bridge_port *port,
struct br_ip *group,
struct net_bridge_port_group __rcu *next,
unsigned char state)
{
struct net_bridge_port_group *p;
p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (unlikely(!p))
return NULL;
p->addr = *group;
p->port = port;
p->state = state;
rcu_assign_pointer(p->next, next);
hlist_add_head(&p->mglist, &port->mglist);
setup_timer(&p->timer, br_multicast_port_group_expired,
(unsigned long)p);
return p;
}
static int br_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
int err;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto err;
if (!port) {
mp->mglist = true;
goto out;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
goto out;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = br_multicast_new_port_group(port, group, *pp, MDB_TEMPORARY);
if (unlikely(!p))
goto err;
rcu_assign_pointer(*pp, p);
br_mdb_notify(br->dev, port, group, RTM_NEWMDB);
out:
err = 0;
err:
spin_unlock(&br->multicast_lock);
return err;
}
static int br_ip4_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
__be32 group,
__u16 vid)
{
struct br_ip br_group;
if (ipv4_is_local_multicast(group))
return 0;
br_group.u.ip4 = group;
br_group.proto = htons(ETH_P_IP);
br_group.vid = vid;
return br_multicast_add_group(br, port, &br_group);
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
const struct in6_addr *group,
__u16 vid)
{
struct br_ip br_group;
if (!ipv6_is_transient_multicast(group))
return 0;
br_group.u.ip6 = *group;
br_group.proto = htons(ETH_P_IPV6);
br_group.vid = vid;
return br_multicast_add_group(br, port, &br_group);
}
#endif
static void br_multicast_router_expired(unsigned long data)
{
struct net_bridge_port *port = (void *)data;
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (port->multicast_router != 1 ||
timer_pending(&port->multicast_router_timer) ||
hlist_unhashed(&port->rlist))
goto out;
hlist_del_init_rcu(&port->rlist);
out:
spin_unlock(&br->multicast_lock);
}
static void br_multicast_local_router_expired(unsigned long data)
{
}
static void br_multicast_querier_expired(unsigned long data)
{
struct net_bridge *br = (void *)data;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || br->multicast_disabled)
goto out;
br_multicast_start_querier(br);
out:
spin_unlock(&br->multicast_lock);
}
static void __br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *ip)
{
struct sk_buff *skb;
skb = br_multicast_alloc_query(br, ip);
if (!skb)
return;
if (port) {
__skb_push(skb, sizeof(struct ethhdr));
skb->dev = port->dev;
NF_HOOK(NFPROTO_BRIDGE, NF_BR_LOCAL_OUT, skb, NULL, skb->dev,
dev_queue_xmit);
} else
netif_rx(skb);
}
static void br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port, u32 sent)
{
unsigned long time;
struct br_ip br_group;
if (!netif_running(br->dev) || br->multicast_disabled ||
!br->multicast_querier ||
timer_pending(&br->multicast_querier_timer))
return;
memset(&br_group.u, 0, sizeof(br_group.u));
br_group.proto = htons(ETH_P_IP);
__br_multicast_send_query(br, port, &br_group);
#if IS_ENABLED(CONFIG_IPV6)
br_group.proto = htons(ETH_P_IPV6);
__br_multicast_send_query(br, port, &br_group);
#endif
time = jiffies;
time += sent < br->multicast_startup_query_count ?
br->multicast_startup_query_interval :
br->multicast_query_interval;
mod_timer(port ? &port->multicast_query_timer :
&br->multicast_query_timer, time);
}
static void br_multicast_port_query_expired(unsigned long data)
{
struct net_bridge_port *port = (void *)data;
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (port->state == BR_STATE_DISABLED ||
port->state == BR_STATE_BLOCKING)
goto out;
if (port->multicast_startup_queries_sent <
br->multicast_startup_query_count)
port->multicast_startup_queries_sent++;
br_multicast_send_query(port->br, port,
port->multicast_startup_queries_sent);
out:
spin_unlock(&br->multicast_lock);
}
void br_multicast_add_port(struct net_bridge_port *port)
{
port->multicast_router = 1;
setup_timer(&port->multicast_router_timer, br_multicast_router_expired,
(unsigned long)port);
setup_timer(&port->multicast_query_timer,
br_multicast_port_query_expired, (unsigned long)port);
}
void br_multicast_del_port(struct net_bridge_port *port)
{
del_timer_sync(&port->multicast_router_timer);
}
static void __br_multicast_enable_port(struct net_bridge_port *port)
{
port->multicast_startup_queries_sent = 0;
if (try_to_del_timer_sync(&port->multicast_query_timer) >= 0 ||
del_timer(&port->multicast_query_timer))
mod_timer(&port->multicast_query_timer, jiffies);
}
void br_multicast_enable_port(struct net_bridge_port *port)
{
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (br->multicast_disabled || !netif_running(br->dev))
goto out;
__br_multicast_enable_port(port);
out:
spin_unlock(&br->multicast_lock);
}
void br_multicast_disable_port(struct net_bridge_port *port)
{
struct net_bridge *br = port->br;
struct net_bridge_port_group *pg;
struct hlist_node *n;
spin_lock(&br->multicast_lock);
hlist_for_each_entry_safe(pg, n, &port->mglist, mglist)
br_multicast_del_pg(br, pg);
if (!hlist_unhashed(&port->rlist))
hlist_del_init_rcu(&port->rlist);
del_timer(&port->multicast_router_timer);
del_timer(&port->multicast_query_timer);
spin_unlock(&br->multicast_lock);
}
static int br_ip4_multicast_igmp3_report(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct igmpv3_report *ih;
struct igmpv3_grec *grec;
int i;
int len;
int num;
int type;
int err = 0;
__be32 group;
u16 vid = 0;
if (!pskb_may_pull(skb, sizeof(*ih)))
return -EINVAL;
br_vlan_get_tag(skb, &vid);
ih = igmpv3_report_hdr(skb);
num = ntohs(ih->ngrec);
len = sizeof(*ih);
for (i = 0; i < num; i++) {
len += sizeof(*grec);
if (!pskb_may_pull(skb, len))
return -EINVAL;
grec = (void *)(skb->data + len - sizeof(*grec));
group = grec->grec_mca;
type = grec->grec_type;
len += ntohs(grec->grec_nsrcs) * 4;
if (!pskb_may_pull(skb, len))
return -EINVAL;
/* We treat this as an IGMPv2 report for now. */
switch (type) {
case IGMPV3_MODE_IS_INCLUDE:
case IGMPV3_MODE_IS_EXCLUDE:
case IGMPV3_CHANGE_TO_INCLUDE:
case IGMPV3_CHANGE_TO_EXCLUDE:
case IGMPV3_ALLOW_NEW_SOURCES:
case IGMPV3_BLOCK_OLD_SOURCES:
break;
default:
continue;
}
err = br_ip4_multicast_add_group(br, port, group, vid);
if (err)
break;
}
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_mld2_report(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct icmp6hdr *icmp6h;
struct mld2_grec *grec;
int i;
int len;
int num;
int err = 0;
u16 vid = 0;
if (!pskb_may_pull(skb, sizeof(*icmp6h)))
return -EINVAL;
br_vlan_get_tag(skb, &vid);
icmp6h = icmp6_hdr(skb);
num = ntohs(icmp6h->icmp6_dataun.un_data16[1]);
len = sizeof(*icmp6h);
for (i = 0; i < num; i++) {
__be16 *nsrcs, _nsrcs;
nsrcs = skb_header_pointer(skb,
len + offsetof(struct mld2_grec,
grec_nsrcs),
sizeof(_nsrcs), &_nsrcs);
if (!nsrcs)
return -EINVAL;
if (!pskb_may_pull(skb,
len + sizeof(*grec) +
sizeof(struct in6_addr) * ntohs(*nsrcs)))
return -EINVAL;
grec = (struct mld2_grec *)(skb->data + len);
len += sizeof(*grec) +
sizeof(struct in6_addr) * ntohs(*nsrcs);
/* We treat these as MLDv1 reports for now. */
switch (grec->grec_type) {
case MLD2_MODE_IS_INCLUDE:
case MLD2_MODE_IS_EXCLUDE:
case MLD2_CHANGE_TO_INCLUDE:
case MLD2_CHANGE_TO_EXCLUDE:
case MLD2_ALLOW_NEW_SOURCES:
case MLD2_BLOCK_OLD_SOURCES:
break;
default:
continue;
}
err = br_ip6_multicast_add_group(br, port, &grec->grec_mca,
vid);
if (!err)
break;
}
return err;
}
#endif
/*
* Add port to router_list
* list is maintained ordered by pointer value
* and locked by br->multicast_lock and RCU
*/
static void br_multicast_add_router(struct net_bridge *br,
struct net_bridge_port *port)
{
struct net_bridge_port *p;
struct hlist_node *slot = NULL;
hlist_for_each_entry(p, &br->router_list, rlist) {
if ((unsigned long) port >= (unsigned long) p)
break;
slot = &p->rlist;
}
if (slot)
hlist_add_after_rcu(slot, &port->rlist);
else
hlist_add_head_rcu(&port->rlist, &br->router_list);
}
static void br_multicast_mark_router(struct net_bridge *br,
struct net_bridge_port *port)
{
unsigned long now = jiffies;
if (!port) {
if (br->multicast_router == 1)
mod_timer(&br->multicast_router_timer,
now + br->multicast_querier_interval);
return;
}
if (port->multicast_router != 1)
return;
if (!hlist_unhashed(&port->rlist))
goto timer;
br_multicast_add_router(br, port);
timer:
mod_timer(&port->multicast_router_timer,
now + br->multicast_querier_interval);
}
static void br_multicast_query_received(struct net_bridge *br,
struct net_bridge_port *port,
int saddr)
{
if (saddr)
mod_timer(&br->multicast_querier_timer,
jiffies + br->multicast_querier_interval);
else if (timer_pending(&br->multicast_querier_timer))
return;
br_multicast_mark_router(br, port);
}
static int br_ip4_multicast_query(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct igmphdr *ih = igmp_hdr(skb);
struct net_bridge_mdb_entry *mp;
struct igmpv3_query *ih3;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long max_delay;
unsigned long now = jiffies;
__be32 group;
int err = 0;
u16 vid = 0;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
br_multicast_query_received(br, port, !!iph->saddr);
group = ih->group;
if (skb->len == sizeof(*ih)) {
max_delay = ih->code * (HZ / IGMP_TIMER_SCALE);
if (!max_delay) {
max_delay = 10 * HZ;
group = 0;
}
} else {
if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) {
err = -EINVAL;
goto out;
}
ih3 = igmpv3_query_hdr(skb);
if (ih3->nsrcs)
goto out;
max_delay = ih3->code ?
IGMPV3_MRC(ih3->code) * (HZ / IGMP_TIMER_SCALE) : 1;
}
if (!group)
goto out;
br_vlan_get_tag(skb, &vid);
mp = br_mdb_ip4_get(mlock_dereference(br->mdb, br), group, vid);
if (!mp)
goto out;
setup_timer(&mp->timer, br_multicast_group_expired, (unsigned long)mp);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
mp->timer_armed = true;
max_delay *= br->multicast_last_member_count;
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, now + max_delay) :
try_to_del_timer_sync(&mp->timer) >= 0))
mod_timer(&mp->timer, now + max_delay);
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (timer_pending(&p->timer) ?
time_after(p->timer.expires, now + max_delay) :
try_to_del_timer_sync(&p->timer) >= 0)
mod_timer(&p->timer, now + max_delay);
}
out:
spin_unlock(&br->multicast_lock);
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_query(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
const struct ipv6hdr *ip6h = ipv6_hdr(skb);
struct mld_msg *mld;
struct net_bridge_mdb_entry *mp;
struct mld2_query *mld2q;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long max_delay;
unsigned long now = jiffies;
const struct in6_addr *group = NULL;
int err = 0;
u16 vid = 0;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
br_multicast_query_received(br, port, !ipv6_addr_any(&ip6h->saddr));
if (skb->len == sizeof(*mld)) {
if (!pskb_may_pull(skb, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *) icmp6_hdr(skb);
max_delay = msecs_to_jiffies(ntohs(mld->mld_maxdelay));
if (max_delay)
group = &mld->mld_mca;
} else if (skb->len >= sizeof(*mld2q)) {
if (!pskb_may_pull(skb, sizeof(*mld2q))) {
err = -EINVAL;
goto out;
}
mld2q = (struct mld2_query *)icmp6_hdr(skb);
if (!mld2q->mld2q_nsrcs)
group = &mld2q->mld2q_mca;
max_delay = mld2q->mld2q_mrc ? MLDV2_MRC(ntohs(mld2q->mld2q_mrc)) : 1;
}
if (!group)
goto out;
br_vlan_get_tag(skb, &vid);
mp = br_mdb_ip6_get(mlock_dereference(br->mdb, br), group, vid);
if (!mp)
goto out;
setup_timer(&mp->timer, br_multicast_group_expired, (unsigned long)mp);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
mp->timer_armed = true;
max_delay *= br->multicast_last_member_count;
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, now + max_delay) :
try_to_del_timer_sync(&mp->timer) >= 0))
mod_timer(&mp->timer, now + max_delay);
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (timer_pending(&p->timer) ?
time_after(p->timer.expires, now + max_delay) :
try_to_del_timer_sync(&p->timer) >= 0)
mod_timer(&p->timer, now + max_delay);
}
out:
spin_unlock(&br->multicast_lock);
return err;
}
#endif
static void br_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
unsigned long now;
unsigned long time;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED) ||
timer_pending(&br->multicast_querier_timer))
goto out;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, group);
if (!mp)
goto out;
if (br->multicast_querier &&
!timer_pending(&br->multicast_querier_timer)) {
__br_multicast_send_query(br, port, &mp->addr);
time = jiffies + br->multicast_last_member_count *
br->multicast_last_member_interval;
mod_timer(port ? &port->multicast_query_timer :
&br->multicast_query_timer, time);
for (p = mlock_dereference(mp->ports, br);
p != NULL;
p = mlock_dereference(p->next, br)) {
if (p->port != port)
continue;
if (!hlist_unhashed(&p->mglist) &&
(timer_pending(&p->timer) ?
time_after(p->timer.expires, time) :
try_to_del_timer_sync(&p->timer) >= 0)) {
mod_timer(&p->timer, time);
}
break;
}
}
if (port && (port->flags & BR_MULTICAST_FAST_LEAVE)) {
struct net_bridge_port_group __rcu **pp;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port != port)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
br_mdb_notify(br->dev, port, group, RTM_DELMDB);
if (!mp->ports && !mp->mglist && mp->timer_armed &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
}
goto out;
}
now = jiffies;
time = now + br->multicast_last_member_count *
br->multicast_last_member_interval;
if (!port) {
if (mp->mglist && mp->timer_armed &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, time) :
try_to_del_timer_sync(&mp->timer) >= 0)) {
mod_timer(&mp->timer, time);
}
}
out:
spin_unlock(&br->multicast_lock);
}
static void br_ip4_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
__be32 group,
__u16 vid)
{
struct br_ip br_group;
if (ipv4_is_local_multicast(group))
return;
br_group.u.ip4 = group;
br_group.proto = htons(ETH_P_IP);
br_group.vid = vid;
br_multicast_leave_group(br, port, &br_group);
}
#if IS_ENABLED(CONFIG_IPV6)
static void br_ip6_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
const struct in6_addr *group,
__u16 vid)
{
struct br_ip br_group;
if (!ipv6_is_transient_multicast(group))
return;
br_group.u.ip6 = *group;
br_group.proto = htons(ETH_P_IPV6);
br_group.vid = vid;
br_multicast_leave_group(br, port, &br_group);
}
#endif
static int br_multicast_ipv4_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2 = skb;
const struct iphdr *iph;
struct igmphdr *ih;
unsigned int len;
unsigned int offset;
int err;
u16 vid = 0;
/* We treat OOM as packet loss for now. */
if (!pskb_may_pull(skb, sizeof(*iph)))
return -EINVAL;
iph = ip_hdr(skb);
if (iph->ihl < 5 || iph->version != 4)
return -EINVAL;
if (!pskb_may_pull(skb, ip_hdrlen(skb)))
return -EINVAL;
iph = ip_hdr(skb);
if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl)))
return -EINVAL;
if (iph->protocol != IPPROTO_IGMP) {
if (!ipv4_is_local_multicast(iph->daddr))
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
return 0;
}
len = ntohs(iph->tot_len);
if (skb->len < len || len < ip_hdrlen(skb))
return -EINVAL;
if (skb->len > len) {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = pskb_trim_rcsum(skb2, len);
if (err)
goto err_out;
}
len -= ip_hdrlen(skb2);
offset = skb_network_offset(skb2) + ip_hdrlen(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
err = -EINVAL;
if (!pskb_may_pull(skb2, sizeof(*ih)))
goto out;
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_fold(skb2->csum))
break;
/* fall through */
case CHECKSUM_NONE:
skb2->csum = 0;
if (skb_checksum_complete(skb2))
goto out;
}
err = 0;
br_vlan_get_tag(skb2, &vid);
BR_INPUT_SKB_CB(skb)->igmp = 1;
ih = igmp_hdr(skb2);
switch (ih->type) {
case IGMP_HOST_MEMBERSHIP_REPORT:
case IGMPV2_HOST_MEMBERSHIP_REPORT:
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
err = br_ip4_multicast_add_group(br, port, ih->group, vid);
break;
case IGMPV3_HOST_MEMBERSHIP_REPORT:
err = br_ip4_multicast_igmp3_report(br, port, skb2);
break;
case IGMP_HOST_MEMBERSHIP_QUERY:
err = br_ip4_multicast_query(br, port, skb2);
break;
case IGMP_HOST_LEAVE_MESSAGE:
br_ip4_multicast_leave_group(br, port, ih->group, vid);
break;
}
out:
__skb_push(skb2, offset);
err_out:
if (skb2 != skb)
kfree_skb(skb2);
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_multicast_ipv6_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2;
const struct ipv6hdr *ip6h;
u8 icmp6_type;
u8 nexthdr;
__be16 frag_off;
unsigned int len;
int offset;
int err;
u16 vid = 0;
if (!pskb_may_pull(skb, sizeof(*ip6h)))
return -EINVAL;
ip6h = ipv6_hdr(skb);
/*
* We're interested in MLD messages only.
* - Version is 6
* - MLD has always Router Alert hop-by-hop option
* - But we do not support jumbrograms.
*/
if (ip6h->version != 6 ||
ip6h->nexthdr != IPPROTO_HOPOPTS ||
ip6h->payload_len == 0)
return 0;
len = ntohs(ip6h->payload_len) + sizeof(*ip6h);
if (skb->len < len)
return -EINVAL;
nexthdr = ip6h->nexthdr;
offset = ipv6_skip_exthdr(skb, sizeof(*ip6h), &nexthdr, &frag_off);
if (offset < 0 || nexthdr != IPPROTO_ICMPV6)
return 0;
/* Okay, we found ICMPv6 header */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = -EINVAL;
if (!pskb_may_pull(skb2, offset + sizeof(struct icmp6hdr)))
goto out;
len -= offset - skb_network_offset(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
skb_postpull_rcsum(skb2, skb_network_header(skb2),
skb_network_header_len(skb2));
icmp6_type = icmp6_hdr(skb2)->icmp6_type;
switch (icmp6_type) {
case ICMPV6_MGM_QUERY:
case ICMPV6_MGM_REPORT:
case ICMPV6_MGM_REDUCTION:
case ICMPV6_MLD2_REPORT:
break;
default:
err = 0;
goto out;
}
/* Okay, we found MLD message. Check further. */
if (skb2->len > len) {
err = pskb_trim_rcsum(skb2, len);
if (err)
goto out;
err = -EINVAL;
}
ip6h = ipv6_hdr(skb2);
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr, skb2->len,
IPPROTO_ICMPV6, skb2->csum))
break;
/*FALLTHROUGH*/
case CHECKSUM_NONE:
skb2->csum = ~csum_unfold(csum_ipv6_magic(&ip6h->saddr,
&ip6h->daddr,
skb2->len,
IPPROTO_ICMPV6, 0));
if (__skb_checksum_complete(skb2))
goto out;
}
err = 0;
br_vlan_get_tag(skb, &vid);
BR_INPUT_SKB_CB(skb)->igmp = 1;
switch (icmp6_type) {
case ICMPV6_MGM_REPORT:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
err = br_ip6_multicast_add_group(br, port, &mld->mld_mca, vid);
break;
}
case ICMPV6_MLD2_REPORT:
err = br_ip6_multicast_mld2_report(br, port, skb2);
break;
case ICMPV6_MGM_QUERY:
err = br_ip6_multicast_query(br, port, skb2);
break;
case ICMPV6_MGM_REDUCTION:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
br_ip6_multicast_leave_group(br, port, &mld->mld_mca, vid);
}
}
out:
kfree_skb(skb2);
return err;
}
#endif
int br_multicast_rcv(struct net_bridge *br, struct net_bridge_port *port,
struct sk_buff *skb)
{
BR_INPUT_SKB_CB(skb)->igmp = 0;
BR_INPUT_SKB_CB(skb)->mrouters_only = 0;
if (br->multicast_disabled)
return 0;
switch (skb->protocol) {
case htons(ETH_P_IP):
return br_multicast_ipv4_rcv(br, port, skb);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return br_multicast_ipv6_rcv(br, port, skb);
#endif
}
return 0;
}
static void br_multicast_query_expired(unsigned long data)
{
struct net_bridge *br = (void *)data;
spin_lock(&br->multicast_lock);
if (br->multicast_startup_queries_sent <
br->multicast_startup_query_count)
br->multicast_startup_queries_sent++;
br_multicast_send_query(br, NULL, br->multicast_startup_queries_sent);
spin_unlock(&br->multicast_lock);
}
void br_multicast_init(struct net_bridge *br)
{
br->hash_elasticity = 4;
br->hash_max = 512;
br->multicast_router = 1;
br->multicast_querier = 0;
br->multicast_query_use_ifaddr = 0;
br->multicast_last_member_count = 2;
br->multicast_startup_query_count = 2;
br->multicast_last_member_interval = HZ;
br->multicast_query_response_interval = 10 * HZ;
br->multicast_startup_query_interval = 125 * HZ / 4;
br->multicast_query_interval = 125 * HZ;
br->multicast_querier_interval = 255 * HZ;
br->multicast_membership_interval = 260 * HZ;
spin_lock_init(&br->multicast_lock);
setup_timer(&br->multicast_router_timer,
br_multicast_local_router_expired, 0);
setup_timer(&br->multicast_querier_timer,
br_multicast_querier_expired, (unsigned long)br);
setup_timer(&br->multicast_query_timer, br_multicast_query_expired,
(unsigned long)br);
}
void br_multicast_open(struct net_bridge *br)
{
br->multicast_startup_queries_sent = 0;
if (br->multicast_disabled)
return;
mod_timer(&br->multicast_query_timer, jiffies);
}
void br_multicast_stop(struct net_bridge *br)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct hlist_node *n;
u32 ver;
int i;
del_timer_sync(&br->multicast_router_timer);
del_timer_sync(&br->multicast_querier_timer);
del_timer_sync(&br->multicast_query_timer);
spin_lock_bh(&br->multicast_lock);
mdb = mlock_dereference(br->mdb, br);
if (!mdb)
goto out;
br->mdb = NULL;
ver = mdb->ver;
for (i = 0; i < mdb->max; i++) {
hlist_for_each_entry_safe(mp, n, &mdb->mhash[i],
hlist[ver]) {
del_timer(&mp->timer);
mp->timer_armed = false;
call_rcu_bh(&mp->rcu, br_multicast_free_group);
}
}
if (mdb->old) {
spin_unlock_bh(&br->multicast_lock);
rcu_barrier_bh();
spin_lock_bh(&br->multicast_lock);
WARN_ON(mdb->old);
}
mdb->old = mdb;
call_rcu_bh(&mdb->rcu, br_mdb_free);
out:
spin_unlock_bh(&br->multicast_lock);
}
int br_multicast_set_router(struct net_bridge *br, unsigned long val)
{
int err = -ENOENT;
spin_lock_bh(&br->multicast_lock);
if (!netif_running(br->dev))
goto unlock;
switch (val) {
case 0:
case 2:
del_timer(&br->multicast_router_timer);
/* fall through */
case 1:
br->multicast_router = val;
err = 0;
break;
default:
err = -EINVAL;
break;
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
int br_multicast_set_port_router(struct net_bridge_port *p, unsigned long val)
{
struct net_bridge *br = p->br;
int err = -ENOENT;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || p->state == BR_STATE_DISABLED)
goto unlock;
switch (val) {
case 0:
case 1:
case 2:
p->multicast_router = val;
err = 0;
if (val < 2 && !hlist_unhashed(&p->rlist))
hlist_del_init_rcu(&p->rlist);
if (val == 1)
break;
del_timer(&p->multicast_router_timer);
if (val == 0)
break;
br_multicast_add_router(br, p);
break;
default:
err = -EINVAL;
break;
}
unlock:
spin_unlock(&br->multicast_lock);
return err;
}
static void br_multicast_start_querier(struct net_bridge *br)
{
struct net_bridge_port *port;
br_multicast_open(br);
list_for_each_entry(port, &br->port_list, list) {
if (port->state == BR_STATE_DISABLED ||
port->state == BR_STATE_BLOCKING)
continue;
__br_multicast_enable_port(port);
}
}
int br_multicast_toggle(struct net_bridge *br, unsigned long val)
{
int err = 0;
struct net_bridge_mdb_htable *mdb;
spin_lock_bh(&br->multicast_lock);
if (br->multicast_disabled == !val)
goto unlock;
br->multicast_disabled = !val;
if (br->multicast_disabled)
goto unlock;
if (!netif_running(br->dev))
goto unlock;
mdb = mlock_dereference(br->mdb, br);
if (mdb) {
if (mdb->old) {
err = -EEXIST;
rollback:
br->multicast_disabled = !!val;
goto unlock;
}
err = br_mdb_rehash(&br->mdb, mdb->max,
br->hash_elasticity);
if (err)
goto rollback;
}
br_multicast_start_querier(br);
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
int br_multicast_set_querier(struct net_bridge *br, unsigned long val)
{
val = !!val;
spin_lock_bh(&br->multicast_lock);
if (br->multicast_querier == val)
goto unlock;
br->multicast_querier = val;
if (val)
br_multicast_start_querier(br);
unlock:
spin_unlock_bh(&br->multicast_lock);
return 0;
}
int br_multicast_set_hash_max(struct net_bridge *br, unsigned long val)
{
int err = -ENOENT;
u32 old;
struct net_bridge_mdb_htable *mdb;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev))
goto unlock;
err = -EINVAL;
if (!is_power_of_2(val))
goto unlock;
mdb = mlock_dereference(br->mdb, br);
if (mdb && val < mdb->size)
goto unlock;
err = 0;
old = br->hash_max;
br->hash_max = val;
if (mdb) {
if (mdb->old) {
err = -EEXIST;
rollback:
br->hash_max = old;
goto unlock;
}
err = br_mdb_rehash(&br->mdb, br->hash_max,
br->hash_elasticity);
if (err)
goto rollback;
}
unlock:
spin_unlock(&br->multicast_lock);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5718_1 |
crossvul-cpp_data_bad_5844_1 | /*
* 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.
*
* "Ping" sockets
*
* 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.
*
* Based on ipv4/udp.c code.
*
* Authors: Vasiliy Kulikov / Openwall (for Linux 2.6),
* Pavel Kankovsky (for Linux 2.4.32)
*
* Pavel gave all rights to bugs to Vasiliy,
* none of the bugs are Pavel's now.
*
*/
#include <linux/uaccess.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/in.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <net/snmp.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <linux/proc_fs.h>
#include <linux/export.h>
#include <net/sock.h>
#include <net/ping.h>
#include <net/udp.h>
#include <net/route.h>
#include <net/inet_common.h>
#include <net/checksum.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/in6.h>
#include <linux/icmpv6.h>
#include <net/addrconf.h>
#include <net/ipv6.h>
#include <net/transp_v6.h>
#endif
struct ping_table ping_table;
struct pingv6_ops pingv6_ops;
EXPORT_SYMBOL_GPL(pingv6_ops);
static u16 ping_port_rover;
static inline int ping_hashfn(struct net *net, unsigned int num, unsigned int mask)
{
int res = (num + net_hash_mix(net)) & mask;
pr_debug("hash(%d) = %d\n", num, res);
return res;
}
EXPORT_SYMBOL_GPL(ping_hash);
static inline struct hlist_nulls_head *ping_hashslot(struct ping_table *table,
struct net *net, unsigned int num)
{
return &table->hash[ping_hashfn(net, num, PING_HTABLE_MASK)];
}
int ping_get_port(struct sock *sk, unsigned short ident)
{
struct hlist_nulls_node *node;
struct hlist_nulls_head *hlist;
struct inet_sock *isk, *isk2;
struct sock *sk2 = NULL;
isk = inet_sk(sk);
write_lock_bh(&ping_table.lock);
if (ident == 0) {
u32 i;
u16 result = ping_port_rover + 1;
for (i = 0; i < (1L << 16); i++, result++) {
if (!result)
result++; /* avoid zero */
hlist = ping_hashslot(&ping_table, sock_net(sk),
result);
ping_portaddr_for_each_entry(sk2, node, hlist) {
isk2 = inet_sk(sk2);
if (isk2->inet_num == result)
goto next_port;
}
/* found */
ping_port_rover = ident = result;
break;
next_port:
;
}
if (i >= (1L << 16))
goto fail;
} else {
hlist = ping_hashslot(&ping_table, sock_net(sk), ident);
ping_portaddr_for_each_entry(sk2, node, hlist) {
isk2 = inet_sk(sk2);
/* BUG? Why is this reuse and not reuseaddr? ping.c
* doesn't turn off SO_REUSEADDR, and it doesn't expect
* that other ping processes can steal its packets.
*/
if ((isk2->inet_num == ident) &&
(sk2 != sk) &&
(!sk2->sk_reuse || !sk->sk_reuse))
goto fail;
}
}
pr_debug("found port/ident = %d\n", ident);
isk->inet_num = ident;
if (sk_unhashed(sk)) {
pr_debug("was not hashed\n");
sock_hold(sk);
hlist_nulls_add_head(&sk->sk_nulls_node, hlist);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
}
write_unlock_bh(&ping_table.lock);
return 0;
fail:
write_unlock_bh(&ping_table.lock);
return 1;
}
EXPORT_SYMBOL_GPL(ping_get_port);
void ping_hash(struct sock *sk)
{
pr_debug("ping_hash(sk->port=%u)\n", inet_sk(sk)->inet_num);
BUG(); /* "Please do not press this button again." */
}
void ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
}
EXPORT_SYMBOL_GPL(ping_unhash);
static struct sock *ping_lookup(struct net *net, struct sk_buff *skb, u16 ident)
{
struct hlist_nulls_head *hslot = ping_hashslot(&ping_table, net, ident);
struct sock *sk = NULL;
struct inet_sock *isk;
struct hlist_nulls_node *hnode;
int dif = skb->dev->ifindex;
if (skb->protocol == htons(ETH_P_IP)) {
pr_debug("try to find: num = %d, daddr = %pI4, dif = %d\n",
(int)ident, &ip_hdr(skb)->daddr, dif);
#if IS_ENABLED(CONFIG_IPV6)
} else if (skb->protocol == htons(ETH_P_IPV6)) {
pr_debug("try to find: num = %d, daddr = %pI6c, dif = %d\n",
(int)ident, &ipv6_hdr(skb)->daddr, dif);
#endif
}
read_lock_bh(&ping_table.lock);
ping_portaddr_for_each_entry(sk, hnode, hslot) {
isk = inet_sk(sk);
pr_debug("iterate\n");
if (isk->inet_num != ident)
continue;
if (skb->protocol == htons(ETH_P_IP) &&
sk->sk_family == AF_INET) {
pr_debug("found: %p: num=%d, daddr=%pI4, dif=%d\n", sk,
(int) isk->inet_num, &isk->inet_rcv_saddr,
sk->sk_bound_dev_if);
if (isk->inet_rcv_saddr &&
isk->inet_rcv_saddr != ip_hdr(skb)->daddr)
continue;
#if IS_ENABLED(CONFIG_IPV6)
} else if (skb->protocol == htons(ETH_P_IPV6) &&
sk->sk_family == AF_INET6) {
pr_debug("found: %p: num=%d, daddr=%pI6c, dif=%d\n", sk,
(int) isk->inet_num,
&sk->sk_v6_rcv_saddr,
sk->sk_bound_dev_if);
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr) &&
!ipv6_addr_equal(&sk->sk_v6_rcv_saddr,
&ipv6_hdr(skb)->daddr))
continue;
#endif
}
if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)
continue;
sock_hold(sk);
goto exit;
}
sk = NULL;
exit:
read_unlock_bh(&ping_table.lock);
return sk;
}
static void inet_get_ping_group_range_net(struct net *net, kgid_t *low,
kgid_t *high)
{
kgid_t *data = net->ipv4.sysctl_ping_group_range;
unsigned int seq;
do {
seq = read_seqbegin(&net->ipv4.sysctl_local_ports.lock);
*low = data[0];
*high = data[1];
} while (read_seqretry(&net->ipv4.sysctl_local_ports.lock, seq));
}
int ping_init_sock(struct sock *sk)
{
struct net *net = sock_net(sk);
kgid_t group = current_egid();
struct group_info *group_info = get_current_groups();
int i, j, count = group_info->ngroups;
kgid_t low, high;
inet_get_ping_group_range_net(net, &low, &high);
if (gid_lte(low, group) && gid_lte(group, high))
return 0;
for (i = 0; i < group_info->nblocks; i++) {
int cp_count = min_t(int, NGROUPS_PER_BLOCK, count);
for (j = 0; j < cp_count; j++) {
kgid_t gid = group_info->blocks[i][j];
if (gid_lte(low, gid) && gid_lte(gid, high))
return 0;
}
count -= cp_count;
}
return -EACCES;
}
EXPORT_SYMBOL_GPL(ping_init_sock);
void ping_close(struct sock *sk, long timeout)
{
pr_debug("ping_close(sk=%p,sk->num=%u)\n",
inet_sk(sk), inet_sk(sk)->inet_num);
pr_debug("isk->refcnt = %d\n", sk->sk_refcnt.counter);
sk_common_release(sk);
}
EXPORT_SYMBOL_GPL(ping_close);
/* Checks the bind address and possibly modifies sk->sk_bound_dev_if. */
static int ping_check_bind_addr(struct sock *sk, struct inet_sock *isk,
struct sockaddr *uaddr, int addr_len) {
struct net *net = sock_net(sk);
if (sk->sk_family == AF_INET) {
struct sockaddr_in *addr = (struct sockaddr_in *) uaddr;
int chk_addr_ret;
if (addr_len < sizeof(*addr))
return -EINVAL;
pr_debug("ping_check_bind_addr(sk=%p,addr=%pI4,port=%d)\n",
sk, &addr->sin_addr.s_addr, ntohs(addr->sin_port));
chk_addr_ret = inet_addr_type(net, addr->sin_addr.s_addr);
if (addr->sin_addr.s_addr == htonl(INADDR_ANY))
chk_addr_ret = RTN_LOCAL;
if ((sysctl_ip_nonlocal_bind == 0 &&
isk->freebind == 0 && isk->transparent == 0 &&
chk_addr_ret != RTN_LOCAL) ||
chk_addr_ret == RTN_MULTICAST ||
chk_addr_ret == RTN_BROADCAST)
return -EADDRNOTAVAIL;
#if IS_ENABLED(CONFIG_IPV6)
} else if (sk->sk_family == AF_INET6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) uaddr;
int addr_type, scoped, has_addr;
struct net_device *dev = NULL;
if (addr_len < sizeof(*addr))
return -EINVAL;
pr_debug("ping_check_bind_addr(sk=%p,addr=%pI6c,port=%d)\n",
sk, addr->sin6_addr.s6_addr, ntohs(addr->sin6_port));
addr_type = ipv6_addr_type(&addr->sin6_addr);
scoped = __ipv6_addr_needs_scope_id(addr_type);
if ((addr_type != IPV6_ADDR_ANY &&
!(addr_type & IPV6_ADDR_UNICAST)) ||
(scoped && !addr->sin6_scope_id))
return -EINVAL;
rcu_read_lock();
if (addr->sin6_scope_id) {
dev = dev_get_by_index_rcu(net, addr->sin6_scope_id);
if (!dev) {
rcu_read_unlock();
return -ENODEV;
}
}
has_addr = pingv6_ops.ipv6_chk_addr(net, &addr->sin6_addr, dev,
scoped);
rcu_read_unlock();
if (!(isk->freebind || isk->transparent || has_addr ||
addr_type == IPV6_ADDR_ANY))
return -EADDRNOTAVAIL;
if (scoped)
sk->sk_bound_dev_if = addr->sin6_scope_id;
#endif
} else {
return -EAFNOSUPPORT;
}
return 0;
}
static void ping_set_saddr(struct sock *sk, struct sockaddr *saddr)
{
if (saddr->sa_family == AF_INET) {
struct inet_sock *isk = inet_sk(sk);
struct sockaddr_in *addr = (struct sockaddr_in *) saddr;
isk->inet_rcv_saddr = isk->inet_saddr = addr->sin_addr.s_addr;
#if IS_ENABLED(CONFIG_IPV6)
} else if (saddr->sa_family == AF_INET6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) saddr;
struct ipv6_pinfo *np = inet6_sk(sk);
sk->sk_v6_rcv_saddr = np->saddr = addr->sin6_addr;
#endif
}
}
static void ping_clear_saddr(struct sock *sk, int dif)
{
sk->sk_bound_dev_if = dif;
if (sk->sk_family == AF_INET) {
struct inet_sock *isk = inet_sk(sk);
isk->inet_rcv_saddr = isk->inet_saddr = 0;
#if IS_ENABLED(CONFIG_IPV6)
} else if (sk->sk_family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
memset(&sk->sk_v6_rcv_saddr, 0, sizeof(sk->sk_v6_rcv_saddr));
memset(&np->saddr, 0, sizeof(np->saddr));
#endif
}
}
/*
* We need our own bind because there are no privileged id's == local ports.
* Moreover, we don't allow binding to multi- and broadcast addresses.
*/
int ping_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *isk = inet_sk(sk);
unsigned short snum;
int err;
int dif = sk->sk_bound_dev_if;
err = ping_check_bind_addr(sk, isk, uaddr, addr_len);
if (err)
return err;
lock_sock(sk);
err = -EINVAL;
if (isk->inet_num != 0)
goto out;
err = -EADDRINUSE;
ping_set_saddr(sk, uaddr);
snum = ntohs(((struct sockaddr_in *)uaddr)->sin_port);
if (ping_get_port(sk, snum) != 0) {
ping_clear_saddr(sk, dif);
goto out;
}
pr_debug("after bind(): num = %d, dif = %d\n",
(int)isk->inet_num,
(int)sk->sk_bound_dev_if);
err = 0;
if (sk->sk_family == AF_INET && isk->inet_rcv_saddr)
sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6 && !ipv6_addr_any(&sk->sk_v6_rcv_saddr))
sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
#endif
if (snum)
sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
isk->inet_sport = htons(isk->inet_num);
isk->inet_daddr = 0;
isk->inet_dport = 0;
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6)
memset(&sk->sk_v6_daddr, 0, sizeof(sk->sk_v6_daddr));
#endif
sk_dst_reset(sk);
out:
release_sock(sk);
pr_debug("ping_v4_bind -> %d\n", err);
return err;
}
EXPORT_SYMBOL_GPL(ping_bind);
/*
* Is this a supported type of ICMP message?
*/
static inline int ping_supported(int family, int type, int code)
{
return (family == AF_INET && type == ICMP_ECHO && code == 0) ||
(family == AF_INET6 && type == ICMPV6_ECHO_REQUEST && code == 0);
}
/*
* This routine is called by the ICMP module when it gets some
* sort of error condition.
*/
void ping_err(struct sk_buff *skb, int offset, u32 info)
{
int family;
struct icmphdr *icmph;
struct inet_sock *inet_sock;
int type;
int code;
struct net *net = dev_net(skb->dev);
struct sock *sk;
int harderr;
int err;
if (skb->protocol == htons(ETH_P_IP)) {
family = AF_INET;
type = icmp_hdr(skb)->type;
code = icmp_hdr(skb)->code;
icmph = (struct icmphdr *)(skb->data + offset);
} else if (skb->protocol == htons(ETH_P_IPV6)) {
family = AF_INET6;
type = icmp6_hdr(skb)->icmp6_type;
code = icmp6_hdr(skb)->icmp6_code;
icmph = (struct icmphdr *) (skb->data + offset);
} else {
BUG();
}
/* We assume the packet has already been checked by icmp_unreach */
if (!ping_supported(family, icmph->type, icmph->code))
return;
pr_debug("ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n",
skb->protocol, type, code, ntohs(icmph->un.echo.id),
ntohs(icmph->un.echo.sequence));
sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
if (sk == NULL) {
pr_debug("no socket, dropping\n");
return; /* No socket for error */
}
pr_debug("err on socket %p\n", sk);
err = 0;
harderr = 0;
inet_sock = inet_sk(sk);
if (skb->protocol == htons(ETH_P_IP)) {
switch (type) {
default:
case ICMP_TIME_EXCEEDED:
err = EHOSTUNREACH;
break;
case ICMP_SOURCE_QUENCH:
/* This is not a real error but ping wants to see it.
* Report it with some fake errno.
*/
err = EREMOTEIO;
break;
case ICMP_PARAMETERPROB:
err = EPROTO;
harderr = 1;
break;
case ICMP_DEST_UNREACH:
if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
ipv4_sk_update_pmtu(skb, sk, info);
if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) {
err = EMSGSIZE;
harderr = 1;
break;
}
goto out;
}
err = EHOSTUNREACH;
if (code <= NR_ICMP_UNREACH) {
harderr = icmp_err_convert[code].fatal;
err = icmp_err_convert[code].errno;
}
break;
case ICMP_REDIRECT:
/* See ICMP_SOURCE_QUENCH */
ipv4_sk_redirect(skb, sk);
err = EREMOTEIO;
break;
}
#if IS_ENABLED(CONFIG_IPV6)
} else if (skb->protocol == htons(ETH_P_IPV6)) {
harderr = pingv6_ops.icmpv6_err_convert(type, code, &err);
#endif
}
/*
* RFC1122: OK. Passes ICMP errors back to application, as per
* 4.1.3.3.
*/
if ((family == AF_INET && !inet_sock->recverr) ||
(family == AF_INET6 && !inet6_sk(sk)->recverr)) {
if (!harderr || sk->sk_state != TCP_ESTABLISHED)
goto out;
} else {
if (family == AF_INET) {
ip_icmp_error(sk, skb, err, 0 /* no remote port */,
info, (u8 *)icmph);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
pingv6_ops.ipv6_icmp_error(sk, skb, err, 0,
info, (u8 *)icmph);
#endif
}
}
sk->sk_err = err;
sk->sk_error_report(sk);
out:
sock_put(sk);
}
EXPORT_SYMBOL_GPL(ping_err);
/*
* Copy and checksum an ICMP Echo packet from user space into a buffer
* starting from the payload.
*/
int ping_getfrag(void *from, char *to,
int offset, int fraglen, int odd, struct sk_buff *skb)
{
struct pingfakehdr *pfh = (struct pingfakehdr *)from;
if (offset == 0) {
if (fraglen < sizeof(struct icmphdr))
BUG();
if (csum_partial_copy_fromiovecend(to + sizeof(struct icmphdr),
pfh->iov, 0, fraglen - sizeof(struct icmphdr),
&pfh->wcheck))
return -EFAULT;
} else if (offset < sizeof(struct icmphdr)) {
BUG();
} else {
if (csum_partial_copy_fromiovecend
(to, pfh->iov, offset - sizeof(struct icmphdr),
fraglen, &pfh->wcheck))
return -EFAULT;
}
#if IS_ENABLED(CONFIG_IPV6)
/* For IPv6, checksum each skb as we go along, as expected by
* icmpv6_push_pending_frames. For IPv4, accumulate the checksum in
* wcheck, it will be finalized in ping_v4_push_pending_frames.
*/
if (pfh->family == AF_INET6) {
skb->csum = pfh->wcheck;
skb->ip_summed = CHECKSUM_NONE;
pfh->wcheck = 0;
}
#endif
return 0;
}
EXPORT_SYMBOL_GPL(ping_getfrag);
static int ping_v4_push_pending_frames(struct sock *sk, struct pingfakehdr *pfh,
struct flowi4 *fl4)
{
struct sk_buff *skb = skb_peek(&sk->sk_write_queue);
pfh->wcheck = csum_partial((char *)&pfh->icmph,
sizeof(struct icmphdr), pfh->wcheck);
pfh->icmph.checksum = csum_fold(pfh->wcheck);
memcpy(icmp_hdr(skb), &pfh->icmph, sizeof(struct icmphdr));
skb->ip_summed = CHECKSUM_NONE;
return ip_push_pending_frames(sk, fl4);
}
int ping_common_sendmsg(int family, struct msghdr *msg, size_t len,
void *user_icmph, size_t icmph_len) {
u8 type, code;
if (len > 0xFFFF)
return -EMSGSIZE;
/*
* Check the flags.
*/
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Fetch the ICMP header provided by the userland.
* iovec is modified! The ICMP header is consumed.
*/
if (memcpy_fromiovec(user_icmph, msg->msg_iov, icmph_len))
return -EFAULT;
if (family == AF_INET) {
type = ((struct icmphdr *) user_icmph)->type;
code = ((struct icmphdr *) user_icmph)->code;
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
type = ((struct icmp6hdr *) user_icmph)->icmp6_type;
code = ((struct icmp6hdr *) user_icmph)->icmp6_code;
#endif
} else {
BUG();
}
if (!ping_supported(family, type, code))
return -EINVAL;
return 0;
}
EXPORT_SYMBOL_GPL(ping_common_sendmsg);
int ping_v4_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len)
{
struct net *net = sock_net(sk);
struct flowi4 fl4;
struct inet_sock *inet = inet_sk(sk);
struct ipcm_cookie ipc;
struct icmphdr user_icmph;
struct pingfakehdr pfh;
struct rtable *rt = NULL;
struct ip_options_data opt_copy;
int free = 0;
__be32 saddr, daddr, faddr;
u8 tos;
int err;
pr_debug("ping_v4_sendmsg(sk=%p,sk->num=%u)\n", inet, inet->inet_num);
err = ping_common_sendmsg(AF_INET, msg, len, &user_icmph,
sizeof(user_icmph));
if (err)
return err;
/*
* Get and verify the address.
*/
if (msg->msg_name) {
struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
if (msg->msg_namelen < sizeof(*usin))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EINVAL;
daddr = usin->sin_addr.s_addr;
/* no remote port */
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = inet->inet_daddr;
/* no remote port */
}
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.oif = sk->sk_bound_dev_if;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
sock_tx_timestamp(sk, &ipc.tx_flags);
if (msg->msg_controllen) {
err = ip_cmsg_send(sock_net(sk), msg, &ipc);
if (err)
return err;
if (ipc.opt)
free = 1;
}
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
saddr = ipc.addr;
ipc.addr = faddr = daddr;
if (ipc.opt && ipc.opt->opt.srr) {
if (!daddr)
return -EINVAL;
faddr = ipc.opt->opt.faddr;
}
tos = get_rttos(&ipc, inet);
if (sock_flag(sk, SOCK_LOCALROUTE) ||
(msg->msg_flags & MSG_DONTROUTE) ||
(ipc.opt && ipc.opt->opt.is_strictroute)) {
tos |= RTO_ONLINK;
}
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE, sk->sk_protocol,
inet_sk_flowi_flags(sk), faddr, saddr, 0, 0);
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(net, &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
if (err == -ENETUNREACH)
IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
goto out;
}
err = -EACCES;
if ((rt->rt_flags & RTCF_BROADCAST) &&
!sock_flag(sk, SOCK_BROADCAST))
goto out;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
pfh.icmph.type = user_icmph.type; /* already checked */
pfh.icmph.code = user_icmph.code; /* ditto */
pfh.icmph.checksum = 0;
pfh.icmph.un.echo.id = inet->inet_sport;
pfh.icmph.un.echo.sequence = user_icmph.un.echo.sequence;
pfh.iov = msg->msg_iov;
pfh.wcheck = 0;
pfh.family = AF_INET;
err = ip_append_data(sk, &fl4, ping_getfrag, &pfh, len,
0, &ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else
err = ping_v4_push_pending_frames(sk, &pfh, &fl4);
release_sock(sk);
out:
ip_rt_put(rt);
if (free)
kfree(ipc.opt);
if (!err) {
icmp_out_count(sock_net(sk), user_icmph.type);
return len;
}
return err;
do_confirm:
dst_confirm(&rt->dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto out;
}
int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *isk = inet_sk(sk);
int family = sk->sk_family;
struct sockaddr_in *sin;
struct sockaddr_in6 *sin6;
struct sk_buff *skb;
int copied, err;
pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
if (addr_len) {
if (family == AF_INET)
*addr_len = sizeof(*sin);
else if (family == AF_INET6 && addr_len)
*addr_len = sizeof(*sin6);
}
if (flags & MSG_ERRQUEUE) {
if (family == AF_INET) {
return ip_recv_error(sk, msg, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
return pingv6_ops.ipv6_recv_error(sk, msg, len);
#endif
}
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* Don't bother checking the checksum */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address and add cmsg data. */
if (family == AF_INET) {
sin = (struct sockaddr_in *) msg->msg_name;
sin->sin_family = AF_INET;
sin->sin_port = 0 /* skb->h.uh->source */;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
if (isk->cmsg_flags)
ip_cmsg_recv(msg, skb);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *ip6 = ipv6_hdr(skb);
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ip6->saddr;
sin6->sin6_flowinfo = 0;
if (np->sndflow)
sin6->sin6_flowinfo = ip6_flowinfo(ip6);
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
if (inet6_sk(sk)->rxopt.all)
pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);
#endif
} else {
BUG();
}
err = copied;
done:
skb_free_datagram(sk, skb);
out:
pr_debug("ping_recvmsg -> %d\n", err);
return err;
}
EXPORT_SYMBOL_GPL(ping_recvmsg);
int ping_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
pr_debug("ping_queue_rcv_skb(sk=%p,sk->num=%d,skb=%p)\n",
inet_sk(sk), inet_sk(sk)->inet_num, skb);
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
pr_debug("ping_queue_rcv_skb -> failed\n");
return -1;
}
return 0;
}
EXPORT_SYMBOL_GPL(ping_queue_rcv_skb);
/*
* All we need to do is get the socket.
*/
void ping_rcv(struct sk_buff *skb)
{
struct sock *sk;
struct net *net = dev_net(skb->dev);
struct icmphdr *icmph = icmp_hdr(skb);
/* We assume the packet has already been checked by icmp_rcv */
pr_debug("ping_rcv(skb=%p,id=%04x,seq=%04x)\n",
skb, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence));
/* Push ICMP header back */
skb_push(skb, skb->data - (u8 *)icmph);
sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
if (sk != NULL) {
pr_debug("rcv on socket %p\n", sk);
ping_queue_rcv_skb(sk, skb_get(skb));
sock_put(sk);
return;
}
pr_debug("no socket, dropping\n");
/* We're called from icmp_rcv(). kfree_skb() is done there. */
}
EXPORT_SYMBOL_GPL(ping_rcv);
struct proto ping_prot = {
.name = "PING",
.owner = THIS_MODULE,
.init = ping_init_sock,
.close = ping_close,
.connect = ip4_datagram_connect,
.disconnect = udp_disconnect,
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.sendmsg = ping_v4_sendmsg,
.recvmsg = ping_recvmsg,
.bind = ping_bind,
.backlog_rcv = ping_queue_rcv_skb,
.release_cb = ip4_datagram_release_cb,
.hash = ping_hash,
.unhash = ping_unhash,
.get_port = ping_get_port,
.obj_size = sizeof(struct inet_sock),
};
EXPORT_SYMBOL(ping_prot);
#ifdef CONFIG_PROC_FS
static struct sock *ping_get_first(struct seq_file *seq, int start)
{
struct sock *sk;
struct ping_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
for (state->bucket = start; state->bucket < PING_HTABLE_SIZE;
++state->bucket) {
struct hlist_nulls_node *node;
struct hlist_nulls_head *hslot;
hslot = &ping_table.hash[state->bucket];
if (hlist_nulls_empty(hslot))
continue;
sk_nulls_for_each(sk, node, hslot) {
if (net_eq(sock_net(sk), net) &&
sk->sk_family == state->family)
goto found;
}
}
sk = NULL;
found:
return sk;
}
static struct sock *ping_get_next(struct seq_file *seq, struct sock *sk)
{
struct ping_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
do {
sk = sk_nulls_next(sk);
} while (sk && (!net_eq(sock_net(sk), net)));
if (!sk)
return ping_get_first(seq, state->bucket + 1);
return sk;
}
static struct sock *ping_get_idx(struct seq_file *seq, loff_t pos)
{
struct sock *sk = ping_get_first(seq, 0);
if (sk)
while (pos && (sk = ping_get_next(seq, sk)) != NULL)
--pos;
return pos ? NULL : sk;
}
void *ping_seq_start(struct seq_file *seq, loff_t *pos, sa_family_t family)
{
struct ping_iter_state *state = seq->private;
state->bucket = 0;
state->family = family;
read_lock_bh(&ping_table.lock);
return *pos ? ping_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
}
EXPORT_SYMBOL_GPL(ping_seq_start);
static void *ping_v4_seq_start(struct seq_file *seq, loff_t *pos)
{
return ping_seq_start(seq, pos, AF_INET);
}
void *ping_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *sk;
if (v == SEQ_START_TOKEN)
sk = ping_get_idx(seq, 0);
else
sk = ping_get_next(seq, v);
++*pos;
return sk;
}
EXPORT_SYMBOL_GPL(ping_seq_next);
void ping_seq_stop(struct seq_file *seq, void *v)
{
read_unlock_bh(&ping_table.lock);
}
EXPORT_SYMBOL_GPL(ping_seq_stop);
static void ping_v4_format_sock(struct sock *sp, struct seq_file *f,
int bucket, int *len)
{
struct inet_sock *inet = inet_sk(sp);
__be32 dest = inet->inet_daddr;
__be32 src = inet->inet_rcv_saddr;
__u16 destp = ntohs(inet->inet_dport);
__u16 srcp = ntohs(inet->inet_sport);
seq_printf(f, "%5d: %08X:%04X %08X:%04X"
" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d%n",
bucket, src, srcp, dest, destp, sp->sk_state,
sk_wmem_alloc_get(sp),
sk_rmem_alloc_get(sp),
0, 0L, 0,
from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
0, sock_i_ino(sp),
atomic_read(&sp->sk_refcnt), sp,
atomic_read(&sp->sk_drops), len);
}
static int ping_v4_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, "%-127s\n",
" sl local_address rem_address st tx_queue "
"rx_queue tr tm->when retrnsmt uid timeout "
"inode ref pointer drops");
else {
struct ping_iter_state *state = seq->private;
int len;
ping_v4_format_sock(v, seq, state->bucket, &len);
seq_printf(seq, "%*s\n", 127 - len, "");
}
return 0;
}
static const struct seq_operations ping_v4_seq_ops = {
.show = ping_v4_seq_show,
.start = ping_v4_seq_start,
.next = ping_seq_next,
.stop = ping_seq_stop,
};
static int ping_seq_open(struct inode *inode, struct file *file)
{
struct ping_seq_afinfo *afinfo = PDE_DATA(inode);
return seq_open_net(inode, file, &afinfo->seq_ops,
sizeof(struct ping_iter_state));
}
const struct file_operations ping_seq_fops = {
.open = ping_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
EXPORT_SYMBOL_GPL(ping_seq_fops);
static struct ping_seq_afinfo ping_v4_seq_afinfo = {
.name = "icmp",
.family = AF_INET,
.seq_fops = &ping_seq_fops,
.seq_ops = {
.start = ping_v4_seq_start,
.show = ping_v4_seq_show,
.next = ping_seq_next,
.stop = ping_seq_stop,
},
};
int ping_proc_register(struct net *net, struct ping_seq_afinfo *afinfo)
{
struct proc_dir_entry *p;
p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
afinfo->seq_fops, afinfo);
if (!p)
return -ENOMEM;
return 0;
}
EXPORT_SYMBOL_GPL(ping_proc_register);
void ping_proc_unregister(struct net *net, struct ping_seq_afinfo *afinfo)
{
remove_proc_entry(afinfo->name, net->proc_net);
}
EXPORT_SYMBOL_GPL(ping_proc_unregister);
static int __net_init ping_v4_proc_init_net(struct net *net)
{
return ping_proc_register(net, &ping_v4_seq_afinfo);
}
static void __net_exit ping_v4_proc_exit_net(struct net *net)
{
ping_proc_unregister(net, &ping_v4_seq_afinfo);
}
static struct pernet_operations ping_v4_net_ops = {
.init = ping_v4_proc_init_net,
.exit = ping_v4_proc_exit_net,
};
int __init ping_proc_init(void)
{
return register_pernet_subsys(&ping_v4_net_ops);
}
void ping_proc_exit(void)
{
unregister_pernet_subsys(&ping_v4_net_ops);
}
#endif
void __init ping_init(void)
{
int i;
for (i = 0; i < PING_HTABLE_SIZE; i++)
INIT_HLIST_NULLS_HEAD(&ping_table.hash[i], i);
rwlock_init(&ping_table.lock);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_1 |
crossvul-cpp_data_bad_5595_0 | /*
* Copyright (C) 2001 MandrakeSoft S.A.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* MandrakeSoft S.A.
* 43, rue d'Aboukir
* 75002 Paris - France
* http://www.linux-mandrake.com/
* http://www.mandrakesoft.com/
*
* This library 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 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Yunhong Jiang <yunhong.jiang@intel.com>
* Yaozu (Eddie) Dong <eddie.dong@intel.com>
* Based on Xen 3.1 code.
*/
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/hrtimer.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/processor.h>
#include <asm/page.h>
#include <asm/current.h>
#include <trace/events/kvm.h>
#include "ioapic.h"
#include "lapic.h"
#include "irq.h"
#if 0
#define ioapic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg)
#else
#define ioapic_debug(fmt, arg...)
#endif
static int ioapic_deliver(struct kvm_ioapic *vioapic, int irq);
static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic,
unsigned long addr,
unsigned long length)
{
unsigned long result = 0;
switch (ioapic->ioregsel) {
case IOAPIC_REG_VERSION:
result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16)
| (IOAPIC_VERSION_ID & 0xff));
break;
case IOAPIC_REG_APIC_ID:
case IOAPIC_REG_ARB_ID:
result = ((ioapic->id & 0xf) << 24);
break;
default:
{
u32 redir_index = (ioapic->ioregsel - 0x10) >> 1;
u64 redir_content;
ASSERT(redir_index < IOAPIC_NUM_PINS);
redir_content = ioapic->redirtbl[redir_index].bits;
result = (ioapic->ioregsel & 0x1) ?
(redir_content >> 32) & 0xffffffff :
redir_content & 0xffffffff;
break;
}
}
return result;
}
static int ioapic_service(struct kvm_ioapic *ioapic, unsigned int idx)
{
union kvm_ioapic_redirect_entry *pent;
int injected = -1;
pent = &ioapic->redirtbl[idx];
if (!pent->fields.mask) {
injected = ioapic_deliver(ioapic, idx);
if (injected && pent->fields.trig_mode == IOAPIC_LEVEL_TRIG)
pent->fields.remote_irr = 1;
}
return injected;
}
static void update_handled_vectors(struct kvm_ioapic *ioapic)
{
DECLARE_BITMAP(handled_vectors, 256);
int i;
memset(handled_vectors, 0, sizeof(handled_vectors));
for (i = 0; i < IOAPIC_NUM_PINS; ++i)
__set_bit(ioapic->redirtbl[i].fields.vector, handled_vectors);
memcpy(ioapic->handled_vectors, handled_vectors,
sizeof(handled_vectors));
smp_wmb();
}
void kvm_ioapic_calculate_eoi_exitmap(struct kvm_vcpu *vcpu,
u64 *eoi_exit_bitmap)
{
struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic;
union kvm_ioapic_redirect_entry *e;
struct kvm_lapic_irq irqe;
int index;
spin_lock(&ioapic->lock);
/* traverse ioapic entry to set eoi exit bitmap*/
for (index = 0; index < IOAPIC_NUM_PINS; index++) {
e = &ioapic->redirtbl[index];
if (!e->fields.mask &&
(e->fields.trig_mode == IOAPIC_LEVEL_TRIG ||
kvm_irq_has_notifier(ioapic->kvm, KVM_IRQCHIP_IOAPIC,
index))) {
irqe.dest_id = e->fields.dest_id;
irqe.vector = e->fields.vector;
irqe.dest_mode = e->fields.dest_mode;
irqe.delivery_mode = e->fields.delivery_mode << 8;
kvm_calculate_eoi_exitmap(vcpu, &irqe, eoi_exit_bitmap);
}
}
spin_unlock(&ioapic->lock);
}
EXPORT_SYMBOL_GPL(kvm_ioapic_calculate_eoi_exitmap);
void kvm_ioapic_make_eoibitmap_request(struct kvm *kvm)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
if (!kvm_apic_vid_enabled(kvm) || !ioapic)
return;
kvm_make_update_eoibitmap_request(kvm);
}
static void ioapic_write_indirect(struct kvm_ioapic *ioapic, u32 val)
{
unsigned index;
bool mask_before, mask_after;
union kvm_ioapic_redirect_entry *e;
switch (ioapic->ioregsel) {
case IOAPIC_REG_VERSION:
/* Writes are ignored. */
break;
case IOAPIC_REG_APIC_ID:
ioapic->id = (val >> 24) & 0xf;
break;
case IOAPIC_REG_ARB_ID:
break;
default:
index = (ioapic->ioregsel - 0x10) >> 1;
ioapic_debug("change redir index %x val %x\n", index, val);
if (index >= IOAPIC_NUM_PINS)
return;
e = &ioapic->redirtbl[index];
mask_before = e->fields.mask;
if (ioapic->ioregsel & 1) {
e->bits &= 0xffffffff;
e->bits |= (u64) val << 32;
} else {
e->bits &= ~0xffffffffULL;
e->bits |= (u32) val;
e->fields.remote_irr = 0;
}
update_handled_vectors(ioapic);
mask_after = e->fields.mask;
if (mask_before != mask_after)
kvm_fire_mask_notifiers(ioapic->kvm, KVM_IRQCHIP_IOAPIC, index, mask_after);
if (e->fields.trig_mode == IOAPIC_LEVEL_TRIG
&& ioapic->irr & (1 << index))
ioapic_service(ioapic, index);
kvm_ioapic_make_eoibitmap_request(ioapic->kvm);
break;
}
}
static int ioapic_deliver(struct kvm_ioapic *ioapic, int irq)
{
union kvm_ioapic_redirect_entry *entry = &ioapic->redirtbl[irq];
struct kvm_lapic_irq irqe;
ioapic_debug("dest=%x dest_mode=%x delivery_mode=%x "
"vector=%x trig_mode=%x\n",
entry->fields.dest_id, entry->fields.dest_mode,
entry->fields.delivery_mode, entry->fields.vector,
entry->fields.trig_mode);
irqe.dest_id = entry->fields.dest_id;
irqe.vector = entry->fields.vector;
irqe.dest_mode = entry->fields.dest_mode;
irqe.trig_mode = entry->fields.trig_mode;
irqe.delivery_mode = entry->fields.delivery_mode << 8;
irqe.level = 1;
irqe.shorthand = 0;
return kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe);
}
int kvm_ioapic_set_irq(struct kvm_ioapic *ioapic, int irq, int irq_source_id,
int level)
{
u32 old_irr;
u32 mask = 1 << irq;
union kvm_ioapic_redirect_entry entry;
int ret, irq_level;
BUG_ON(irq < 0 || irq >= IOAPIC_NUM_PINS);
spin_lock(&ioapic->lock);
old_irr = ioapic->irr;
irq_level = __kvm_irq_line_state(&ioapic->irq_states[irq],
irq_source_id, level);
entry = ioapic->redirtbl[irq];
irq_level ^= entry.fields.polarity;
if (!irq_level) {
ioapic->irr &= ~mask;
ret = 1;
} else {
int edge = (entry.fields.trig_mode == IOAPIC_EDGE_TRIG);
ioapic->irr |= mask;
if ((edge && old_irr != ioapic->irr) ||
(!edge && !entry.fields.remote_irr))
ret = ioapic_service(ioapic, irq);
else
ret = 0; /* report coalesced interrupt */
}
trace_kvm_ioapic_set_irq(entry.bits, irq, ret == 0);
spin_unlock(&ioapic->lock);
return ret;
}
void kvm_ioapic_clear_all(struct kvm_ioapic *ioapic, int irq_source_id)
{
int i;
spin_lock(&ioapic->lock);
for (i = 0; i < KVM_IOAPIC_NUM_PINS; i++)
__clear_bit(irq_source_id, &ioapic->irq_states[i]);
spin_unlock(&ioapic->lock);
}
static void __kvm_ioapic_update_eoi(struct kvm_ioapic *ioapic, int vector,
int trigger_mode)
{
int i;
for (i = 0; i < IOAPIC_NUM_PINS; i++) {
union kvm_ioapic_redirect_entry *ent = &ioapic->redirtbl[i];
if (ent->fields.vector != vector)
continue;
/*
* We are dropping lock while calling ack notifiers because ack
* notifier callbacks for assigned devices call into IOAPIC
* recursively. Since remote_irr is cleared only after call
* to notifiers if the same vector will be delivered while lock
* is dropped it will be put into irr and will be delivered
* after ack notifier returns.
*/
spin_unlock(&ioapic->lock);
kvm_notify_acked_irq(ioapic->kvm, KVM_IRQCHIP_IOAPIC, i);
spin_lock(&ioapic->lock);
if (trigger_mode != IOAPIC_LEVEL_TRIG)
continue;
ASSERT(ent->fields.trig_mode == IOAPIC_LEVEL_TRIG);
ent->fields.remote_irr = 0;
if (!ent->fields.mask && (ioapic->irr & (1 << i)))
ioapic_service(ioapic, i);
}
}
bool kvm_ioapic_handles_vector(struct kvm *kvm, int vector)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
smp_rmb();
return test_bit(vector, ioapic->handled_vectors);
}
void kvm_ioapic_update_eoi(struct kvm *kvm, int vector, int trigger_mode)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
spin_lock(&ioapic->lock);
__kvm_ioapic_update_eoi(ioapic, vector, trigger_mode);
spin_unlock(&ioapic->lock);
}
static inline struct kvm_ioapic *to_ioapic(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_ioapic, dev);
}
static inline int ioapic_in_range(struct kvm_ioapic *ioapic, gpa_t addr)
{
return ((addr >= ioapic->base_address &&
(addr < ioapic->base_address + IOAPIC_MEM_LENGTH)));
}
static int ioapic_mmio_read(struct kvm_io_device *this, gpa_t addr, int len,
void *val)
{
struct kvm_ioapic *ioapic = to_ioapic(this);
u32 result;
if (!ioapic_in_range(ioapic, addr))
return -EOPNOTSUPP;
ioapic_debug("addr %lx\n", (unsigned long)addr);
ASSERT(!(addr & 0xf)); /* check alignment */
addr &= 0xff;
spin_lock(&ioapic->lock);
switch (addr) {
case IOAPIC_REG_SELECT:
result = ioapic->ioregsel;
break;
case IOAPIC_REG_WINDOW:
result = ioapic_read_indirect(ioapic, addr, len);
break;
default:
result = 0;
break;
}
spin_unlock(&ioapic->lock);
switch (len) {
case 8:
*(u64 *) val = result;
break;
case 1:
case 2:
case 4:
memcpy(val, (char *)&result, len);
break;
default:
printk(KERN_WARNING "ioapic: wrong length %d\n", len);
}
return 0;
}
static int ioapic_mmio_write(struct kvm_io_device *this, gpa_t addr, int len,
const void *val)
{
struct kvm_ioapic *ioapic = to_ioapic(this);
u32 data;
if (!ioapic_in_range(ioapic, addr))
return -EOPNOTSUPP;
ioapic_debug("ioapic_mmio_write addr=%p len=%d val=%p\n",
(void*)addr, len, val);
ASSERT(!(addr & 0xf)); /* check alignment */
switch (len) {
case 8:
case 4:
data = *(u32 *) val;
break;
case 2:
data = *(u16 *) val;
break;
case 1:
data = *(u8 *) val;
break;
default:
printk(KERN_WARNING "ioapic: Unsupported size %d\n", len);
return 0;
}
addr &= 0xff;
spin_lock(&ioapic->lock);
switch (addr) {
case IOAPIC_REG_SELECT:
ioapic->ioregsel = data & 0xFF; /* 8-bit register */
break;
case IOAPIC_REG_WINDOW:
ioapic_write_indirect(ioapic, data);
break;
#ifdef CONFIG_IA64
case IOAPIC_REG_EOI:
__kvm_ioapic_update_eoi(ioapic, data, IOAPIC_LEVEL_TRIG);
break;
#endif
default:
break;
}
spin_unlock(&ioapic->lock);
return 0;
}
void kvm_ioapic_reset(struct kvm_ioapic *ioapic)
{
int i;
for (i = 0; i < IOAPIC_NUM_PINS; i++)
ioapic->redirtbl[i].fields.mask = 1;
ioapic->base_address = IOAPIC_DEFAULT_BASE_ADDRESS;
ioapic->ioregsel = 0;
ioapic->irr = 0;
ioapic->id = 0;
update_handled_vectors(ioapic);
}
static const struct kvm_io_device_ops ioapic_mmio_ops = {
.read = ioapic_mmio_read,
.write = ioapic_mmio_write,
};
int kvm_ioapic_init(struct kvm *kvm)
{
struct kvm_ioapic *ioapic;
int ret;
ioapic = kzalloc(sizeof(struct kvm_ioapic), GFP_KERNEL);
if (!ioapic)
return -ENOMEM;
spin_lock_init(&ioapic->lock);
kvm->arch.vioapic = ioapic;
kvm_ioapic_reset(ioapic);
kvm_iodevice_init(&ioapic->dev, &ioapic_mmio_ops);
ioapic->kvm = kvm;
mutex_lock(&kvm->slots_lock);
ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, ioapic->base_address,
IOAPIC_MEM_LENGTH, &ioapic->dev);
mutex_unlock(&kvm->slots_lock);
if (ret < 0) {
kvm->arch.vioapic = NULL;
kfree(ioapic);
}
return ret;
}
void kvm_ioapic_destroy(struct kvm *kvm)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
if (ioapic) {
kvm_io_bus_unregister_dev(kvm, KVM_MMIO_BUS, &ioapic->dev);
kvm->arch.vioapic = NULL;
kfree(ioapic);
}
}
int kvm_get_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state)
{
struct kvm_ioapic *ioapic = ioapic_irqchip(kvm);
if (!ioapic)
return -EINVAL;
spin_lock(&ioapic->lock);
memcpy(state, ioapic, sizeof(struct kvm_ioapic_state));
spin_unlock(&ioapic->lock);
return 0;
}
int kvm_set_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state)
{
struct kvm_ioapic *ioapic = ioapic_irqchip(kvm);
if (!ioapic)
return -EINVAL;
spin_lock(&ioapic->lock);
memcpy(ioapic, state, sizeof(struct kvm_ioapic_state));
update_handled_vectors(ioapic);
kvm_ioapic_make_eoibitmap_request(kvm);
spin_unlock(&ioapic->lock);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5595_0 |
crossvul-cpp_data_bad_3070_5 | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/ocsp.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/dh.h>
#include <openssl/bn.h>
#include "ssl_locl.h"
#include <openssl/ct.h>
#define CHECKLEN(curr, val, limit) \
(((curr) >= (limit)) || (size_t)((limit) - (curr)) < (size_t)(val))
static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
const unsigned char *sess_id, int sesslen,
SSL_SESSION **psess);
static int ssl_check_clienthello_tlsext_early(SSL *s);
static int ssl_check_serverhello_tlsext(SSL *s);
SSL3_ENC_METHOD const TLSv1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
0,
SSL3_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
ssl3_handshake_write
};
SSL3_ENC_METHOD const TLSv1_1_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
SSL_ENC_FLAG_EXPLICIT_IV,
SSL3_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
ssl3_handshake_write
};
SSL3_ENC_METHOD const TLSv1_2_enc_data = {
tls1_enc,
tls1_mac,
tls1_setup_key_block,
tls1_generate_master_secret,
tls1_change_cipher_state,
tls1_final_finish_mac,
TLS1_FINISH_MAC_LENGTH,
TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
tls1_alert_code,
tls1_export_keying_material,
SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
| SSL_ENC_FLAG_TLS1_2_CIPHERS,
SSL3_HM_HEADER_LENGTH,
ssl3_set_handshake_header,
ssl3_handshake_write
};
long tls1_default_timeout(void)
{
/*
* 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
* http, the cache would over fill
*/
return (60 * 60 * 2);
}
int tls1_new(SSL *s)
{
if (!ssl3_new(s))
return (0);
s->method->ssl_clear(s);
return (1);
}
void tls1_free(SSL *s)
{
OPENSSL_free(s->tlsext_session_ticket);
ssl3_free(s);
}
void tls1_clear(SSL *s)
{
ssl3_clear(s);
if (s->method->version == TLS_ANY_VERSION)
s->version = TLS_MAX_VERSION;
else
s->version = s->method->version;
}
#ifndef OPENSSL_NO_EC
typedef struct {
int nid; /* Curve NID */
int secbits; /* Bits of security (from SP800-57) */
unsigned int flags; /* Flags: currently just field type */
} tls_curve_info;
/*
* Table of curve information.
* Do not delete entries or reorder this array! It is used as a lookup
* table: the index of each entry is one less than the TLS curve id.
*/
static const tls_curve_info nid_list[] = {
{NID_sect163k1, 80, TLS_CURVE_CHAR2}, /* sect163k1 (1) */
{NID_sect163r1, 80, TLS_CURVE_CHAR2}, /* sect163r1 (2) */
{NID_sect163r2, 80, TLS_CURVE_CHAR2}, /* sect163r2 (3) */
{NID_sect193r1, 80, TLS_CURVE_CHAR2}, /* sect193r1 (4) */
{NID_sect193r2, 80, TLS_CURVE_CHAR2}, /* sect193r2 (5) */
{NID_sect233k1, 112, TLS_CURVE_CHAR2}, /* sect233k1 (6) */
{NID_sect233r1, 112, TLS_CURVE_CHAR2}, /* sect233r1 (7) */
{NID_sect239k1, 112, TLS_CURVE_CHAR2}, /* sect239k1 (8) */
{NID_sect283k1, 128, TLS_CURVE_CHAR2}, /* sect283k1 (9) */
{NID_sect283r1, 128, TLS_CURVE_CHAR2}, /* sect283r1 (10) */
{NID_sect409k1, 192, TLS_CURVE_CHAR2}, /* sect409k1 (11) */
{NID_sect409r1, 192, TLS_CURVE_CHAR2}, /* sect409r1 (12) */
{NID_sect571k1, 256, TLS_CURVE_CHAR2}, /* sect571k1 (13) */
{NID_sect571r1, 256, TLS_CURVE_CHAR2}, /* sect571r1 (14) */
{NID_secp160k1, 80, TLS_CURVE_PRIME}, /* secp160k1 (15) */
{NID_secp160r1, 80, TLS_CURVE_PRIME}, /* secp160r1 (16) */
{NID_secp160r2, 80, TLS_CURVE_PRIME}, /* secp160r2 (17) */
{NID_secp192k1, 80, TLS_CURVE_PRIME}, /* secp192k1 (18) */
{NID_X9_62_prime192v1, 80, TLS_CURVE_PRIME}, /* secp192r1 (19) */
{NID_secp224k1, 112, TLS_CURVE_PRIME}, /* secp224k1 (20) */
{NID_secp224r1, 112, TLS_CURVE_PRIME}, /* secp224r1 (21) */
{NID_secp256k1, 128, TLS_CURVE_PRIME}, /* secp256k1 (22) */
{NID_X9_62_prime256v1, 128, TLS_CURVE_PRIME}, /* secp256r1 (23) */
{NID_secp384r1, 192, TLS_CURVE_PRIME}, /* secp384r1 (24) */
{NID_secp521r1, 256, TLS_CURVE_PRIME}, /* secp521r1 (25) */
{NID_brainpoolP256r1, 128, TLS_CURVE_PRIME}, /* brainpoolP256r1 (26) */
{NID_brainpoolP384r1, 192, TLS_CURVE_PRIME}, /* brainpoolP384r1 (27) */
{NID_brainpoolP512r1, 256, TLS_CURVE_PRIME}, /* brainpool512r1 (28) */
{NID_X25519, 128, TLS_CURVE_CUSTOM}, /* X25519 (29) */
};
static const unsigned char ecformats_default[] = {
TLSEXT_ECPOINTFORMAT_uncompressed,
TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
};
/* The default curves */
static const unsigned char eccurves_default[] = {
0, 29, /* X25519 (29) */
0, 23, /* secp256r1 (23) */
0, 25, /* secp521r1 (25) */
0, 24, /* secp384r1 (24) */
};
static const unsigned char suiteb_curves[] = {
0, TLSEXT_curve_P_256,
0, TLSEXT_curve_P_384
};
int tls1_ec_curve_id2nid(int curve_id, unsigned int *pflags)
{
const tls_curve_info *cinfo;
/* ECC curves from RFC 4492 and RFC 7027 */
if ((curve_id < 1) || ((unsigned int)curve_id > OSSL_NELEM(nid_list)))
return 0;
cinfo = nid_list + curve_id - 1;
if (pflags)
*pflags = cinfo->flags;
return cinfo->nid;
}
int tls1_ec_nid2curve_id(int nid)
{
size_t i;
for (i = 0; i < OSSL_NELEM(nid_list); i++) {
if (nid_list[i].nid == nid)
return i + 1;
}
return 0;
}
/*
* Get curves list, if "sess" is set return client curves otherwise
* preferred list.
* Sets |num_curves| to the number of curves in the list, i.e.,
* the length of |pcurves| is 2 * num_curves.
* Returns 1 on success and 0 if the client curves list has invalid format.
* The latter indicates an internal error: we should not be accepting such
* lists in the first place.
* TODO(emilia): we should really be storing the curves list in explicitly
* parsed form instead. (However, this would affect binary compatibility
* so cannot happen in the 1.0.x series.)
*/
static int tls1_get_curvelist(SSL *s, int sess,
const unsigned char **pcurves, size_t *num_curves)
{
size_t pcurveslen = 0;
if (sess) {
*pcurves = s->session->tlsext_ellipticcurvelist;
pcurveslen = s->session->tlsext_ellipticcurvelist_length;
} else {
/* For Suite B mode only include P-256, P-384 */
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*pcurves = suiteb_curves;
pcurveslen = sizeof(suiteb_curves);
break;
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*pcurves = suiteb_curves;
pcurveslen = 2;
break;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*pcurves = suiteb_curves + 2;
pcurveslen = 2;
break;
default:
*pcurves = s->tlsext_ellipticcurvelist;
pcurveslen = s->tlsext_ellipticcurvelist_length;
}
if (!*pcurves) {
*pcurves = eccurves_default;
pcurveslen = sizeof(eccurves_default);
}
}
/* We do not allow odd length arrays to enter the system. */
if (pcurveslen & 1) {
SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
*num_curves = 0;
return 0;
}
*num_curves = pcurveslen / 2;
return 1;
}
/* See if curve is allowed by security callback */
static int tls_curve_allowed(SSL *s, const unsigned char *curve, int op)
{
const tls_curve_info *cinfo;
if (curve[0])
return 1;
if ((curve[1] < 1) || ((size_t)curve[1] > OSSL_NELEM(nid_list)))
return 0;
cinfo = &nid_list[curve[1] - 1];
# ifdef OPENSSL_NO_EC2M
if (cinfo->flags & TLS_CURVE_CHAR2)
return 0;
# endif
return ssl_security(s, op, cinfo->secbits, cinfo->nid, (void *)curve);
}
/* Check a curve is one of our preferences */
int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
{
const unsigned char *curves;
size_t num_curves, i;
unsigned int suiteb_flags = tls1_suiteb(s);
if (len != 3 || p[0] != NAMED_CURVE_TYPE)
return 0;
/* Check curve matches Suite B preferences */
if (suiteb_flags) {
unsigned long cid = s->s3->tmp.new_cipher->id;
if (p[1])
return 0;
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
if (p[2] != TLSEXT_curve_P_256)
return 0;
} else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
if (p[2] != TLSEXT_curve_P_384)
return 0;
} else /* Should never happen */
return 0;
}
if (!tls1_get_curvelist(s, 0, &curves, &num_curves))
return 0;
for (i = 0; i < num_curves; i++, curves += 2) {
if (p[1] == curves[0] && p[2] == curves[1])
return tls_curve_allowed(s, p + 1, SSL_SECOP_CURVE_CHECK);
}
return 0;
}
/*-
* For nmatch >= 0, return the NID of the |nmatch|th shared curve or NID_undef
* if there is no match.
* For nmatch == -1, return number of matches
* For nmatch == -2, return the NID of the curve to use for
* an EC tmp key, or NID_undef if there is no match.
*/
int tls1_shared_curve(SSL *s, int nmatch)
{
const unsigned char *pref, *supp;
size_t num_pref, num_supp, i, j;
int k;
/* Can't do anything on client side */
if (s->server == 0)
return -1;
if (nmatch == -2) {
if (tls1_suiteb(s)) {
/*
* For Suite B ciphersuite determines curve: we already know
* these are acceptable due to previous checks.
*/
unsigned long cid = s->s3->tmp.new_cipher->id;
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
return NID_X9_62_prime256v1; /* P-256 */
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
return NID_secp384r1; /* P-384 */
/* Should never happen */
return NID_undef;
}
/* If not Suite B just return first preference shared curve */
nmatch = 0;
}
/*
* Avoid truncation. tls1_get_curvelist takes an int
* but s->options is a long...
*/
if (!tls1_get_curvelist(s,
(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0,
&supp, &num_supp))
/* In practice, NID_undef == 0 but let's be precise. */
return nmatch == -1 ? 0 : NID_undef;
if (!tls1_get_curvelist(s,
(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0,
&pref, &num_pref))
return nmatch == -1 ? 0 : NID_undef;
for (k = 0, i = 0; i < num_pref; i++, pref += 2) {
const unsigned char *tsupp = supp;
for (j = 0; j < num_supp; j++, tsupp += 2) {
if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) {
if (!tls_curve_allowed(s, pref, SSL_SECOP_CURVE_SHARED))
continue;
if (nmatch == k) {
int id = (pref[0] << 8) | pref[1];
return tls1_ec_curve_id2nid(id, NULL);
}
k++;
}
}
}
if (nmatch == -1)
return k;
/* Out of range (nmatch > k). */
return NID_undef;
}
int tls1_set_curves(unsigned char **pext, size_t *pextlen,
int *curves, size_t ncurves)
{
unsigned char *clist, *p;
size_t i;
/*
* Bitmap of curves included to detect duplicates: only works while curve
* ids < 32
*/
unsigned long dup_list = 0;
clist = OPENSSL_malloc(ncurves * 2);
if (clist == NULL)
return 0;
for (i = 0, p = clist; i < ncurves; i++) {
unsigned long idmask;
int id;
id = tls1_ec_nid2curve_id(curves[i]);
idmask = 1L << id;
if (!id || (dup_list & idmask)) {
OPENSSL_free(clist);
return 0;
}
dup_list |= idmask;
s2n(id, p);
}
OPENSSL_free(*pext);
*pext = clist;
*pextlen = ncurves * 2;
return 1;
}
# define MAX_CURVELIST 28
typedef struct {
size_t nidcnt;
int nid_arr[MAX_CURVELIST];
} nid_cb_st;
static int nid_cb(const char *elem, int len, void *arg)
{
nid_cb_st *narg = arg;
size_t i;
int nid;
char etmp[20];
if (elem == NULL)
return 0;
if (narg->nidcnt == MAX_CURVELIST)
return 0;
if (len > (int)(sizeof(etmp) - 1))
return 0;
memcpy(etmp, elem, len);
etmp[len] = 0;
nid = EC_curve_nist2nid(etmp);
if (nid == NID_undef)
nid = OBJ_sn2nid(etmp);
if (nid == NID_undef)
nid = OBJ_ln2nid(etmp);
if (nid == NID_undef)
return 0;
for (i = 0; i < narg->nidcnt; i++)
if (narg->nid_arr[i] == nid)
return 0;
narg->nid_arr[narg->nidcnt++] = nid;
return 1;
}
/* Set curves based on a colon separate list */
int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, const char *str)
{
nid_cb_st ncb;
ncb.nidcnt = 0;
if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
return 0;
if (pext == NULL)
return 1;
return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
}
/* For an EC key set TLS id and required compression based on parameters */
static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
EC_KEY *ec)
{
int id;
const EC_GROUP *grp;
if (!ec)
return 0;
/* Determine if it is a prime field */
grp = EC_KEY_get0_group(ec);
if (!grp)
return 0;
/* Determine curve ID */
id = EC_GROUP_get_curve_name(grp);
id = tls1_ec_nid2curve_id(id);
/* If no id return error: we don't support arbitrary explicit curves */
if (id == 0)
return 0;
curve_id[0] = 0;
curve_id[1] = (unsigned char)id;
if (comp_id) {
if (EC_KEY_get0_public_key(ec) == NULL)
return 0;
if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_UNCOMPRESSED) {
*comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
} else {
if ((nid_list[id - 1].flags & TLS_CURVE_TYPE) == TLS_CURVE_PRIME)
*comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
else
*comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
}
}
return 1;
}
/* Check an EC key is compatible with extensions */
static int tls1_check_ec_key(SSL *s,
unsigned char *curve_id, unsigned char *comp_id)
{
const unsigned char *pformats, *pcurves;
size_t num_formats, num_curves, i;
int j;
/*
* If point formats extension present check it, otherwise everything is
* supported (see RFC4492).
*/
if (comp_id && s->session->tlsext_ecpointformatlist) {
pformats = s->session->tlsext_ecpointformatlist;
num_formats = s->session->tlsext_ecpointformatlist_length;
for (i = 0; i < num_formats; i++, pformats++) {
if (*comp_id == *pformats)
break;
}
if (i == num_formats)
return 0;
}
if (!curve_id)
return 1;
/* Check curve is consistent with client and server preferences */
for (j = 0; j <= 1; j++) {
if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
return 0;
if (j == 1 && num_curves == 0) {
/*
* If we've not received any curves then skip this check.
* RFC 4492 does not require the supported elliptic curves extension
* so if it is not sent we can just choose any curve.
* It is invalid to send an empty list in the elliptic curves
* extension, so num_curves == 0 always means no extension.
*/
break;
}
for (i = 0; i < num_curves; i++, pcurves += 2) {
if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1])
break;
}
if (i == num_curves)
return 0;
/* For clients can only check sent curve list */
if (!s->server)
break;
}
return 1;
}
static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
size_t *num_formats)
{
/*
* If we have a custom point format list use it otherwise use default
*/
if (s->tlsext_ecpointformatlist) {
*pformats = s->tlsext_ecpointformatlist;
*num_formats = s->tlsext_ecpointformatlist_length;
} else {
*pformats = ecformats_default;
/* For Suite B we don't support char2 fields */
if (tls1_suiteb(s))
*num_formats = sizeof(ecformats_default) - 1;
else
*num_formats = sizeof(ecformats_default);
}
}
/*
* Check cert parameters compatible with extensions: currently just checks EC
* certificates have compatible curves and compression.
*/
static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
{
unsigned char comp_id, curve_id[2];
EVP_PKEY *pkey;
int rv;
pkey = X509_get0_pubkey(x);
if (!pkey)
return 0;
/* If not EC nothing to do */
if (EVP_PKEY_id(pkey) != EVP_PKEY_EC)
return 1;
rv = tls1_set_ec_id(curve_id, &comp_id, EVP_PKEY_get0_EC_KEY(pkey));
if (!rv)
return 0;
/*
* Can't check curve_id for client certs as we don't have a supported
* curves extension.
*/
rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
if (!rv)
return 0;
/*
* Special case for suite B. We *MUST* sign using SHA256+P-256 or
* SHA384+P-384, adjust digest if necessary.
*/
if (set_ee_md && tls1_suiteb(s)) {
int check_md;
size_t i;
CERT *c = s->cert;
if (curve_id[0])
return 0;
/* Check to see we have necessary signing algorithm */
if (curve_id[1] == TLSEXT_curve_P_256)
check_md = NID_ecdsa_with_SHA256;
else if (curve_id[1] == TLSEXT_curve_P_384)
check_md = NID_ecdsa_with_SHA384;
else
return 0; /* Should never happen */
for (i = 0; i < c->shared_sigalgslen; i++)
if (check_md == c->shared_sigalgs[i].signandhash_nid)
break;
if (i == c->shared_sigalgslen)
return 0;
if (set_ee_md == 2) {
if (check_md == NID_ecdsa_with_SHA256)
s->s3->tmp.md[SSL_PKEY_ECC] = EVP_sha256();
else
s->s3->tmp.md[SSL_PKEY_ECC] = EVP_sha384();
}
}
return rv;
}
# ifndef OPENSSL_NO_EC
/*
* tls1_check_ec_tmp_key - Check EC temporary key compatibility
* @s: SSL connection
* @cid: Cipher ID we're considering using
*
* Checks that the kECDHE cipher suite we're considering using
* is compatible with the client extensions.
*
* Returns 0 when the cipher can't be used or 1 when it can.
*/
int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
{
/*
* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
* curves permitted.
*/
if (tls1_suiteb(s)) {
unsigned char curve_id[2];
/* Curve to check determined by ciphersuite */
if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
curve_id[1] = TLSEXT_curve_P_256;
else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
curve_id[1] = TLSEXT_curve_P_384;
else
return 0;
curve_id[0] = 0;
/* Check this curve is acceptable */
if (!tls1_check_ec_key(s, curve_id, NULL))
return 0;
return 1;
}
/* Need a shared curve */
if (tls1_shared_curve(s, 0))
return 1;
return 0;
}
# endif /* OPENSSL_NO_EC */
#else
static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
{
return 1;
}
#endif /* OPENSSL_NO_EC */
/*
* List of supported signature algorithms and hashes. Should make this
* customisable at some point, for now include everything we support.
*/
#ifdef OPENSSL_NO_RSA
# define tlsext_sigalg_rsa(md) /* */
#else
# define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
#endif
#ifdef OPENSSL_NO_DSA
# define tlsext_sigalg_dsa(md) /* */
#else
# define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
#endif
#ifdef OPENSSL_NO_EC
# define tlsext_sigalg_ecdsa(md)/* */
#else
# define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
#endif
#define tlsext_sigalg(md) \
tlsext_sigalg_rsa(md) \
tlsext_sigalg_dsa(md) \
tlsext_sigalg_ecdsa(md)
static const unsigned char tls12_sigalgs[] = {
tlsext_sigalg(TLSEXT_hash_sha512)
tlsext_sigalg(TLSEXT_hash_sha384)
tlsext_sigalg(TLSEXT_hash_sha256)
tlsext_sigalg(TLSEXT_hash_sha224)
tlsext_sigalg(TLSEXT_hash_sha1)
#ifndef OPENSSL_NO_GOST
TLSEXT_hash_gostr3411, TLSEXT_signature_gostr34102001,
TLSEXT_hash_gostr34112012_256, TLSEXT_signature_gostr34102012_256,
TLSEXT_hash_gostr34112012_512, TLSEXT_signature_gostr34102012_512
#endif
};
#ifndef OPENSSL_NO_EC
static const unsigned char suiteb_sigalgs[] = {
tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
};
#endif
size_t tls12_get_psigalgs(SSL *s, int sent, const unsigned char **psigs)
{
/*
* If Suite B mode use Suite B sigalgs only, ignore any other
* preferences.
*/
#ifndef OPENSSL_NO_EC
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*psigs = suiteb_sigalgs;
return sizeof(suiteb_sigalgs);
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*psigs = suiteb_sigalgs;
return 2;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*psigs = suiteb_sigalgs + 2;
return 2;
}
#endif
/* If server use client authentication sigalgs if not NULL */
if (s->server == sent && s->cert->client_sigalgs) {
*psigs = s->cert->client_sigalgs;
return s->cert->client_sigalgslen;
} else if (s->cert->conf_sigalgs) {
*psigs = s->cert->conf_sigalgs;
return s->cert->conf_sigalgslen;
} else {
*psigs = tls12_sigalgs;
return sizeof(tls12_sigalgs);
}
}
/*
* Check signature algorithm is consistent with sent supported signature
* algorithms and if so return relevant digest.
*/
int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
const unsigned char *sig, EVP_PKEY *pkey)
{
const unsigned char *sent_sigs;
size_t sent_sigslen, i;
int sigalg = tls12_get_sigid(pkey);
/* Should never happen */
if (sigalg == -1)
return -1;
/* Check key type is consistent with signature */
if (sigalg != (int)sig[1]) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
#ifndef OPENSSL_NO_EC
if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
unsigned char curve_id[2], comp_id;
/* Check compression and curve matches extensions */
if (!tls1_set_ec_id(curve_id, &comp_id, EVP_PKEY_get0_EC_KEY(pkey)))
return 0;
if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
return 0;
}
/* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
if (tls1_suiteb(s)) {
if (curve_id[0])
return 0;
if (curve_id[1] == TLSEXT_curve_P_256) {
if (sig[0] != TLSEXT_hash_sha256) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
SSL_R_ILLEGAL_SUITEB_DIGEST);
return 0;
}
} else if (curve_id[1] == TLSEXT_curve_P_384) {
if (sig[0] != TLSEXT_hash_sha384) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
SSL_R_ILLEGAL_SUITEB_DIGEST);
return 0;
}
} else
return 0;
}
} else if (tls1_suiteb(s))
return 0;
#endif
/* Check signature matches a type we sent */
sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
break;
}
/* Allow fallback to SHA1 if not strict mode */
if (i == sent_sigslen
&& (sig[0] != TLSEXT_hash_sha1
|| s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
*pmd = tls12_get_hash(sig[0]);
if (*pmd == NULL) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST);
return 0;
}
/* Make sure security callback allows algorithm */
if (!ssl_security(s, SSL_SECOP_SIGALG_CHECK,
EVP_MD_size(*pmd) * 4, EVP_MD_type(*pmd), (void *)sig)) {
SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
return 0;
}
/*
* Store the digest used so applications can retrieve it if they wish.
*/
s->s3->tmp.peer_md = *pmd;
return 1;
}
/*
* Set a mask of disabled algorithms: an algorithm is disabled if it isn't
* supported, doesn't appear in supported signature algorithms, isn't supported
* by the enabled protocol versions or by the security level.
*
* This function should only be used for checking which ciphers are supported
* by the client.
*
* Call ssl_cipher_disabled() to check that it's enabled or not.
*/
void ssl_set_client_disabled(SSL *s)
{
s->s3->tmp.mask_a = 0;
s->s3->tmp.mask_k = 0;
ssl_set_sig_mask(&s->s3->tmp.mask_a, s, SSL_SECOP_SIGALG_MASK);
ssl_get_client_min_max_version(s, &s->s3->tmp.min_ver, &s->s3->tmp.max_ver);
#ifndef OPENSSL_NO_PSK
/* with PSK there must be client callback set */
if (!s->psk_client_callback) {
s->s3->tmp.mask_a |= SSL_aPSK;
s->s3->tmp.mask_k |= SSL_PSK;
}
#endif /* OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
s->s3->tmp.mask_a |= SSL_aSRP;
s->s3->tmp.mask_k |= SSL_kSRP;
}
#endif
}
/*
* ssl_cipher_disabled - check that a cipher is disabled or not
* @s: SSL connection that you want to use the cipher on
* @c: cipher to check
* @op: Security check that you want to do
*
* Returns 1 when it's disabled, 0 when enabled.
*/
int ssl_cipher_disabled(SSL *s, const SSL_CIPHER *c, int op)
{
if (c->algorithm_mkey & s->s3->tmp.mask_k
|| c->algorithm_auth & s->s3->tmp.mask_a)
return 1;
if (s->s3->tmp.max_ver == 0)
return 1;
if (!SSL_IS_DTLS(s) && ((c->min_tls > s->s3->tmp.max_ver)
|| (c->max_tls < s->s3->tmp.min_ver)))
return 1;
if (SSL_IS_DTLS(s) && (DTLS_VERSION_GT(c->min_dtls, s->s3->tmp.max_ver)
|| DTLS_VERSION_LT(c->max_dtls, s->s3->tmp.min_ver)))
return 1;
return !ssl_security(s, op, c->strength_bits, 0, (void *)c);
}
static int tls_use_ticket(SSL *s)
{
if (s->options & SSL_OP_NO_TICKET)
return 0;
return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL);
}
static int compare_uint(const void *p1, const void *p2)
{
unsigned int u1 = *((const unsigned int *)p1);
unsigned int u2 = *((const unsigned int *)p2);
if (u1 < u2)
return -1;
else if (u1 > u2)
return 1;
else
return 0;
}
/*
* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
* more than one extension of the same type in a ClientHello or ServerHello.
* This function does an initial scan over the extensions block to filter those
* out. It returns 1 if all extensions are unique, and 0 if the extensions
* contain duplicates, could not be successfully parsed, or an internal error
* occurred.
*/
static int tls1_check_duplicate_extensions(const PACKET *packet)
{
PACKET extensions = *packet;
size_t num_extensions = 0, i = 0;
unsigned int *extension_types = NULL;
int ret = 0;
/* First pass: count the extensions. */
while (PACKET_remaining(&extensions) > 0) {
unsigned int type;
PACKET extension;
if (!PACKET_get_net_2(&extensions, &type) ||
!PACKET_get_length_prefixed_2(&extensions, &extension)) {
goto done;
}
num_extensions++;
}
if (num_extensions <= 1)
return 1;
extension_types = OPENSSL_malloc(sizeof(unsigned int) * num_extensions);
if (extension_types == NULL) {
SSLerr(SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS, ERR_R_MALLOC_FAILURE);
goto done;
}
/* Second pass: gather the extension types. */
extensions = *packet;
for (i = 0; i < num_extensions; i++) {
PACKET extension;
if (!PACKET_get_net_2(&extensions, &extension_types[i]) ||
!PACKET_get_length_prefixed_2(&extensions, &extension)) {
/* This should not happen. */
SSLerr(SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS, ERR_R_INTERNAL_ERROR);
goto done;
}
}
if (PACKET_remaining(&extensions) != 0) {
SSLerr(SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS, ERR_R_INTERNAL_ERROR);
goto done;
}
/* Sort the extensions and make sure there are no duplicates. */
qsort(extension_types, num_extensions, sizeof(unsigned int), compare_uint);
for (i = 1; i < num_extensions; i++) {
if (extension_types[i - 1] == extension_types[i])
goto done;
}
ret = 1;
done:
OPENSSL_free(extension_types);
return ret;
}
unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf,
unsigned char *limit, int *al)
{
int extdatalen = 0;
unsigned char *orig = buf;
unsigned char *ret = buf;
#ifndef OPENSSL_NO_EC
/* See if we support any ECC ciphersuites */
int using_ecc = 0;
if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) {
int i;
unsigned long alg_k, alg_a;
STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
const SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
alg_k = c->algorithm_mkey;
alg_a = c->algorithm_auth;
if ((alg_k & (SSL_kECDHE | SSL_kECDHEPSK))
|| (alg_a & SSL_aECDSA)) {
using_ecc = 1;
break;
}
}
}
#endif
ret += 2;
if (ret >= limit)
return NULL; /* this really never occurs, but ... */
/* Add RI if renegotiating */
if (s->renegotiate) {
int el;
if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_renegotiate, ret);
s2n(el, ret);
if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
/* Only add RI for SSLv3 */
if (s->client_version == SSL3_VERSION)
goto done;
if (s->tlsext_hostname != NULL) {
/* Add TLS extension servername to the Client Hello message */
size_t size_str;
/*-
* check for enough space.
* 4 for the servername type and extension length
* 2 for servernamelist length
* 1 for the hostname type
* 2 for hostname length
* + hostname length
*/
size_str = strlen(s->tlsext_hostname);
if (CHECKLEN(ret, 9 + size_str, limit))
return NULL;
/* extension type and length */
s2n(TLSEXT_TYPE_server_name, ret);
s2n(size_str + 5, ret);
/* length of servername list */
s2n(size_str + 3, ret);
/* hostname type, length and hostname */
*(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name;
s2n(size_str, ret);
memcpy(ret, s->tlsext_hostname, size_str);
ret += size_str;
}
#ifndef OPENSSL_NO_SRP
/* Add SRP username if there is one */
if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the
* Client Hello message */
size_t login_len = strlen(s->srp_ctx.login);
if (login_len > 255 || login_len == 0) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 for the srp type type and extension length
* 1 for the srp user identity
* + srp user identity length
*/
if (CHECKLEN(ret, 5 + login_len, limit))
return NULL;
/* fill in the extension */
s2n(TLSEXT_TYPE_srp, ret);
s2n(login_len + 1, ret);
(*ret++) = (unsigned char)login_len;
memcpy(ret, s->srp_ctx.login, login_len);
ret += login_len;
}
#endif
#ifndef OPENSSL_NO_EC
if (using_ecc) {
/*
* Add TLS extension ECPointFormats to the ClientHello message
*/
const unsigned char *pcurves, *pformats;
size_t num_curves, num_formats, curves_list_len;
size_t i;
unsigned char *etmp;
tls1_get_formatlist(s, &pformats, &num_formats);
if (num_formats > 255) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the ec point formats type and extension length
* 1 byte for the length of the formats
* + formats length
*/
if (CHECKLEN(ret, 5 + num_formats, limit))
return NULL;
s2n(TLSEXT_TYPE_ec_point_formats, ret);
/* The point format list has 1-byte length. */
s2n(num_formats + 1, ret);
*(ret++) = (unsigned char)num_formats;
memcpy(ret, pformats, num_formats);
ret += num_formats;
/*
* Add TLS extension EllipticCurves to the ClientHello message
*/
pcurves = s->tlsext_ellipticcurvelist;
if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
return NULL;
if (num_curves > 65532 / 2) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the ec curves type and extension length
* 2 bytes for the curve list length
* + curve list length
*/
if (CHECKLEN(ret, 6 + (num_curves * 2), limit))
return NULL;
s2n(TLSEXT_TYPE_elliptic_curves, ret);
etmp = ret + 4;
/* Copy curve ID if supported */
for (i = 0; i < num_curves; i++, pcurves += 2) {
if (tls_curve_allowed(s, pcurves, SSL_SECOP_CURVE_SUPPORTED)) {
*etmp++ = pcurves[0];
*etmp++ = pcurves[1];
}
}
curves_list_len = etmp - ret - 4;
s2n(curves_list_len + 2, ret);
s2n(curves_list_len, ret);
ret += curves_list_len;
}
#endif /* OPENSSL_NO_EC */
if (tls_use_ticket(s)) {
size_t ticklen;
if (!s->new_session && s->session && s->session->tlsext_tick)
ticklen = s->session->tlsext_ticklen;
else if (s->session && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data) {
ticklen = s->tlsext_session_ticket->length;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (s->session->tlsext_tick == NULL)
return NULL;
memcpy(s->session->tlsext_tick,
s->tlsext_session_ticket->data, ticklen);
s->session->tlsext_ticklen = ticklen;
} else
ticklen = 0;
if (ticklen == 0 && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data == NULL)
goto skip_ext;
/*
* Check for enough room 2 for extension type, 2 for len rest for
* ticket
*/
if (CHECKLEN(ret, 4 + ticklen, limit))
return NULL;
s2n(TLSEXT_TYPE_session_ticket, ret);
s2n(ticklen, ret);
if (ticklen > 0) {
memcpy(ret, s->session->tlsext_tick, ticklen);
ret += ticklen;
}
}
skip_ext:
if (SSL_CLIENT_USE_SIGALGS(s)) {
size_t salglen;
const unsigned char *salg;
unsigned char *etmp;
salglen = tls12_get_psigalgs(s, 1, &salg);
/*-
* check for enough space.
* 4 bytes for the sigalgs type and extension length
* 2 bytes for the sigalg list length
* + sigalg list length
*/
if (CHECKLEN(ret, salglen + 6, limit))
return NULL;
s2n(TLSEXT_TYPE_signature_algorithms, ret);
etmp = ret;
/* Skip over lengths for now */
ret += 4;
salglen = tls12_copy_sigalgs(s, ret, salg, salglen);
/* Fill in lengths */
s2n(salglen + 2, etmp);
s2n(salglen, etmp);
ret += salglen;
}
#ifndef OPENSSL_NO_OCSP
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
int i;
size_t extlen, idlen;
int lentmp;
OCSP_RESPID *id;
idlen = 0;
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
lentmp = i2d_OCSP_RESPID(id, NULL);
if (lentmp <= 0)
return NULL;
idlen += (size_t)lentmp + 2;
}
if (s->tlsext_ocsp_exts) {
lentmp = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
if (lentmp < 0)
return NULL;
extlen = (size_t)lentmp;
} else
extlen = 0;
if (extlen + idlen > 0xFFF0)
return NULL;
/*
* 2 bytes for status request type
* 2 bytes for status request len
* 1 byte for OCSP request type
* 2 bytes for length of ids
* 2 bytes for length of extensions
* + length of ids
* + length of extensions
*/
if (CHECKLEN(ret, 9 + idlen + extlen, limit))
return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
s2n(extlen + idlen + 5, ret);
*(ret++) = TLSEXT_STATUSTYPE_ocsp;
s2n(idlen, ret);
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
/* save position of id len */
unsigned char *q = ret;
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
/* skip over id len */
ret += 2;
lentmp = i2d_OCSP_RESPID(id, &ret);
/* write id len */
s2n(lentmp, q);
}
s2n(extlen, ret);
if (extlen > 0)
i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
}
#endif
#ifndef OPENSSL_NO_HEARTBEATS
if (SSL_IS_DTLS(s)) {
/* Add Heartbeat extension */
/*-
* check for enough space.
* 4 bytes for the heartbeat ext type and extension length
* 1 byte for the mode
*/
if (CHECKLEN(ret, 5, limit))
return NULL;
s2n(TLSEXT_TYPE_heartbeat, ret);
s2n(1, ret);
/*-
* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_DTLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_DTLSEXT_HB_ENABLED;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
/*
* The client advertises an empty extension to indicate its support
* for Next Protocol Negotiation
*/
/*-
* check for enough space.
* 4 bytes for the NPN ext type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg, ret);
s2n(0, ret);
}
#endif
/*
* finish_md_len is non-zero during a renegotiation, so
* this avoids sending ALPN during the renegotiation
* (see longer comment below)
*/
if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
/*-
* check for enough space.
* 4 bytes for the ALPN type and extension length
* 2 bytes for the ALPN protocol list length
* + ALPN protocol list length
*/
if (CHECKLEN(ret, 6 + s->alpn_client_proto_list_len, limit))
return NULL;
s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
s2n(2 + s->alpn_client_proto_list_len, ret);
s2n(s->alpn_client_proto_list_len, ret);
memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
ret += s->alpn_client_proto_list_len;
s->s3->alpn_sent = 1;
}
#ifndef OPENSSL_NO_SRTP
if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
int el;
/* Returns 0 on success!! */
if (ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the SRTP type and extension length
* + SRTP profiles length
*/
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_use_srtp, ret);
s2n(el, ret);
if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#endif
custom_ext_init(&s->cert->cli_ext);
/* Add custom TLS Extensions to ClientHello */
if (!custom_ext_add(s, 0, &ret, limit, al))
return NULL;
/*
* In 1.1.0 before 1.1.0c we negotiated EtM with DTLS, then just
* silently failed to actually do it. It is fixed in 1.1.1 but to
* ease the transition especially from 1.1.0b to 1.1.0c, we just
* disable it in 1.1.0.
*/
if (!SSL_IS_DTLS(s)) {
/*-
* check for enough space.
* 4 bytes for the ETM type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_encrypt_then_mac, ret);
s2n(0, ret);
}
#ifndef OPENSSL_NO_CT
if (s->ct_validation_callback != NULL) {
/*-
* check for enough space.
* 4 bytes for the SCT type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_signed_certificate_timestamp, ret);
s2n(0, ret);
}
#endif
/*-
* check for enough space.
* 4 bytes for the EMS type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_extended_master_secret, ret);
s2n(0, ret);
/*
* Add padding to workaround bugs in F5 terminators. See
* https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
* code works out the length of all existing extensions it MUST always
* appear last.
*/
if (s->options & SSL_OP_TLSEXT_PADDING) {
int hlen = ret - (unsigned char *)s->init_buf->data;
if (hlen > 0xff && hlen < 0x200) {
hlen = 0x200 - hlen;
if (hlen >= 4)
hlen -= 4;
else
hlen = 0;
/*-
* check for enough space. Strictly speaking we know we've already
* got enough space because to get here the message size is < 0x200,
* but we know that we've allocated far more than that in the buffer
* - but for consistency and robustness we're going to check anyway.
*
* 4 bytes for the padding type and extension length
* + padding length
*/
if (CHECKLEN(ret, 4 + hlen, limit))
return NULL;
s2n(TLSEXT_TYPE_padding, ret);
s2n(hlen, ret);
memset(ret, 0, hlen);
ret += hlen;
}
}
done:
if ((extdatalen = ret - orig - 2) == 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
unsigned char *limit, int *al)
{
int extdatalen = 0;
unsigned char *orig = buf;
unsigned char *ret = buf;
#ifndef OPENSSL_NO_NEXTPROTONEG
int next_proto_neg_seen;
#endif
#ifndef OPENSSL_NO_EC
unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
int using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
#endif
ret += 2;
if (ret >= limit)
return NULL; /* this really never occurs, but ... */
if (s->s3->send_connection_binding) {
int el;
if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the reneg type and extension length
* + reneg data length
*/
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_renegotiate, ret);
s2n(el, ret);
if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
/* Only add RI for SSLv3 */
if (s->version == SSL3_VERSION)
goto done;
if (!s->hit && s->servername_done == 1
&& s->session->tlsext_hostname != NULL) {
/*-
* check for enough space.
* 4 bytes for the server name type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_server_name, ret);
s2n(0, ret);
}
#ifndef OPENSSL_NO_EC
if (using_ecc) {
const unsigned char *plist;
size_t plistlen;
/*
* Add TLS extension ECPointFormats to the ServerHello message
*/
tls1_get_formatlist(s, &plist, &plistlen);
if (plistlen > 255) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the ec points format type and extension length
* 1 byte for the points format list length
* + length of points format list
*/
if (CHECKLEN(ret, 5 + plistlen, limit))
return NULL;
s2n(TLSEXT_TYPE_ec_point_formats, ret);
s2n(plistlen + 1, ret);
*(ret++) = (unsigned char)plistlen;
memcpy(ret, plist, plistlen);
ret += plistlen;
}
/*
* Currently the server should not respond with a SupportedCurves
* extension
*/
#endif /* OPENSSL_NO_EC */
if (s->tlsext_ticket_expected && tls_use_ticket(s)) {
/*-
* check for enough space.
* 4 bytes for the Ticket type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_session_ticket, ret);
s2n(0, ret);
} else {
/*
* if we don't add the above TLSEXT, we can't add a session ticket
* later
*/
s->tlsext_ticket_expected = 0;
}
if (s->tlsext_status_expected) {
/*-
* check for enough space.
* 4 bytes for the Status request type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
s2n(0, ret);
}
#ifndef OPENSSL_NO_SRTP
if (SSL_IS_DTLS(s) && s->srtp_profile) {
int el;
/* Returns 0 on success!! */
if (ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/*-
* check for enough space.
* 4 bytes for the SRTP profiles type and extension length
* + length of the SRTP profiles list
*/
if (CHECKLEN(ret, 4 + el, limit))
return NULL;
s2n(TLSEXT_TYPE_use_srtp, ret);
s2n(el, ret);
if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#endif
if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80
|| (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)
&& (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {
const unsigned char cryptopro_ext[36] = {
0xfd, 0xe8, /* 65000 */
0x00, 0x20, /* 32 bytes length */
0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
};
/* check for enough space. */
if (CHECKLEN(ret, sizeof(cryptopro_ext), limit))
return NULL;
memcpy(ret, cryptopro_ext, sizeof(cryptopro_ext));
ret += sizeof(cryptopro_ext);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* Add Heartbeat extension if we've received one */
if (SSL_IS_DTLS(s) && (s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED)) {
/*-
* check for enough space.
* 4 bytes for the Heartbeat type and extension length
* 1 byte for the mode
*/
if (CHECKLEN(ret, 5, limit))
return NULL;
s2n(TLSEXT_TYPE_heartbeat, ret);
s2n(1, ret);
/*-
* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_DTLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_DTLSEXT_HB_ENABLED;
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
next_proto_neg_seen = s->s3->next_proto_neg_seen;
s->s3->next_proto_neg_seen = 0;
if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
const unsigned char *npa;
unsigned int npalen;
int r;
r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
s->
ctx->next_protos_advertised_cb_arg);
if (r == SSL_TLSEXT_ERR_OK) {
/*-
* check for enough space.
* 4 bytes for the NPN type and extension length
* + length of protocols list
*/
if (CHECKLEN(ret, 4 + npalen, limit))
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg, ret);
s2n(npalen, ret);
memcpy(ret, npa, npalen);
ret += npalen;
s->s3->next_proto_neg_seen = 1;
}
}
#endif
if (!custom_ext_add(s, 1, &ret, limit, al))
return NULL;
if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) {
/*
* Don't use encrypt_then_mac if AEAD or RC4 might want to disable
* for other cases too.
*/
if (SSL_IS_DTLS(s) || s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
|| s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4
|| s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
|| s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12)
s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
else {
/*-
* check for enough space.
* 4 bytes for the ETM type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_encrypt_then_mac, ret);
s2n(0, ret);
}
}
if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) {
/*-
* check for enough space.
* 4 bytes for the EMS type and extension length
*/
if (CHECKLEN(ret, 4, limit))
return NULL;
s2n(TLSEXT_TYPE_extended_master_secret, ret);
s2n(0, ret);
}
if (s->s3->alpn_selected != NULL) {
const unsigned char *selected = s->s3->alpn_selected;
size_t len = s->s3->alpn_selected_len;
/*-
* check for enough space.
* 4 bytes for the ALPN type and extension length
* 2 bytes for ALPN data length
* 1 byte for selected protocol length
* + length of the selected protocol
*/
if (CHECKLEN(ret, 7 + len, limit))
return NULL;
s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
s2n(3 + len, ret);
s2n(1 + len, ret);
*ret++ = len;
memcpy(ret, selected, len);
ret += len;
}
done:
if ((extdatalen = ret - orig - 2) == 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
/*
* Save the ALPN extension in a ClientHello.
* pkt: the contents of the ALPN extension, not including type and length.
* al: a pointer to the alert value to send in the event of a failure.
* returns: 1 on success, 0 on error.
*/
static int tls1_alpn_handle_client_hello(SSL *s, PACKET *pkt, int *al)
{
PACKET protocol_list, save_protocol_list, protocol;
*al = SSL_AD_DECODE_ERROR;
if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
|| PACKET_remaining(&protocol_list) < 2) {
return 0;
}
save_protocol_list = protocol_list;
do {
/* Protocol names can't be empty. */
if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
|| PACKET_remaining(&protocol) == 0) {
return 0;
}
} while (PACKET_remaining(&protocol_list) != 0);
if (!PACKET_memdup(&save_protocol_list,
&s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
return 1;
}
/*
* Process the ALPN extension in a ClientHello.
* al: a pointer to the alert value to send in the event of a failure.
* returns 1 on success, 0 on error.
*/
static int tls1_alpn_handle_client_hello_late(SSL *s, int *al)
{
const unsigned char *selected = NULL;
unsigned char selected_len = 0;
if (s->ctx->alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
s->s3->alpn_proposed,
s->s3->alpn_proposed_len,
s->ctx->alpn_select_cb_arg);
if (r == SSL_TLSEXT_ERR_OK) {
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
if (s->s3->alpn_selected == NULL) {
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
s->s3->alpn_selected_len = selected_len;
#ifndef OPENSSL_NO_NEXTPROTONEG
/* ALPN takes precedence over NPN. */
s->s3->next_proto_neg_seen = 0;
#endif
} else {
*al = SSL_AD_NO_APPLICATION_PROTOCOL;
return 0;
}
}
return 1;
}
#ifndef OPENSSL_NO_EC
/*-
* ssl_check_for_safari attempts to fingerprint Safari using OS X
* SecureTransport using the TLS extension block in |pkt|.
* Safari, since 10.6, sends exactly these extensions, in this order:
* SNI,
* elliptic_curves
* ec_point_formats
*
* We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
* but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
* Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
* 10.8..10.8.3 (which don't work).
*/
static void ssl_check_for_safari(SSL *s, const PACKET *pkt)
{
unsigned int type;
PACKET sni, tmppkt;
size_t ext_len;
static const unsigned char kSafariExtensionsBlock[] = {
0x00, 0x0a, /* elliptic_curves extension */
0x00, 0x08, /* 8 bytes */
0x00, 0x06, /* 6 bytes of curve ids */
0x00, 0x17, /* P-256 */
0x00, 0x18, /* P-384 */
0x00, 0x19, /* P-521 */
0x00, 0x0b, /* ec_point_formats */
0x00, 0x02, /* 2 bytes */
0x01, /* 1 point format */
0x00, /* uncompressed */
/* The following is only present in TLS 1.2 */
0x00, 0x0d, /* signature_algorithms */
0x00, 0x0c, /* 12 bytes */
0x00, 0x0a, /* 10 bytes */
0x05, 0x01, /* SHA-384/RSA */
0x04, 0x01, /* SHA-256/RSA */
0x02, 0x01, /* SHA-1/RSA */
0x04, 0x03, /* SHA-256/ECDSA */
0x02, 0x03, /* SHA-1/ECDSA */
};
/* Length of the common prefix (first two extensions). */
static const size_t kSafariCommonExtensionsLength = 18;
tmppkt = *pkt;
if (!PACKET_forward(&tmppkt, 2)
|| !PACKET_get_net_2(&tmppkt, &type)
|| !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
return;
}
if (type != TLSEXT_TYPE_server_name)
return;
ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
ext_len);
}
#endif /* !OPENSSL_NO_EC */
/*
* Parse ClientHello extensions and stash extension info in various parts of
* the SSL object. Verify that there are no duplicate extensions.
*
* Behaviour upon resumption is extension-specific. If the extension has no
* effect during resumption, it is parsed (to verify its format) but otherwise
* ignored.
*
* Consumes the entire packet in |pkt|. Returns 1 on success and 0 on failure.
* Upon failure, sets |al| to the appropriate alert.
*/
static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)
{
unsigned int type;
int renegotiate_seen = 0;
PACKET extensions;
*al = SSL_AD_DECODE_ERROR;
s->servername_done = 0;
s->tlsext_status_type = -1;
#ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
#endif
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = NULL;
s->s3->alpn_selected_len = 0;
OPENSSL_free(s->s3->alpn_proposed);
s->s3->alpn_proposed = NULL;
s->s3->alpn_proposed_len = 0;
#ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_DTLSEXT_HB_ENABLED |
SSL_DTLSEXT_HB_DONT_SEND_REQUESTS);
#endif
#ifndef OPENSSL_NO_EC
if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
ssl_check_for_safari(s, pkt);
#endif /* !OPENSSL_NO_EC */
/* Clear any signature algorithms extension received */
OPENSSL_free(s->s3->tmp.peer_sigalgs);
s->s3->tmp.peer_sigalgs = NULL;
s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
#ifndef OPENSSL_NO_SRP
OPENSSL_free(s->srp_ctx.login);
s->srp_ctx.login = NULL;
#endif
s->srtp_profile = NULL;
if (PACKET_remaining(pkt) == 0)
goto ri_check;
if (!PACKET_as_length_prefixed_2(pkt, &extensions))
return 0;
if (!tls1_check_duplicate_extensions(&extensions))
return 0;
/*
* We parse all extensions to ensure the ClientHello is well-formed but,
* unless an extension specifies otherwise, we ignore extensions upon
* resumption.
*/
while (PACKET_get_net_2(&extensions, &type)) {
PACKET extension;
if (!PACKET_get_length_prefixed_2(&extensions, &extension))
return 0;
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 0, type, PACKET_data(&extension),
PACKET_remaining(&extension),
s->tlsext_debug_arg);
if (type == TLSEXT_TYPE_renegotiate) {
if (!ssl_parse_clienthello_renegotiate_ext(s, &extension, al))
return 0;
renegotiate_seen = 1;
} else if (s->version == SSL3_VERSION) {
}
/*-
* The servername extension is treated as follows:
*
* - Only the hostname type is supported with a maximum length of 255.
* - The servername is rejected if too long or if it contains zeros,
* in which case an fatal alert is generated.
* - The servername field is maintained together with the session cache.
* - When a session is resumed, the servername call back invoked in order
* to allow the application to position itself to the right context.
* - The servername is acknowledged if it is new for a session or when
* it is identical to a previously used for the same session.
* Applications can control the behaviour. They can at any time
* set a 'desirable' servername for a new SSL object. This can be the
* case for example with HTTPS when a Host: header field is received and
* a renegotiation is requested. In this case, a possible servername
* presented in the new client hello is only acknowledged if it matches
* the value of the Host: field.
* - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
* if they provide for changing an explicit servername context for the
* session, i.e. when the session has been established with a servername
* extension.
* - On session reconnect, the servername extension may be absent.
*
*/
else if (type == TLSEXT_TYPE_server_name) {
unsigned int servname_type;
PACKET sni, hostname;
if (!PACKET_as_length_prefixed_2(&extension, &sni)
/* ServerNameList must be at least 1 byte long. */
|| PACKET_remaining(&sni) == 0) {
return 0;
}
/*
* Although the server_name extension was intended to be
* extensible to new name types, RFC 4366 defined the
* syntax inextensibility and OpenSSL 1.0.x parses it as
* such.
* RFC 6066 corrected the mistake but adding new name types
* is nevertheless no longer feasible, so act as if no other
* SNI types can exist, to simplify parsing.
*
* Also note that the RFC permits only one SNI value per type,
* i.e., we can only have a single hostname.
*/
if (!PACKET_get_1(&sni, &servname_type)
|| servname_type != TLSEXT_NAMETYPE_host_name
|| !PACKET_as_length_prefixed_2(&sni, &hostname)) {
return 0;
}
if (!s->hit) {
if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
if (PACKET_contains_zero_byte(&hostname)) {
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
if (!PACKET_strndup(&hostname, &s->session->tlsext_hostname)) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->servername_done = 1;
} else {
/*
* TODO(openssl-team): if the SNI doesn't match, we MUST
* fall back to a full handshake.
*/
s->servername_done = s->session->tlsext_hostname
&& PACKET_equal(&hostname, s->session->tlsext_hostname,
strlen(s->session->tlsext_hostname));
}
}
#ifndef OPENSSL_NO_SRP
else if (type == TLSEXT_TYPE_srp) {
PACKET srp_I;
if (!PACKET_as_length_prefixed_1(&extension, &srp_I))
return 0;
if (PACKET_contains_zero_byte(&srp_I))
return 0;
/*
* TODO(openssl-team): currently, we re-authenticate the user
* upon resumption. Instead, we MUST ignore the login.
*/
if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats) {
PACKET ec_point_format_list;
if (!PACKET_as_length_prefixed_1(&extension, &ec_point_format_list)
|| PACKET_remaining(&ec_point_format_list) == 0) {
return 0;
}
if (!s->hit) {
if (!PACKET_memdup(&ec_point_format_list,
&s->session->tlsext_ecpointformatlist,
&s->
session->tlsext_ecpointformatlist_length)) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
} else if (type == TLSEXT_TYPE_elliptic_curves) {
PACKET elliptic_curve_list;
/* Each NamedCurve is 2 bytes and we must have at least 1. */
if (!PACKET_as_length_prefixed_2(&extension, &elliptic_curve_list)
|| PACKET_remaining(&elliptic_curve_list) == 0
|| (PACKET_remaining(&elliptic_curve_list) % 2) != 0) {
return 0;
}
if (!s->hit) {
if (!PACKET_memdup(&elliptic_curve_list,
&s->session->tlsext_ellipticcurvelist,
&s->
session->tlsext_ellipticcurvelist_length)) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
}
#endif /* OPENSSL_NO_EC */
else if (type == TLSEXT_TYPE_session_ticket) {
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, PACKET_data(&extension),
PACKET_remaining(&extension),
s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
} else if (type == TLSEXT_TYPE_signature_algorithms) {
PACKET supported_sig_algs;
if (!PACKET_as_length_prefixed_2(&extension, &supported_sig_algs)
|| (PACKET_remaining(&supported_sig_algs) % 2) != 0
|| PACKET_remaining(&supported_sig_algs) == 0) {
return 0;
}
if (!s->hit) {
if (!tls1_save_sigalgs(s, PACKET_data(&supported_sig_algs),
PACKET_remaining(&supported_sig_algs))) {
return 0;
}
}
} else if (type == TLSEXT_TYPE_status_request) {
if (!PACKET_get_1(&extension,
(unsigned int *)&s->tlsext_status_type)) {
return 0;
}
#ifndef OPENSSL_NO_OCSP
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
const unsigned char *ext_data;
PACKET responder_id_list, exts;
if (!PACKET_get_length_prefixed_2
(&extension, &responder_id_list))
return 0;
/*
* We remove any OCSP_RESPIDs from a previous handshake
* to prevent unbounded memory growth - CVE-2016-6304
*/
sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids,
OCSP_RESPID_free);
if (PACKET_remaining(&responder_id_list) > 0) {
s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
if (s->tlsext_ocsp_ids == NULL) {
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
} else {
s->tlsext_ocsp_ids = NULL;
}
while (PACKET_remaining(&responder_id_list) > 0) {
OCSP_RESPID *id;
PACKET responder_id;
const unsigned char *id_data;
if (!PACKET_get_length_prefixed_2(&responder_id_list,
&responder_id)
|| PACKET_remaining(&responder_id) == 0) {
return 0;
}
id_data = PACKET_data(&responder_id);
id = d2i_OCSP_RESPID(NULL, &id_data,
PACKET_remaining(&responder_id));
if (id == NULL)
return 0;
if (id_data != PACKET_end(&responder_id)) {
OCSP_RESPID_free(id);
return 0;
}
if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
/* Read in request_extensions */
if (!PACKET_as_length_prefixed_2(&extension, &exts))
return 0;
if (PACKET_remaining(&exts) > 0) {
ext_data = PACKET_data(&exts);
sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
X509_EXTENSION_free);
s->tlsext_ocsp_exts =
d2i_X509_EXTENSIONS(NULL, &ext_data,
PACKET_remaining(&exts));
if (s->tlsext_ocsp_exts == NULL
|| ext_data != PACKET_end(&exts)) {
return 0;
}
}
} else
#endif
{
/*
* We don't know what to do with any other type so ignore it.
*/
s->tlsext_status_type = -1;
}
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_heartbeat) {
unsigned int hbtype;
if (!PACKET_get_1(&extension, &hbtype)
|| PACKET_remaining(&extension)) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
switch (hbtype) {
case 0x01: /* Client allows us to send HB requests */
s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED;
break;
case 0x02: /* Client doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_DTLSEXT_HB_DONT_SEND_REQUESTS;
break;
default:
*al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0) {
/*-
* We shouldn't accept this extension on a
* renegotiation.
*
* s->new_session will be set on renegotiation, but we
* probably shouldn't rely that it couldn't be set on
* the initial renegotiation too in certain cases (when
* there's some other reason to disallow resuming an
* earlier session -- the current code won't be doing
* anything like that, but this might change).
*
* A valid sign that there's been a previous handshake
* in this connection is if s->s3->tmp.finish_md_len >
* 0. (We are talking about a check that will happen
* in the Hello protocol round, well before a new
* Finished message could have been computed.)
*/
s->s3->next_proto_neg_seen = 1;
}
#endif
else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
s->s3->tmp.finish_md_len == 0) {
if (!tls1_alpn_handle_client_hello(s, &extension, al))
return 0;
}
/* session ticket processed earlier */
#ifndef OPENSSL_NO_SRTP
else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
&& type == TLSEXT_TYPE_use_srtp) {
if (ssl_parse_clienthello_use_srtp_ext(s, &extension, al))
return 0;
}
#endif
else if (type == TLSEXT_TYPE_encrypt_then_mac)
s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
/*
* Note: extended master secret extension handled in
* tls_check_serverhello_tlsext_early()
*/
/*
* If this ClientHello extension was unhandled and this is a
* nonresumed connection, check whether the extension is a custom
* TLS Extension (has a custom_srv_ext_record), and if so call the
* callback and record the extension number so that an appropriate
* ServerHello may be later returned.
*/
else if (!s->hit) {
if (custom_ext_parse(s, 1, type, PACKET_data(&extension),
PACKET_remaining(&extension), al) <= 0)
return 0;
}
}
if (PACKET_remaining(pkt) != 0) {
/*
* tls1_check_duplicate_extensions should ensure this never happens.
*/
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
ri_check:
/* Need RI if renegotiating */
if (!renegotiate_seen && s->renegotiate &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
/*
* This function currently has no state to clean up, so it returns directly.
* If parsing fails at any point, the function returns early.
* The SSL object may be left with partial data from extensions, but it must
* then no longer be used, and clearing it up will free the leftovers.
*/
return 1;
}
int ssl_parse_clienthello_tlsext(SSL *s, PACKET *pkt)
{
int al = -1;
custom_ext_init(&s->cert->srv_ext);
if (ssl_scan_clienthello_tlsext(s, pkt, &al) <= 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
if (ssl_check_clienthello_tlsext_early(s) <= 0) {
SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
return 0;
}
return 1;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
/*
* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
* elements of zero length are allowed and the set of elements must exactly
* fill the length of the block.
*/
static char ssl_next_proto_validate(PACKET *pkt)
{
PACKET tmp_protocol;
while (PACKET_remaining(pkt)) {
if (!PACKET_get_length_prefixed_1(pkt, &tmp_protocol)
|| PACKET_remaining(&tmp_protocol) == 0)
return 0;
}
return 1;
}
#endif
static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al)
{
unsigned int length, type, size;
int tlsext_servername = 0;
int renegotiate_seen = 0;
#ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
#endif
s->tlsext_ticket_expected = 0;
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = NULL;
#ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_DTLSEXT_HB_ENABLED |
SSL_DTLSEXT_HB_DONT_SEND_REQUESTS);
#endif
s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
if (!PACKET_get_net_2(pkt, &length))
goto ri_check;
if (PACKET_remaining(pkt) != length) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!tls1_check_duplicate_extensions(pkt)) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
while (PACKET_get_net_2(pkt, &type) && PACKET_get_net_2(pkt, &size)) {
const unsigned char *data;
PACKET spkt;
if (!PACKET_get_sub_packet(pkt, &spkt, size)
|| !PACKET_peek_bytes(&spkt, &data, size))
goto ri_check;
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
if (type == TLSEXT_TYPE_renegotiate) {
if (!ssl_parse_serverhello_renegotiate_ext(s, &spkt, al))
return 0;
renegotiate_seen = 1;
} else if (s->version == SSL3_VERSION) {
} else if (type == TLSEXT_TYPE_server_name) {
if (s->tlsext_hostname == NULL || size > 0) {
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
tlsext_servername = 1;
}
#ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats) {
unsigned int ecpointformatlist_length;
if (!PACKET_get_1(&spkt, &ecpointformatlist_length)
|| ecpointformatlist_length != size - 1) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (!s->hit) {
s->session->tlsext_ecpointformatlist_length = 0;
OPENSSL_free(s->session->tlsext_ecpointformatlist);
if ((s->session->tlsext_ecpointformatlist =
OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length =
ecpointformatlist_length;
if (!PACKET_copy_bytes(&spkt,
s->session->tlsext_ecpointformatlist,
ecpointformatlist_length)) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
}
}
#endif /* OPENSSL_NO_EC */
else if (type == TLSEXT_TYPE_session_ticket) {
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size,
s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
if (!tls_use_ticket(s) || (size > 0)) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
s->tlsext_ticket_expected = 1;
} else if (type == TLSEXT_TYPE_status_request) {
/*
* MUST be empty and only sent if we've requested a status
* request message.
*/
if ((s->tlsext_status_type == -1) || (size > 0)) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/* Set flag to expect CertificateStatus message */
s->tlsext_status_expected = 1;
}
#ifndef OPENSSL_NO_CT
/*
* Only take it if we asked for it - i.e if there is no CT validation
* callback set, then a custom extension MAY be processing it, so we
* need to let control continue to flow to that.
*/
else if (type == TLSEXT_TYPE_signed_certificate_timestamp &&
s->ct_validation_callback != NULL) {
/* Simply copy it off for later processing */
if (s->tlsext_scts != NULL) {
OPENSSL_free(s->tlsext_scts);
s->tlsext_scts = NULL;
}
s->tlsext_scts_len = size;
if (size > 0) {
s->tlsext_scts = OPENSSL_malloc(size);
if (s->tlsext_scts == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->tlsext_scts, data, size);
}
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0) {
unsigned char *selected;
unsigned char selected_len;
/* We must have requested it. */
if (s->ctx->next_proto_select_cb == NULL) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/* The data must be valid */
if (!ssl_next_proto_validate(&spkt)) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data,
size,
s->
ctx->next_proto_select_cb_arg) !=
SSL_TLSEXT_ERR_OK) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
/*
* Could be non-NULL if server has sent multiple NPN extensions in
* a single Serverhello
*/
OPENSSL_free(s->next_proto_negotiated);
s->next_proto_negotiated = OPENSSL_malloc(selected_len);
if (s->next_proto_negotiated == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->next_proto_negotiated, selected, selected_len);
s->next_proto_negotiated_len = selected_len;
s->s3->next_proto_neg_seen = 1;
}
#endif
else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
unsigned len;
/* We must have requested it. */
if (!s->s3->alpn_sent) {
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/*-
* The extension data consists of:
* uint16 list_length
* uint8 proto_length;
* uint8 proto[proto_length];
*/
if (!PACKET_get_net_2(&spkt, &len)
|| PACKET_remaining(&spkt) != len || !PACKET_get_1(&spkt, &len)
|| PACKET_remaining(&spkt) != len) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = OPENSSL_malloc(len);
if (s->s3->alpn_selected == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
if (!PACKET_copy_bytes(&spkt, s->s3->alpn_selected, len)) {
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
s->s3->alpn_selected_len = len;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_heartbeat) {
unsigned int hbtype;
if (!PACKET_get_1(&spkt, &hbtype)) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
switch (hbtype) {
case 0x01: /* Server allows us to send HB requests */
s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED;
break;
case 0x02: /* Server doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_DTLSEXT_HB_DONT_SEND_REQUESTS;
break;
default:
*al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_SRTP
else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
if (ssl_parse_serverhello_use_srtp_ext(s, &spkt, al))
return 0;
}
#endif
else if (type == TLSEXT_TYPE_encrypt_then_mac) {
/* Ignore if inappropriate ciphersuite */
if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD
&& s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4)
s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
} else if (type == TLSEXT_TYPE_extended_master_secret) {
s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
if (!s->hit)
s->session->flags |= SSL_SESS_FLAG_EXTMS;
}
/*
* If this extension type was not otherwise handled, but matches a
* custom_cli_ext_record, then send it to the c callback
*/
else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
return 0;
}
if (PACKET_remaining(pkt) != 0) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!s->hit && tlsext_servername == 1) {
if (s->tlsext_hostname) {
if (s->session->tlsext_hostname == NULL) {
s->session->tlsext_hostname =
OPENSSL_strdup(s->tlsext_hostname);
if (!s->session->tlsext_hostname) {
*al = SSL_AD_UNRECOGNIZED_NAME;
return 0;
}
} else {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
}
ri_check:
/*
* Determine if we need to see RI. Strictly speaking if we want to avoid
* an attack we should *always* see RI even on initial server hello
* because the client doesn't see any renegotiation during an attack.
* However this would mean we could not connect to any server which
* doesn't support RI so for the immediate future tolerate RI absence
*/
if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
if (s->hit) {
/*
* Check extended master secret extension is consistent with
* original session.
*/
if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
!(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_INCONSISTENT_EXTMS);
return 0;
}
}
return 1;
}
int ssl_prepare_clienthello_tlsext(SSL *s)
{
s->s3->alpn_sent = 0;
return 1;
}
int ssl_prepare_serverhello_tlsext(SSL *s)
{
return 1;
}
static int ssl_check_clienthello_tlsext_early(SSL *s)
{
int ret = SSL_TLSEXT_ERR_NOACK;
int al = SSL_AD_UNRECOGNIZED_NAME;
#ifndef OPENSSL_NO_EC
/*
* The handling of the ECPointFormats extension is done elsewhere, namely
* in ssl3_choose_cipher in s3_lib.c.
*/
/*
* The handling of the EllipticCurves extension is done elsewhere, namely
* in ssl3_choose_cipher in s3_lib.c.
*/
#endif
if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
ret =
s->ctx->tlsext_servername_callback(s, &al,
s->ctx->tlsext_servername_arg);
else if (s->session_ctx != NULL
&& s->session_ctx->tlsext_servername_callback != 0)
ret =
s->session_ctx->tlsext_servername_callback(s, &al,
s->
session_ctx->tlsext_servername_arg);
switch (ret) {
case SSL_TLSEXT_ERR_ALERT_FATAL:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return -1;
case SSL_TLSEXT_ERR_ALERT_WARNING:
ssl3_send_alert(s, SSL3_AL_WARNING, al);
return 1;
case SSL_TLSEXT_ERR_NOACK:
s->servername_done = 0;
default:
return 1;
}
}
/* Initialise digests to default values */
void ssl_set_default_md(SSL *s)
{
const EVP_MD **pmd = s->s3->tmp.md;
#ifndef OPENSSL_NO_DSA
pmd[SSL_PKEY_DSA_SIGN] = ssl_md(SSL_MD_SHA1_IDX);
#endif
#ifndef OPENSSL_NO_RSA
if (SSL_USE_SIGALGS(s))
pmd[SSL_PKEY_RSA_SIGN] = ssl_md(SSL_MD_SHA1_IDX);
else
pmd[SSL_PKEY_RSA_SIGN] = ssl_md(SSL_MD_MD5_SHA1_IDX);
pmd[SSL_PKEY_RSA_ENC] = pmd[SSL_PKEY_RSA_SIGN];
#endif
#ifndef OPENSSL_NO_EC
pmd[SSL_PKEY_ECC] = ssl_md(SSL_MD_SHA1_IDX);
#endif
#ifndef OPENSSL_NO_GOST
pmd[SSL_PKEY_GOST01] = ssl_md(SSL_MD_GOST94_IDX);
pmd[SSL_PKEY_GOST12_256] = ssl_md(SSL_MD_GOST12_256_IDX);
pmd[SSL_PKEY_GOST12_512] = ssl_md(SSL_MD_GOST12_512_IDX);
#endif
}
int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared signature algorithms */
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
s->cert->shared_sigalgslen = 0;
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->s3->tmp.md[i] = NULL;
s->s3->tmp.valid_flags[i] = 0;
}
/* If sigalgs received process it. */
if (s->s3->tmp.peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else {
ssl_set_default_md(s);
}
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
/*
* Upon success, returns 1.
* Upon failure, returns 0 and sets |al| to the appropriate fatal alert.
*/
int ssl_check_clienthello_tlsext_late(SSL *s, int *al)
{
s->tlsext_status_expected = 0;
/*
* If status request then ask callback what to do. Note: this must be
* called after servername callbacks in case the certificate has changed,
* and must be called after the cipher has been chosen because this may
* influence which certificate is sent
*/
if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
int ret;
CERT_PKEY *certpkey;
certpkey = ssl_get_server_send_pkey(s);
/* If no certificate can't return certificate status */
if (certpkey != NULL) {
/*
* Set current certificate to one we will use so SSL_get_certificate
* et al can pick it up.
*/
s->cert->key = certpkey;
ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
switch (ret) {
/* We don't want to send a status request response */
case SSL_TLSEXT_ERR_NOACK:
s->tlsext_status_expected = 0;
break;
/* status request response should be sent */
case SSL_TLSEXT_ERR_OK:
if (s->tlsext_ocsp_resp)
s->tlsext_status_expected = 1;
break;
/* something bad happened */
case SSL_TLSEXT_ERR_ALERT_FATAL:
default:
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
}
if (!tls1_alpn_handle_client_hello_late(s, al)) {
return 0;
}
return 1;
}
int ssl_check_serverhello_tlsext(SSL *s)
{
int ret = SSL_TLSEXT_ERR_NOACK;
int al = SSL_AD_UNRECOGNIZED_NAME;
#ifndef OPENSSL_NO_EC
/*
* If we are client and using an elliptic curve cryptography cipher
* suite, then if server returns an EC point formats lists extension it
* must contain uncompressed.
*/
unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
if ((s->tlsext_ecpointformatlist != NULL)
&& (s->tlsext_ecpointformatlist_length > 0)
&& (s->session->tlsext_ecpointformatlist != NULL)
&& (s->session->tlsext_ecpointformatlist_length > 0)
&& ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
/* we are using an ECC cipher */
size_t i;
unsigned char *list;
int found_uncompressed = 0;
list = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
found_uncompressed = 1;
break;
}
}
if (!found_uncompressed) {
SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
return -1;
}
}
ret = SSL_TLSEXT_ERR_OK;
#endif /* OPENSSL_NO_EC */
if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
ret =
s->ctx->tlsext_servername_callback(s, &al,
s->ctx->tlsext_servername_arg);
else if (s->session_ctx != NULL
&& s->session_ctx->tlsext_servername_callback != 0)
ret =
s->session_ctx->tlsext_servername_callback(s, &al,
s->
session_ctx->tlsext_servername_arg);
/*
* Ensure we get sensible values passed to tlsext_status_cb in the event
* that we don't receive a status message
*/
OPENSSL_free(s->tlsext_ocsp_resp);
s->tlsext_ocsp_resp = NULL;
s->tlsext_ocsp_resplen = -1;
switch (ret) {
case SSL_TLSEXT_ERR_ALERT_FATAL:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return -1;
case SSL_TLSEXT_ERR_ALERT_WARNING:
ssl3_send_alert(s, SSL3_AL_WARNING, al);
return 1;
case SSL_TLSEXT_ERR_NOACK:
s->servername_done = 0;
default:
return 1;
}
}
int ssl_parse_serverhello_tlsext(SSL *s, PACKET *pkt)
{
int al = -1;
if (s->version < SSL3_VERSION)
return 1;
if (ssl_scan_serverhello_tlsext(s, pkt, &al) <= 0) {
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
if (ssl_check_serverhello_tlsext(s) <= 0) {
SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
return 0;
}
return 1;
}
/*-
* Since the server cache lookup is done early on in the processing of the
* ClientHello and other operations depend on the result some extensions
* need to be handled at the same time.
*
* Two extensions are currently handled, session ticket and extended master
* secret.
*
* session_id: ClientHello session ID.
* ext: ClientHello extensions (including length prefix)
* ret: (output) on return, if a ticket was decrypted, then this is set to
* point to the resulting session.
*
* If s->tls_session_secret_cb is set then we are expecting a pre-shared key
* ciphersuite, in which case we have no use for session tickets and one will
* never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
*
* Returns:
* -1: fatal error, either from parsing or decrypting the ticket.
* 0: no ticket was found (or was ignored, based on settings).
* 1: a zero length extension was found, indicating that the client supports
* session tickets but doesn't currently have one to offer.
* 2: either s->tls_session_secret_cb was set, or a ticket was offered but
* couldn't be decrypted because of a non-fatal error.
* 3: a ticket was successfully decrypted and *ret was set.
*
* Side effects:
* Sets s->tlsext_ticket_expected to 1 if the server will have to issue
* a new session ticket to the client because the client indicated support
* (and s->tls_session_secret_cb is NULL) but the client either doesn't have
* a session ticket or we couldn't use the one it gave us, or if
* s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
* Otherwise, s->tlsext_ticket_expected is set to 0.
*
* For extended master secret flag is set if the extension is present.
*
*/
int tls_check_serverhello_tlsext_early(SSL *s, const PACKET *ext,
const PACKET *session_id,
SSL_SESSION **ret)
{
unsigned int i;
PACKET local_ext = *ext;
int retv = -1;
int have_ticket = 0;
int use_ticket = tls_use_ticket(s);
*ret = NULL;
s->tlsext_ticket_expected = 0;
s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
/*
* If tickets disabled behave as if no ticket present to permit stateful
* resumption.
*/
if ((s->version <= SSL3_VERSION))
return 0;
if (!PACKET_get_net_2(&local_ext, &i)) {
retv = 0;
goto end;
}
while (PACKET_remaining(&local_ext) >= 4) {
unsigned int type, size;
if (!PACKET_get_net_2(&local_ext, &type)
|| !PACKET_get_net_2(&local_ext, &size)) {
/* Shouldn't ever happen */
retv = -1;
goto end;
}
if (PACKET_remaining(&local_ext) < size) {
retv = 0;
goto end;
}
if (type == TLSEXT_TYPE_session_ticket && use_ticket) {
int r;
const unsigned char *etick;
/* Duplicate extension */
if (have_ticket != 0) {
retv = -1;
goto end;
}
have_ticket = 1;
if (size == 0) {
/*
* The client will accept a ticket but doesn't currently have
* one.
*/
s->tlsext_ticket_expected = 1;
retv = 1;
continue;
}
if (s->tls_session_secret_cb) {
/*
* Indicate that the ticket couldn't be decrypted rather than
* generating the session from ticket now, trigger
* abbreviated handshake based on external mechanism to
* calculate the master secret later.
*/
retv = 2;
continue;
}
if (!PACKET_get_bytes(&local_ext, &etick, size)) {
/* Shouldn't ever happen */
retv = -1;
goto end;
}
r = tls_decrypt_ticket(s, etick, size, PACKET_data(session_id),
PACKET_remaining(session_id), ret);
switch (r) {
case 2: /* ticket couldn't be decrypted */
s->tlsext_ticket_expected = 1;
retv = 2;
break;
case 3: /* ticket was decrypted */
retv = r;
break;
case 4: /* ticket decrypted but need to renew */
s->tlsext_ticket_expected = 1;
retv = 3;
break;
default: /* fatal error */
retv = -1;
break;
}
continue;
} else {
if (type == TLSEXT_TYPE_extended_master_secret)
s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
if (!PACKET_forward(&local_ext, size)) {
retv = -1;
goto end;
}
}
}
if (have_ticket == 0)
retv = 0;
end:
return retv;
}
/*-
* tls_decrypt_ticket attempts to decrypt a session ticket.
*
* etick: points to the body of the session ticket extension.
* eticklen: the length of the session tickets extension.
* sess_id: points at the session ID.
* sesslen: the length of the session ID.
* psess: (output) on return, if a ticket was decrypted, then this is set to
* point to the resulting session.
*
* Returns:
* -2: fatal error, malloc failure.
* -1: fatal error, either from parsing or decrypting the ticket.
* 2: the ticket couldn't be decrypted.
* 3: a ticket was successfully decrypted and *psess was set.
* 4: same as 3, but the ticket needs to be renewed.
*/
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
int eticklen, const unsigned char *sess_id,
int sesslen, SSL_SESSION **psess)
{
SSL_SESSION *sess;
unsigned char *sdec;
const unsigned char *p;
int slen, mlen, renew_ticket = 0, ret = -1;
unsigned char tick_hmac[EVP_MAX_MD_SIZE];
HMAC_CTX *hctx = NULL;
EVP_CIPHER_CTX *ctx;
SSL_CTX *tctx = s->session_ctx;
/* Initialize session ticket encryption and HMAC contexts */
hctx = HMAC_CTX_new();
if (hctx == NULL)
return -2;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
ret = -2;
goto err;
}
if (tctx->tlsext_ticket_key_cb) {
unsigned char *nctick = (unsigned char *)etick;
int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
ctx, hctx, 0);
if (rv < 0)
goto err;
if (rv == 0) {
ret = 2;
goto err;
}
if (rv == 2)
renew_ticket = 1;
} else {
/* Check key name matches */
if (memcmp(etick, tctx->tlsext_tick_key_name,
sizeof(tctx->tlsext_tick_key_name)) != 0) {
ret = 2;
goto err;
}
if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
sizeof(tctx->tlsext_tick_hmac_key),
EVP_sha256(), NULL) <= 0
|| EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
tctx->tlsext_tick_aes_key,
etick + sizeof(tctx->tlsext_tick_key_name)) <=
0) {
goto err;
}
}
/*
* Attempt to process session ticket, first conduct sanity and integrity
* checks on ticket.
*/
mlen = HMAC_size(hctx);
if (mlen < 0) {
goto err;
}
/* Sanity check ticket length: must exceed keyname + IV + HMAC */
if (eticklen <=
TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx) + mlen) {
ret = 2;
goto err;
}
eticklen -= mlen;
/* Check HMAC of encrypted ticket */
if (HMAC_Update(hctx, etick, eticklen) <= 0
|| HMAC_Final(hctx, tick_hmac, NULL) <= 0) {
goto err;
}
HMAC_CTX_free(hctx);
if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
EVP_CIPHER_CTX_free(ctx);
return 2;
}
/* Attempt to decrypt session data */
/* Move p after IV to start of encrypted ticket, update length */
p = etick + TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx);
eticklen -= TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx);
sdec = OPENSSL_malloc(eticklen);
if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) {
EVP_CIPHER_CTX_free(ctx);
OPENSSL_free(sdec);
return -1;
}
if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) {
EVP_CIPHER_CTX_free(ctx);
OPENSSL_free(sdec);
return 2;
}
slen += mlen;
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
p = sdec;
sess = d2i_SSL_SESSION(NULL, &p, slen);
OPENSSL_free(sdec);
if (sess) {
/*
* The session ID, if non-empty, is used by some clients to detect
* that the ticket has been accepted. So we copy it to the session
* structure. If it is empty set length to zero as required by
* standard.
*/
if (sesslen)
memcpy(sess->session_id, sess_id, sesslen);
sess->session_id_length = sesslen;
*psess = sess;
if (renew_ticket)
return 4;
else
return 3;
}
ERR_clear_error();
/*
* For session parse failure, indicate that we need to send a new ticket.
*/
return 2;
err:
EVP_CIPHER_CTX_free(ctx);
HMAC_CTX_free(hctx);
return ret;
}
/* Tables to translate from NIDs to TLS v1.2 ids */
typedef struct {
int nid;
int id;
} tls12_lookup;
static const tls12_lookup tls12_md[] = {
{NID_md5, TLSEXT_hash_md5},
{NID_sha1, TLSEXT_hash_sha1},
{NID_sha224, TLSEXT_hash_sha224},
{NID_sha256, TLSEXT_hash_sha256},
{NID_sha384, TLSEXT_hash_sha384},
{NID_sha512, TLSEXT_hash_sha512},
{NID_id_GostR3411_94, TLSEXT_hash_gostr3411},
{NID_id_GostR3411_2012_256, TLSEXT_hash_gostr34112012_256},
{NID_id_GostR3411_2012_512, TLSEXT_hash_gostr34112012_512},
};
static const tls12_lookup tls12_sig[] = {
{EVP_PKEY_RSA, TLSEXT_signature_rsa},
{EVP_PKEY_DSA, TLSEXT_signature_dsa},
{EVP_PKEY_EC, TLSEXT_signature_ecdsa},
{NID_id_GostR3410_2001, TLSEXT_signature_gostr34102001},
{NID_id_GostR3410_2012_256, TLSEXT_signature_gostr34102012_256},
{NID_id_GostR3410_2012_512, TLSEXT_signature_gostr34102012_512}
};
static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen)
{
size_t i;
for (i = 0; i < tlen; i++) {
if (table[i].nid == nid)
return table[i].id;
}
return -1;
}
static int tls12_find_nid(int id, const tls12_lookup *table, size_t tlen)
{
size_t i;
for (i = 0; i < tlen; i++) {
if ((table[i].id) == id)
return table[i].nid;
}
return NID_undef;
}
int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
{
int sig_id, md_id;
if (!md)
return 0;
md_id = tls12_find_id(EVP_MD_type(md), tls12_md, OSSL_NELEM(tls12_md));
if (md_id == -1)
return 0;
sig_id = tls12_get_sigid(pk);
if (sig_id == -1)
return 0;
p[0] = (unsigned char)md_id;
p[1] = (unsigned char)sig_id;
return 1;
}
int tls12_get_sigid(const EVP_PKEY *pk)
{
return tls12_find_id(EVP_PKEY_id(pk), tls12_sig, OSSL_NELEM(tls12_sig));
}
typedef struct {
int nid;
int secbits;
int md_idx;
unsigned char tlsext_hash;
} tls12_hash_info;
static const tls12_hash_info tls12_md_info[] = {
{NID_md5, 64, SSL_MD_MD5_IDX, TLSEXT_hash_md5},
{NID_sha1, 80, SSL_MD_SHA1_IDX, TLSEXT_hash_sha1},
{NID_sha224, 112, SSL_MD_SHA224_IDX, TLSEXT_hash_sha224},
{NID_sha256, 128, SSL_MD_SHA256_IDX, TLSEXT_hash_sha256},
{NID_sha384, 192, SSL_MD_SHA384_IDX, TLSEXT_hash_sha384},
{NID_sha512, 256, SSL_MD_SHA512_IDX, TLSEXT_hash_sha512},
{NID_id_GostR3411_94, 128, SSL_MD_GOST94_IDX, TLSEXT_hash_gostr3411},
{NID_id_GostR3411_2012_256, 128, SSL_MD_GOST12_256_IDX,
TLSEXT_hash_gostr34112012_256},
{NID_id_GostR3411_2012_512, 256, SSL_MD_GOST12_512_IDX,
TLSEXT_hash_gostr34112012_512},
};
static const tls12_hash_info *tls12_get_hash_info(unsigned char hash_alg)
{
unsigned int i;
if (hash_alg == 0)
return NULL;
for (i = 0; i < OSSL_NELEM(tls12_md_info); i++) {
if (tls12_md_info[i].tlsext_hash == hash_alg)
return tls12_md_info + i;
}
return NULL;
}
const EVP_MD *tls12_get_hash(unsigned char hash_alg)
{
const tls12_hash_info *inf;
if (hash_alg == TLSEXT_hash_md5 && FIPS_mode())
return NULL;
inf = tls12_get_hash_info(hash_alg);
if (!inf)
return NULL;
return ssl_md(inf->md_idx);
}
static int tls12_get_pkey_idx(unsigned char sig_alg)
{
switch (sig_alg) {
#ifndef OPENSSL_NO_RSA
case TLSEXT_signature_rsa:
return SSL_PKEY_RSA_SIGN;
#endif
#ifndef OPENSSL_NO_DSA
case TLSEXT_signature_dsa:
return SSL_PKEY_DSA_SIGN;
#endif
#ifndef OPENSSL_NO_EC
case TLSEXT_signature_ecdsa:
return SSL_PKEY_ECC;
#endif
#ifndef OPENSSL_NO_GOST
case TLSEXT_signature_gostr34102001:
return SSL_PKEY_GOST01;
case TLSEXT_signature_gostr34102012_256:
return SSL_PKEY_GOST12_256;
case TLSEXT_signature_gostr34102012_512:
return SSL_PKEY_GOST12_512;
#endif
}
return -1;
}
/* Convert TLS 1.2 signature algorithm extension values into NIDs */
static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
int *psignhash_nid, const unsigned char *data)
{
int sign_nid = NID_undef, hash_nid = NID_undef;
if (!phash_nid && !psign_nid && !psignhash_nid)
return;
if (phash_nid || psignhash_nid) {
hash_nid = tls12_find_nid(data[0], tls12_md, OSSL_NELEM(tls12_md));
if (phash_nid)
*phash_nid = hash_nid;
}
if (psign_nid || psignhash_nid) {
sign_nid = tls12_find_nid(data[1], tls12_sig, OSSL_NELEM(tls12_sig));
if (psign_nid)
*psign_nid = sign_nid;
}
if (psignhash_nid) {
if (sign_nid == NID_undef || hash_nid == NID_undef
|| OBJ_find_sigid_by_algs(psignhash_nid, hash_nid, sign_nid) <= 0)
*psignhash_nid = NID_undef;
}
}
/* Check to see if a signature algorithm is allowed */
static int tls12_sigalg_allowed(SSL *s, int op, const unsigned char *ptmp)
{
/* See if we have an entry in the hash table and it is enabled */
const tls12_hash_info *hinf = tls12_get_hash_info(ptmp[0]);
if (hinf == NULL || ssl_md(hinf->md_idx) == NULL)
return 0;
/* See if public key algorithm allowed */
if (tls12_get_pkey_idx(ptmp[1]) == -1)
return 0;
/* Finally see if security callback allows it */
return ssl_security(s, op, hinf->secbits, hinf->nid, (void *)ptmp);
}
/*
* Get a mask of disabled public key algorithms based on supported signature
* algorithms. For example if no signature algorithm supports RSA then RSA is
* disabled.
*/
void ssl_set_sig_mask(uint32_t *pmask_a, SSL *s, int op)
{
const unsigned char *sigalgs;
size_t i, sigalgslen;
int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
/*
* Now go through all signature algorithms seeing if we support any for
* RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2. To keep
* down calls to security callback only check if we have to.
*/
sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
switch (sigalgs[1]) {
#ifndef OPENSSL_NO_RSA
case TLSEXT_signature_rsa:
if (!have_rsa && tls12_sigalg_allowed(s, op, sigalgs))
have_rsa = 1;
break;
#endif
#ifndef OPENSSL_NO_DSA
case TLSEXT_signature_dsa:
if (!have_dsa && tls12_sigalg_allowed(s, op, sigalgs))
have_dsa = 1;
break;
#endif
#ifndef OPENSSL_NO_EC
case TLSEXT_signature_ecdsa:
if (!have_ecdsa && tls12_sigalg_allowed(s, op, sigalgs))
have_ecdsa = 1;
break;
#endif
}
}
if (!have_rsa)
*pmask_a |= SSL_aRSA;
if (!have_dsa)
*pmask_a |= SSL_aDSS;
if (!have_ecdsa)
*pmask_a |= SSL_aECDSA;
}
size_t tls12_copy_sigalgs(SSL *s, unsigned char *out,
const unsigned char *psig, size_t psiglen)
{
unsigned char *tmpout = out;
size_t i;
for (i = 0; i < psiglen; i += 2, psig += 2) {
if (tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, psig)) {
*tmpout++ = psig[0];
*tmpout++ = psig[1];
}
}
return tmpout - out;
}
/* Given preference and allowed sigalgs set shared sigalgs */
static int tls12_shared_sigalgs(SSL *s, TLS_SIGALGS *shsig,
const unsigned char *pref, size_t preflen,
const unsigned char *allow, size_t allowlen)
{
const unsigned char *ptmp, *atmp;
size_t i, j, nmatch = 0;
for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
/* Skip disabled hashes or signature algorithms */
if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, ptmp))
continue;
for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
nmatch++;
if (shsig) {
shsig->rhash = ptmp[0];
shsig->rsign = ptmp[1];
tls1_lookup_sigalg(&shsig->hash_nid,
&shsig->sign_nid,
&shsig->signandhash_nid, ptmp);
shsig++;
}
break;
}
}
}
return nmatch;
}
/* Set shared signature algorithms for SSL structures */
static int tls1_set_shared_sigalgs(SSL *s)
{
const unsigned char *pref, *allow, *conf;
size_t preflen, allowlen, conflen;
size_t nmatch;
TLS_SIGALGS *salgs = NULL;
CERT *c = s->cert;
unsigned int is_suiteb = tls1_suiteb(s);
OPENSSL_free(c->shared_sigalgs);
c->shared_sigalgs = NULL;
c->shared_sigalgslen = 0;
/* If client use client signature algorithms if not NULL */
if (!s->server && c->client_sigalgs && !is_suiteb) {
conf = c->client_sigalgs;
conflen = c->client_sigalgslen;
} else if (c->conf_sigalgs && !is_suiteb) {
conf = c->conf_sigalgs;
conflen = c->conf_sigalgslen;
} else
conflen = tls12_get_psigalgs(s, 0, &conf);
if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
pref = conf;
preflen = conflen;
allow = s->s3->tmp.peer_sigalgs;
allowlen = s->s3->tmp.peer_sigalgslen;
} else {
allow = conf;
allowlen = conflen;
pref = s->s3->tmp.peer_sigalgs;
preflen = s->s3->tmp.peer_sigalgslen;
}
nmatch = tls12_shared_sigalgs(s, NULL, pref, preflen, allow, allowlen);
if (nmatch) {
salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
if (salgs == NULL)
return 0;
nmatch = tls12_shared_sigalgs(s, salgs, pref, preflen, allow, allowlen);
} else {
salgs = NULL;
}
c->shared_sigalgs = salgs;
c->shared_sigalgslen = nmatch;
return 1;
}
/* Set preferred digest for each key type */
int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
{
CERT *c = s->cert;
/* Extension ignored for inappropriate versions */
if (!SSL_USE_SIGALGS(s))
return 1;
/* Should never happen */
if (!c)
return 0;
OPENSSL_free(s->s3->tmp.peer_sigalgs);
s->s3->tmp.peer_sigalgs = OPENSSL_malloc(dsize);
if (s->s3->tmp.peer_sigalgs == NULL)
return 0;
s->s3->tmp.peer_sigalgslen = dsize;
memcpy(s->s3->tmp.peer_sigalgs, data, dsize);
return 1;
}
int tls1_process_sigalgs(SSL *s)
{
int idx;
size_t i;
const EVP_MD *md;
const EVP_MD **pmd = s->s3->tmp.md;
uint32_t *pvalid = s->s3->tmp.valid_flags;
CERT *c = s->cert;
TLS_SIGALGS *sigptr;
if (!tls1_set_shared_sigalgs(s))
return 0;
for (i = 0, sigptr = c->shared_sigalgs;
i < c->shared_sigalgslen; i++, sigptr++) {
idx = tls12_get_pkey_idx(sigptr->rsign);
if (idx > 0 && pmd[idx] == NULL) {
md = tls12_get_hash(sigptr->rhash);
pmd[idx] = md;
pvalid[idx] = CERT_PKEY_EXPLICIT_SIGN;
if (idx == SSL_PKEY_RSA_SIGN) {
pvalid[SSL_PKEY_RSA_ENC] = CERT_PKEY_EXPLICIT_SIGN;
pmd[SSL_PKEY_RSA_ENC] = md;
}
}
}
/*
* In strict mode leave unset digests as NULL to indicate we can't use
* the certificate for signing.
*/
if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
/*
* Set any remaining keys to default values. NOTE: if alg is not
* supported it stays as NULL.
*/
#ifndef OPENSSL_NO_DSA
if (pmd[SSL_PKEY_DSA_SIGN] == NULL)
pmd[SSL_PKEY_DSA_SIGN] = EVP_sha1();
#endif
#ifndef OPENSSL_NO_RSA
if (pmd[SSL_PKEY_RSA_SIGN] == NULL) {
pmd[SSL_PKEY_RSA_SIGN] = EVP_sha1();
pmd[SSL_PKEY_RSA_ENC] = EVP_sha1();
}
#endif
#ifndef OPENSSL_NO_EC
if (pmd[SSL_PKEY_ECC] == NULL)
pmd[SSL_PKEY_ECC] = EVP_sha1();
#endif
#ifndef OPENSSL_NO_GOST
if (pmd[SSL_PKEY_GOST01] == NULL)
pmd[SSL_PKEY_GOST01] = EVP_get_digestbynid(NID_id_GostR3411_94);
if (pmd[SSL_PKEY_GOST12_256] == NULL)
pmd[SSL_PKEY_GOST12_256] =
EVP_get_digestbynid(NID_id_GostR3411_2012_256);
if (pmd[SSL_PKEY_GOST12_512] == NULL)
pmd[SSL_PKEY_GOST12_512] =
EVP_get_digestbynid(NID_id_GostR3411_2012_512);
#endif
}
return 1;
}
int SSL_get_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignhash,
unsigned char *rsig, unsigned char *rhash)
{
const unsigned char *psig = s->s3->tmp.peer_sigalgs;
if (psig == NULL)
return 0;
if (idx >= 0) {
idx <<= 1;
if (idx >= (int)s->s3->tmp.peer_sigalgslen)
return 0;
psig += idx;
if (rhash)
*rhash = psig[0];
if (rsig)
*rsig = psig[1];
tls1_lookup_sigalg(phash, psign, psignhash, psig);
}
return s->s3->tmp.peer_sigalgslen / 2;
}
int SSL_get_shared_sigalgs(SSL *s, int idx,
int *psign, int *phash, int *psignhash,
unsigned char *rsig, unsigned char *rhash)
{
TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
return 0;
shsigalgs += idx;
if (phash)
*phash = shsigalgs->hash_nid;
if (psign)
*psign = shsigalgs->sign_nid;
if (psignhash)
*psignhash = shsigalgs->signandhash_nid;
if (rsig)
*rsig = shsigalgs->rsign;
if (rhash)
*rhash = shsigalgs->rhash;
return s->cert->shared_sigalgslen;
}
#define MAX_SIGALGLEN (TLSEXT_hash_num * TLSEXT_signature_num * 2)
typedef struct {
size_t sigalgcnt;
int sigalgs[MAX_SIGALGLEN];
} sig_cb_st;
static void get_sigorhash(int *psig, int *phash, const char *str)
{
if (strcmp(str, "RSA") == 0) {
*psig = EVP_PKEY_RSA;
} else if (strcmp(str, "DSA") == 0) {
*psig = EVP_PKEY_DSA;
} else if (strcmp(str, "ECDSA") == 0) {
*psig = EVP_PKEY_EC;
} else {
*phash = OBJ_sn2nid(str);
if (*phash == NID_undef)
*phash = OBJ_ln2nid(str);
}
}
static int sig_cb(const char *elem, int len, void *arg)
{
sig_cb_st *sarg = arg;
size_t i;
char etmp[20], *p;
int sig_alg = NID_undef, hash_alg = NID_undef;
if (elem == NULL)
return 0;
if (sarg->sigalgcnt == MAX_SIGALGLEN)
return 0;
if (len > (int)(sizeof(etmp) - 1))
return 0;
memcpy(etmp, elem, len);
etmp[len] = 0;
p = strchr(etmp, '+');
if (!p)
return 0;
*p = 0;
p++;
if (!*p)
return 0;
get_sigorhash(&sig_alg, &hash_alg, etmp);
get_sigorhash(&sig_alg, &hash_alg, p);
if (sig_alg == NID_undef || hash_alg == NID_undef)
return 0;
for (i = 0; i < sarg->sigalgcnt; i += 2) {
if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
return 0;
}
sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
return 1;
}
/*
* Set supported signature algorithms based on a colon separated list of the
* form sig+hash e.g. RSA+SHA512:DSA+SHA512
*/
int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
{
sig_cb_st sig;
sig.sigalgcnt = 0;
if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
return 0;
if (c == NULL)
return 1;
return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
}
int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
{
unsigned char *sigalgs, *sptr;
int rhash, rsign;
size_t i;
if (salglen & 1)
return 0;
sigalgs = OPENSSL_malloc(salglen);
if (sigalgs == NULL)
return 0;
for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
rhash = tls12_find_id(*psig_nids++, tls12_md, OSSL_NELEM(tls12_md));
rsign = tls12_find_id(*psig_nids++, tls12_sig, OSSL_NELEM(tls12_sig));
if (rhash == -1 || rsign == -1)
goto err;
*sptr++ = rhash;
*sptr++ = rsign;
}
if (client) {
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen;
} else {
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen;
}
return 1;
err:
OPENSSL_free(sigalgs);
return 0;
}
static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
{
int sig_nid;
size_t i;
if (default_nid == -1)
return 1;
sig_nid = X509_get_signature_nid(x);
if (default_nid)
return sig_nid == default_nid ? 1 : 0;
for (i = 0; i < c->shared_sigalgslen; i++)
if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
return 1;
return 0;
}
/* Check to see if a certificate issuer name matches list of CA names */
static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
{
X509_NAME *nm;
int i;
nm = X509_get_issuer_name(x);
for (i = 0; i < sk_X509_NAME_num(names); i++) {
if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
return 1;
}
return 0;
}
/*
* Check certificate chain is consistent with TLS extensions and is usable by
* server. This servers two purposes: it allows users to check chains before
* passing them to the server and it allows the server to check chains before
* attempting to use them.
*/
/* Flags which need to be set for a certificate when stict mode not set */
#define CERT_PKEY_VALID_FLAGS \
(CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
/* Strict mode flags */
#define CERT_PKEY_STRICT_FLAGS \
(CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
| CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
int idx)
{
int i;
int rv = 0;
int check_flags = 0, strict_mode;
CERT_PKEY *cpk = NULL;
CERT *c = s->cert;
uint32_t *pvalid;
unsigned int suiteb_flags = tls1_suiteb(s);
/* idx == -1 means checking server chains */
if (idx != -1) {
/* idx == -2 means checking client certificate chains */
if (idx == -2) {
cpk = c->key;
idx = cpk - c->pkeys;
} else
cpk = c->pkeys + idx;
pvalid = s->s3->tmp.valid_flags + idx;
x = cpk->x509;
pk = cpk->privatekey;
chain = cpk->chain;
strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
/* If no cert or key, forget it */
if (!x || !pk)
goto end;
} else {
if (!x || !pk)
return 0;
idx = ssl_cert_type(x, pk);
if (idx == -1)
return 0;
pvalid = s->s3->tmp.valid_flags + idx;
if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
check_flags = CERT_PKEY_STRICT_FLAGS;
else
check_flags = CERT_PKEY_VALID_FLAGS;
strict_mode = 1;
}
if (suiteb_flags) {
int ok;
if (check_flags)
check_flags |= CERT_PKEY_SUITEB;
ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
if (ok == X509_V_OK)
rv |= CERT_PKEY_SUITEB;
else if (!check_flags)
goto end;
}
/*
* Check all signature algorithms are consistent with signature
* algorithms extension if TLS 1.2 or later and strict mode.
*/
if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
int default_nid;
unsigned char rsign = 0;
if (s->s3->tmp.peer_sigalgs)
default_nid = 0;
/* If no sigalgs extension use defaults from RFC5246 */
else {
switch (idx) {
case SSL_PKEY_RSA_ENC:
case SSL_PKEY_RSA_SIGN:
rsign = TLSEXT_signature_rsa;
default_nid = NID_sha1WithRSAEncryption;
break;
case SSL_PKEY_DSA_SIGN:
rsign = TLSEXT_signature_dsa;
default_nid = NID_dsaWithSHA1;
break;
case SSL_PKEY_ECC:
rsign = TLSEXT_signature_ecdsa;
default_nid = NID_ecdsa_with_SHA1;
break;
case SSL_PKEY_GOST01:
rsign = TLSEXT_signature_gostr34102001;
default_nid = NID_id_GostR3411_94_with_GostR3410_2001;
break;
case SSL_PKEY_GOST12_256:
rsign = TLSEXT_signature_gostr34102012_256;
default_nid = NID_id_tc26_signwithdigest_gost3410_2012_256;
break;
case SSL_PKEY_GOST12_512:
rsign = TLSEXT_signature_gostr34102012_512;
default_nid = NID_id_tc26_signwithdigest_gost3410_2012_512;
break;
default:
default_nid = -1;
break;
}
}
/*
* If peer sent no signature algorithms extension and we have set
* preferred signature algorithms check we support sha1.
*/
if (default_nid > 0 && c->conf_sigalgs) {
size_t j;
const unsigned char *p = c->conf_sigalgs;
for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
break;
}
if (j == c->conf_sigalgslen) {
if (check_flags)
goto skip_sigs;
else
goto end;
}
}
/* Check signature algorithm of each cert in chain */
if (!tls1_check_sig_alg(c, x, default_nid)) {
if (!check_flags)
goto end;
} else
rv |= CERT_PKEY_EE_SIGNATURE;
rv |= CERT_PKEY_CA_SIGNATURE;
for (i = 0; i < sk_X509_num(chain); i++) {
if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
if (check_flags) {
rv &= ~CERT_PKEY_CA_SIGNATURE;
break;
} else
goto end;
}
}
}
/* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
else if (check_flags)
rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
skip_sigs:
/* Check cert parameters are consistent */
if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
rv |= CERT_PKEY_EE_PARAM;
else if (!check_flags)
goto end;
if (!s->server)
rv |= CERT_PKEY_CA_PARAM;
/* In strict mode check rest of chain too */
else if (strict_mode) {
rv |= CERT_PKEY_CA_PARAM;
for (i = 0; i < sk_X509_num(chain); i++) {
X509 *ca = sk_X509_value(chain, i);
if (!tls1_check_cert_param(s, ca, 0)) {
if (check_flags) {
rv &= ~CERT_PKEY_CA_PARAM;
break;
} else
goto end;
}
}
}
if (!s->server && strict_mode) {
STACK_OF(X509_NAME) *ca_dn;
int check_type = 0;
switch (EVP_PKEY_id(pk)) {
case EVP_PKEY_RSA:
check_type = TLS_CT_RSA_SIGN;
break;
case EVP_PKEY_DSA:
check_type = TLS_CT_DSS_SIGN;
break;
case EVP_PKEY_EC:
check_type = TLS_CT_ECDSA_SIGN;
break;
}
if (check_type) {
const unsigned char *ctypes;
int ctypelen;
if (c->ctypes) {
ctypes = c->ctypes;
ctypelen = (int)c->ctype_num;
} else {
ctypes = (unsigned char *)s->s3->tmp.ctype;
ctypelen = s->s3->tmp.ctype_num;
}
for (i = 0; i < ctypelen; i++) {
if (ctypes[i] == check_type) {
rv |= CERT_PKEY_CERT_TYPE;
break;
}
}
if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
goto end;
} else
rv |= CERT_PKEY_CERT_TYPE;
ca_dn = s->s3->tmp.ca_names;
if (!sk_X509_NAME_num(ca_dn))
rv |= CERT_PKEY_ISSUER_NAME;
if (!(rv & CERT_PKEY_ISSUER_NAME)) {
if (ssl_check_ca_name(ca_dn, x))
rv |= CERT_PKEY_ISSUER_NAME;
}
if (!(rv & CERT_PKEY_ISSUER_NAME)) {
for (i = 0; i < sk_X509_num(chain); i++) {
X509 *xtmp = sk_X509_value(chain, i);
if (ssl_check_ca_name(ca_dn, xtmp)) {
rv |= CERT_PKEY_ISSUER_NAME;
break;
}
}
}
if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
goto end;
} else
rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
if (!check_flags || (rv & check_flags) == check_flags)
rv |= CERT_PKEY_VALID;
end:
if (TLS1_get_version(s) >= TLS1_2_VERSION) {
if (*pvalid & CERT_PKEY_EXPLICIT_SIGN)
rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
else if (s->s3->tmp.md[idx] != NULL)
rv |= CERT_PKEY_SIGN;
} else
rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
/*
* When checking a CERT_PKEY structure all flags are irrelevant if the
* chain is invalid.
*/
if (!check_flags) {
if (rv & CERT_PKEY_VALID)
*pvalid = rv;
else {
/* Preserve explicit sign flag, clear rest */
*pvalid &= CERT_PKEY_EXPLICIT_SIGN;
return 0;
}
}
return rv;
}
/* Set validity of certificates in an SSL structure */
void tls1_set_cert_validity(SSL *s)
{
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST01);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_256);
tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_512);
}
/* User level utiity function to check a chain is suitable */
int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
{
return tls1_check_chain(s, x, pk, chain, -1);
}
#ifndef OPENSSL_NO_DH
DH *ssl_get_auto_dh(SSL *s)
{
int dh_secbits = 80;
if (s->cert->dh_tmp_auto == 2)
return DH_get_1024_160();
if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aPSK)) {
if (s->s3->tmp.new_cipher->strength_bits == 256)
dh_secbits = 128;
else
dh_secbits = 80;
} else {
CERT_PKEY *cpk = ssl_get_server_send_pkey(s);
dh_secbits = EVP_PKEY_security_bits(cpk->privatekey);
}
if (dh_secbits >= 128) {
DH *dhp = DH_new();
BIGNUM *p, *g;
if (dhp == NULL)
return NULL;
g = BN_new();
if (g != NULL)
BN_set_word(g, 2);
if (dh_secbits >= 192)
p = BN_get_rfc3526_prime_8192(NULL);
else
p = BN_get_rfc3526_prime_3072(NULL);
if (p == NULL || g == NULL || !DH_set0_pqg(dhp, p, NULL, g)) {
DH_free(dhp);
BN_free(p);
BN_free(g);
return NULL;
}
return dhp;
}
if (dh_secbits >= 112)
return DH_get_2048_224();
return DH_get_1024_160();
}
#endif
static int ssl_security_cert_key(SSL *s, SSL_CTX *ctx, X509 *x, int op)
{
int secbits = -1;
EVP_PKEY *pkey = X509_get0_pubkey(x);
if (pkey) {
/*
* If no parameters this will return -1 and fail using the default
* security callback for any non-zero security level. This will
* reject keys which omit parameters but this only affects DSA and
* omission of parameters is never (?) done in practice.
*/
secbits = EVP_PKEY_security_bits(pkey);
}
if (s)
return ssl_security(s, op, secbits, 0, x);
else
return ssl_ctx_security(ctx, op, secbits, 0, x);
}
static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op)
{
/* Lookup signature algorithm digest */
int secbits = -1, md_nid = NID_undef, sig_nid;
/* Don't check signature if self signed */
if ((X509_get_extension_flags(x) & EXFLAG_SS) != 0)
return 1;
sig_nid = X509_get_signature_nid(x);
if (sig_nid && OBJ_find_sigid_algs(sig_nid, &md_nid, NULL)) {
const EVP_MD *md;
if (md_nid && (md = EVP_get_digestbynid(md_nid)))
secbits = EVP_MD_size(md) * 4;
}
if (s)
return ssl_security(s, op, secbits, md_nid, x);
else
return ssl_ctx_security(ctx, op, secbits, md_nid, x);
}
int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee)
{
if (vfy)
vfy = SSL_SECOP_PEER;
if (is_ee) {
if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_EE_KEY | vfy))
return SSL_R_EE_KEY_TOO_SMALL;
} else {
if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_CA_KEY | vfy))
return SSL_R_CA_KEY_TOO_SMALL;
}
if (!ssl_security_cert_sig(s, ctx, x, SSL_SECOP_CA_MD | vfy))
return SSL_R_CA_MD_TOO_WEAK;
return 1;
}
/*
* Check security of a chain, if sk includes the end entity certificate then
* x is NULL. If vfy is 1 then we are verifying a peer chain and not sending
* one to the peer. Return values: 1 if ok otherwise error code to use
*/
int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *x, int vfy)
{
int rv, start_idx, i;
if (x == NULL) {
x = sk_X509_value(sk, 0);
start_idx = 1;
} else
start_idx = 0;
rv = ssl_security_cert(s, NULL, x, vfy, 1);
if (rv != 1)
return rv;
for (i = start_idx; i < sk_X509_num(sk); i++) {
x = sk_X509_value(sk, i);
rv = ssl_security_cert(s, NULL, x, vfy, 0);
if (rv != 1)
return rv;
}
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3070_5 |
crossvul-cpp_data_good_2434_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD DDDD SSSSS %
% D D D D SS %
% D D D D SSS %
% D D D D SS %
% DDDD DDDD SSSSS %
% %
% %
% Read/Write Microsoft Direct Draw Surface Image Format %
% %
% Software Design %
% Bianca van Schaik %
% March 2008 %
% Dirk Lemstra %
% September 2013 %
% %
% %
% Copyright 1999-2015 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 %
% %
% http://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 "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if (max - min < steps) \
max = Min(min + steps, 255); \
if (max - min < steps) \
min = Max(min - steps, 0)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t, const DDSVector4 *, const DDSVector3,
DDSVector4 *, DDSVector4 *, unsigned char *, size_t);
static MagickBooleanType
ReadDDSInfo(Image *, DDSInfo *);
static MagickBooleanType
ReadDXT1(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadDXT3(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadDXT5(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadUncompressedRGB(Image *, DDSInfo *, ExceptionInfo *);
static MagickBooleanType
ReadUncompressedRGBA(Image *, DDSInfo *, ExceptionInfo *);
static void
RemapIndices(const ssize_t *, const unsigned char *, unsigned char *);
static void
SkipDXTMipmaps(Image *, DDSInfo *, int);
static void
SkipRGBMipmaps(Image *, DDSInfo *, int);
static
MagickBooleanType WriteDDSImage(const ImageInfo *, Image *);
static void
WriteDDSInfo(Image *, const size_t, const size_t, const size_t);
static void
WriteFourCC(Image *, const size_t, const MagickBooleanType,
const MagickBooleanType, ExceptionInfo *);
static void
WriteImageData(Image *, const size_t, const size_t, const MagickBooleanType,
const MagickBooleanType, ExceptionInfo *);
static void
WriteIndices(Image *, const DDSVector3, const DDSVector3, unsigned char *);
static MagickBooleanType
WriteMipmaps(Image *, const size_t, const size_t, const size_t,
const MagickBooleanType, const MagickBooleanType, ExceptionInfo *);
static void
WriteSingleColorFit(Image *, const DDSVector4 *, const ssize_t *);
static void
WriteUncompressed(Image *, ExceptionInfo *);
static inline size_t Max(size_t one, size_t two)
{
if (one > two)
return one;
return two;
}
static inline float MaxF(float one, float two)
{
if (one > two)
return one;
return two;
}
static inline size_t Min(size_t one, size_t two)
{
if (one < two)
return one;
return two;
}
static inline float MinF(float one, float two)
{
if (one < two)
return one;
return two;
}
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
value->w = MinF(1.0f,MaxF(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MinF(1.0f,MaxF(0.0f,value->x));
value->y = MinF(1.0f,MaxF(0.0f,value->y));
value->z = MinF(1.0f,MaxF(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex;
ssize_t
i;
unsigned char
*o,
order[128],
unordered[16];
VectorInit(half,0.5f);
VectorInit(two,2.0f);
VectorInit(onethird_onethird2,1.0f/3.0f);
onethird_onethird2.w = 1.0f/9.0f;
VectorInit(twothirds_twothirds2,2.0f/3.0f);
twothirds_twothirds2.w = 4.0f/9.0f;
VectorInit(twonineths,2.0f/9.0f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
grid.w = 0.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
gridrcp.w = 0.0f;
xSumwSum.x = 0.0f;
xSumwSum.y = 0.0f;
xSumwSum.z = 0.0f;
xSumwSum.w = 0.0f;
ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
for (iterationIndex = 0;;)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,1) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
part0,
part1,
part2;
size_t
ii,
j,
k,
kmin;
VectorInit(part0,0.0f);
for(ii=0; ii < (size_t) i; ii++)
VectorAdd(pointsWeights[ii],part0,&part0);
VectorInit(part1,0.0f);
for (j=(size_t) i;;)
{
if (j == 0)
{
VectorCopy44(pointsWeights[0],&part2);
kmin = 1;
}
else
{
VectorInit(part2,0.0f);
kmin = j;
}
for (k=kmin;;)
{
DDSVector4
a,
alpha2_sum,
alphax_sum,
alphabeta_sum,
b,
beta2_sum,
betax_sum,
e1,
e2,
factor,
part3;
float
error;
VectorSubtract(xSumwSum,part2,&part3);
VectorSubtract(part3,part1,&part3);
VectorSubtract(part3,part0,&part3);
VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
VectorInit(alpha2_sum,alphax_sum.w);
VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
VectorInit(beta2_sum,betax_sum.w);
VectorAdd(part1,part2,&alphabeta_sum);
VectorInit(alphabeta_sum,alphabeta_sum.w);
VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
VectorMultiply(alpha2_sum,beta2_sum,&factor);
VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
&factor);
VectorReciprocal(factor,&factor);
VectorMultiply(alphax_sum,beta2_sum,&a);
VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
VectorMultiply(a,factor,&a);
VectorMultiply(betax_sum,alpha2_sum,&b);
VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
VectorMultiply(b,factor,&b);
VectorClamp(&a);
VectorMultiplyAdd(grid,a,half,&a);
VectorTruncate(&a);
VectorMultiply(a,gridrcp,&a);
VectorClamp(&b);
VectorMultiplyAdd(grid,b,half,&b);
VectorTruncate(&b);
VectorMultiply(b,gridrcp,&b);
VectorMultiply(b,b,&e1);
VectorMultiply(e1,beta2_sum,&e1);
VectorMultiply(a,a,&e2);
VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
VectorMultiply(a,b,&e2);
VectorMultiply(e2,alphabeta_sum,&e2);
VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
VectorMultiplyAdd(two,e2,e1,&e2);
VectorMultiply(e2,metric,&e2);
error = e2.x + e2.y + e2.z;
if (error < bestError)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (DDS_CompressClusterFit)
#endif
{
if (error < bestError)
{
VectorCopy43(a,start);
VectorCopy43(b,end);
bestError = error;
besti = i;
bestj = j;
bestk = k;
bestIteration = iterationIndex;
}
}
}
if (k == count)
break;
VectorAdd(pointsWeights[k],part2,&part2);
k++;
}
if (j == count)
break;
VectorAdd(pointsWeights[j],part1,&part1);
j++;
}
}
if (bestIteration != iterationIndex)
break;
iterationIndex++;
if (iterationIndex == 8)
break;
VectorSubtract3(*end,*start,&axis);
if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
iterationIndex) == MagickFalse)
break;
}
o = order + (16*bestIteration);
for (i=0; i < (ssize_t) besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < (ssize_t) bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < (ssize_t) bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < (ssize_t) count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = 1.0f / MaxF(w.x,MaxF(w.y,w.z));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(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 IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface 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 ReadDDSImage method is:
%
% Image *ReadDDSImage(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 Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if (colors.a[code] && image->matte == MagickFalse)
/* Correct matte */
image->matte = MagickTrue;
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 8);
return MagickTrue;
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
MagickSizeType
alpha_bits;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 3);
return MagickTrue;
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 4);
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS 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 RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = SetMagickInfo("DDS");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT1");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT5");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if (clusterFit == MagickFalse || count == 0)
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (!image->matte)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (option != (char *) NULL && LocaleCompare(option,"true") == 0)
weightByAlpha=MagickTrue;
}
}
}
maxMipmaps=SIZE_MAX;
mipmaps=0;
if ((image->columns & (image->columns - 1)) == 0 &&
(image->rows & (image->rows - 1)) == 0)
{
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while (columns != 1 && rows != 1 && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
&image->exception);
if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
clusterFit,weightByAlpha,&image->exception) == MagickFalse)
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const PixelPacket *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(p));
else
alpha = 255;
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p++;
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression, const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value,
const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char* indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
Image*
resize_image;
register ssize_t
i;
size_t
columns,
rows;
columns = image->columns;
rows = image->rows;
for (i=0; i< (ssize_t) mipmaps; i++)
{
resize_image = ResizeImage(image,columns/2,rows/2,TriangleFilter,1.0,
exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
DestroyBlob(resize_image);
resize_image->blob=ReferenceBlob(image->blob);
WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
resize_image=DestroyImage(resize_image);
columns = DIV2(columns);
rows = DIV2(rows);
}
return(MagickTrue);
}
static void WriteSingleColorFit(Image *image, const DDSVector4* points,
const ssize_t* map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
p++;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2434_0 |
crossvul-cpp_data_good_4700_0 | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.danga.com/memcached/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <mellon@pobox.com>
* Brad Fitzpatrick <brad@danga.com>
*/
#include "memcached.h"
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sysexits.h>
#include <stddef.h>
/* FreeBSD 4.x doesn't have IOV_MAX exposed. */
#ifndef IOV_MAX
#if defined(__FreeBSD__) || defined(__APPLE__)
# define IOV_MAX 1024
#endif
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static int try_read_command(conn *c);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occured (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static void conn_set_state(conn *c, enum conn_states state);
/* stats */
static void stats_init(void);
static void server_stats(ADD_STAT add_stats, conn *c);
static void process_stat_settings(ADD_STAT add_stats, void *c);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void process_command(conn *c, char *command);
static void write_and_free(conn *c, char *buf, int bytes);
static int ensure_iov_space(conn *c);
static int add_iov(conn *c, const void *buf, int len);
static int add_msghdr(conn *c);
/* time handling */
static void set_current_time(void); /* update the global variable holding
global 32-bit seconds-since-start time
(to avoid 64 bit time_t) */
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct settings settings;
time_t process_started; /* when the process was started */
/** file scope variables **/
static conn *listen_conn = NULL;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
static enum transmit_result transmit(conn *c);
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
static rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
stats.curr_items = stats.total_items = stats.curr_conns = stats.total_conns = stats.conn_structs = 0;
stats.get_cmds = stats.set_cmds = stats.get_hits = stats.get_misses = stats.evictions = 0;
stats.curr_bytes = stats.listen_disabled_num = 0;
stats.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - 2;
stats_prefix_init();
}
static void stats_reset(void) {
STATS_LOCK();
stats.total_items = stats.total_conns = 0;
stats.evictions = 0;
stats.listen_disabled_num = 0;
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 11211;
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_msghdr(conn *c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (! msg)
return -1;
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
if (c->request_addr_size > 0) {
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
}
c->msgbytes = 0;
c->msgused++;
if (IS_UDP(c->transport)) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE);
}
return 0;
}
/*
* Free list management for connections.
*/
static conn **freeconns;
static int freetotal;
static int freecurr;
/* Lock for connection freelist */
static pthread_mutex_t conn_lock = PTHREAD_MUTEX_INITIALIZER;
static void conn_init(void) {
freetotal = 200;
freecurr = 0;
if ((freeconns = calloc(freetotal, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
}
return;
}
/*
* Returns a connection from the freelist, if any.
*/
conn *conn_from_freelist() {
conn *c;
pthread_mutex_lock(&conn_lock);
if (freecurr > 0) {
c = freeconns[--freecurr];
} else {
c = NULL;
}
pthread_mutex_unlock(&conn_lock);
return c;
}
/*
* Adds a connection to the freelist. 0 = success.
*/
bool conn_add_to_freelist(conn *c) {
bool ret = true;
pthread_mutex_lock(&conn_lock);
if (freecurr < freetotal) {
freeconns[freecurr++] = c;
ret = false;
} else {
/* try to enlarge free connections array */
size_t newsize = freetotal * 2;
conn **new_freeconns = realloc(freeconns, sizeof(conn *) * newsize);
if (new_freeconns) {
freetotal = newsize;
freeconns = new_freeconns;
freeconns[freecurr++] = c;
ret = false;
}
}
pthread_mutex_unlock(&conn_lock);
return ret;
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
}
return rv;
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base) {
conn *c = conn_from_freelist();
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
fprintf(stderr, "calloc()\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->rbuf = c->wbuf = 0;
c->ilist = 0;
c->suffixlist = 0;
c->iov = 0;
c->msglist = 0;
c->hdrbuf = 0;
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->suffixsize = SUFFIX_LIST_INITIAL;
c->iovsize = IOV_LIST_INITIAL;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize);
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 ||
c->msglist == 0 || c->suffixlist == 0) {
conn_free(c);
fprintf(stderr, "malloc()\n");
return NULL;
}
STATS_LOCK();
stats.conn_structs++;
STATS_UNLOCK();
}
c->transport = transport;
c->protocol = settings.binding_protocol;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
c->sfd = sfd;
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = c->wbytes = 0;
c->wcurr = c->wbuf;
c->rcurr = c->rbuf;
c->ritem = 0;
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
c->ileft = 0;
c->suffixleft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->write_and_go = init_state;
c->write_and_free = 0;
c->item = 0;
c->noreply = false;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
if (conn_add_to_freelist(c)) {
conn_free(c);
}
perror("event_add");
return NULL;
}
STATS_LOCK();
stats.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
if (c->item) {
item_remove(c->item);
c->item = 0;
}
if (c->ileft != 0) {
for (; c->ileft > 0; c->ileft--,c->icurr++) {
item_remove(*(c->icurr));
}
}
if (c->suffixleft != 0) {
for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) {
cache_free(c->thread->suffix_cache, *(c->suffixcurr));
}
}
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
MEMCACHED_CONN_DESTROY(c);
if (c->hdrbuf)
free(c->hdrbuf);
if (c->msglist)
free(c->msglist);
if (c->rbuf)
free(c->rbuf);
if (c->wbuf)
free(c->wbuf);
if (c->ilist)
free(c->ilist);
if (c->suffixlist)
free(c->suffixlist);
if (c->iov)
free(c->iov);
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
MEMCACHED_CONN_RELEASE(c->sfd);
close(c->sfd);
accept_new_conns(true);
conn_cleanup(c);
/* if the connection has big buffers, just free it */
if (c->rsize > READ_BUFFER_HIGHWAT || conn_add_to_freelist(c)) {
conn_free(c);
}
STATS_LOCK();
stats.curr_conns--;
STATS_UNLOCK();
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
static void conn_shrink(conn *c) {
assert(c != NULL);
if (IS_UDP(c->transport))
return;
if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) {
char *newbuf;
if (c->rcurr != c->rbuf)
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
if (newbuf) {
c->rbuf = newbuf;
c->rsize = DATA_BUFFER_SIZE;
}
/* TODO check other branch... */
c->rcurr = c->rbuf;
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]));
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0]));
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->iovsize > IOV_LIST_HIGHWAT) {
struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0]));
if (newbuf) {
c->iov = newbuf;
c->iovsize = IOV_LIST_INITIAL;
}
/* TODO check return value */
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);
if (state != c->state) {
if (settings.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state),
state_text(state));
}
c->state = state;
if (state == conn_write || state == conn_mwrite) {
MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes);
}
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov = (struct iovec *)realloc(c->iov,
(c->iovsize * 2) * sizeof(struct iovec));
if (! new_iov)
return -1;
c->iov = new_iov;
c->iovsize *= 2;
/* Point all the msghdr structures at the new list. */
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_iov(conn *c, const void *buf, int len) {
struct msghdr *m;
int leftover;
bool limit_to_mtu;
assert(c != NULL);
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets, and the first payloads of TCP replies, to
* UDP_MAX_PAYLOAD_SIZE bytes.
*/
limit_to_mtu = IS_UDP(c->transport) || (1 == c->msgused);
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(limit_to_mtu && c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (limit_to_mtu && len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
static int build_udp_headers(conn *c) {
int i;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf)
new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE);
else
new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE);
if (! new_hdrbuf)
return -1;
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = (void*)hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = 0;
*hdr++ = 0;
assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn *c, const char *str) {
size_t len;
assert(c != NULL);
if (c->noreply) {
if (settings.verbose > 1)
fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str);
c->noreply = false;
conn_set_state(c, conn_new_cmd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
return;
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->cmd, and the item is ready in c->item.
*/
static void complete_nread_ascii(conn *c) {
assert(c != NULL);
item *it = c->item;
int comm = c->cmd;
enum store_item_type ret;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) != 0) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
ret = store_item(it, comm, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_CAS:
MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes,
cas);
break;
}
#endif
switch (ret) {
case STORED:
out_string(c, "STORED");
break;
case EXISTS:
out_string(c, "EXISTS");
break;
case NOT_FOUND:
out_string(c, "NOT_FOUND");
break;
case NOT_STORED:
out_string(c, "NOT_STORED");
break;
default:
out_string(c, "SERVER_ERROR Unhandled storage type.");
}
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
/**
* get a pointer to the start of the request struct for the current command
*/
static void* binary_get_request(conn *c) {
char *ret = c->rcurr;
ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen +
c->binary_header.request.extlen);
assert(ret >= c->rbuf);
return ret;
}
/**
* get a pointer to the key in this request
*/
static char* binary_get_key(conn *c) {
return c->rcurr - (c->binary_header.request.keylen);
}
static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) {
protocol_binary_response_header* header;
assert(c);
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
/* XXX: out_string is inappropriate here */
out_string(c, "SERVER_ERROR out of memory");
return;
}
header = (protocol_binary_response_header *)c->wbuf;
header->response.magic = (uint8_t)PROTOCOL_BINARY_RES;
header->response.opcode = c->binary_header.request.opcode;
header->response.keylen = (uint16_t)htons(key_len);
header->response.extlen = (uint8_t)hdr_len;
header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
header->response.status = (uint16_t)htons(err);
header->response.bodylen = htonl(body_len);
header->response.opaque = c->opaque;
header->response.cas = htonll(c->cas);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d Writing bin response:", c->sfd);
for (ii = 0; ii < sizeof(header->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n>%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", header->bytes[ii]);
}
fprintf(stderr, "\n");
}
add_iov(c, c->wbuf, sizeof(header->response));
}
static void write_bin_error(conn *c, protocol_binary_response_status err, int swallow) {
const char *errstr = "Unknown error";
size_t len;
switch (err) {
case PROTOCOL_BINARY_RESPONSE_ENOMEM:
errstr = "Out of memory";
break;
case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
errstr = "Unknown command";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
errstr = "Not found";
break;
case PROTOCOL_BINARY_RESPONSE_EINVAL:
errstr = "Invalid arguments";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
errstr = "Data exists for key.";
break;
case PROTOCOL_BINARY_RESPONSE_E2BIG:
errstr = "Too large.";
break;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL:
errstr = "Non-numeric server-side value for incr or decr";
break;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
errstr = "Not stored.";
break;
case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR:
errstr = "Auth failure.";
break;
default:
assert(false);
errstr = "UNHANDLED ERROR";
fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err);
}
if (settings.verbose > 1) {
fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr);
}
len = strlen(errstr);
add_bin_header(c, err, 0, 0, len);
if (len > 0) {
add_iov(c, errstr, len);
}
conn_set_state(c, conn_mwrite);
if(swallow > 0) {
c->sbytes = swallow;
c->write_and_go = conn_swallow;
} else {
c->write_and_go = conn_new_cmd;
}
}
/* Form and send a response to a command over the binary protocol */
static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) {
if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET ||
c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_bin_header(c, 0, hlen, keylen, dlen);
if(dlen > 0) {
add_iov(c, d, dlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
conn_set_state(c, conn_new_cmd);
}
}
static void complete_incr_bin(conn *c) {
item *it;
char *key;
size_t nkey;
protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf;
protocol_binary_request_incr* req = binary_get_request(c);
assert(c != NULL);
assert(c->wsize >= sizeof(*rsp));
/* fix byteorder in the request */
req->message.body.delta = ntohll(req->message.body.delta);
req->message.body.initial = ntohll(req->message.body.initial);
req->message.body.expiration = ntohl(req->message.body.expiration);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int i;
fprintf(stderr, "incr ");
for (i = 0; i < nkey; i++) {
fprintf(stderr, "%c", key[i]);
}
fprintf(stderr, " %lld, %llu, %d\n",
(long long)req->message.body.delta,
(long long)req->message.body.initial,
req->message.body.expiration);
}
it = item_get(key, nkey);
if (it && (c->binary_header.request.cas == 0 ||
c->binary_header.request.cas == ITEM_get_cas(it))) {
/* Weird magic in add_delta forces me to pad here */
char tmpbuf[INCR_MAX_STORAGE_LEN];
protocol_binary_response_status st = PROTOCOL_BINARY_RESPONSE_SUCCESS;
switch(add_delta(c, it, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT,
req->message.body.delta, tmpbuf)) {
case OK:
break;
case NON_NUMERIC:
st = PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL;
break;
case EOM:
st = PROTOCOL_BINARY_RESPONSE_ENOMEM;
break;
}
if (st != PROTOCOL_BINARY_RESPONSE_SUCCESS) {
write_bin_error(c, st, 0);
} else {
rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10));
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0,
sizeof(rsp->message.body.value));
}
item_remove(it); /* release our reference */
} else if (!it && req->message.body.expiration != 0xffffffff) {
/* Save some room for the response */
rsp->message.body.value = htonll(req->message.body.initial);
it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration),
INCR_MAX_STORAGE_LEN);
if (it != NULL) {
snprintf(ITEM_data(it), INCR_MAX_STORAGE_LEN, "%llu",
(unsigned long long)req->message.body.initial);
if (store_item(it, NREAD_SET, c)) {
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value));
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
}
} else if (it) {
/* incorrect CAS */
item_remove(it); /* release our reference */
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
static void complete_update_bin(conn *c) {
protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL;
enum store_item_type ret = NOT_STORED;
assert(c != NULL);
item *it = c->item;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We don't actually receive the trailing two characters in the bin
* protocol, so we're going to just set them here */
*(ITEM_data(it) + it->nbytes - 2) = '\r';
*(ITEM_data(it) + it->nbytes - 1) = '\n';
ret = store_item(it, c->cmd, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
}
#endif
switch (ret) {
case STORED:
/* Stored */
write_bin_response(c, NULL, 0, 0, 0);
break;
case EXISTS:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
break;
case NOT_FOUND:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
break;
case NOT_STORED:
if (c->cmd == NREAD_ADD) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;
} else if(c->cmd == NREAD_REPLACE) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED;
}
write_bin_error(c, eno, 0);
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
static void process_bin_get(conn *c) {
item *it;
protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf;
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d GET ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
it = item_get(key, nkey);
if (it) {
/* the length has two unnecessary bytes ("\r\n") */
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_cmds++;
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
bodylen += nkey;
keylen = nkey;
}
add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen);
rsp->message.header.response.cas = htonll(ITEM_get_cas(it));
// add the flags
rsp->message.body.flags = htonl(strtoul(ITEM_suffix(it), NULL, 10));
add_iov(c, &rsp->message.body, sizeof(rsp->message.body));
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_iov(c, ITEM_key(it), nkey);
}
/* Add the data minus the CRLF */
add_iov(c, ITEM_data(it), it->nbytes - 2);
conn_set_state(c, conn_mwrite);
/* Remember this command so we can garbage collect it later */
c->item = it;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_cmds++;
c->thread->stats.get_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
if (c->noreply) {
conn_set_state(c, conn_new_cmd);
} else {
if (c->cmd == PROTOCOL_BINARY_CMD_GETK) {
char *ofs = c->wbuf + sizeof(protocol_binary_response_header);
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, nkey, nkey);
memcpy(ofs, key, nkey);
add_iov(c, ofs, nkey);
conn_set_state(c, conn_mwrite);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
}
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
}
static void append_bin_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *buf = c->stats.buffer + c->stats.offset;
uint32_t bodylen = klen + vlen;
protocol_binary_response_header header = {
.response.magic = (uint8_t)PROTOCOL_BINARY_RES,
.response.opcode = PROTOCOL_BINARY_CMD_STAT,
.response.keylen = (uint16_t)htons(klen),
.response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES,
.response.bodylen = htonl(bodylen),
.response.opaque = c->opaque
};
memcpy(buf, header.bytes, sizeof(header.response));
buf += sizeof(header.response);
if (klen > 0) {
memcpy(buf, key, klen);
buf += klen;
if (vlen > 0) {
memcpy(buf, val, vlen);
}
}
c->stats.offset += sizeof(header.response) + bodylen;
}
static void append_ascii_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *pos = c->stats.buffer + c->stats.offset;
uint32_t nbytes = 0;
int remaining = c->stats.size - c->stats.offset;
int room = remaining - 1;
if (klen == 0 && vlen == 0) {
nbytes = snprintf(pos, room, "END\r\n");
} else if (vlen == 0) {
nbytes = snprintf(pos, room, "STAT %s\r\n", key);
} else {
nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val);
}
c->stats.offset += nbytes;
}
static bool grow_stats_buf(conn *c, size_t needed) {
size_t nsize = c->stats.size;
size_t available = nsize - c->stats.offset;
bool rv = true;
/* Special case: No buffer -- need to allocate fresh */
if (c->stats.buffer == NULL) {
nsize = 1024;
available = c->stats.size = c->stats.offset = 0;
}
while (needed > available) {
assert(nsize > 0);
nsize = nsize << 1;
available = nsize - c->stats.offset;
}
if (nsize != c->stats.size) {
char *ptr = realloc(c->stats.buffer, nsize);
if (ptr) {
c->stats.buffer = ptr;
c->stats.size = nsize;
} else {
rv = false;
}
}
return rv;
}
static void append_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
const void *cookie)
{
/* value without a key is invalid */
if (klen == 0 && vlen > 0) {
return ;
}
conn *c = (conn*)cookie;
if (c->protocol == binary_prot) {
size_t needed = vlen + klen + sizeof(protocol_binary_response_header);
if (!grow_stats_buf(c, needed)) {
return ;
}
append_bin_stats(key, klen, val, vlen, c);
} else {
size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n"
if (!grow_stats_buf(c, needed)) {
return ;
}
append_ascii_stats(key, klen, val, vlen, c);
}
assert(c->stats.offset <= c->stats.size);
}
static void process_bin_stat(conn *c) {
char *subcommand = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d STATS ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", subcommand[ii]);
}
fprintf(stderr, "\n");
}
if (nkey == 0) {
/* request all statistics */
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strncmp(subcommand, "reset", 5) == 0) {
stats_reset();
} else if (strncmp(subcommand, "settings", 8) == 0) {
process_stat_settings(&append_stats, c);
} else if (strncmp(subcommand, "detail", 6) == 0) {
char *subcmd_pos = subcommand + 6;
if (strncmp(subcmd_pos, " dump", 5) == 0) {
int len;
char *dump_buf = stats_prefix_dump(&len);
if (dump_buf == NULL || len <= 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
return ;
} else {
append_stats("detailed", strlen("detailed"), dump_buf, len, c);
free(dump_buf);
}
} else if (strncmp(subcmd_pos, " on", 3) == 0) {
settings.detail_enabled = 1;
} else if (strncmp(subcmd_pos, " off", 4) == 0) {
settings.detail_enabled = 0;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
return;
}
} else {
if (get_stats(subcommand, nkey, &append_stats, c)) {
if (c->stats.buffer == NULL) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
return;
}
/* Append termination package and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, 0);
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) {
assert(c);
c->substate = next_substate;
c->rlbytes = c->keylen + extra;
/* Ok... do we have room for the extras and the key in the input buffer? */
ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf;
if (c->rlbytes > c->rsize - offset) {
size_t nsize = c->rsize;
size_t size = c->rlbytes + sizeof(protocol_binary_request_header);
while (size > nsize) {
nsize *= 2;
}
if (nsize != c->rsize) {
if (settings.verbose > 1) {
fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n",
c->sfd, (unsigned long)c->rsize, (unsigned long)nsize);
}
char *newm = realloc(c->rbuf, nsize);
if (newm == NULL) {
if (settings.verbose) {
fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n",
c->sfd);
}
conn_set_state(c, conn_closing);
return;
}
c->rbuf= newm;
/* rcurr should point to the same offset in the packet */
c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header);
c->rsize = nsize;
}
if (c->rbuf != c->rcurr) {
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Repack input buffer\n", c->sfd);
}
}
}
/* preserve the header in the buffer.. */
c->ritem = c->rcurr + sizeof(protocol_binary_request_header);
conn_set_state(c, conn_nread);
}
/* Just write an error message and disconnect the client */
static void handle_binary_protocol_error(conn *c) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, 0);
if (settings.verbose) {
fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n",
c->binary_header.request.opcode, c->sfd);
}
c->write_and_go = conn_closing;
}
static void init_sasl_conn(conn *c) {
assert(c);
/* should something else be returned? */
if (!settings.sasl)
return;
if (!c->sasl_conn) {
int result=sasl_server_new("memcached",
NULL, NULL, NULL, NULL,
NULL, 0, &c->sasl_conn);
if (result != SASL_OK) {
if (settings.verbose) {
fprintf(stderr, "Failed to initialize SASL conn.\n");
}
c->sasl_conn = NULL;
}
}
}
static void bin_list_sasl_mechs(conn *c) {
// Guard against a disabled SASL.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
init_sasl_conn(c);
const char *result_string = NULL;
unsigned int string_length = 0;
int result=sasl_listmech(c->sasl_conn, NULL,
"", /* What to prepend the string with */
" ", /* What to separate mechanisms with */
"", /* What to append to the string */
&result_string, &string_length,
NULL);
if (result != SASL_OK) {
/* Perhaps there's a better error for this... */
if (settings.verbose) {
fprintf(stderr, "Failed to list SASL mechanisms.\n");
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
return;
}
write_bin_response(c, (char*)result_string, 0, 0, string_length);
}
static void process_bin_sasl_auth(conn *c) {
// Guard for handling disabled SASL on the server.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
assert(c->binary_header.request.extlen == 0);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > MAX_SASL_MECH_LEN) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, vlen);
c->write_and_go = conn_swallow;
return;
}
char *key = binary_get_key(c);
assert(key);
item *it = item_alloc(key, nkey, 0, 0, vlen);
if (it == 0) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
c->write_and_go = conn_swallow;
return;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_reading_sasl_auth_data;
}
static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
}
}
static bool authenticated(conn *c) {
assert(settings.sasl);
bool rv = false;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */
rv = true;
break;
default:
if (c->sasl_conn) {
const void *uname = NULL;
sasl_getprop(c->sasl_conn, SASL_USERNAME, &uname);
rv = uname != NULL;
}
}
if (settings.verbose > 1) {
fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n",
c->cmd, rv ? "true" : "false");
}
return rv;
}
static void dispatch_bin_command(conn *c) {
int protocol_error = 0;
int extlen = c->binary_header.request.extlen;
int keylen = c->binary_header.request.keylen;
uint32_t bodylen = c->binary_header.request.bodylen;
if (settings.sasl && !authenticated(c)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
c->write_and_go = conn_closing;
return;
}
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
c->noreply = true;
/* binprot supports 16bit keys, but internals are still 8bit */
if (keylen > KEY_MAX_LENGTH) {
handle_binary_protocol_error(c);
return;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SETQ:
c->cmd = PROTOCOL_BINARY_CMD_SET;
break;
case PROTOCOL_BINARY_CMD_ADDQ:
c->cmd = PROTOCOL_BINARY_CMD_ADD;
break;
case PROTOCOL_BINARY_CMD_REPLACEQ:
c->cmd = PROTOCOL_BINARY_CMD_REPLACE;
break;
case PROTOCOL_BINARY_CMD_DELETEQ:
c->cmd = PROTOCOL_BINARY_CMD_DELETE;
break;
case PROTOCOL_BINARY_CMD_INCREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_INCREMENT;
break;
case PROTOCOL_BINARY_CMD_DECREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_DECREMENT;
break;
case PROTOCOL_BINARY_CMD_QUITQ:
c->cmd = PROTOCOL_BINARY_CMD_QUIT;
break;
case PROTOCOL_BINARY_CMD_FLUSHQ:
c->cmd = PROTOCOL_BINARY_CMD_FLUSH;
break;
case PROTOCOL_BINARY_CMD_APPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_PREPEND;
break;
case PROTOCOL_BINARY_CMD_GETQ:
c->cmd = PROTOCOL_BINARY_CMD_GET;
break;
case PROTOCOL_BINARY_CMD_GETKQ:
c->cmd = PROTOCOL_BINARY_CMD_GETK;
break;
default:
c->noreply = false;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_VERSION:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, VERSION, 0, 0, strlen(VERSION));
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_FLUSH:
if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) {
bin_read_key(c, bin_read_flush_exptime, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_NOOP:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_REPLACE:
if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) {
bin_read_key(c, bin_reading_set_header, 8);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETK:
if (extlen == 0 && bodylen == keylen && keylen > 0) {
bin_read_key(c, bin_reading_get_key, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_DELETE:
if (keylen > 0 && extlen == 0 && bodylen == keylen) {
bin_read_key(c, bin_reading_del_header, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_INCREMENT:
case PROTOCOL_BINARY_CMD_DECREMENT:
if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) {
bin_read_key(c, bin_reading_incr_header, 20);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_APPEND:
case PROTOCOL_BINARY_CMD_PREPEND:
if (keylen > 0 && extlen == 0) {
bin_read_key(c, bin_reading_set_header, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_STAT:
if (extlen == 0) {
bin_read_key(c, bin_reading_stat, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_QUIT:
if (keylen == 0 && extlen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
c->write_and_go = conn_closing;
if (c->noreply) {
conn_set_state(c, conn_closing);
}
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
bin_list_sasl_mechs(c);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_AUTH:
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (extlen == 0 && keylen != 0) {
bin_read_key(c, bin_reading_sasl_auth, 0);
} else {
protocol_error = 1;
}
break;
default:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, bodylen);
}
if (protocol_error)
handle_binary_protocol_error(c);
}
static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, vlen);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
}
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey);
if (it) {
item_unlink(it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_append_prepend(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
vlen = c->binary_header.request.bodylen - nkey;
if (settings.verbose > 1) {
fprintf(stderr, "Value len is %d\n", vlen);
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, 0, 0, vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, 0, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, vlen);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, vlen);
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_APPEND:
c->cmd = NREAD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPEND:
c->cmd = NREAD_PREPEND;
break;
default:
assert(0);
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_flush(conn *c) {
time_t exptime = 0;
protocol_binary_request_flush* req = binary_get_request(c);
if (c->binary_header.request.extlen == sizeof(req->message.body)) {
exptime = ntohl(req->message.body.expiration);
}
set_current_time();
if (exptime > 0) {
settings.oldest_live = realtime(exptime) - 1;
} else {
settings.oldest_live = current_time - 1;
}
item_flush_expired();
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_response(c, NULL, 0, 0, 0);
}
static void process_bin_delete(conn *c) {
item *it;
protocol_binary_request_delete* req = binary_get_request(c);
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
assert(c != NULL);
if (settings.verbose > 1) {
fprintf(stderr, "Deleting %s\n", key);
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey);
if (it) {
uint64_t cas = ntohll(req->message.header.request.cas);
if (cas == 0 || cas == ITEM_get_cas(it)) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
item_unlink(it);
write_bin_response(c, NULL, 0, 0, 0);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, 0);
}
item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0);
}
}
static void complete_nread_binary(conn *c) {
assert(c != NULL);
assert(c->cmd >= 0);
switch(c->substate) {
case bin_reading_set_header:
if (c->cmd == PROTOCOL_BINARY_CMD_APPEND ||
c->cmd == PROTOCOL_BINARY_CMD_PREPEND) {
process_bin_append_prepend(c);
} else {
process_bin_update(c);
}
break;
case bin_read_set_value:
complete_update_bin(c);
break;
case bin_reading_get_key:
process_bin_get(c);
break;
case bin_reading_stat:
process_bin_stat(c);
break;
case bin_reading_del_header:
process_bin_delete(c);
break;
case bin_reading_incr_header:
complete_incr_bin(c);
break;
case bin_read_flush_exptime:
process_bin_flush(c);
break;
case bin_reading_sasl_auth:
process_bin_sasl_auth(c);
break;
case bin_reading_sasl_auth_data:
process_bin_complete_sasl_auth(c);
break;
default:
fprintf(stderr, "Not handling substate %d\n", c->substate);
assert(0);
}
}
static void reset_cmd_handler(conn *c) {
c->cmd = -1;
c->substate = bin_no_state;
if(c->item != NULL) {
item_remove(c->item);
c->item = NULL;
}
conn_shrink(c);
if (c->rbytes > 0) {
conn_set_state(c, conn_parse_cmd);
} else {
conn_set_state(c, conn_waiting);
}
}
static void complete_nread(conn *c) {
assert(c != NULL);
assert(c->protocol == ascii_prot
|| c->protocol == binary_prot);
if (c->protocol == ascii_prot) {
complete_nread_ascii(c);
} else if (c->protocol == binary_prot) {
complete_nread_binary(c);
}
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns the state of storage.
*/
enum store_item_type do_store_item(item *it, int comm, conn *c) {
char *key = ITEM_key(it);
item *old_it = do_item_get(key, it->nkey);
enum store_item_type stored = NOT_STORED;
item *new_it = NULL;
int flags;
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && (comm == NREAD_REPLACE
|| comm == NREAD_APPEND || comm == NREAD_PREPEND))
{
/* replace only replaces an existing value; don't store */
} else if (comm == NREAD_CAS) {
/* validate cas operation */
if(old_it == NULL) {
// LRU expired
stored = NOT_FOUND;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.cas_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) {
// cas validates
// it and old_it may belong to different classes.
// I'm updating the stats for the one that's getting pushed out
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[old_it->slabs_clsid].cas_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_replace(old_it, it);
stored = STORED;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[old_it->slabs_clsid].cas_badval++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(settings.verbose > 1) {
fprintf(stderr, "CAS: failure: expected %llu, got %llu\n",
(unsigned long long)ITEM_get_cas(old_it),
(unsigned long long)ITEM_get_cas(it));
}
stored = EXISTS;
}
} else {
/*
* Append - combine new and old record into single one. Here it's
* atomic and thread-safe.
*/
if (comm == NREAD_APPEND || comm == NREAD_PREPEND) {
/*
* Validate CAS
*/
if (ITEM_get_cas(it) != 0) {
// CAS much be equal
if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) {
stored = EXISTS;
}
}
if (stored == NOT_STORED) {
/* we have it and old_it here - alloc memory to hold both */
/* flags was already lost - so recover them from ITEM_suffix(it) */
flags = (int) strtol(ITEM_suffix(old_it), (char **) NULL, 10);
new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */);
if (new_it == NULL) {
/* SERVER_ERROR out of memory */
if (old_it != NULL)
do_item_remove(old_it);
return NOT_STORED;
}
/* copy data from it and old_it to new_it */
if (comm == NREAD_APPEND) {
memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes);
memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(it), it->nbytes);
} else {
/* NREAD_PREPEND */
memcpy(ITEM_data(new_it), ITEM_data(it), it->nbytes);
memcpy(ITEM_data(new_it) + it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes);
}
it = new_it;
}
}
if (stored == NOT_STORED) {
if (old_it != NULL)
item_replace(old_it, it);
else
do_item_link(it);
c->cas = ITEM_get_cas(it);
stored = STORED;
}
}
if (old_it != NULL)
do_item_remove(old_it); /* release our reference */
if (new_it != NULL)
do_item_remove(new_it);
if (stored == STORED) {
c->cas = ITEM_get_cas(it);
}
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 8
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
for (s = e = command; ntokens < max_tokens - 1; ++e) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
}
s = e + 1;
}
else if (*e == '\0') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
break; /* string end */
}
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
/* set up a connection to write a buffer then free it, used for stats */
static void write_and_free(conn *c, char *buf, int bytes) {
if (buf) {
c->write_and_free = buf;
c->wcurr = buf;
c->wbytes = bytes;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
} else {
out_string(c, "SERVER_ERROR out of memory writing stats");
}
}
static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens)
{
int noreply_index = ntokens - 2;
/*
NOTE: this function is not the first place where we are going to
send the reply. We could send it instead from process_command()
if the request line has wrong number of tokens. However parsing
malformed line for "noreply" option is not reliable anyway, so
it can't be helped.
*/
if (tokens[noreply_index].value
&& strcmp(tokens[noreply_index].value, "noreply") == 0) {
c->noreply = true;
}
return c->noreply;
}
void append_stat(const char *name, ADD_STAT add_stats, conn *c,
const char *fmt, ...) {
char val_str[STAT_VAL_LEN];
int vlen;
va_list ap;
assert(name);
assert(add_stats);
assert(c);
assert(fmt);
va_start(ap, fmt);
vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap);
va_end(ap);
add_stats(name, strlen(name), val_str, vlen, c);
}
inline static void process_stats_detail(conn *c, const char *command) {
assert(c != NULL);
if (strcmp(command, "on") == 0) {
settings.detail_enabled = 1;
out_string(c, "OK");
}
else if (strcmp(command, "off") == 0) {
settings.detail_enabled = 0;
out_string(c, "OK");
}
else if (strcmp(command, "dump") == 0) {
int len;
char *stats = stats_prefix_dump(&len);
write_and_free(c, stats, len);
}
else {
out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump");
}
}
/* return server specific stats only */
static void server_stats(ADD_STAT add_stats, conn *c) {
pid_t pid = getpid();
rel_time_t now = current_time;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(&thread_stats);
struct slab_stats slab_stats;
slab_stats_aggregate(&thread_stats, &slab_stats);
#ifndef WIN32
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
#endif /* !WIN32 */
STATS_LOCK();
APPEND_STAT("pid", "%lu", (long)pid);
APPEND_STAT("uptime", "%u", now);
APPEND_STAT("time", "%ld", now + (long)process_started);
APPEND_STAT("version", "%s", VERSION);
APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *)));
#ifndef WIN32
append_stat("rusage_user", add_stats, c, "%ld.%06ld",
(long)usage.ru_utime.tv_sec,
(long)usage.ru_utime.tv_usec);
append_stat("rusage_system", add_stats, c, "%ld.%06ld",
(long)usage.ru_stime.tv_sec,
(long)usage.ru_stime.tv_usec);
#endif /* !WIN32 */
APPEND_STAT("curr_connections", "%u", stats.curr_conns - 1);
APPEND_STAT("total_connections", "%u", stats.total_conns);
APPEND_STAT("connection_structures", "%u", stats.conn_structs);
APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds);
APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds);
APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds);
APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits);
APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses);
APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses);
APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits);
APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses);
APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits);
APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses);
APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits);
APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses);
APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits);
APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval);
APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read);
APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written);
APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("accepting_conns", "%u", stats.accepting_conns);
APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num);
APPEND_STAT("threads", "%d", settings.num_threads);
APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields);
STATS_UNLOCK();
}
static void process_stat_settings(ADD_STAT add_stats, void *c) {
assert(add_stats);
APPEND_STAT("maxbytes", "%u", (unsigned int)settings.maxbytes);
APPEND_STAT("maxconns", "%d", settings.maxconns);
APPEND_STAT("tcpport", "%d", settings.port);
APPEND_STAT("udpport", "%d", settings.udpport);
APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL");
APPEND_STAT("verbosity", "%d", settings.verbose);
APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live);
APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off");
APPEND_STAT("domain_socket", "%s",
settings.socketpath ? settings.socketpath : "NULL");
APPEND_STAT("umask", "%o", settings.access);
APPEND_STAT("growth_factor", "%.2f", settings.factor);
APPEND_STAT("chunk_size", "%d", settings.chunk_size);
APPEND_STAT("num_threads", "%d", settings.num_threads);
APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter);
APPEND_STAT("detail_enabled", "%s",
settings.detail_enabled ? "yes" : "no");
APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event);
APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no");
APPEND_STAT("tcp_backlog", "%d", settings.backlog);
APPEND_STAT("binding_protocol", "%s",
prot_text(settings.binding_protocol));
APPEND_STAT("item_size_max", "%d", settings.item_size_max);
}
static void process_stat(conn *c, token_t *tokens, const size_t ntokens) {
const char *subcommand = tokens[SUBCOMMAND_TOKEN].value;
assert(c != NULL);
if (ntokens < 2) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (ntokens == 2) {
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strcmp(subcommand, "reset") == 0) {
stats_reset();
out_string(c, "RESET");
return ;
} else if (strcmp(subcommand, "detail") == 0) {
/* NOTE: how to tackle detail with binary? */
if (ntokens < 4)
process_stats_detail(c, ""); /* outputs the error message */
else
process_stats_detail(c, tokens[2].value);
/* Output already generated */
return ;
} else if (strcmp(subcommand, "settings") == 0) {
process_stat_settings(&append_stats, c);
} else if (strcmp(subcommand, "cachedump") == 0) {
char *buf;
unsigned int bytes, id, limit = 0;
if (ntokens < 5) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (!safe_strtoul(tokens[2].value, &id) ||
!safe_strtoul(tokens[3].value, &limit)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (id >= POWER_LARGEST) {
out_string(c, "CLIENT_ERROR Illegal slab id");
return;
}
buf = item_cachedump(id, limit, &bytes);
write_and_free(c, buf, bytes);
return ;
} else {
/* getting here means that the subcommand is either engine specific or
is invalid. query the engine and see. */
if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_string(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
out_string(c, "ERROR");
}
return ;
}
/* append terminator and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_string(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
/* ntokens is overwritten here... shrug.. */
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) {
char *key;
size_t nkey;
int i = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
assert(c != NULL);
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
it = item_get(key, nkey);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
item_remove(it);
break;
}
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
item_remove(it);
break;
}
}
suffix = cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
out_string(c, "SERVER_ERROR out of memory making CAS suffix");
item_remove(it);
return;
}
*(c->suffixlist + i) = suffix;
int suffix_len = snprintf(suffix, SUFFIX_SIZE,
" %llu\r\n",
(unsigned long long)ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0 ||
add_iov(c, suffix, suffix_len) != 0 ||
add_iov(c, ITEM_data(it), it->nbytes) != 0)
{
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
}
if (settings.verbose > 1)
fprintf(stderr, ">%d sending key %s\n", c->sfd, ITEM_key(it));
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_update(it);
*(c->ilist + i) = it;
i++;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_misses++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas) {
c->suffixcurr = c->suffixlist;
c->suffixleft = i;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_string(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
return;
}
static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
// does cas value exist?
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
vlen += 2;
if (vlen < 0 || vlen - 2 < 0) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
if (! item_size_ok(nkey, flags, vlen))
out_string(c, "SERVER_ERROR object too large for cache");
else
out_string(c, "SERVER_ERROR out of memory storing object");
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey);
if (it) {
item_unlink(it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) {
char temp[INCR_MAX_STORAGE_LEN];
item *it;
uint64_t delta;
char *key;
size_t nkey;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtoull(tokens[2].value, &delta)) {
out_string(c, "CLIENT_ERROR invalid numeric delta argument");
return;
}
it = item_get(key, nkey);
if (!it) {
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
return;
}
switch(add_delta(c, it, incr, delta, temp)) {
case OK:
out_string(c, temp);
break;
case NON_NUMERIC:
out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value");
break;
case EOM:
out_string(c, "SERVER_ERROR out of memory");
break;
}
item_remove(it); /* release our reference */
}
/*
* adds a delta value to a numeric item.
*
* c connection requesting the operation
* it item to adjust
* incr true to increment value, false to decrement
* delta amount to adjust value by
* buf buffer for response string
*
* returns a response string to send back to the client.
*/
enum delta_result_type do_add_delta(conn *c, item *it, const bool incr,
const int64_t delta, char *buf) {
char *ptr;
uint64_t value;
int res;
ptr = ITEM_data(it);
if (!safe_strtoull(ptr, &value)) {
return NON_NUMERIC;
}
if (incr) {
value += delta;
MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value);
} else {
if(delta > value) {
value = 0;
} else {
value -= delta;
}
MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value);
}
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.slab_stats[it->slabs_clsid].incr_hits++;
} else {
c->thread->stats.slab_stats[it->slabs_clsid].decr_hits++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value);
res = strlen(buf);
if (res + 2 > it->nbytes) { /* need to realloc */
item *new_it;
new_it = do_item_alloc(ITEM_key(it), it->nkey, atoi(ITEM_suffix(it) + 1), it->exptime, res + 2 );
if (new_it == 0) {
return EOM;
}
memcpy(ITEM_data(new_it), buf, res);
memcpy(ITEM_data(new_it) + res, "\r\n", 2);
item_replace(it, new_it);
do_item_remove(new_it); /* release our reference */
} else { /* replace in-place */
/* When changing the value without replacing the item, we
need to update the CAS on the existing item. */
ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
memcpy(ITEM_data(it), buf, res);
memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2);
}
return OK;
}
static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
item *it;
assert(c != NULL);
if (ntokens == 4) {
if (!set_noreply_maybe(c, tokens, ntokens)) {
out_string(c, "CLIENT_ERROR bad command line format. "
"Usage: delete <key> [noreply]");
return;
}
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get(key, nkey);
if (it) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_unlink(it);
item_remove(it); /* release our reference */
out_string(c, "DELETED");
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
level = strtoul(tokens[1].value, NULL, 10);
settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level;
out_string(c, "OK");
return;
}
static void process_command(conn *c, char *command) {
token_t tokens[MAX_TOKENS];
size_t ntokens;
int comm;
assert(c != NULL);
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
if (settings.verbose > 1)
fprintf(stderr, "<%d %s\n", c->sfd, command);
/*
* for commands set/add/replace, we build an item and read the data
* directly into it, then continue in nread_complete().
*/
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory preparing response");
return;
}
ntokens = tokenize_command(command, tokens, MAX_TOKENS);
if (ntokens >= 3 &&
((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) ||
(strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) {
process_get_command(c, tokens, ntokens, false);
} else if ((ntokens == 6 || ntokens == 7) &&
((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) {
process_update_command(c, tokens, ntokens, comm, false);
} else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) {
process_update_command(c, tokens, ntokens, comm, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 1);
} else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) {
process_get_command(c, tokens, ntokens, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 0);
} else if (ntokens >= 3 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) {
process_delete_command(c, tokens, ntokens);
} else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) {
process_stat(c, tokens, ntokens);
} else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) {
time_t exptime = 0;
set_current_time();
set_noreply_maybe(c, tokens, ntokens);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(ntokens == (c->noreply ? 3 : 2)) {
settings.oldest_live = current_time - 1;
item_flush_expired();
out_string(c, "OK");
return;
}
exptime = strtol(tokens[1].value, NULL, 10);
if(errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/*
If exptime is zero realtime() would return zero too, and
realtime(exptime) - 1 would overflow to the max unsigned
value. So we process exptime == 0 the same way we do when
no delay is given at all.
*/
if (exptime > 0)
settings.oldest_live = realtime(exptime) - 1;
else /* exptime == 0 */
settings.oldest_live = current_time - 1;
item_flush_expired();
out_string(c, "OK");
return;
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) {
out_string(c, "VERSION " VERSION);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) {
conn_set_state(c, conn_closing);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) {
process_verbosity_command(c, tokens, ntokens);
} else {
out_string(c, "ERROR");
}
return;
}
/*
* if we have a complete line in the buffer, process it.
*/
static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (ptr - c->rcurr > 100 ||
(strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
/*
* read a UDP request.
*/
static enum try_read_result try_read_udp(conn *c) {
int res;
assert(c != NULL);
c->request_addr_size = sizeof(c->request_addr);
res = recvfrom(c->sfd, c->rbuf, c->rsize,
0, &c->request_addr, &c->request_addr_size);
if (res > 8) {
unsigned char *buf = (unsigned char *)c->rbuf;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* Beginning of UDP packet is the request ID; save it. */
c->request_id = buf[0] * 256 + buf[1];
/* If this is a multi-packet request, drop it. */
if (buf[4] != 0 || buf[5] != 1) {
out_string(c, "SERVER_ERROR multi-packet request not supported");
return READ_NO_DATA_RECEIVED;
}
/* Don't care about any of the rest of the header. */
res -= 8;
memmove(c->rbuf, c->rbuf + 8, res);
c->rbytes += res;
c->rcurr = c->rbuf;
return READ_DATA_RECEIVED;
}
return READ_NO_DATA_RECEIVED;
}
/*
* read from network as much as we can, handle buffer overflow and connection
* close.
* before reading, move the remaining incomplete fragment of a command
* (if any) to the beginning of the buffer.
*
* To protect us from someone flooding a connection with bogus data causing
* the connection to eat up all available memory, break out and start looking
* at the data I've got after a number of reallocs...
*
* @return enum try_read_result
*/
static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
int num_allocs = 0;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
if (num_allocs == 4) {
return gotdata;
}
++num_allocs;
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't realloc input buffer\n");
c->rbytes = 0; /* ignore what we read */
out_string(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = read(c->sfd, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
static bool update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags)
return true;
if (event_del(&c->event) == -1) return false;
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) return false;
return true;
}
/*
* Sets whether we are listening for new connections or not.
*/
void do_accept_new_conns(const bool do_accept) {
conn *next;
for (next = listen_conn; next; next = next->next) {
if (do_accept) {
update_event(next, EV_READ | EV_PERSIST);
if (listen(next->sfd, settings.backlog) != 0) {
perror("listen");
}
}
else {
update_event(next, 0);
if (listen(next->sfd, 0) != 0) {
perror("listen");
}
}
}
if (do_accept) {
STATS_LOCK();
stats.accepting_conns = true;
STATS_UNLOCK();
} else {
STATS_LOCK();
stats.accepting_conns = false;
stats.listen_disabled_num++;
STATS_UNLOCK();
}
}
/*
* Transmit the next chunk of data from our list of msgbuf structures.
*
* Returns:
* TRANSMIT_COMPLETE All done writing.
* TRANSMIT_INCOMPLETE More data remaining to write.
* TRANSMIT_SOFT_ERROR Can't write any more right now.
* TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
*/
static enum transmit_result transmit(conn *c) {
assert(c != NULL);
if (c->msgcurr < c->msgused &&
c->msglist[c->msgcurr].msg_iovlen == 0) {
/* Finished writing the current msg; advance to the next. */
c->msgcurr++;
}
if (c->msgcurr < c->msgused) {
ssize_t res;
struct msghdr *m = &c->msglist[c->msgcurr];
res = sendmsg(c->sfd, m, 0);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_written += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We've written some of the data. Remove the completed
iovec entries from the list of pending writes. */
while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) {
res -= m->msg_iov->iov_len;
m->msg_iovlen--;
m->msg_iov++;
}
/* Might have written just part of the last iovec entry;
adjust it so the next write will do the rest. */
if (res > 0) {
m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res;
m->msg_iov->iov_len -= res;
}
return TRANSMIT_INCOMPLETE;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
}
return TRANSMIT_SOFT_ERROR;
}
/* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK,
we have a real error, on which we close the connection */
if (settings.verbose > 0)
perror("Failed to write, and not due to blocking");
if (IS_UDP(c->transport))
conn_set_state(c, conn_read);
else
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
} else {
return TRANSMIT_COMPLETE;
}
}
static void drive_machine(conn *c) {
bool stop = false;
int sfd, flags = 1;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, tcp_transport);
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = read(c->sfd, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes == 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
while (c->suffixleft > 0) {
char *suffix = *(c->suffixcurr);
cache_free(c->thread->suffix_cache, suffix);
c->suffixcurr++;
c->suffixleft--;
}
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
}
void event_handler(const int fd, const short which, void *arg) {
conn *c;
c = (conn *)arg;
assert(c != NULL);
c->which = which;
/* sanity */
if (fd != c->sfd) {
if (settings.verbose > 0)
fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n");
conn_close(c);
return;
}
drive_machine(c);
/* wait for next event */
return;
}
static int new_socket(struct addrinfo *ai) {
int sfd;
int flags;
if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
/*
* Sets a socket's send buffer size to the maximum allowed by the system.
*/
static void maximize_sndbuf(const int sfd) {
socklen_t intsize = sizeof(int);
int last_good = 0;
int min, max, avg;
int old_size;
/* Start with the default size. */
if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) {
if (settings.verbose > 0)
perror("getsockopt(SO_SNDBUF)");
return;
}
/* Binary-search for the real maximum. */
min = old_size;
max = MAX_SENDBUF_SIZE;
while (min <= max) {
avg = ((unsigned int)(min + max)) / 2;
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) {
last_good = avg;
min = avg + 1;
} else {
max = avg - 1;
}
}
if (settings.verbose > 1)
fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good);
}
/**
* Create a socket and bind it to a specific port number
* @param port the port number to bind to
* @param transport the transport protocol (TCP / UDP)
* @param portnumber_file A filepointer to write the port numbers to
* when they are successfully added to the list of ports we
* listen on.
*/
static int server_socket(int port, enum network_transport transport,
FILE *portnumber_file) {
int sfd;
struct linger ling = {0, 0};
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = { .ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC };
char port_buf[NI_MAXSERV];
int error;
int success = 0;
int flags =1;
hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM;
if (port == -1) {
port = 0;
}
snprintf(port_buf, sizeof(port_buf), "%d", port);
error= getaddrinfo(settings.inter, port_buf, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM)
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
else
perror("getaddrinfo()");
return 1;
}
for (next= ai; next; next= next->ai_next) {
conn *listen_conn_add;
if ((sfd = new_socket(next)) == -1) {
/* getaddrinfo can return "junk" addresses,
* we make sure at least one works before erroring.
*/
continue;
}
#ifdef IPV6_V6ONLY
if (next->ai_family == AF_INET6) {
error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags));
if (error != 0) {
perror("setsockopt");
close(sfd);
continue;
}
}
#endif
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
if (IS_UDP(transport)) {
maximize_sndbuf(sfd);
} else {
error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
}
if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
if (errno != EADDRINUSE) {
perror("bind()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
close(sfd);
continue;
} else {
success++;
if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
if (portnumber_file != NULL &&
(next->ai_addr->sa_family == AF_INET ||
next->ai_addr->sa_family == AF_INET6)) {
union {
struct sockaddr_in in;
struct sockaddr_in6 in6;
} my_sockaddr;
socklen_t len = sizeof(my_sockaddr);
if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
if (next->ai_addr->sa_family == AF_INET) {
fprintf(portnumber_file, "%s INET: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in.sin_port));
} else {
fprintf(portnumber_file, "%s INET6: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in6.sin6_port));
}
}
}
}
if (IS_UDP(transport)) {
int c;
for (c = 0; c < settings.num_threads; c++) {
/* this is guaranteed to hit all threads because we round-robin */
dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,
UDP_READ_BUFFER_SIZE, transport);
}
} else {
if (!(listen_conn_add = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
listen_conn_add->next = listen_conn;
listen_conn = listen_conn_add;
}
}
freeaddrinfo(ai);
/* Return zero iff we detected no errors in starting up connections */
return success == 0;
}
static int new_socket_unix(void) {
int sfd;
int flags;
if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket()");
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
static int server_socket_unix(const char *path, int access_mask) {
int sfd;
struct linger ling = {0, 0};
struct sockaddr_un addr;
struct stat tstat;
int flags =1;
int old_umask;
if (!path) {
return 1;
}
if ((sfd = new_socket_unix()) == -1) {
return 1;
}
/*
* Clean up a previous socket file if we left it around
*/
if (lstat(path, &tstat) == 0) {
if (S_ISSOCK(tstat.st_mode))
unlink(path);
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/*
* the memset call clears nonstandard fields in some impementations
* that otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
assert(strcmp(addr.sun_path, path) == 0);
old_umask = umask( ~(access_mask&0777));
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind()");
close(sfd);
umask(old_umask);
return 1;
}
umask(old_umask);
if (listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
return 1;
}
if (!(listen_conn = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
local_transport, main_base))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*
* We keep the current time of day in a global variable that's updated by a
* timer event. This saves us a bunch of time() system calls (we really only
* need to get the time once a second, whereas there can be tens of thousands
* of requests a second) and allows us to use server-start-relative timestamps
* rather than absolute UNIX timestamps, a space savings on systems where
* sizeof(time_t) > sizeof(unsigned int).
*/
volatile rel_time_t current_time;
static struct event clockevent;
/* time-sensitive callers can call it by hand with this, outside the normal ever-1-second timer */
static void set_current_time(void) {
struct timeval timer;
gettimeofday(&timer, NULL);
current_time = (rel_time_t) (timer.tv_sec - process_started);
}
static void clock_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
static bool initialized = false;
if (initialized) {
/* only delete the event if it's actually there. */
evtimer_del(&clockevent);
} else {
initialized = true;
}
evtimer_set(&clockevent, clock_handler, 0);
event_base_set(main_base, &clockevent);
evtimer_add(&clockevent, &t);
set_current_time();
}
static void usage(void) {
printf(PACKAGE " " VERSION "\n");
printf("-p <num> TCP port number to listen on (default: 11211)\n"
"-U <num> UDP port number to listen on (default: 11211, 0 is off)\n"
"-s <file> UNIX socket path to listen on (disables network support)\n"
"-a <mask> access mask for UNIX socket, in octal (default: 0700)\n"
"-l <ip_addr> interface to listen on (default: INADDR_ANY, all addresses)\n"
"-d run as a daemon\n"
"-r maximize core file limit\n"
"-u <username> assume identity of <username> (only when run as root)\n"
"-m <num> max memory to use for items in megabytes (default: 64 MB)\n"
"-M return error on memory exhausted (rather than removing items)\n"
"-c <num> max simultaneous connections (default: 1024)\n"
"-k lock down all paged memory. Note that there is a\n"
" limit on how much memory you may lock. Trying to\n"
" allocate more than that would fail, so be sure you\n"
" set the limit correctly for the user you started\n"
" the daemon with (not for -u <username> user;\n"
" under sh this is done with 'ulimit -S -l NUM_KB').\n"
"-v verbose (print errors/warnings while in event loop)\n"
"-vv very verbose (also print client commands/reponses)\n"
"-vvv extremely verbose (also print internal state transitions)\n"
"-h print this help and exit\n"
"-i print memcached and libevent license\n"
"-P <file> save PID in <file>, only used with -d option\n"
"-f <factor> chunk size growth factor (default: 1.25)\n"
"-n <bytes> minimum space allocated for key+value+flags (default: 48)\n");
printf("-L Try to use large memory pages (if available). Increasing\n"
" the memory page size could reduce the number of TLB misses\n"
" and improve the performance. In order to get large pages\n"
" from the OS, memcached will allocate the total item-cache\n"
" in one large chunk.\n");
printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n"
" This is used for per-prefix stats reporting. The default is\n"
" \":\" (colon). If this option is specified, stats collection\n"
" is turned on automatically; if not, then it may be turned on\n"
" by sending the \"stats detail on\" command to the server.\n");
printf("-t <num> number of threads to use (default: 4)\n");
printf("-R Maximum number of requests per event, limits the number of\n"
" requests process for a given connection to prevent \n"
" starvation (default: 20)\n");
printf("-C Disable use of CAS\n");
printf("-b Set the backlog queue limit (default: 1024)\n");
printf("-B Binding protocol - one of ascii, binary, or auto (default)\n");
printf("-I Override the size of each slab page. Adjusts max item size\n"
" (default: 1mb, min: 1k, max: 128m)\n");
#ifdef ENABLE_SASL
printf("-S Turn on Sasl authentication\n");
#endif
return;
}
static void usage_license(void) {
printf(PACKAGE " " VERSION "\n\n");
printf(
"Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are\n"
"met:\n"
"\n"
" * Redistributions of source code must retain the above copyright\n"
"notice, this list of conditions and the following disclaimer.\n"
"\n"
" * Redistributions in binary form must reproduce the above\n"
"copyright notice, this list of conditions and the following disclaimer\n"
"in the documentation and/or other materials provided with the\n"
"distribution.\n"
"\n"
" * Neither the name of the Danga Interactive nor the names of its\n"
"contributors may be used to endorse or promote products derived from\n"
"this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"\n"
"\n"
"This product includes software developed by Niels Provos.\n"
"\n"
"[ libevent ]\n"
"\n"
"Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions\n"
"are met:\n"
"1. Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
"3. All advertising materials mentioning features or use of this software\n"
" must display the following acknowledgement:\n"
" This product includes software developed by Niels Provos.\n"
"4. The name of the author may not be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n"
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
);
return;
}
static void save_pid(const pid_t pid, const char *pid_file) {
FILE *fp;
if (pid_file == NULL)
return;
if ((fp = fopen(pid_file, "w")) == NULL) {
fprintf(stderr, "Could not open the pid file %s for writing\n", pid_file);
return;
}
fprintf(fp,"%ld\n", (long)pid);
if (fclose(fp) == -1) {
fprintf(stderr, "Could not close the pid file %s.\n", pid_file);
return;
}
}
static void remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
fprintf(stderr, "Could not remove the pid file %s.\n", pid_file);
}
}
static void sig_handler(const int sig) {
printf("SIGINT handled.\n");
exit(EXIT_SUCCESS);
}
#ifndef HAVE_SIGIGNORE
static int sigignore(int sig) {
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 };
if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) {
return -1;
}
return 0;
}
#endif
/*
* On systems that supports multiple page sizes we may reduce the
* number of TLB-misses by using the biggest available page size
*/
static int enable_large_pages(void) {
#if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL)
int ret = -1;
size_t sizes[32];
int avail = getpagesizes(sizes, 32);
if (avail != -1) {
size_t max = sizes[0];
struct memcntl_mha arg = {0};
int ii;
for (ii = 1; ii < avail; ++ii) {
if (max < sizes[ii]) {
max = sizes[ii];
}
}
arg.mha_flags = 0;
arg.mha_pagesize = max;
arg.mha_cmd = MHA_MAPSIZE_BSSBRK;
if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) {
fprintf(stderr, "Failed to set large pages: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
} else {
ret = 0;
}
} else {
fprintf(stderr, "Failed to get supported pagesizes: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
}
return ret;
#else
return 0;
#endif
}
int main (int argc, char **argv) {
int c;
bool lock_memory = false;
bool do_daemonize = false;
bool preallocate = false;
int maxcore = 0;
char *username = NULL;
char *pid_file = NULL;
struct passwd *pw;
struct rlimit rlim;
char unit = '\0';
int size_max = 0;
/* listening sockets */
static int *l_socket = NULL;
/* udp socket */
static int *u_socket = NULL;
bool protocol_specified = false;
bool tcp_specified = false;
bool udp_specified = false;
/* handle SIGINT */
signal(SIGINT, sig_handler);
/* init settings */
settings_init();
/* set stderr non-buffering (for running under, say, daemontools) */
setbuf(stderr, NULL);
/* process arguments */
while (-1 != (c = getopt(argc, argv,
"a:" /* access mask for unix socket */
"p:" /* TCP port number to listen on */
"s:" /* unix socket path to listen on */
"U:" /* UDP port number to listen on */
"m:" /* max memory to use for items in megabytes */
"M" /* return error on memory exhausted */
"c:" /* max simultaneous connections */
"k" /* lock down all paged memory */
"hi" /* help, licence info */
"r" /* maximize core file limit */
"v" /* verbose */
"d" /* daemon mode */
"l:" /* interface to listen on */
"u:" /* user identity to run as */
"P:" /* save PID in file */
"f:" /* factor? */
"n:" /* minimum space allocated for key+value+flags */
"t:" /* threads */
"D:" /* prefix delimiter? */
"L" /* Large memory pages */
"R:" /* max requests per event */
"C" /* Disable use of CAS */
"b:" /* backlog queue limit */
"B:" /* Binding protocol */
"I:" /* Max item size */
"S" /* Sasl ON */
))) {
switch (c) {
case 'a':
/* access for unix domain socket, as octal mask (like chmod)*/
settings.access= strtol(optarg,NULL,8);
break;
case 'U':
settings.udpport = atoi(optarg);
udp_specified = true;
break;
case 'p':
settings.port = atoi(optarg);
tcp_specified = true;
break;
case 's':
settings.socketpath = optarg;
break;
case 'm':
settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
break;
case 'M':
settings.evict_to_free = 0;
break;
case 'c':
settings.maxconns = atoi(optarg);
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'i':
usage_license();
exit(EXIT_SUCCESS);
case 'k':
lock_memory = true;
break;
case 'v':
settings.verbose++;
break;
case 'l':
settings.inter= strdup(optarg);
break;
case 'd':
do_daemonize = true;
break;
case 'r':
maxcore = 1;
break;
case 'R':
settings.reqs_per_event = atoi(optarg);
if (settings.reqs_per_event == 0) {
fprintf(stderr, "Number of requests per event must be greater than 0\n");
return 1;
}
break;
case 'u':
username = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'f':
settings.factor = atof(optarg);
if (settings.factor <= 1.0) {
fprintf(stderr, "Factor must be greater than 1\n");
return 1;
}
break;
case 'n':
settings.chunk_size = atoi(optarg);
if (settings.chunk_size == 0) {
fprintf(stderr, "Chunk size must be greater than 0\n");
return 1;
}
break;
case 't':
settings.num_threads = atoi(optarg);
if (settings.num_threads <= 0) {
fprintf(stderr, "Number of threads must be greater than 0\n");
return 1;
}
/* There're other problems when you get above 64 threads.
* In the future we should portably detect # of cores for the
* default.
*/
if (settings.num_threads > 64) {
fprintf(stderr, "WARNING: Setting a high number of worker"
"threads is not recommended.\n"
" Set this value to the number of cores in"
" your machine or less.\n");
}
break;
case 'D':
if (! optarg || ! optarg[0]) {
fprintf(stderr, "No delimiter specified\n");
return 1;
}
settings.prefix_delimiter = optarg[0];
settings.detail_enabled = 1;
break;
case 'L' :
if (enable_large_pages() == 0) {
preallocate = true;
}
break;
case 'C' :
settings.use_cas = false;
break;
case 'b' :
settings.backlog = atoi(optarg);
break;
case 'B':
protocol_specified = true;
if (strcmp(optarg, "auto") == 0) {
settings.binding_protocol = negotiating_prot;
} else if (strcmp(optarg, "binary") == 0) {
settings.binding_protocol = binary_prot;
} else if (strcmp(optarg, "ascii") == 0) {
settings.binding_protocol = ascii_prot;
} else {
fprintf(stderr, "Invalid value for binding protocol: %s\n"
" -- should be one of auto, binary, or ascii\n", optarg);
exit(EX_USAGE);
}
break;
case 'I':
unit = optarg[strlen(optarg)-1];
if (unit == 'k' || unit == 'm' ||
unit == 'K' || unit == 'M') {
optarg[strlen(optarg)-1] = '\0';
size_max = atoi(optarg);
if (unit == 'k' || unit == 'K')
size_max *= 1024;
if (unit == 'm' || unit == 'M')
size_max *= 1024 * 1024;
settings.item_size_max = size_max;
} else {
settings.item_size_max = atoi(optarg);
}
if (settings.item_size_max < 1024) {
fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n");
return 1;
}
if (settings.item_size_max > 1024 * 1024 * 128) {
fprintf(stderr, "Cannot set item size limit higher than 128 mb.\n");
return 1;
}
if (settings.item_size_max > 1024 * 1024) {
fprintf(stderr, "WARNING: Setting item max size above 1MB is not"
" recommended!\n"
" Raising this limit increases the minimum memory requirements\n"
" and will decrease your memory efficiency.\n"
);
}
break;
case 'S': /* set Sasl authentication to true. Default is false */
#ifndef ENABLE_SASL
fprintf(stderr, "This server is not built with SASL support.\n");
exit(EX_USAGE);
#endif
settings.sasl = true;
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
return 1;
}
}
if (settings.sasl) {
if (!protocol_specified) {
settings.binding_protocol = binary_prot;
} else {
if (settings.binding_protocol != binary_prot) {
fprintf(stderr, "WARNING: You shouldn't allow the ASCII protocol while using SASL\n");
exit(EX_USAGE);
}
}
}
if (tcp_specified && !udp_specified) {
settings.udpport = settings.port;
} else if (udp_specified && !tcp_specified) {
settings.port = settings.udpport;
}
if (maxcore != 0) {
struct rlimit rlim_new;
/*
* First try raising to infinity; if that fails, try bringing
* the soft limit to the hard.
*/
if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) {
/* failed. try raising just to the old max */
rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
(void)setrlimit(RLIMIT_CORE, &rlim_new);
}
}
/*
* getrlimit again to see what we ended up with. Only fail if
* the soft limit ends up 0, because then no core files will be
* created at all.
*/
if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) {
fprintf(stderr, "failed to ensure corefile creation\n");
exit(EX_OSERR);
}
}
/*
* If needed, increase rlimits to allow as many connections
* as needed.
*/
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to getrlimit number of files\n");
exit(EX_OSERR);
} else {
int maxfiles = settings.maxconns;
if (rlim.rlim_cur < maxfiles)
rlim.rlim_cur = maxfiles;
if (rlim.rlim_max < rlim.rlim_cur)
rlim.rlim_max = rlim.rlim_cur;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to set rlimit for open files. Try running as root or requesting smaller maxconns value.\n");
exit(EX_OSERR);
}
}
/* lose root privileges if we have them */
if (getuid() == 0 || geteuid() == 0) {
if (username == 0 || *username == '\0') {
fprintf(stderr, "can't run as root without the -u switch\n");
exit(EX_USAGE);
}
if ((pw = getpwnam(username)) == 0) {
fprintf(stderr, "can't find the user %s to switch to\n", username);
exit(EX_NOUSER);
}
if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
fprintf(stderr, "failed to assume identity of user %s\n", username);
exit(EX_OSERR);
}
}
/* Initialize Sasl if -S was specified */
if (settings.sasl) {
init_sasl();
}
/* daemonize if requested */
/* if we want to ensure our ability to dump core, don't chdir to / */
if (do_daemonize) {
if (sigignore(SIGHUP) == -1) {
perror("Failed to ignore SIGHUP");
}
if (daemonize(maxcore, settings.verbose) == -1) {
fprintf(stderr, "failed to daemon() in order to daemonize\n");
exit(EXIT_FAILURE);
}
}
/* lock paged memory if needed */
if (lock_memory) {
#ifdef HAVE_MLOCKALL
int res = mlockall(MCL_CURRENT | MCL_FUTURE);
if (res != 0) {
fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n",
strerror(errno));
}
#else
fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n");
#endif
}
/* initialize main thread libevent instance */
main_base = event_init();
/* initialize other stuff */
stats_init();
assoc_init();
conn_init();
slabs_init(settings.maxbytes, settings.factor, preallocate);
/*
* ignore SIGPIPE signals; we can use errno == EPIPE if we
* need that information
*/
if (sigignore(SIGPIPE) == -1) {
perror("failed to ignore SIGPIPE; sigaction");
exit(EX_OSERR);
}
/* start up worker threads if MT mode */
thread_init(settings.num_threads, main_base);
/* save the PID in if we're a daemon, do this after thread_init due to
a file descriptor handling bug somewhere in libevent */
if (start_assoc_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (do_daemonize)
save_pid(getpid(), pid_file);
/* initialise clock event */
clock_handler(0, 0, 0);
/* create unix mode sockets after dropping privileges */
if (settings.socketpath != NULL) {
errno = 0;
if (server_socket_unix(settings.socketpath,settings.access)) {
vperror("failed to listen on UNIX socket: %s", settings.socketpath);
exit(EX_OSERR);
}
}
/* create the listening socket, bind it, and init */
if (settings.socketpath == NULL) {
int udp_port;
const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME");
char temp_portnumber_filename[PATH_MAX];
FILE *portnumber_file = NULL;
if (portnumber_filename != NULL) {
snprintf(temp_portnumber_filename,
sizeof(temp_portnumber_filename),
"%s.lck", portnumber_filename);
portnumber_file = fopen(temp_portnumber_filename, "a");
if (portnumber_file == NULL) {
fprintf(stderr, "Failed to open \"%s\": %s\n",
temp_portnumber_filename, strerror(errno));
}
}
errno = 0;
if (settings.port && server_socket(settings.port, tcp_transport,
portnumber_file)) {
vperror("failed to listen on TCP port %d", settings.port);
exit(EX_OSERR);
}
/*
* initialization order: first create the listening sockets
* (may need root on low ports), then drop root if needed,
* then daemonise if needed, then init libevent (in some cases
* descriptors created by libevent wouldn't survive forking).
*/
udp_port = settings.udpport ? settings.udpport : settings.port;
/* create the UDP listening socket and bind it */
errno = 0;
if (settings.udpport && server_socket(settings.udpport, udp_transport,
portnumber_file)) {
vperror("failed to listen on UDP port %d", settings.udpport);
exit(EX_OSERR);
}
if (portnumber_file) {
fclose(portnumber_file);
rename(temp_portnumber_filename, portnumber_filename);
}
}
/* Drop privileges no longer needed */
drop_privileges();
/* enter the event loop */
event_base_loop(main_base, 0);
stop_assoc_maintenance_thread();
/* remove the PID file if we're a daemon */
if (do_daemonize)
remove_pidfile(pid_file);
/* Clean up strdup() call for bind() address */
if (settings.inter)
free(settings.inter);
if (l_socket)
free(l_socket);
if (u_socket)
free(u_socket);
return EXIT_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4700_0 |
crossvul-cpp_data_good_3192_0 | /*
* bplist.c
* Binary plist implementation
*
* Copyright (c) 2011-2017 Nikias Bassen, All Rights Reserved.
* Copyright (c) 2008-2010 Jonathan Beck, All Rights Reserved.
*
* This library 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.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <plist/plist.h>
#include "plist.h"
#include "hashtable.h"
#include "bytearray.h"
#include "ptrarray.h"
#include <node.h>
#include <node_iterator.h>
/* Magic marker and size. */
#define BPLIST_MAGIC ((uint8_t*)"bplist")
#define BPLIST_MAGIC_SIZE 6
#define BPLIST_VERSION ((uint8_t*)"00")
#define BPLIST_VERSION_SIZE 2
typedef struct __attribute__((packed)) {
uint8_t unused[6];
uint8_t offset_size;
uint8_t ref_size;
uint64_t num_objects;
uint64_t root_object_index;
uint64_t offset_table_offset;
} bplist_trailer_t;
enum
{
BPLIST_NULL = 0x00,
BPLIST_FALSE = 0x08,
BPLIST_TRUE = 0x09,
BPLIST_FILL = 0x0F, /* will be used for length grabbing */
BPLIST_UINT = 0x10,
BPLIST_REAL = 0x20,
BPLIST_DATE = 0x30,
BPLIST_DATA = 0x40,
BPLIST_STRING = 0x50,
BPLIST_UNICODE = 0x60,
BPLIST_UNK_0x70 = 0x70,
BPLIST_UID = 0x80,
BPLIST_ARRAY = 0xA0,
BPLIST_SET = 0xC0,
BPLIST_DICT = 0xD0,
BPLIST_MASK = 0xF0
};
union plist_uint_ptr
{
const void *src;
uint8_t *u8ptr;
uint16_t *u16ptr;
uint32_t *u32ptr;
uint64_t *u64ptr;
};
#define get_unaligned(ptr) \
({ \
struct __attribute__((packed)) { \
typeof(*(ptr)) __v; \
} *__p = (void *) (ptr); \
__p->__v; \
})
#ifndef bswap16
#define bswap16(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
#endif
#ifndef bswap32
#define bswap32(x) ((((x) & 0xFF000000) >> 24) \
| (((x) & 0x00FF0000) >> 8) \
| (((x) & 0x0000FF00) << 8) \
| (((x) & 0x000000FF) << 24))
#endif
#ifndef bswap64
#define bswap64(x) ((((x) & 0xFF00000000000000ull) >> 56) \
| (((x) & 0x00FF000000000000ull) >> 40) \
| (((x) & 0x0000FF0000000000ull) >> 24) \
| (((x) & 0x000000FF00000000ull) >> 8) \
| (((x) & 0x00000000FF000000ull) << 8) \
| (((x) & 0x0000000000FF0000ull) << 24) \
| (((x) & 0x000000000000FF00ull) << 40) \
| (((x) & 0x00000000000000FFull) << 56))
#endif
#ifndef be16toh
#ifdef __BIG_ENDIAN__
#define be16toh(x) (x)
#else
#define be16toh(x) bswap16(x)
#endif
#endif
#ifndef be32toh
#ifdef __BIG_ENDIAN__
#define be32toh(x) (x)
#else
#define be32toh(x) bswap32(x)
#endif
#endif
#ifndef be64toh
#ifdef __BIG_ENDIAN__
#define be64toh(x) (x)
#else
#define be64toh(x) bswap64(x)
#endif
#endif
#ifdef __BIG_ENDIAN__
#define beNtoh(x,n) (x >> ((8-n) << 3))
#else
#define beNtoh(x,n) be64toh(x << ((8-n) << 3))
#endif
#define UINT_TO_HOST(x, n) \
({ \
union plist_uint_ptr __up; \
__up.src = (n > 8) ? x + (n - 8) : x; \
(n >= 8 ? be64toh( get_unaligned(__up.u64ptr) ) : \
(n == 4 ? be32toh( get_unaligned(__up.u32ptr) ) : \
(n == 2 ? be16toh( get_unaligned(__up.u16ptr) ) : \
(n == 1 ? *__up.u8ptr : \
beNtoh( get_unaligned(__up.u64ptr), n) \
)))); \
})
#define get_needed_bytes(x) \
( ((uint64_t)x) < (1ULL << 8) ? 1 : \
( ((uint64_t)x) < (1ULL << 16) ? 2 : \
( ((uint64_t)x) < (1ULL << 24) ? 3 : \
( ((uint64_t)x) < (1ULL << 32) ? 4 : 8))))
#define get_real_bytes(x) (x == (float) x ? sizeof(float) : sizeof(double))
#if (defined(__LITTLE_ENDIAN__) \
&& !defined(__FLOAT_WORD_ORDER__)) \
|| (defined(__FLOAT_WORD_ORDER__) \
&& __FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define float_bswap64(x) bswap64(x)
#define float_bswap32(x) bswap32(x)
#else
#define float_bswap64(x) (x)
#define float_bswap32(x) (x)
#endif
#define NODE_IS_ROOT(x) (((node_t*)x)->isRoot)
struct bplist_data {
const char* data;
uint64_t size;
uint64_t num_objects;
uint8_t ref_size;
uint8_t offset_size;
const char* offset_table;
uint32_t level;
plist_t used_indexes;
};
#ifdef DEBUG
static int plist_bin_debug = 0;
#define PLIST_BIN_ERR(...) if (plist_bin_debug) { fprintf(stderr, "libplist[binparser] ERROR: " __VA_ARGS__); }
#else
#define PLIST_BIN_ERR(...)
#endif
void plist_bin_init(void)
{
/* init binary plist stuff */
#ifdef DEBUG
char *env_debug = getenv("PLIST_BIN_DEBUG");
if (env_debug && !strcmp(env_debug, "1")) {
plist_bin_debug = 1;
}
#endif
}
void plist_bin_deinit(void)
{
/* deinit binary plist stuff */
}
static plist_t parse_bin_node_at_index(struct bplist_data *bplist, uint32_t node_index);
static plist_t parse_uint_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
size = 1 << size; // make length less misleading
switch (size)
{
case sizeof(uint8_t):
case sizeof(uint16_t):
case sizeof(uint32_t):
case sizeof(uint64_t):
data->length = sizeof(uint64_t);
break;
case 16:
data->length = size;
break;
default:
free(data);
PLIST_BIN_ERR("%s: Invalid byte size for integer node\n", __func__);
return NULL;
};
data->intval = UINT_TO_HOST(*bnode, size);
(*bnode) += size;
data->type = PLIST_UINT;
return node_create(NULL, data);
}
static plist_t parse_real_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
uint8_t buf[8];
size = 1 << size; // make length less misleading
switch (size)
{
case sizeof(uint32_t):
*(uint32_t*)buf = float_bswap32(*(uint32_t*)*bnode);
data->realval = *(float *) buf;
break;
case sizeof(uint64_t):
*(uint64_t*)buf = float_bswap64(*(uint64_t*)*bnode);
data->realval = *(double *) buf;
break;
default:
free(data);
PLIST_BIN_ERR("%s: Invalid byte size for real node\n", __func__);
return NULL;
}
data->type = PLIST_REAL;
data->length = sizeof(double);
return node_create(NULL, data);
}
static plist_t parse_date_node(const char **bnode, uint8_t size)
{
plist_t node = parse_real_node(bnode, size);
plist_data_t data = plist_get_data(node);
data->type = PLIST_DATE;
return node;
}
static plist_t parse_string_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_STRING;
data->strval = (char *) malloc(sizeof(char) * (size + 1));
if (!data->strval) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(char) * (size + 1));
return NULL;
}
memcpy(data->strval, *bnode, size);
data->strval[size] = '\0';
data->length = strlen(data->strval);
return node_create(NULL, data);
}
static char *plist_utf16_to_utf8(uint16_t *unistr, long len, long *items_read, long *items_written)
{
if (!unistr || (len <= 0)) return NULL;
char *outbuf;
int p = 0;
long i = 0;
uint16_t wc;
uint32_t w;
int read_lead_surrogate = 0;
outbuf = (char*)malloc(4*(len+1));
if (!outbuf) {
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, (uint64_t)(4*(len+1)));
return NULL;
}
while (i < len) {
wc = unistr[i++];
if (wc >= 0xD800 && wc <= 0xDBFF) {
if (!read_lead_surrogate) {
read_lead_surrogate = 1;
w = 0x010000 + ((wc & 0x3FF) << 10);
} else {
// This is invalid, the next 16 bit char should be a trail surrogate.
// Handling error by skipping.
read_lead_surrogate = 0;
}
} else if (wc >= 0xDC00 && wc <= 0xDFFF) {
if (read_lead_surrogate) {
read_lead_surrogate = 0;
w = w | (wc & 0x3FF);
outbuf[p++] = (char)(0xF0 + ((w >> 18) & 0x7));
outbuf[p++] = (char)(0x80 + ((w >> 12) & 0x3F));
outbuf[p++] = (char)(0x80 + ((w >> 6) & 0x3F));
outbuf[p++] = (char)(0x80 + (w & 0x3F));
} else {
// This is invalid. A trail surrogate should always follow a lead surrogate.
// Handling error by skipping
}
} else if (wc >= 0x800) {
outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF));
outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F));
outbuf[p++] = (char)(0x80 + (wc & 0x3F));
} else if (wc >= 0x80) {
outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F));
outbuf[p++] = (char)(0x80 + (wc & 0x3F));
} else {
outbuf[p++] = (char)(wc & 0x7F);
}
}
if (items_read) {
*items_read = i;
}
if (items_written) {
*items_written = p;
}
outbuf[p] = 0;
return outbuf;
}
static plist_t parse_unicode_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
uint64_t i = 0;
uint16_t *unicodestr = NULL;
char *tmpstr = NULL;
long items_read = 0;
long items_written = 0;
data->type = PLIST_STRING;
unicodestr = (uint16_t*) malloc(sizeof(uint16_t) * size);
if (!unicodestr) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(uint16_t) * size);
return NULL;
}
for (i = 0; i < size; i++)
unicodestr[i] = be16toh(((uint16_t*)*bnode)[i]);
tmpstr = plist_utf16_to_utf8(unicodestr, size, &items_read, &items_written);
free(unicodestr);
if (!tmpstr) {
plist_free_data(data);
return NULL;
}
tmpstr[items_written] = '\0';
data->type = PLIST_STRING;
data->strval = realloc(tmpstr, items_written+1);
if (!data->strval)
data->strval = tmpstr;
data->length = items_written;
return node_create(NULL, data);
}
static plist_t parse_data_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_DATA;
data->length = size;
data->buff = (uint8_t *) malloc(sizeof(uint8_t) * size);
if (!data->strval) {
plist_free_data(data);
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(uint8_t) * size);
return NULL;
}
memcpy(data->buff, *bnode, sizeof(uint8_t) * size);
return node_create(NULL, data);
}
static plist_t parse_dict_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint64_t str_i = 0, str_j = 0;
uint64_t index1, index2;
plist_data_t data = plist_new_plist_data();
const char *index1_ptr = NULL;
const char *index2_ptr = NULL;
data->type = PLIST_DICT;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_i = j * bplist->ref_size;
str_j = (j + size) * bplist->ref_size;
index1_ptr = (*bnode) + str_i;
index2_ptr = (*bnode) + str_j;
if ((index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) ||
(index2_ptr < bplist->data || index2_ptr + bplist->ref_size > bplist->offset_table)) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 " is outside of valid range\n", __func__, j);
return NULL;
}
index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size);
index2 = UINT_TO_HOST(index2_ptr, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": key index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
if (index2 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": value index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
/* process key node */
plist_t key = parse_bin_node_at_index(bplist, index1);
if (!key) {
plist_free(node);
return NULL;
}
if (plist_get_data(key)->type != PLIST_STRING) {
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": invalid node type for key\n", __func__, j);
plist_free(key);
plist_free(node);
return NULL;
}
/* enforce key type */
plist_get_data(key)->type = PLIST_KEY;
if (!plist_get_data(key)->strval) {
PLIST_BIN_ERR("%s: dict entry %" PRIu64 ": key must not be NULL\n", __func__, j);
plist_free(key);
plist_free(node);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index2);
if (!val) {
plist_free(key);
plist_free(node);
return NULL;
}
node_attach(node, key);
node_attach(node, val);
}
return node;
}
static plist_t parse_array_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint64_t str_j = 0;
uint64_t index1;
plist_data_t data = plist_new_plist_data();
const char *index1_ptr = NULL;
data->type = PLIST_ARRAY;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_j = j * bplist->ref_size;
index1_ptr = (*bnode) + str_j;
if (index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) {
plist_free(node);
PLIST_BIN_ERR("%s: array item %" PRIu64 " is outside of valid range\n", __func__, j);
return NULL;
}
index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
PLIST_BIN_ERR("%s: array item %" PRIu64 " object index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index1);
if (!val) {
plist_free(node);
return NULL;
}
node_attach(node, val);
}
return node;
}
static plist_t parse_uid_node(const char **bnode, uint8_t size)
{
plist_data_t data = plist_new_plist_data();
size = size + 1;
data->intval = UINT_TO_HOST(*bnode, size);
if (data->intval > UINT32_MAX) {
PLIST_BIN_ERR("%s: value %" PRIu64 " too large for UID node (must be <= %u)\n", __func__, (uint64_t)data->intval, UINT32_MAX);
free(data);
return NULL;
}
(*bnode) += size;
data->type = PLIST_UID;
data->length = sizeof(uint64_t);
return node_create(NULL, data);
}
static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (size*2 < size) {
PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__);
return NULL;
}
if (*object + size*2 < *object || *object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DICT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
static plist_t parse_bin_node_at_index(struct bplist_data *bplist, uint32_t node_index)
{
int i = 0;
const char* ptr = NULL;
plist_t plist = NULL;
const char* idx_ptr = NULL;
if (node_index >= bplist->num_objects) {
PLIST_BIN_ERR("node index (%u) must be smaller than the number of objects (%" PRIu64 ")\n", node_index, bplist->num_objects);
return NULL;
}
idx_ptr = bplist->offset_table + node_index * bplist->offset_size;
if (idx_ptr < bplist->offset_table ||
idx_ptr >= bplist->offset_table + bplist->num_objects * bplist->offset_size) {
PLIST_BIN_ERR("node index %u points outside of valid range\n", node_index);
return NULL;
}
ptr = bplist->data + UINT_TO_HOST(idx_ptr, bplist->offset_size);
/* make sure the node offset is in a sane range */
if ((ptr < bplist->data) || (ptr >= bplist->offset_table)) {
PLIST_BIN_ERR("offset for node index %u points outside of valid range\n", node_index);
return NULL;
}
/* store node_index for current recursion level */
if (plist_array_get_size(bplist->used_indexes) < bplist->level+1) {
while (plist_array_get_size(bplist->used_indexes) < bplist->level+1) {
plist_array_append_item(bplist->used_indexes, plist_new_uint(node_index));
}
} else {
plist_array_set_item(bplist->used_indexes, plist_new_uint(node_index), bplist->level);
}
/* recursion check */
if (bplist->level > 0) {
for (i = bplist->level-1; i >= 0; i--) {
plist_t node_i = plist_array_get_item(bplist->used_indexes, i);
plist_t node_level = plist_array_get_item(bplist->used_indexes, bplist->level);
if (plist_compare_node_value(node_i, node_level)) {
PLIST_BIN_ERR("recursion detected in binary plist\n");
return NULL;
}
}
}
/* finally parse node */
bplist->level++;
plist = parse_bin_node(bplist, &ptr);
bplist->level--;
return plist;
}
PLIST_API void plist_from_bin(const char *plist_bin, uint32_t length, plist_t * plist)
{
bplist_trailer_t *trailer = NULL;
uint8_t offset_size = 0;
uint8_t ref_size = 0;
uint64_t num_objects = 0;
uint64_t root_object = 0;
const char *offset_table = NULL;
const char *start_data = NULL;
const char *end_data = NULL;
//first check we have enough data
if (!(length >= BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE + sizeof(bplist_trailer_t))) {
PLIST_BIN_ERR("plist data is to small to hold a binary plist\n");
return;
}
//check that plist_bin in actually a plist
if (memcmp(plist_bin, BPLIST_MAGIC, BPLIST_MAGIC_SIZE) != 0) {
PLIST_BIN_ERR("bplist magic mismatch\n");
return;
}
//check for known version
if (memcmp(plist_bin + BPLIST_MAGIC_SIZE, BPLIST_VERSION, BPLIST_VERSION_SIZE) != 0) {
PLIST_BIN_ERR("unsupported binary plist version '%.2s\n", plist_bin+BPLIST_MAGIC_SIZE);
return;
}
start_data = plist_bin + BPLIST_MAGIC_SIZE + BPLIST_VERSION_SIZE;
end_data = plist_bin + length - sizeof(bplist_trailer_t);
//now parse trailer
trailer = (bplist_trailer_t*)end_data;
offset_size = trailer->offset_size;
ref_size = trailer->ref_size;
num_objects = be64toh(trailer->num_objects);
root_object = be64toh(trailer->root_object_index);
offset_table = (char *)(plist_bin + be64toh(trailer->offset_table_offset));
if (num_objects == 0) {
PLIST_BIN_ERR("number of objects must be larger than 0\n");
return;
}
if (offset_size == 0) {
PLIST_BIN_ERR("offset size in trailer must be larger than 0\n");
return;
}
if (ref_size == 0) {
PLIST_BIN_ERR("object reference size in trailer must be larger than 0\n");
return;
}
if (root_object >= num_objects) {
PLIST_BIN_ERR("root object index (%" PRIu64 ") must be smaller than number of objects (%" PRIu64 ")\n", root_object, num_objects);
return;
}
if (offset_table < start_data || offset_table >= end_data) {
PLIST_BIN_ERR("offset table offset points outside of valid range\n");
return;
}
if (num_objects * offset_size < num_objects) {
PLIST_BIN_ERR("integer overflow when calculating offset table size (too many objects)\n");
return;
}
if (offset_table + num_objects * offset_size > end_data) {
PLIST_BIN_ERR("offset table points outside of valid range\n");
return;
}
struct bplist_data bplist;
bplist.data = plist_bin;
bplist.size = length;
bplist.num_objects = num_objects;
bplist.ref_size = ref_size;
bplist.offset_size = offset_size;
bplist.offset_table = offset_table;
bplist.level = 0;
bplist.used_indexes = plist_new_array();
if (!bplist.used_indexes) {
PLIST_BIN_ERR("failed to create array to hold used node indexes. Out of memory?\n");
return;
}
*plist = parse_bin_node_at_index(&bplist, root_object);
plist_free(bplist.used_indexes);
}
static unsigned int plist_data_hash(const void* key)
{
plist_data_t data = plist_get_data((plist_t) key);
unsigned int hash = data->type;
unsigned int i = 0;
char *buff = NULL;
unsigned int size = 0;
switch (data->type)
{
case PLIST_BOOLEAN:
case PLIST_UINT:
case PLIST_REAL:
case PLIST_DATE:
case PLIST_UID:
buff = (char *) &data->intval; //works also for real as we use an union
size = 8;
break;
case PLIST_KEY:
case PLIST_STRING:
buff = data->strval;
size = data->length;
break;
case PLIST_DATA:
case PLIST_ARRAY:
case PLIST_DICT:
//for these types only hash pointer
buff = (char *) &key;
size = sizeof(const void*);
break;
default:
break;
}
// now perform hash using djb2 hashing algorithm
// see: http://www.cse.yorku.ca/~oz/hash.html
hash += 5381;
for (i = 0; i < size; buff++, i++) {
hash = ((hash << 5) + hash) + *buff;
}
return hash;
}
struct serialize_s
{
ptrarray_t* objects;
hashtable_t* ref_table;
};
static void serialize_plist(node_t* node, void* data)
{
uint64_t *index_val = NULL;
struct serialize_s *ser = (struct serialize_s *) data;
uint64_t current_index = ser->objects->len;
//first check that node is not yet in objects
void* val = hash_table_lookup(ser->ref_table, node);
if (val)
{
//data is already in table
return;
}
//insert new ref
index_val = (uint64_t *) malloc(sizeof(uint64_t));
assert(index_val != NULL);
*index_val = current_index;
hash_table_insert(ser->ref_table, node, index_val);
//now append current node to object array
ptr_array_add(ser->objects, node);
//now recurse on children
node_iterator_t *ni = node_iterator_create(node->children);
node_t *ch;
while ((ch = node_iterator_next(ni))) {
serialize_plist(ch, data);
}
node_iterator_destroy(ni);
return;
}
#define Log2(x) (x == 8 ? 3 : (x == 4 ? 2 : (x == 2 ? 1 : 0)))
static void write_int(bytearray_t * bplist, uint64_t val)
{
int size = get_needed_bytes(val);
uint8_t sz;
//do not write 3bytes int node
if (size == 3)
size++;
sz = BPLIST_UINT | Log2(size);
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, (uint8_t*)&val + (8-size), size);
}
static void write_uint(bytearray_t * bplist, uint64_t val)
{
uint8_t sz = BPLIST_UINT | 4;
uint64_t zero = 0;
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, &zero, sizeof(uint64_t));
byte_array_append(bplist, &val, sizeof(uint64_t));
}
static void write_real(bytearray_t * bplist, double val)
{
int size = get_real_bytes(val); //cheat to know used space
uint8_t buff[9];
buff[0] = BPLIST_REAL | Log2(size);
if (size == sizeof(float)) {
float floatval = (float)val;
*(uint32_t*)(buff+1) = float_bswap32(*(uint32_t*)&floatval);
} else {
*(uint64_t*)(buff+1) = float_bswap64(*(uint64_t*)&val);
}
byte_array_append(bplist, buff, size+1);
}
static void write_date(bytearray_t * bplist, double val)
{
uint8_t buff[9];
buff[0] = BPLIST_DATE | 3;
*(uint64_t*)(buff+1) = float_bswap64(*(uint64_t*)&val);
byte_array_append(bplist, buff, sizeof(buff));
}
static void write_raw_data(bytearray_t * bplist, uint8_t mark, uint8_t * val, uint64_t size)
{
uint8_t marker = mark | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
if (BPLIST_UNICODE==mark) size <<= 1;
byte_array_append(bplist, val, size);
}
static void write_data(bytearray_t * bplist, uint8_t * val, uint64_t size)
{
write_raw_data(bplist, BPLIST_DATA, val, size);
}
static void write_string(bytearray_t * bplist, char *val)
{
uint64_t size = strlen(val);
write_raw_data(bplist, BPLIST_STRING, (uint8_t *) val, size);
}
static void write_unicode(bytearray_t * bplist, uint16_t * val, uint64_t size)
{
uint64_t i = 0;
uint16_t *buff = (uint16_t*)malloc(size << 1);
for (i = 0; i < size; i++)
buff[i] = be16toh(val[i]);
write_raw_data(bplist, BPLIST_UNICODE, (uint8_t*)buff, size);
free(buff);
}
static void write_array(bytearray_t * bplist, node_t* node, hashtable_t* ref_table, uint8_t ref_size)
{
node_t* cur = NULL;
uint64_t i = 0;
uint64_t size = node_n_children(node);
uint8_t marker = BPLIST_ARRAY | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(cur), i++) {
uint64_t idx = *(uint64_t *) (hash_table_lookup(ref_table, cur));
idx = be64toh(idx);
byte_array_append(bplist, (uint8_t*)&idx + (sizeof(uint64_t) - ref_size), ref_size);
}
}
static void write_dict(bytearray_t * bplist, node_t* node, hashtable_t* ref_table, uint8_t ref_size)
{
node_t* cur = NULL;
uint64_t i = 0;
uint64_t size = node_n_children(node) / 2;
uint8_t marker = BPLIST_DICT | (size < 15 ? size : 0xf);
byte_array_append(bplist, &marker, sizeof(uint8_t));
if (size >= 15) {
write_int(bplist, size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(node_next_sibling(cur)), i++) {
uint64_t idx1 = *(uint64_t *) (hash_table_lookup(ref_table, cur));
idx1 = be64toh(idx1);
byte_array_append(bplist, (uint8_t*)&idx1 + (sizeof(uint64_t) - ref_size), ref_size);
}
for (i = 0, cur = node_first_child(node); cur && i < size; cur = node_next_sibling(node_next_sibling(cur)), i++) {
uint64_t idx2 = *(uint64_t *) (hash_table_lookup(ref_table, cur->next));
idx2 = be64toh(idx2);
byte_array_append(bplist, (uint8_t*)&idx2 + (sizeof(uint64_t) - ref_size), ref_size);
}
}
static void write_uid(bytearray_t * bplist, uint64_t val)
{
val = (uint32_t)val;
int size = get_needed_bytes(val);
uint8_t sz;
//do not write 3bytes int node
if (size == 3)
size++;
sz = BPLIST_UID | (size-1); // yes, this is what Apple does...
val = be64toh(val);
byte_array_append(bplist, &sz, 1);
byte_array_append(bplist, (uint8_t*)&val + (8-size), size);
}
static int is_ascii_string(char* s, int len)
{
int ret = 1, i = 0;
for(i = 0; i < len; i++)
{
if ( !isascii( s[i] ) )
{
ret = 0;
break;
}
}
return ret;
}
static uint16_t *plist_utf8_to_utf16(char *unistr, long size, long *items_read, long *items_written)
{
uint16_t *outbuf;
int p = 0;
long i = 0;
unsigned char c0;
unsigned char c1;
unsigned char c2;
unsigned char c3;
uint32_t w;
outbuf = (uint16_t*)malloc(((size*2)+1)*sizeof(uint16_t));
if (!outbuf) {
PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, (uint64_t)((size*2)+1)*sizeof(uint16_t));
return NULL;
}
while (i < size) {
c0 = unistr[i];
c1 = (i < size-1) ? unistr[i+1] : 0;
c2 = (i < size-2) ? unistr[i+2] : 0;
c3 = (i < size-3) ? unistr[i+3] : 0;
if ((c0 >= 0xF0) && (i < size-3) && (c1 >= 0x80) && (c2 >= 0x80) && (c3 >= 0x80)) {
// 4 byte sequence. Need to generate UTF-16 surrogate pair
w = ((((c0 & 7) << 18) + ((c1 & 0x3F) << 12) + ((c2 & 0x3F) << 6) + (c3 & 0x3F)) & 0x1FFFFF) - 0x010000;
outbuf[p++] = 0xD800 + (w >> 10);
outbuf[p++] = 0xDC00 + (w & 0x3FF);
i+=4;
} else if ((c0 >= 0xE0) && (i < size-2) && (c1 >= 0x80) && (c2 >= 0x80)) {
// 3 byte sequence
outbuf[p++] = ((c2 & 0x3F) + ((c1 & 3) << 6)) + (((c1 >> 2) & 15) << 8) + ((c0 & 15) << 12);
i+=3;
} else if ((c0 >= 0xC0) && (i < size-1) && (c1 >= 0x80)) {
// 2 byte sequence
outbuf[p++] = ((c1 & 0x3F) + ((c0 & 3) << 6)) + (((c0 >> 2) & 7) << 8);
i+=2;
} else if (c0 < 0x80) {
// 1 byte sequence
outbuf[p++] = c0;
i+=1;
} else {
// invalid character
PLIST_BIN_ERR("%s: invalid utf8 sequence in string at index %lu\n", __func__, i);
break;
}
}
if (items_read) {
*items_read = i;
}
if (items_written) {
*items_written = p;
}
outbuf[p] = 0;
return outbuf;
}
PLIST_API void plist_to_bin(plist_t plist, char **plist_bin, uint32_t * length)
{
ptrarray_t* objects = NULL;
hashtable_t* ref_table = NULL;
struct serialize_s ser_s;
uint8_t offset_size = 0;
uint8_t ref_size = 0;
uint64_t num_objects = 0;
uint64_t root_object = 0;
uint64_t offset_table_index = 0;
bytearray_t *bplist_buff = NULL;
uint64_t i = 0;
uint8_t *buff = NULL;
uint64_t *offsets = NULL;
bplist_trailer_t trailer;
//for string
long len = 0;
long items_read = 0;
long items_written = 0;
uint16_t *unicodestr = NULL;
uint64_t objects_len = 0;
uint64_t buff_len = 0;
//check for valid input
if (!plist || !plist_bin || *plist_bin || !length)
return;
//list of objects
objects = ptr_array_new(256);
//hashtable to write only once same nodes
ref_table = hash_table_new(plist_data_hash, plist_data_compare, free);
//serialize plist
ser_s.objects = objects;
ser_s.ref_table = ref_table;
serialize_plist(plist, &ser_s);
//now stream to output buffer
offset_size = 0; //unknown yet
objects_len = objects->len;
ref_size = get_needed_bytes(objects_len);
num_objects = objects->len;
root_object = 0; //root is first in list
offset_table_index = 0; //unknown yet
//setup a dynamic bytes array to store bplist in
bplist_buff = byte_array_new();
//set magic number and version
byte_array_append(bplist_buff, BPLIST_MAGIC, BPLIST_MAGIC_SIZE);
byte_array_append(bplist_buff, BPLIST_VERSION, BPLIST_VERSION_SIZE);
//write objects and table
offsets = (uint64_t *) malloc(num_objects * sizeof(uint64_t));
assert(offsets != NULL);
for (i = 0; i < num_objects; i++)
{
plist_data_t data = plist_get_data(ptr_array_index(objects, i));
offsets[i] = bplist_buff->len;
switch (data->type)
{
case PLIST_BOOLEAN:
buff = (uint8_t *) malloc(sizeof(uint8_t));
buff[0] = data->boolval ? BPLIST_TRUE : BPLIST_FALSE;
byte_array_append(bplist_buff, buff, sizeof(uint8_t));
free(buff);
break;
case PLIST_UINT:
if (data->length == 16) {
write_uint(bplist_buff, data->intval);
} else {
write_int(bplist_buff, data->intval);
}
break;
case PLIST_REAL:
write_real(bplist_buff, data->realval);
break;
case PLIST_KEY:
case PLIST_STRING:
len = strlen(data->strval);
if ( is_ascii_string(data->strval, len) )
{
write_string(bplist_buff, data->strval);
}
else
{
unicodestr = plist_utf8_to_utf16(data->strval, len, &items_read, &items_written);
write_unicode(bplist_buff, unicodestr, items_written);
free(unicodestr);
}
break;
case PLIST_DATA:
write_data(bplist_buff, data->buff, data->length);
case PLIST_ARRAY:
write_array(bplist_buff, ptr_array_index(objects, i), ref_table, ref_size);
break;
case PLIST_DICT:
write_dict(bplist_buff, ptr_array_index(objects, i), ref_table, ref_size);
break;
case PLIST_DATE:
write_date(bplist_buff, data->realval);
break;
case PLIST_UID:
write_uid(bplist_buff, data->intval);
break;
default:
break;
}
}
//free intermediate objects
ptr_array_free(objects);
hash_table_destroy(ref_table);
//write offsets
buff_len = bplist_buff->len;
offset_size = get_needed_bytes(buff_len);
offset_table_index = bplist_buff->len;
for (i = 0; i < num_objects; i++) {
uint64_t offset = be64toh(offsets[i]);
byte_array_append(bplist_buff, (uint8_t*)&offset + (sizeof(uint64_t) - offset_size), offset_size);
}
free(offsets);
//setup trailer
memset(trailer.unused, '\0', sizeof(trailer.unused));
trailer.offset_size = offset_size;
trailer.ref_size = ref_size;
trailer.num_objects = be64toh(num_objects);
trailer.root_object_index = be64toh(root_object);
trailer.offset_table_offset = be64toh(offset_table_index);
byte_array_append(bplist_buff, &trailer, sizeof(bplist_trailer_t));
//set output buffer and size
*plist_bin = bplist_buff->data;
*length = bplist_buff->len;
bplist_buff->data = NULL; // make sure we don't free the output buffer
byte_array_free(bplist_buff);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3192_0 |
crossvul-cpp_data_bad_2891_9 | /* Manage a process's keyrings
*
* Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/sched/user.h>
#include <linux/keyctl.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/security.h>
#include <linux/user_namespace.h>
#include <linux/uaccess.h>
#include "internal.h"
/* Session keyring create vs join semaphore */
static DEFINE_MUTEX(key_session_mutex);
/* User keyring creation semaphore */
static DEFINE_MUTEX(key_user_keyring_mutex);
/* The root user's tracking struct */
struct key_user root_key_user = {
.usage = REFCOUNT_INIT(3),
.cons_lock = __MUTEX_INITIALIZER(root_key_user.cons_lock),
.lock = __SPIN_LOCK_UNLOCKED(root_key_user.lock),
.nkeys = ATOMIC_INIT(2),
.nikeys = ATOMIC_INIT(2),
.uid = GLOBAL_ROOT_UID,
};
/*
* Install the user and user session keyrings for the current process's UID.
*/
int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_UID_KEYRING |
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
/*
* Install a thread keyring to the given credentials struct if it didn't have
* one already. This is allowed to overrun the quota.
*
* Return: 0 if a thread keyring is now present; -errno on failure.
*/
int install_thread_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->thread_keyring)
return 0;
keyring = keyring_alloc("_tid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->thread_keyring = keyring;
return 0;
}
/*
* Install a thread keyring to the current task if it didn't have one already.
*
* Return: 0 if a thread keyring is now present; -errno on failure.
*/
static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Install a process keyring to the given credentials struct if it didn't have
* one already. This is allowed to overrun the quota.
*
* Return: 0 if a process keyring is now present; -errno on failure.
*/
int install_process_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->process_keyring)
return 0;
keyring = keyring_alloc("_pid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->process_keyring = keyring;
return 0;
}
/*
* Install a process keyring to the current task if it didn't have one already.
*
* Return: 0 if a process keyring is now present; -errno on failure.
*/
static int install_process_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_process_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Install the given keyring as the session keyring of the given credentials
* struct, replacing the existing one if any. If the given keyring is NULL,
* then install a new anonymous session keyring.
*
* Return: 0 on success; -errno on failure.
*/
int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
{
unsigned long flags;
struct key *old;
might_sleep();
/* create an empty session keyring */
if (!keyring) {
flags = KEY_ALLOC_QUOTA_OVERRUN;
if (cred->session_keyring)
flags = KEY_ALLOC_IN_QUOTA;
keyring = keyring_alloc("_ses", cred->uid, cred->gid, cred,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
flags, NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
} else {
__key_get(keyring);
}
/* install the keyring */
old = cred->session_keyring;
rcu_assign_pointer(cred->session_keyring, keyring);
if (old)
key_put(old);
return 0;
}
/*
* Install the given keyring as the session keyring of the current task,
* replacing the existing one if any. If the given keyring is NULL, then
* install a new anonymous session keyring.
*
* Return: 0 on success; -errno on failure.
*/
static int install_session_keyring(struct key *keyring)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Handle the fsuid changing.
*/
void key_fsuid_changed(struct task_struct *tsk)
{
/* update the ownership of the thread keyring */
BUG_ON(!tsk->cred);
if (tsk->cred->thread_keyring) {
down_write(&tsk->cred->thread_keyring->sem);
tsk->cred->thread_keyring->uid = tsk->cred->fsuid;
up_write(&tsk->cred->thread_keyring->sem);
}
}
/*
* Handle the fsgid changing.
*/
void key_fsgid_changed(struct task_struct *tsk)
{
/* update the ownership of the thread keyring */
BUG_ON(!tsk->cred);
if (tsk->cred->thread_keyring) {
down_write(&tsk->cred->thread_keyring->sem);
tsk->cred->thread_keyring->gid = tsk->cred->fsgid;
up_write(&tsk->cred->thread_keyring->sem);
}
}
/*
* Search the process keyrings attached to the supplied cred for the first
* matching key.
*
* The search criteria are the type and the match function. The description is
* given to the match function as a parameter, but doesn't otherwise influence
* the search. Typically the match function will compare the description
* parameter to the key's description.
*
* This can only search keyrings that grant Search permission to the supplied
* credentials. Keyrings linked to searched keyrings will also be searched if
* they grant Search permission too. Keys can only be found if they grant
* Search permission to the credentials.
*
* Returns a pointer to the key with the key usage count incremented if
* successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only
* matched negative keys.
*
* In the case of a successful return, the possession attribute is set on the
* returned key reference.
*/
key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx)
{
key_ref_t key_ref, ret, err;
/* we want to return -EAGAIN or -ENOKEY if any of the keyrings were
* searchable, but we failed to find a key or we found a negative key;
* otherwise we want to return a sample error (probably -EACCES) if
* none of the keyrings were searchable
*
* in terms of priority: success > -ENOKEY > -EAGAIN > other error
*/
key_ref = NULL;
ret = NULL;
err = ERR_PTR(-EAGAIN);
/* search the thread keyring first */
if (ctx->cred->thread_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->thread_keyring, 1), ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* search the process keyring second */
if (ctx->cred->process_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->process_keyring, 1), ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* search the session keyring */
if (ctx->cred->session_keyring) {
rcu_read_lock();
key_ref = keyring_search_aux(
make_key_ref(rcu_dereference(ctx->cred->session_keyring), 1),
ctx);
rcu_read_unlock();
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* or search the user-session keyring */
else if (ctx->cred->user->session_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->user->session_keyring, 1),
ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* no key - decide on the error we're going to go for */
key_ref = ret ? ret : err;
found:
return key_ref;
}
/*
* Search the process keyrings attached to the supplied cred for the first
* matching key in the manner of search_my_process_keyrings(), but also search
* the keys attached to the assumed authorisation key using its credentials if
* one is available.
*
* Return same as search_my_process_keyrings().
*/
key_ref_t search_process_keyrings(struct keyring_search_context *ctx)
{
struct request_key_auth *rka;
key_ref_t key_ref, ret = ERR_PTR(-EACCES), err;
might_sleep();
key_ref = search_my_process_keyrings(ctx);
if (!IS_ERR(key_ref))
goto found;
err = key_ref;
/* if this process has an instantiation authorisation key, then we also
* search the keyrings of the process mentioned there
* - we don't permit access to request_key auth keys via this method
*/
if (ctx->cred->request_key_auth &&
ctx->cred == current_cred() &&
ctx->index_key.type != &key_type_request_key_auth
) {
const struct cred *cred = ctx->cred;
/* defend against the auth key being revoked */
down_read(&cred->request_key_auth->sem);
if (key_validate(ctx->cred->request_key_auth) == 0) {
rka = ctx->cred->request_key_auth->payload.data[0];
ctx->cred = rka->cred;
key_ref = search_process_keyrings(ctx);
ctx->cred = cred;
up_read(&cred->request_key_auth->sem);
if (!IS_ERR(key_ref))
goto found;
ret = key_ref;
} else {
up_read(&cred->request_key_auth->sem);
}
}
/* no key - decide on the error we're going to go for */
if (err == ERR_PTR(-ENOKEY) || ret == ERR_PTR(-ENOKEY))
key_ref = ERR_PTR(-ENOKEY);
else if (err == ERR_PTR(-EACCES))
key_ref = ret;
else
key_ref = err;
found:
return key_ref;
}
/*
* See if the key we're looking at is the target key.
*/
bool lookup_user_key_possessed(const struct key *key,
const struct key_match_data *match_data)
{
return key == match_data->raw_data;
}
/*
* Look up a key ID given us by userspace with a given permissions mask to get
* the key it refers to.
*
* Flags can be passed to request that special keyrings be created if referred
* to directly, to permit partially constructed keys to be found and to skip
* validity and permission checks on the found key.
*
* Returns a pointer to the key with an incremented usage count if successful;
* -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond
* to a key or the best found key was a negative key; -EKEYREVOKED or
* -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the
* found key doesn't grant the requested permit or the LSM denied access to it;
* or -ENOMEM if a special keyring couldn't be created.
*
* In the case of a successful return, the possession attribute is set on the
* returned key reference.
*/
key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
key_perm_t perm)
{
struct keyring_search_context ctx = {
.match_data.cmp = lookup_user_key_possessed,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
struct request_key_auth *rka;
struct key *key;
key_ref_t key_ref, skey_ref;
int ret;
try_again:
ctx.cred = get_current_cred();
key_ref = ERR_PTR(-ENOKEY);
switch (id) {
case KEY_SPEC_THREAD_KEYRING:
if (!ctx.cred->thread_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_thread_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->thread_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_PROCESS_KEYRING:
if (!ctx.cred->process_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_process_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->process_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_SESSION_KEYRING:
if (!ctx.cred->session_keyring) {
/* always install a session keyring upon access if one
* doesn't exist yet */
ret = install_user_keyrings();
if (ret < 0)
goto error;
if (lflags & KEY_LOOKUP_CREATE)
ret = join_session_keyring(NULL);
else
ret = install_session_keyring(
ctx.cred->user->session_keyring);
if (ret < 0)
goto error;
goto reget_creds;
} else if (ctx.cred->session_keyring ==
ctx.cred->user->session_keyring &&
lflags & KEY_LOOKUP_CREATE) {
ret = join_session_keyring(NULL);
if (ret < 0)
goto error;
goto reget_creds;
}
rcu_read_lock();
key = rcu_dereference(ctx.cred->session_keyring);
__key_get(key);
rcu_read_unlock();
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_KEYRING:
if (!ctx.cred->user->uid_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->uid_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_SESSION_KEYRING:
if (!ctx.cred->user->session_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->session_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_GROUP_KEYRING:
/* group keyrings are not yet supported */
key_ref = ERR_PTR(-EINVAL);
goto error;
case KEY_SPEC_REQKEY_AUTH_KEY:
key = ctx.cred->request_key_auth;
if (!key)
goto error;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_REQUESTOR_KEYRING:
if (!ctx.cred->request_key_auth)
goto error;
down_read(&ctx.cred->request_key_auth->sem);
if (test_bit(KEY_FLAG_REVOKED,
&ctx.cred->request_key_auth->flags)) {
key_ref = ERR_PTR(-EKEYREVOKED);
key = NULL;
} else {
rka = ctx.cred->request_key_auth->payload.data[0];
key = rka->dest_keyring;
__key_get(key);
}
up_read(&ctx.cred->request_key_auth->sem);
if (!key)
goto error;
key_ref = make_key_ref(key, 1);
break;
default:
key_ref = ERR_PTR(-EINVAL);
if (id < 1)
goto error;
key = key_lookup(id);
if (IS_ERR(key)) {
key_ref = ERR_CAST(key);
goto error;
}
key_ref = make_key_ref(key, 0);
/* check to see if we possess the key */
ctx.index_key.type = key->type;
ctx.index_key.description = key->description;
ctx.index_key.desc_len = strlen(key->description);
ctx.match_data.raw_data = key;
kdebug("check possessed");
skey_ref = search_process_keyrings(&ctx);
kdebug("possessed=%p", skey_ref);
if (!IS_ERR(skey_ref)) {
key_put(key);
key_ref = skey_ref;
}
break;
}
/* unlink does not use the nominated key in any way, so can skip all
* the permission checks as it is only concerned with the keyring */
if (lflags & KEY_LOOKUP_FOR_UNLINK) {
ret = 0;
goto error;
}
if (!(lflags & KEY_LOOKUP_PARTIAL)) {
ret = wait_for_key_construction(key, true);
switch (ret) {
case -ERESTARTSYS:
goto invalid_key;
default:
if (perm)
goto invalid_key;
case 0:
break;
}
} else if (perm) {
ret = key_validate(key);
if (ret < 0)
goto invalid_key;
}
ret = -EIO;
if (!(lflags & KEY_LOOKUP_PARTIAL) &&
!test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
goto invalid_key;
/* check the permissions */
ret = key_task_permission(key_ref, ctx.cred, perm);
if (ret < 0)
goto invalid_key;
key->last_used_at = current_kernel_time().tv_sec;
error:
put_cred(ctx.cred);
return key_ref;
invalid_key:
key_ref_put(key_ref);
key_ref = ERR_PTR(ret);
goto error;
/* if we attempted to install a keyring, then it may have caused new
* creds to be installed */
reget_creds:
put_cred(ctx.cred);
goto try_again;
}
/*
* Join the named keyring as the session keyring if possible else attempt to
* create a new one of that name and join that.
*
* If the name is NULL, an empty anonymous keyring will be installed as the
* session keyring.
*
* Named session keyrings are joined with a semaphore held to prevent the
* keyrings from going away whilst the attempt is made to going them and also
* to prevent a race in creating compatible session keyrings.
*/
long join_session_keyring(const char *name)
{
const struct cred *old;
struct cred *new;
struct key *keyring;
long ret, serial;
new = prepare_creds();
if (!new)
return -ENOMEM;
old = current_cred();
/* if no name is provided, install an anonymous keyring */
if (!name) {
ret = install_session_keyring_to_cred(new, NULL);
if (ret < 0)
goto error;
serial = new->session_keyring->serial;
ret = commit_creds(new);
if (ret == 0)
ret = serial;
goto okay;
}
/* allow the user to join or create a named keyring */
mutex_lock(&key_session_mutex);
/* look for an existing keyring of this name */
keyring = find_keyring_by_name(name, false);
if (PTR_ERR(keyring) == -ENOKEY) {
/* not found - try and create a new one */
keyring = keyring_alloc(
name, old->uid, old->gid, old,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
KEY_ALLOC_IN_QUOTA, NULL, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
}
} else if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
} else if (keyring == new->session_keyring) {
ret = 0;
goto error3;
}
/* we've got a keyring - now to install it */
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0)
goto error3;
commit_creds(new);
mutex_unlock(&key_session_mutex);
ret = keyring->serial;
key_put(keyring);
okay:
return ret;
error3:
key_put(keyring);
error2:
mutex_unlock(&key_session_mutex);
error:
abort_creds(new);
return ret;
}
/*
* Replace a process's session keyring on behalf of one of its children when
* the target process is about to resume userspace execution.
*/
void key_change_session_keyring(struct callback_head *twork)
{
const struct cred *old = current_cred();
struct cred *new = container_of(twork, struct cred, rcu);
if (unlikely(current->flags & PF_EXITING)) {
put_cred(new);
return;
}
new-> uid = old-> uid;
new-> euid = old-> euid;
new-> suid = old-> suid;
new->fsuid = old->fsuid;
new-> gid = old-> gid;
new-> egid = old-> egid;
new-> sgid = old-> sgid;
new->fsgid = old->fsgid;
new->user = get_uid(old->user);
new->user_ns = get_user_ns(old->user_ns);
new->group_info = get_group_info(old->group_info);
new->securebits = old->securebits;
new->cap_inheritable = old->cap_inheritable;
new->cap_permitted = old->cap_permitted;
new->cap_effective = old->cap_effective;
new->cap_ambient = old->cap_ambient;
new->cap_bset = old->cap_bset;
new->jit_keyring = old->jit_keyring;
new->thread_keyring = key_get(old->thread_keyring);
new->process_keyring = key_get(old->process_keyring);
security_transfer_creds(new, old);
commit_creds(new);
}
/*
* Make sure that root's user and user-session keyrings exist.
*/
static int __init init_root_keyring(void)
{
return install_user_keyrings();
}
late_initcall(init_root_keyring);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_9 |
crossvul-cpp_data_bad_2313_0 | /*
* Copyright (c) 2007, 2008, 2009 Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <assert.h>
#include <grp.h>
#include <sys/utsname.h>
#include "easside.h"
#include "version.h"
extern char * getVersion(char * progname, int maj, int min, int submin, int svnrev, int beta, int rc);
unsigned char ids[8192];
unsigned short last_id;
int wrap;
int is_dup(unsigned short id)
{
int idx = id/8;
int bit = id % 8;
unsigned char mask = (1 << bit);
if (ids[idx] & mask)
return 1;
ids[idx] |= mask;
return 0;
}
int handle(int s, unsigned char* data, int len, struct sockaddr_in *s_in)
{
char buf[2048];
unsigned short *cmd = (unsigned short *)buf;
int plen;
struct in_addr *addr = &s_in->sin_addr;
unsigned short *pid = (unsigned short*) data;
/* inet check */
if (len == S_HELLO_LEN && memcmp(data, "sorbo", 5) == 0) {
unsigned short *id = (unsigned short*) (data+5);
int x = 2+4+2;
*cmd = htons(S_CMD_INET_CHECK);
memcpy(cmd+1, addr, 4);
memcpy(cmd+1+2, id, 2);
printf("Inet check by %s %d\n",
inet_ntoa(*addr), ntohs(*id));
if (send(s, buf, x, 0) != x)
return 1;
return 0;
}
*cmd++ = htons(S_CMD_PACKET);
*cmd++ = *pid;
plen = len - 2;
last_id = ntohs(*pid);
if (last_id > 20000)
wrap = 1;
if (wrap && last_id < 100) {
wrap = 0;
memset(ids, 0, sizeof(ids));
}
printf("Got packet %d %d", last_id, plen);
if (is_dup(last_id)) {
printf(" (DUP)\n");
return 0;
}
printf("\n");
*cmd++ = htons(plen);
memcpy(cmd, data+2, plen);
plen += 2 + 2 + 2;
assert(plen <= (int) sizeof(buf));
if (send(s, buf, plen, 0) != plen)
return 1;
return 0;
}
void handle_dude(int dude, int udp)
{
unsigned char buf[2048];
int rc;
fd_set rfds;
int maxfd;
struct sockaddr_in s_in;
socklen_t len;
/* handshake */
rc = recv(dude, buf, 5, 0);
if (rc != 5) {
close(dude);
return;
}
if (memcmp(buf, "sorbo", 5) != 0) {
close(dude);
return;
}
if (send(dude, "sorbox", 6, 0) != 6) {
close(dude);
return;
}
printf("Handshake complete\n");
memset(ids, 0, sizeof(ids));
last_id = 0;
wrap = 0;
while (1) {
FD_ZERO(&rfds);
FD_SET(udp, &rfds);
FD_SET(dude, &rfds);
if (dude > udp)
maxfd = dude;
else
maxfd = udp;
if (select(maxfd+1, &rfds, NULL, NULL, NULL) == -1)
err(1, "select()");
if (FD_ISSET(dude, &rfds))
break;
if (!FD_ISSET(udp, &rfds))
continue;
len = sizeof(s_in);
rc = recvfrom(udp, buf, sizeof(buf), 0,
(struct sockaddr*) &s_in, &len);
if (rc == -1)
err(1, "read()");
if (handle(dude, buf, rc, &s_in))
break;
}
close(dude);
}
void drop_privs()
{
if (chroot(".") == -1)
err(1, "chroot()");
if (setgroups(0, NULL) == -1)
err(1, "setgroups()");
if (setgid(69) == -1)
err(1, "setgid()");
if (setuid(69) == -1)
err(1, "setuid()");
}
void usage()
{
printf("\n"
" %s - (C) 2007,2008 Andrea Bittau\n"
" http://www.aircrack-ng.org\n"
"\n"
" Usage: buddy-ng <options>\n"
"\n"
" Options:\n"
"\n"
" -h : This help screen\n"
" -p : Don't drop privileges\n"
"\n",
getVersion("Buddy-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC));
exit(1);
}
int main(int argc, char *argv[])
{
struct utsname utsName;
struct sockaddr_in s_in;
struct sockaddr_in dude_sin;
int len, udp, ch, dude, s;
int port = S_DEFAULT_PORT;
int drop;
while ((ch = getopt(argc, argv, "ph")) != -1) {
switch (ch) {
case 'p':
drop = 0;
break;
default:
case 'h':
usage();
break;
}
}
memset(&s_in, 0, sizeof(s_in));
s_in.sin_family = PF_INET;
s_in.sin_addr.s_addr = INADDR_ANY;
s_in.sin_port = htons(S_DEFAULT_UDP_PORT);
udp = socket(s_in.sin_family, SOCK_DGRAM, IPPROTO_UDP);
if (udp == -1)
err(1, "socket(UDP)");
if (bind(udp, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)
err(1, "bind()");
s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == -1)
err(1, "socket(TCP)");
drop = 1;
// Do not drop privileges on Windows (doing it fails).
if (uname(&utsName) == 0)
{
drop = strncasecmp(utsName.sysname, "cygwin", 6);
}
if (drop)
drop_privs();
memset(&s_in, 0, sizeof(s_in));
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
s_in.sin_addr.s_addr = INADDR_ANY;
len = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &len, sizeof(len)) == -1)
err(1, "setsockopt(SO_REUSEADDR)");
if (bind(s, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)
err(1, "bind()");
if (listen(s, 5) == -1)
err(1, "listen()");
while (1) {
len = sizeof(dude_sin);
printf("Waiting for connexion\n");
dude = accept(s, (struct sockaddr*) &dude_sin,
(socklen_t*) &len);
if (dude == -1)
err(1, "accept()");
printf("Got connection from %s\n",
inet_ntoa(dude_sin.sin_addr));
handle_dude(dude, udp);
printf("That was it\n");
}
exit(0);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2313_0 |
crossvul-cpp_data_bad_5197_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5197_0 |
crossvul-cpp_data_bad_1575_2 | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* http_filter.c --- HTTP routines which either filters or deal with filters.
*/
#include "apr.h"
#include "apr_strings.h"
#include "apr_buckets.h"
#include "apr_lib.h"
#include "apr_signal.h"
#define APR_WANT_STDIO /* for sscanf */
#define APR_WANT_STRFUNC
#define APR_WANT_MEMFUNC
#include "apr_want.h"
#include "util_filter.h"
#include "ap_config.h"
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_main.h"
#include "http_request.h"
#include "http_vhost.h"
#include "http_connection.h"
#include "http_log.h" /* For errors detected in basic auth common
* support code... */
#include "apr_date.h" /* For apr_date_parse_http and APR_DATE_BAD */
#include "util_charset.h"
#include "util_ebcdic.h"
#include "util_time.h"
#include "mod_core.h"
#if APR_HAVE_STDARG_H
#include <stdarg.h>
#endif
#if APR_HAVE_UNISTD_H
#include <unistd.h>
#endif
APLOG_USE_MODULE(http);
#define INVALID_CHAR -2
typedef struct http_filter_ctx
{
apr_off_t remaining;
apr_off_t limit;
apr_off_t limit_used;
apr_int32_t chunk_used;
apr_int16_t chunkbits;
enum
{
BODY_NONE, /* streamed data */
BODY_LENGTH, /* data constrained by content length */
BODY_CHUNK, /* chunk expected */
BODY_CHUNK_PART, /* chunk digits */
BODY_CHUNK_EXT, /* chunk extension */
BODY_CHUNK_DATA, /* data constrained by chunked encoding */
BODY_CHUNK_END, /* chunk terminating CRLF */
BODY_CHUNK_TRAILER /* trailers */
} state;
unsigned int eos_sent :1;
} http_ctx_t;
/**
* Parse a chunk line with optional extension, detect overflow.
* There are two error cases:
* 1) If the conversion would require too many bits, APR_EGENERAL is returned.
* 2) If the conversion used the correct number of bits, but an overflow
* caused only the sign bit to flip, then APR_ENOSPC is returned.
* In general, any negative number can be considered an overflow error.
*/
static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,
apr_size_t len, int linelimit)
{
apr_size_t i = 0;
while (i < len) {
char c = buffer[i];
ap_xlate_proto_from_ascii(&c, 1);
/* handle CRLF after the chunk */
if (ctx->state == BODY_CHUNK_END) {
if (c == LF) {
ctx->state = BODY_CHUNK;
}
i++;
continue;
}
/* handle start of the chunk */
if (ctx->state == BODY_CHUNK) {
if (!apr_isxdigit(c)) {
/*
* Detect invalid character at beginning. This also works for empty
* chunk size lines.
*/
return APR_EGENERAL;
}
else {
ctx->state = BODY_CHUNK_PART;
}
ctx->remaining = 0;
ctx->chunkbits = sizeof(long) * 8;
ctx->chunk_used = 0;
}
/* handle a chunk part, or a chunk extension */
/*
* In theory, we are supposed to expect CRLF only, but our
* test suite sends LF only. Tolerate a missing CR.
*/
if (c == ';' || c == CR) {
ctx->state = BODY_CHUNK_EXT;
}
else if (c == LF) {
if (ctx->remaining) {
ctx->state = BODY_CHUNK_DATA;
}
else {
ctx->state = BODY_CHUNK_TRAILER;
}
}
else if (ctx->state != BODY_CHUNK_EXT) {
int xvalue = 0;
/* ignore leading zeros */
if (!ctx->remaining && c == '0') {
i++;
continue;
}
if (c >= '0' && c <= '9') {
xvalue = c - '0';
}
else if (c >= 'A' && c <= 'F') {
xvalue = c - 'A' + 0xa;
}
else if (c >= 'a' && c <= 'f') {
xvalue = c - 'a' + 0xa;
}
else {
/* bogus character */
return APR_EGENERAL;
}
ctx->remaining = (ctx->remaining << 4) | xvalue;
ctx->chunkbits -= 4;
if (ctx->chunkbits <= 0 || ctx->remaining < 0) {
/* overflow */
return APR_ENOSPC;
}
}
i++;
}
/* sanity check */
ctx->chunk_used += len;
if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {
return APR_ENOSPC;
}
return APR_SUCCESS;
}
static apr_status_t read_chunked_trailers(http_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *b, int merge)
{
int rv;
apr_bucket *e;
request_rec *r = f->r;
apr_table_t *saved_headers_in = r->headers_in;
int saved_status = r->status;
r->status = HTTP_OK;
r->headers_in = r->trailers_in;
apr_table_clear(r->headers_in);
ap_get_mime_headers(r);
if(r->status == HTTP_OK) {
r->status = saved_status;
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
ctx->eos_sent = 1;
rv = APR_SUCCESS;
}
else {
const char *error_notes = apr_table_get(r->notes,
"error-notes");
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02656)
"Error while reading HTTP trailer: %i%s%s",
r->status, error_notes ? ": " : "",
error_notes ? error_notes : "");
rv = APR_EINVAL;
}
if(!merge) {
r->headers_in = saved_headers_in;
}
else {
r->headers_in = apr_table_overlay(r->pool, saved_headers_in,
r->trailers_in);
}
return rv;
}
/* This is the HTTP_INPUT filter for HTTP requests and responses from
* proxied servers (mod_proxy). It handles chunked and content-length
* bodies. This can only be inserted/used after the headers
* are successfully parsed.
*/
apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b,
ap_input_mode_t mode, apr_read_type_e block, apr_off_t readbytes)
{
core_server_config *conf;
apr_bucket *e;
http_ctx_t *ctx = f->ctx;
apr_status_t rv;
apr_off_t totalread;
int again;
conf = (core_server_config *)
ap_get_module_config(f->r->server->module_config, &core_module);
/* just get out of the way of things we don't want. */
if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) {
return ap_get_brigade(f->next, b, mode, block, readbytes);
}
if (!ctx) {
const char *tenc, *lenp;
f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
ctx->state = BODY_NONE;
/* LimitRequestBody does not apply to proxied responses.
* Consider implementing this check in its own filter.
* Would adding a directive to limit the size of proxied
* responses be useful?
*/
if (!f->r->proxyreq) {
ctx->limit = ap_get_limit_req_body(f->r);
}
else {
ctx->limit = 0;
}
tenc = apr_table_get(f->r->headers_in, "Transfer-Encoding");
lenp = apr_table_get(f->r->headers_in, "Content-Length");
if (tenc) {
if (strcasecmp(tenc, "chunked") == 0 /* fast path */
|| ap_find_last_token(f->r->pool, tenc, "chunked")) {
ctx->state = BODY_CHUNK;
}
else if (f->r->proxyreq == PROXYREQ_RESPONSE) {
/* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23
* Section 3.3.3.3: "If a Transfer-Encoding header field is
* present in a response and the chunked transfer coding is not
* the final encoding, the message body length is determined by
* reading the connection until it is closed by the server."
*/
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(02555)
"Unknown Transfer-Encoding: %s;"
" using read-until-close", tenc);
tenc = NULL;
}
else {
/* Something that isn't a HTTP request, unless some future
* edition defines new transfer encodings, is unsupported.
*/
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01585)
"Unknown Transfer-Encoding: %s", tenc);
return APR_EGENERAL;
}
lenp = NULL;
}
if (lenp) {
char *endstr;
ctx->state = BODY_LENGTH;
/* Protects against over/underflow, non-digit chars in the
* string (excluding leading space) (the endstr checks)
* and a negative number. */
if (apr_strtoff(&ctx->remaining, lenp, &endstr, 10)
|| endstr == lenp || *endstr || ctx->remaining < 0) {
ctx->remaining = 0;
ap_log_rerror(
APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01587)
"Invalid Content-Length");
return APR_ENOSPC;
}
/* If we have a limit in effect and we know the C-L ahead of
* time, stop it here if it is invalid.
*/
if (ctx->limit && ctx->limit < ctx->remaining) {
ap_log_rerror(
APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01588)
"Requested content-length of %" APR_OFF_T_FMT
" is larger than the configured limit"
" of %" APR_OFF_T_FMT, ctx->remaining, ctx->limit);
return APR_ENOSPC;
}
}
/* If we don't have a request entity indicated by the headers, EOS.
* (BODY_NONE is a valid intermediate state due to trailers,
* but it isn't a valid starting state.)
*
* RFC 2616 Section 4.4 note 5 states that connection-close
* is invalid for a request entity - request bodies must be
* denoted by C-L or T-E: chunked.
*
* Note that since the proxy uses this filter to handle the
* proxied *response*, proxy responses MUST be exempt.
*/
if (ctx->state == BODY_NONE && f->r->proxyreq != PROXYREQ_RESPONSE) {
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
ctx->eos_sent = 1;
return APR_SUCCESS;
}
/* Since we're about to read data, send 100-Continue if needed.
* Only valid on chunked and C-L bodies where the C-L is > 0. */
if ((ctx->state == BODY_CHUNK
|| (ctx->state == BODY_LENGTH && ctx->remaining > 0))
&& f->r->expecting_100 && f->r->proto_num >= HTTP_VERSION(1,1)
&& !(f->r->eos_sent || f->r->bytes_sent)) {
if (!ap_is_HTTP_SUCCESS(f->r->status)) {
ctx->state = BODY_NONE;
ctx->eos_sent = 1;
}
else {
char *tmp;
int len;
apr_bucket_brigade *bb;
bb = apr_brigade_create(f->r->pool, f->c->bucket_alloc);
/* if we send an interim response, we're no longer
* in a state of expecting one.
*/
f->r->expecting_100 = 0;
tmp = apr_pstrcat(f->r->pool, AP_SERVER_PROTOCOL " ",
ap_get_status_line(HTTP_CONTINUE), CRLF CRLF, NULL);
len = strlen(tmp);
ap_xlate_proto_to_ascii(tmp, len);
e = apr_bucket_pool_create(tmp, len, f->r->pool,
f->c->bucket_alloc);
APR_BRIGADE_INSERT_HEAD(bb, e);
e = apr_bucket_flush_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, e);
rv = ap_pass_brigade(f->c->output_filters, bb);
if (rv != APR_SUCCESS) {
return AP_FILTER_ERROR;
}
}
}
}
/* sanity check in case we're read twice */
if (ctx->eos_sent) {
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
return APR_SUCCESS;
}
do {
apr_brigade_cleanup(b);
again = 0; /* until further notice */
/* read and handle the brigade */
switch (ctx->state) {
case BODY_CHUNK:
case BODY_CHUNK_PART:
case BODY_CHUNK_EXT:
case BODY_CHUNK_END: {
rv = ap_get_brigade(f->next, b, AP_MODE_GETLINE, block, 0);
/* for timeout */
if (block == APR_NONBLOCK_READ
&& ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b))
|| (APR_STATUS_IS_EAGAIN(rv)))) {
return APR_EAGAIN;
}
if (rv == APR_EOF) {
return APR_INCOMPLETE;
}
if (rv != APR_SUCCESS) {
return rv;
}
e = APR_BRIGADE_FIRST(b);
while (e != APR_BRIGADE_SENTINEL(b)) {
const char *buffer;
apr_size_t len;
if (!APR_BUCKET_IS_METADATA(e)) {
rv = apr_bucket_read(e, &buffer, &len, APR_BLOCK_READ);
if (rv == APR_SUCCESS) {
rv = parse_chunk_size(ctx, buffer, len,
f->r->server->limit_req_fieldsize);
}
if (rv != APR_SUCCESS) {
ap_log_rerror(
APLOG_MARK, APLOG_INFO, rv, f->r, APLOGNO(01590) "Error reading chunk %s ", (APR_ENOSPC == rv) ? "(overflow)" : "");
return rv;
}
}
apr_bucket_delete(e);
e = APR_BRIGADE_FIRST(b);
}
again = 1; /* come around again */
if (ctx->state == BODY_CHUNK_TRAILER) {
/* Treat UNSET as DISABLE - trailers aren't merged by default */
int merge_trailers =
conf->merge_trailers == AP_MERGE_TRAILERS_ENABLE;
return read_chunked_trailers(ctx, f, b, merge_trailers);
}
break;
}
case BODY_NONE:
case BODY_LENGTH:
case BODY_CHUNK_DATA: {
/* Ensure that the caller can not go over our boundary point. */
if (ctx->state != BODY_NONE && ctx->remaining < readbytes) {
readbytes = ctx->remaining;
}
if (readbytes > 0) {
rv = ap_get_brigade(f->next, b, mode, block, readbytes);
/* for timeout */
if (block == APR_NONBLOCK_READ
&& ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b))
|| (APR_STATUS_IS_EAGAIN(rv)))) {
return APR_EAGAIN;
}
if (rv == APR_EOF && ctx->state != BODY_NONE
&& ctx->remaining > 0) {
return APR_INCOMPLETE;
}
if (rv != APR_SUCCESS) {
return rv;
}
/* How many bytes did we just read? */
apr_brigade_length(b, 0, &totalread);
/* If this happens, we have a bucket of unknown length. Die because
* it means our assumptions have changed. */
AP_DEBUG_ASSERT(totalread >= 0);
if (ctx->state != BODY_NONE) {
ctx->remaining -= totalread;
if (ctx->remaining > 0) {
e = APR_BRIGADE_LAST(b);
if (APR_BUCKET_IS_EOS(e)) {
apr_bucket_delete(e);
return APR_INCOMPLETE;
}
}
else if (ctx->state == BODY_CHUNK_DATA) {
/* next chunk please */
ctx->state = BODY_CHUNK_END;
ctx->chunk_used = 0;
}
}
}
/* If we have no more bytes remaining on a C-L request,
* save the caller a round trip to discover EOS.
*/
if (ctx->state == BODY_LENGTH && ctx->remaining == 0) {
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
ctx->eos_sent = 1;
}
/* We have a limit in effect. */
if (ctx->limit) {
/* FIXME: Note that we might get slightly confused on chunked inputs
* as we'd need to compensate for the chunk lengths which may not
* really count. This seems to be up for interpretation. */
ctx->limit_used += totalread;
if (ctx->limit < ctx->limit_used) {
ap_log_rerror(
APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01591) "Read content-length of %" APR_OFF_T_FMT " is larger than the configured limit"
" of %" APR_OFF_T_FMT, ctx->limit_used, ctx->limit);
return APR_ENOSPC;
}
}
break;
}
case BODY_CHUNK_TRAILER: {
rv = ap_get_brigade(f->next, b, mode, block, readbytes);
/* for timeout */
if (block == APR_NONBLOCK_READ
&& ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b))
|| (APR_STATUS_IS_EAGAIN(rv)))) {
return APR_EAGAIN;
}
if (rv != APR_SUCCESS) {
return rv;
}
break;
}
default: {
break;
}
}
} while (again);
return APR_SUCCESS;
}
struct check_header_ctx {
request_rec *r;
int error;
};
/* check a single header, to be used with apr_table_do() */
static int check_header(void *arg, const char *name, const char *val)
{
struct check_header_ctx *ctx = arg;
if (name[0] == '\0') {
ctx->error = 1;
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, APLOGNO(02428)
"Empty response header name, aborting request");
return 0;
}
if (ap_has_cntrl(name)) {
ctx->error = 1;
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, APLOGNO(02429)
"Response header name '%s' contains control "
"characters, aborting request",
name);
return 0;
}
if (ap_has_cntrl(val)) {
ctx->error = 1;
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, APLOGNO(02430)
"Response header '%s' contains control characters, "
"aborting request: %s",
name, val);
return 0;
}
return 1;
}
/**
* Check headers for HTTP conformance
* @return 1 if ok, 0 if bad
*/
static APR_INLINE int check_headers(request_rec *r)
{
const char *loc;
struct check_header_ctx ctx = { 0, 0 };
ctx.r = r;
apr_table_do(check_header, &ctx, r->headers_out, NULL);
if (ctx.error)
return 0; /* problem has been logged by check_header() */
if ((loc = apr_table_get(r->headers_out, "Location")) != NULL) {
const char *scheme_end = ap_strchr_c(loc, ':');
/*
* Check that the URI has a valid scheme and is absolute
* XXX Should we do a full uri parse here?
*/
if (!ap_is_url(loc))
goto bad;
if (scheme_end[1] != '/' || scheme_end[2] != '/')
goto bad;
}
return 1;
bad:
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02431)
"Bad Location header in response: '%s', aborting request",
loc);
return 0;
}
typedef struct header_struct {
apr_pool_t *pool;
apr_bucket_brigade *bb;
} header_struct;
/* Send a single HTTP header field to the client. Note that this function
* is used in calls to apr_table_do(), so don't change its interface.
* It returns true unless there was a write error of some kind.
*/
static int form_header_field(header_struct *h,
const char *fieldname, const char *fieldval)
{
#if APR_CHARSET_EBCDIC
char *headfield;
apr_size_t len;
headfield = apr_pstrcat(h->pool, fieldname, ": ", fieldval, CRLF, NULL);
len = strlen(headfield);
ap_xlate_proto_to_ascii(headfield, len);
apr_brigade_write(h->bb, NULL, NULL, headfield, len);
#else
struct iovec vec[4];
struct iovec *v = vec;
v->iov_base = (void *)fieldname;
v->iov_len = strlen(fieldname);
v++;
v->iov_base = ": ";
v->iov_len = sizeof(": ") - 1;
v++;
v->iov_base = (void *)fieldval;
v->iov_len = strlen(fieldval);
v++;
v->iov_base = CRLF;
v->iov_len = sizeof(CRLF) - 1;
apr_brigade_writev(h->bb, NULL, NULL, vec, 4);
#endif /* !APR_CHARSET_EBCDIC */
return 1;
}
/* This routine is called by apr_table_do and merges all instances of
* the passed field values into a single array that will be further
* processed by some later routine. Originally intended to help split
* and recombine multiple Vary fields, though it is generic to any field
* consisting of comma/space-separated tokens.
*/
static int uniq_field_values(void *d, const char *key, const char *val)
{
apr_array_header_t *values;
char *start;
char *e;
char **strpp;
int i;
values = (apr_array_header_t *)d;
e = apr_pstrdup(values->pool, val);
do {
/* Find a non-empty fieldname */
while (*e == ',' || apr_isspace(*e)) {
++e;
}
if (*e == '\0') {
break;
}
start = e;
while (*e != '\0' && *e != ',' && !apr_isspace(*e)) {
++e;
}
if (*e != '\0') {
*e++ = '\0';
}
/* Now add it to values if it isn't already represented.
* Could be replaced by a ap_array_strcasecmp() if we had one.
*/
for (i = 0, strpp = (char **) values->elts; i < values->nelts;
++i, ++strpp) {
if (*strpp && strcasecmp(*strpp, start) == 0) {
break;
}
}
if (i == values->nelts) { /* if not found */
*(char **)apr_array_push(values) = start;
}
} while (*e != '\0');
return 1;
}
/*
* Since some clients choke violently on multiple Vary fields, or
* Vary fields with duplicate tokens, combine any multiples and remove
* any duplicates.
*/
static void fixup_vary(request_rec *r)
{
apr_array_header_t *varies;
varies = apr_array_make(r->pool, 5, sizeof(char *));
/* Extract all Vary fields from the headers_out, separate each into
* its comma-separated fieldname values, and then add them to varies
* if not already present in the array.
*/
apr_table_do((int (*)(void *, const char *, const char *))uniq_field_values,
(void *) varies, r->headers_out, "Vary", NULL);
/* If we found any, replace old Vary fields with unique-ified value */
if (varies->nelts > 0) {
apr_table_setn(r->headers_out, "Vary",
apr_array_pstrcat(r->pool, varies, ','));
}
}
/* Send a request's HTTP response headers to the client.
*/
static apr_status_t send_all_header_fields(header_struct *h,
const request_rec *r)
{
const apr_array_header_t *elts;
const apr_table_entry_t *t_elt;
const apr_table_entry_t *t_end;
struct iovec *vec;
struct iovec *vec_next;
elts = apr_table_elts(r->headers_out);
if (elts->nelts == 0) {
return APR_SUCCESS;
}
t_elt = (const apr_table_entry_t *)(elts->elts);
t_end = t_elt + elts->nelts;
vec = (struct iovec *)apr_palloc(h->pool, 4 * elts->nelts *
sizeof(struct iovec));
vec_next = vec;
/* For each field, generate
* name ": " value CRLF
*/
do {
vec_next->iov_base = (void*)(t_elt->key);
vec_next->iov_len = strlen(t_elt->key);
vec_next++;
vec_next->iov_base = ": ";
vec_next->iov_len = sizeof(": ") - 1;
vec_next++;
vec_next->iov_base = (void*)(t_elt->val);
vec_next->iov_len = strlen(t_elt->val);
vec_next++;
vec_next->iov_base = CRLF;
vec_next->iov_len = sizeof(CRLF) - 1;
vec_next++;
t_elt++;
} while (t_elt < t_end);
if (APLOGrtrace4(r)) {
t_elt = (const apr_table_entry_t *)(elts->elts);
do {
ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, " %s: %s",
ap_escape_logitem(r->pool, t_elt->key),
ap_escape_logitem(r->pool, t_elt->val));
t_elt++;
} while (t_elt < t_end);
}
#if APR_CHARSET_EBCDIC
{
apr_size_t len;
char *tmp = apr_pstrcatv(r->pool, vec, vec_next - vec, &len);
ap_xlate_proto_to_ascii(tmp, len);
return apr_brigade_write(h->bb, NULL, NULL, tmp, len);
}
#else
return apr_brigade_writev(h->bb, NULL, NULL, vec, vec_next - vec);
#endif
}
/* Confirm that the status line is well-formed and matches r->status.
* If they don't match, a filter may have negated the status line set by a
* handler.
* Zap r->status_line if bad.
*/
static apr_status_t validate_status_line(request_rec *r)
{
char *end;
if (r->status_line) {
int len = strlen(r->status_line);
if (len < 3
|| apr_strtoi64(r->status_line, &end, 10) != r->status
|| (end - 3) != r->status_line
|| (len >= 4 && ! apr_isspace(r->status_line[3]))) {
r->status_line = NULL;
return APR_EGENERAL;
}
/* Since we passed the above check, we know that length three
* is equivalent to only a 3 digit numeric http status.
* RFC2616 mandates a trailing space, let's add it.
*/
if (len == 3) {
r->status_line = apr_pstrcat(r->pool, r->status_line, " ", NULL);
return APR_EGENERAL;
}
return APR_SUCCESS;
}
return APR_EGENERAL;
}
/*
* Determine the protocol to use for the response. Potentially downgrade
* to HTTP/1.0 in some situations and/or turn off keepalives.
*
* also prepare r->status_line.
*/
static void basic_http_header_check(request_rec *r,
const char **protocol)
{
apr_status_t rv;
if (r->assbackwards) {
/* no such thing as a response protocol */
return;
}
rv = validate_status_line(r);
if (!r->status_line) {
r->status_line = ap_get_status_line(r->status);
} else if (rv != APR_SUCCESS) {
/* Status line is OK but our own reason phrase
* would be preferred if defined
*/
const char *tmp = ap_get_status_line(r->status);
if (!strncmp(tmp, r->status_line, 3)) {
r->status_line = tmp;
}
}
/* Note that we must downgrade before checking for force responses. */
if (r->proto_num > HTTP_VERSION(1,0)
&& apr_table_get(r->subprocess_env, "downgrade-1.0")) {
r->proto_num = HTTP_VERSION(1,0);
}
/* kludge around broken browsers when indicated by force-response-1.0
*/
if (r->proto_num == HTTP_VERSION(1,0)
&& apr_table_get(r->subprocess_env, "force-response-1.0")) {
*protocol = "HTTP/1.0";
r->connection->keepalive = AP_CONN_CLOSE;
}
else {
*protocol = AP_SERVER_PROTOCOL;
}
}
/* fill "bb" with a barebones/initial HTTP response header */
static void basic_http_header(request_rec *r, apr_bucket_brigade *bb,
const char *protocol)
{
char *date = NULL;
const char *proxy_date = NULL;
const char *server = NULL;
const char *us = ap_get_server_banner();
header_struct h;
struct iovec vec[4];
if (r->assbackwards) {
/* there are no headers to send */
return;
}
/* Output the HTTP/1.x Status-Line and the Date and Server fields */
vec[0].iov_base = (void *)protocol;
vec[0].iov_len = strlen(protocol);
vec[1].iov_base = (void *)" ";
vec[1].iov_len = sizeof(" ") - 1;
vec[2].iov_base = (void *)(r->status_line);
vec[2].iov_len = strlen(r->status_line);
vec[3].iov_base = (void *)CRLF;
vec[3].iov_len = sizeof(CRLF) - 1;
#if APR_CHARSET_EBCDIC
{
char *tmp;
apr_size_t len;
tmp = apr_pstrcatv(r->pool, vec, 4, &len);
ap_xlate_proto_to_ascii(tmp, len);
apr_brigade_write(bb, NULL, NULL, tmp, len);
}
#else
apr_brigade_writev(bb, NULL, NULL, vec, 4);
#endif
h.pool = r->pool;
h.bb = bb;
/*
* keep the set-by-proxy server and date headers, otherwise
* generate a new server header / date header
*/
if (r->proxyreq != PROXYREQ_NONE) {
proxy_date = apr_table_get(r->headers_out, "Date");
if (!proxy_date) {
/*
* proxy_date needs to be const. So use date for the creation of
* our own Date header and pass it over to proxy_date later to
* avoid a compiler warning.
*/
date = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
ap_recent_rfc822_date(date, r->request_time);
}
server = apr_table_get(r->headers_out, "Server");
}
else {
date = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
ap_recent_rfc822_date(date, r->request_time);
}
form_header_field(&h, "Date", proxy_date ? proxy_date : date );
if (!server && *us)
server = us;
if (server)
form_header_field(&h, "Server", server);
if (APLOGrtrace3(r)) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"Response sent with status %d%s",
r->status,
APLOGrtrace4(r) ? ", headers:" : "");
/*
* Date and Server are less interesting, use TRACE5 for them while
* using TRACE4 for the other headers.
*/
ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r, " Date: %s",
proxy_date ? proxy_date : date );
if (server)
ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r, " Server: %s",
server);
}
/* unset so we don't send them again */
apr_table_unset(r->headers_out, "Date"); /* Avoid bogosity */
if (server) {
apr_table_unset(r->headers_out, "Server");
}
}
AP_DECLARE(void) ap_basic_http_header(request_rec *r, apr_bucket_brigade *bb)
{
const char *protocol = NULL;
basic_http_header_check(r, &protocol);
basic_http_header(r, bb, protocol);
}
static void terminate_header(apr_bucket_brigade *bb)
{
char crlf[] = CRLF;
apr_size_t buflen;
buflen = strlen(crlf);
ap_xlate_proto_to_ascii(crlf, buflen);
apr_brigade_write(bb, NULL, NULL, crlf, buflen);
}
AP_DECLARE_NONSTD(int) ap_send_http_trace(request_rec *r)
{
core_server_config *conf;
int rv;
apr_bucket_brigade *bb;
header_struct h;
apr_bucket *b;
int body;
char *bodyread = NULL, *bodyoff;
apr_size_t bodylen = 0;
apr_size_t bodybuf;
long res = -1; /* init to avoid gcc -Wall warning */
if (r->method_number != M_TRACE) {
return DECLINED;
}
/* Get the original request */
while (r->prev) {
r = r->prev;
}
conf = ap_get_core_module_config(r->server->module_config);
if (conf->trace_enable == AP_TRACE_DISABLE) {
apr_table_setn(r->notes, "error-notes",
"TRACE denied by server configuration");
return HTTP_METHOD_NOT_ALLOWED;
}
if (conf->trace_enable == AP_TRACE_EXTENDED)
/* XXX: should be = REQUEST_CHUNKED_PASS */
body = REQUEST_CHUNKED_DECHUNK;
else
body = REQUEST_NO_BODY;
if ((rv = ap_setup_client_block(r, body))) {
if (rv == HTTP_REQUEST_ENTITY_TOO_LARGE)
apr_table_setn(r->notes, "error-notes",
"TRACE with a request body is not allowed");
return rv;
}
if (ap_should_client_block(r)) {
if (r->remaining > 0) {
if (r->remaining > 65536) {
apr_table_setn(r->notes, "error-notes",
"Extended TRACE request bodies cannot exceed 64k\n");
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
/* always 32 extra bytes to catch chunk header exceptions */
bodybuf = (apr_size_t)r->remaining + 32;
}
else {
/* Add an extra 8192 for chunk headers */
bodybuf = 73730;
}
bodyoff = bodyread = apr_palloc(r->pool, bodybuf);
/* only while we have enough for a chunked header */
while ((!bodylen || bodybuf >= 32) &&
(res = ap_get_client_block(r, bodyoff, bodybuf)) > 0) {
bodylen += res;
bodybuf -= res;
bodyoff += res;
}
if (res > 0 && bodybuf < 32) {
/* discard_rest_of_request_body into our buffer */
while (ap_get_client_block(r, bodyread, bodylen) > 0)
;
apr_table_setn(r->notes, "error-notes",
"Extended TRACE request bodies cannot exceed 64k\n");
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
if (res < 0) {
return HTTP_BAD_REQUEST;
}
}
ap_set_content_type(r, "message/http");
/* Now we recreate the request, and echo it back */
bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
#if APR_CHARSET_EBCDIC
{
char *tmp;
apr_size_t len;
len = strlen(r->the_request);
tmp = apr_pmemdup(r->pool, r->the_request, len);
ap_xlate_proto_to_ascii(tmp, len);
apr_brigade_putstrs(bb, NULL, NULL, tmp, CRLF_ASCII, NULL);
}
#else
apr_brigade_putstrs(bb, NULL, NULL, r->the_request, CRLF, NULL);
#endif
h.pool = r->pool;
h.bb = bb;
apr_table_do((int (*) (void *, const char *, const char *))
form_header_field, (void *) &h, r->headers_in, NULL);
apr_brigade_puts(bb, NULL, NULL, CRLF_ASCII);
/* If configured to accept a body, echo the body */
if (bodylen) {
b = apr_bucket_pool_create(bodyread, bodylen,
r->pool, bb->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, b);
}
ap_pass_brigade(r->output_filters, bb);
return DONE;
}
typedef struct header_filter_ctx {
int headers_sent;
} header_filter_ctx;
AP_CORE_DECLARE_NONSTD(apr_status_t) ap_http_header_filter(ap_filter_t *f,
apr_bucket_brigade *b)
{
request_rec *r = f->r;
conn_rec *c = r->connection;
const char *protocol = NULL;
apr_bucket *e;
apr_bucket_brigade *b2;
header_struct h;
header_filter_ctx *ctx = f->ctx;
const char *ctype;
ap_bucket_error *eb = NULL;
core_server_config *conf;
AP_DEBUG_ASSERT(!r->main);
if (r->header_only) {
if (!ctx) {
ctx = f->ctx = apr_pcalloc(r->pool, sizeof(header_filter_ctx));
}
else if (ctx->headers_sent) {
apr_brigade_cleanup(b);
return OK;
}
}
for (e = APR_BRIGADE_FIRST(b);
e != APR_BRIGADE_SENTINEL(b);
e = APR_BUCKET_NEXT(e))
{
if (AP_BUCKET_IS_ERROR(e) && !eb) {
eb = e->data;
continue;
}
/*
* If we see an EOC bucket it is a signal that we should get out
* of the way doing nothing.
*/
if (AP_BUCKET_IS_EOC(e)) {
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, b);
}
}
if (eb) {
int status;
status = eb->status;
apr_brigade_cleanup(b);
ap_die(status, r);
return AP_FILTER_ERROR;
}
if (r->assbackwards) {
r->sent_bodyct = 1;
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, b);
}
/*
* Now that we are ready to send a response, we need to combine the two
* header field tables into a single table. If we don't do this, our
* later attempts to set or unset a given fieldname might be bypassed.
*/
if (!apr_is_empty_table(r->err_headers_out)) {
r->headers_out = apr_table_overlay(r->pool, r->err_headers_out,
r->headers_out);
}
conf = ap_get_core_module_config(r->server->module_config);
if (conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT) {
int ok = check_headers(r);
if (!ok && !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY)) {
ap_die(HTTP_INTERNAL_SERVER_ERROR, r);
return AP_FILTER_ERROR;
}
}
/*
* Remove the 'Vary' header field if the client can't handle it.
* Since this will have nasty effects on HTTP/1.1 caches, force
* the response into HTTP/1.0 mode.
*
* Note: the force-response-1.0 should come before the call to
* basic_http_header_check()
*/
if (apr_table_get(r->subprocess_env, "force-no-vary") != NULL) {
apr_table_unset(r->headers_out, "Vary");
r->proto_num = HTTP_VERSION(1,0);
apr_table_setn(r->subprocess_env, "force-response-1.0", "1");
}
else {
fixup_vary(r);
}
/*
* Now remove any ETag response header field if earlier processing
* says so (such as a 'FileETag None' directive).
*/
if (apr_table_get(r->notes, "no-etag") != NULL) {
apr_table_unset(r->headers_out, "ETag");
}
/* determine the protocol and whether we should use keepalives. */
basic_http_header_check(r, &protocol);
ap_set_keepalive(r);
if (r->chunked) {
apr_table_mergen(r->headers_out, "Transfer-Encoding", "chunked");
apr_table_unset(r->headers_out, "Content-Length");
}
ctype = ap_make_content_type(r, r->content_type);
if (ctype) {
apr_table_setn(r->headers_out, "Content-Type", ctype);
}
if (r->content_encoding) {
apr_table_setn(r->headers_out, "Content-Encoding",
r->content_encoding);
}
if (!apr_is_empty_array(r->content_languages)) {
int i;
char *token;
char **languages = (char **)(r->content_languages->elts);
const char *field = apr_table_get(r->headers_out, "Content-Language");
while (field && (token = ap_get_list_item(r->pool, &field)) != NULL) {
for (i = 0; i < r->content_languages->nelts; ++i) {
if (!strcasecmp(token, languages[i]))
break;
}
if (i == r->content_languages->nelts) {
*((char **) apr_array_push(r->content_languages)) = token;
}
}
field = apr_array_pstrcat(r->pool, r->content_languages, ',');
apr_table_setn(r->headers_out, "Content-Language", field);
}
/*
* Control cachability for non-cachable responses if not already set by
* some other part of the server configuration.
*/
if (r->no_cache && !apr_table_get(r->headers_out, "Expires")) {
char *date = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
ap_recent_rfc822_date(date, r->request_time);
apr_table_addn(r->headers_out, "Expires", date);
}
b2 = apr_brigade_create(r->pool, c->bucket_alloc);
basic_http_header(r, b2, protocol);
h.pool = r->pool;
h.bb = b2;
if (r->status == HTTP_NOT_MODIFIED) {
apr_table_do((int (*)(void *, const char *, const char *)) form_header_field,
(void *) &h, r->headers_out,
"Connection",
"Keep-Alive",
"ETag",
"Content-Location",
"Expires",
"Cache-Control",
"Vary",
"Warning",
"WWW-Authenticate",
"Proxy-Authenticate",
"Set-Cookie",
"Set-Cookie2",
NULL);
}
else {
send_all_header_fields(&h, r);
}
terminate_header(b2);
ap_pass_brigade(f->next, b2);
if (r->header_only) {
apr_brigade_cleanup(b);
ctx->headers_sent = 1;
return OK;
}
r->sent_bodyct = 1; /* Whatever follows is real body stuff... */
if (r->chunked) {
/* We can't add this filter until we have already sent the headers.
* If we add it before this point, then the headers will be chunked
* as well, and that is just wrong.
*/
ap_add_output_filter("CHUNK", NULL, r, r->connection);
}
/* Don't remove this filter until after we have added the CHUNK filter.
* Otherwise, f->next won't be the CHUNK filter and thus the first
* brigade won't be chunked properly.
*/
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, b);
}
/*
* Map specific APR codes returned by the filter stack to HTTP error
* codes, or the default status code provided. Use it as follows:
*
* return ap_map_http_request_error(rv, HTTP_BAD_REQUEST);
*
* If the filter has already handled the error, AP_FILTER_ERROR will
* be returned, which is cleanly passed through.
*
* These mappings imply that the filter stack is reading from the
* downstream client, the proxy will map these codes differently.
*/
AP_DECLARE(int) ap_map_http_request_error(apr_status_t rv, int status)
{
switch (rv) {
case AP_FILTER_ERROR: {
return AP_FILTER_ERROR;
}
case APR_EGENERAL: {
return HTTP_BAD_REQUEST;
}
case APR_ENOSPC: {
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
case APR_ENOTIMPL: {
return HTTP_NOT_IMPLEMENTED;
}
case APR_ETIMEDOUT: {
return HTTP_REQUEST_TIME_OUT;
}
default: {
return status;
}
}
}
/* In HTTP/1.1, any method can have a body. However, most GET handlers
* wouldn't know what to do with a request body if they received one.
* This helper routine tests for and reads any message body in the request,
* simply discarding whatever it receives. We need to do this because
* failing to read the request body would cause it to be interpreted
* as the next request on a persistent connection.
*
* Since we return an error status if the request is malformed, this
* routine should be called at the beginning of a no-body handler, e.g.,
*
* if ((retval = ap_discard_request_body(r)) != OK) {
* return retval;
* }
*/
AP_DECLARE(int) ap_discard_request_body(request_rec *r)
{
apr_bucket_brigade *bb;
int seen_eos;
apr_status_t rv;
/* Sometimes we'll get in a state where the input handling has
* detected an error where we want to drop the connection, so if
* that's the case, don't read the data as that is what we're trying
* to avoid.
*
* This function is also a no-op on a subrequest.
*/
if (r->main || r->connection->keepalive == AP_CONN_CLOSE ||
ap_status_drops_connection(r->status)) {
return OK;
}
bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
seen_eos = 0;
do {
apr_bucket *bucket;
rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
APR_BLOCK_READ, HUGE_STRING_LEN);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(bb);
return ap_map_http_request_error(rv, HTTP_BAD_REQUEST);
}
for (bucket = APR_BRIGADE_FIRST(bb);
bucket != APR_BRIGADE_SENTINEL(bb);
bucket = APR_BUCKET_NEXT(bucket))
{
const char *data;
apr_size_t len;
if (APR_BUCKET_IS_EOS(bucket)) {
seen_eos = 1;
break;
}
/* These are metadata buckets. */
if (bucket->length == 0) {
continue;
}
/* We MUST read because in case we have an unknown-length
* bucket or one that morphs, we want to exhaust it.
*/
rv = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(bb);
return HTTP_BAD_REQUEST;
}
}
apr_brigade_cleanup(bb);
} while (!seen_eos);
return OK;
}
/* Here we deal with getting the request message body from the client.
* Whether or not the request contains a body is signaled by the presence
* of a non-zero Content-Length or by a Transfer-Encoding: chunked.
*
* Note that this is more complicated than it was in Apache 1.1 and prior
* versions, because chunked support means that the module does less.
*
* The proper procedure is this:
*
* 1. Call ap_setup_client_block() near the beginning of the request
* handler. This will set up all the necessary properties, and will
* return either OK, or an error code. If the latter, the module should
* return that error code. The second parameter selects the policy to
* apply if the request message indicates a body, and how a chunked
* transfer-coding should be interpreted. Choose one of
*
* REQUEST_NO_BODY Send 413 error if message has any body
* REQUEST_CHUNKED_ERROR Send 411 error if body without Content-Length
* REQUEST_CHUNKED_DECHUNK If chunked, remove the chunks for me.
* REQUEST_CHUNKED_PASS If chunked, pass the chunk headers with body.
*
* In order to use the last two options, the caller MUST provide a buffer
* large enough to hold a chunk-size line, including any extensions.
*
* 2. When you are ready to read a body (if any), call ap_should_client_block().
* This will tell the module whether or not to read input. If it is 0,
* the module should assume that there is no message body to read.
*
* 3. Finally, call ap_get_client_block in a loop. Pass it a buffer and its size.
* It will put data into the buffer (not necessarily a full buffer), and
* return the length of the input block. When it is done reading, it will
* return 0 if EOF, or -1 if there was an error.
* If an error occurs on input, we force an end to keepalive.
*
* This step also sends a 100 Continue response to HTTP/1.1 clients if appropriate.
*/
AP_DECLARE(int) ap_setup_client_block(request_rec *r, int read_policy)
{
const char *tenc = apr_table_get(r->headers_in, "Transfer-Encoding");
const char *lenp = apr_table_get(r->headers_in, "Content-Length");
r->read_body = read_policy;
r->read_chunked = 0;
r->remaining = 0;
if (tenc) {
if (strcasecmp(tenc, "chunked")) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01592)
"Unknown Transfer-Encoding %s", tenc);
return HTTP_NOT_IMPLEMENTED;
}
if (r->read_body == REQUEST_CHUNKED_ERROR) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01593)
"chunked Transfer-Encoding forbidden: %s", r->uri);
return (lenp) ? HTTP_BAD_REQUEST : HTTP_LENGTH_REQUIRED;
}
r->read_chunked = 1;
}
else if (lenp) {
char *endstr;
if (apr_strtoff(&r->remaining, lenp, &endstr, 10)
|| *endstr || r->remaining < 0) {
r->remaining = 0;
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01594)
"Invalid Content-Length");
return HTTP_BAD_REQUEST;
}
}
if ((r->read_body == REQUEST_NO_BODY)
&& (r->read_chunked || (r->remaining > 0))) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01595)
"%s with body is not allowed for %s", r->method, r->uri);
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
#ifdef AP_DEBUG
{
/* Make sure ap_getline() didn't leave any droppings. */
core_request_config *req_cfg =
(core_request_config *)ap_get_core_module_config(r->request_config);
AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(req_cfg->bb));
}
#endif
return OK;
}
AP_DECLARE(int) ap_should_client_block(request_rec *r)
{
/* First check if we have already read the request body */
if (r->read_length || (!r->read_chunked && (r->remaining <= 0))) {
return 0;
}
return 1;
}
/* get_client_block is called in a loop to get the request message body.
* This is quite simple if the client includes a content-length
* (the normal case), but gets messy if the body is chunked. Note that
* r->remaining is used to maintain state across calls and that
* r->read_length is the total number of bytes given to the caller
* across all invocations. It is messy because we have to be careful not
* to read past the data provided by the client, since these reads block.
* Returns 0 on End-of-body, -1 on error or premature chunk end.
*
*/
AP_DECLARE(long) ap_get_client_block(request_rec *r, char *buffer,
apr_size_t bufsiz)
{
apr_status_t rv;
apr_bucket_brigade *bb;
if (r->remaining < 0 || (!r->read_chunked && r->remaining == 0)) {
return 0;
}
bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
if (bb == NULL) {
r->connection->keepalive = AP_CONN_CLOSE;
return -1;
}
rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
APR_BLOCK_READ, bufsiz);
/* We lose the failure code here. This is why ap_get_client_block should
* not be used.
*/
if (rv == AP_FILTER_ERROR) {
/* AP_FILTER_ERROR means a filter has responded already,
* we are DONE.
*/
apr_brigade_destroy(bb);
return -1;
}
if (rv != APR_SUCCESS) {
apr_bucket *e;
/* work around our silent swallowing of error messages by mapping
* error codes at this point, and sending an error bucket back
* upstream.
*/
apr_brigade_cleanup(bb);
e = ap_bucket_error_create(
ap_map_http_request_error(rv, HTTP_BAD_REQUEST), NULL, r->pool,
r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, e);
e = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, e);
rv = ap_pass_brigade(r->output_filters, bb);
if (APR_SUCCESS != rv) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, rv, r, APLOGNO(02484)
"Error while writing error response");
}
/* if we actually fail here, we want to just return and
* stop trying to read data from the client.
*/
r->connection->keepalive = AP_CONN_CLOSE;
apr_brigade_destroy(bb);
return -1;
}
/* If this fails, it means that a filter is written incorrectly and that
* it needs to learn how to properly handle APR_BLOCK_READ requests by
* returning data when requested.
*/
AP_DEBUG_ASSERT(!APR_BRIGADE_EMPTY(bb));
/* Check to see if EOS in the brigade.
*
* If so, we have to leave a nugget for the *next* ap_get_client_block
* call to return 0.
*/
if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
if (r->read_chunked) {
r->remaining = -1;
}
else {
r->remaining = 0;
}
}
rv = apr_brigade_flatten(bb, buffer, &bufsiz);
if (rv != APR_SUCCESS) {
apr_brigade_destroy(bb);
return -1;
}
/* XXX yank me? */
r->read_length += bufsiz;
apr_brigade_destroy(bb);
return bufsiz;
}
/* Context struct for ap_http_outerror_filter */
typedef struct {
int seen_eoc;
} outerror_filter_ctx_t;
/* Filter to handle any error buckets on output */
apr_status_t ap_http_outerror_filter(ap_filter_t *f,
apr_bucket_brigade *b)
{
request_rec *r = f->r;
outerror_filter_ctx_t *ctx = (outerror_filter_ctx_t *)(f->ctx);
apr_bucket *e;
/* Create context if none is present */
if (!ctx) {
ctx = apr_pcalloc(r->pool, sizeof(outerror_filter_ctx_t));
f->ctx = ctx;
}
for (e = APR_BRIGADE_FIRST(b);
e != APR_BRIGADE_SENTINEL(b);
e = APR_BUCKET_NEXT(e))
{
if (AP_BUCKET_IS_ERROR(e)) {
/*
* Start of error handling state tree. Just one condition
* right now :)
*/
if (((ap_bucket_error *)(e->data))->status == HTTP_BAD_GATEWAY ||
((ap_bucket_error *)(e->data))->status == HTTP_GATEWAY_TIME_OUT) {
/* stream aborted and we have not ended it yet */
r->connection->keepalive = AP_CONN_CLOSE;
}
continue;
}
/* Detect EOC buckets and memorize this in the context. */
if (AP_BUCKET_IS_EOC(e)) {
ctx->seen_eoc = 1;
}
}
/*
* Remove all data buckets that are in a brigade after an EOC bucket
* was seen, as an EOC bucket tells us that no (further) resource
* and protocol data should go out to the client. OTOH meta buckets
* are still welcome as they might trigger needed actions down in
* the chain (e.g. in network filters like SSL).
* Remark 1: It is needed to dump ALL data buckets in the brigade
* since an filter in between might have inserted data
* buckets BEFORE the EOC bucket sent by the original
* sender and we do NOT want this data to be sent.
* Remark 2: Dumping all data buckets here does not necessarily mean
* that no further data is send to the client as:
* 1. Network filters like SSL can still be triggered via
* meta buckets to talk with the client e.g. for a
* clean shutdown.
* 2. There could be still data that was buffered before
* down in the chain that gets flushed by a FLUSH or an
* EOS bucket.
*/
if (ctx->seen_eoc) {
for (e = APR_BRIGADE_FIRST(b);
e != APR_BRIGADE_SENTINEL(b);
e = APR_BUCKET_NEXT(e))
{
if (!APR_BUCKET_IS_METADATA(e)) {
APR_BUCKET_REMOVE(e);
}
}
}
return ap_pass_brigade(f->next, b);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1575_2 |
crossvul-cpp_data_good_243_0 | /**
* @file
* Send/receive commands to/from an IMAP server
*
* @authors
* Copyright (C) 1996-1998,2010,2012 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2011 Brendan Cully <brendan@kublai.com>
*
* @copyright
* 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/>.
*/
/**
* @page imap_command Send/receive commands to/from an IMAP server
*
* Send/receive commands to/from an IMAP server
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "buffy.h"
#include "context.h"
#include "globals.h"
#include "header.h"
#include "imap/imap.h"
#include "mailbox.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_menu.h"
#include "mutt_socket.h"
#include "mx.h"
#include "options.h"
#include "protos.h"
#include "url.h"
#define IMAP_CMD_BUFSIZE 512
/**
* Capabilities - Server capabilities strings that we understand
*
* @note This must be kept in the same order as ImapCaps.
*
* @note Gmail documents one string but use another, so we support both.
*/
static const char *const Capabilities[] = {
"IMAP4", "IMAP4rev1", "STATUS", "ACL",
"NAMESPACE", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=ANONYMOUS",
"STARTTLS", "LOGINDISABLED", "IDLE", "SASL-IR",
"ENABLE", "X-GM-EXT-1", "X-GM-EXT1", NULL,
};
/**
* cmd_queue_full - Is the IMAP command queue full?
* @param idata Server data
* @retval true Queue is full
*/
static bool cmd_queue_full(struct ImapData *idata)
{
if ((idata->nextcmd + 1) % idata->cmdslots == idata->lastcmd)
return true;
return false;
}
/**
* cmd_new - Create and queue a new command control block
* @param idata IMAP data
* @retval NULL if the pipeline is full
* @retval ptr New command
*/
static struct ImapCommand *cmd_new(struct ImapData *idata)
{
struct ImapCommand *cmd = NULL;
if (cmd_queue_full(idata))
{
mutt_debug(3, "IMAP command queue full\n");
return NULL;
}
cmd = idata->cmds + idata->nextcmd;
idata->nextcmd = (idata->nextcmd + 1) % idata->cmdslots;
snprintf(cmd->seq, sizeof(cmd->seq), "a%04u", idata->seqno++);
if (idata->seqno > 9999)
idata->seqno = 0;
cmd->state = IMAP_CMD_NEW;
return cmd;
}
/**
* cmd_queue - Add a IMAP command to the queue
* @param idata Server data
* @param cmdstr Command string
* @param flags Server flags, e.g. #IMAP_CMD_POLL
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If the queue is full, attempts to drain it.
*/
static int cmd_queue(struct ImapData *idata, const char *cmdstr, int flags)
{
if (cmd_queue_full(idata))
{
mutt_debug(3, "Draining IMAP command pipeline\n");
const int rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK | (flags & IMAP_CMD_POLL));
if (rc < 0 && rc != -2)
return rc;
}
struct ImapCommand *cmd = cmd_new(idata);
if (!cmd)
return IMAP_CMD_BAD;
if (mutt_buffer_printf(idata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0)
return IMAP_CMD_BAD;
return 0;
}
/**
* cmd_handle_fatal - When ImapData is in fatal state, do what we can
* @param idata Server data
*/
static void cmd_handle_fatal(struct ImapData *idata)
{
idata->status = IMAP_FATAL;
if ((idata->state >= IMAP_SELECTED) && (idata->reopen & IMAP_REOPEN_ALLOW))
{
mx_fastclose_mailbox(idata->ctx);
mutt_socket_close(idata->conn);
mutt_error(_("Mailbox %s@%s closed"), idata->conn->account.login,
idata->conn->account.host);
idata->state = IMAP_DISCONNECTED;
}
imap_close_connection(idata);
if (!idata->recovering)
{
idata->recovering = true;
if (imap_conn_find(&idata->conn->account, 0))
mutt_clear_error();
idata->recovering = false;
}
}
/**
* cmd_start - Start a new IMAP command
* @param idata Server data
* @param cmdstr Command string
* @param flags Command flags, e.g. #IMAP_CMD_QUEUE
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_start(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return -1;
}
if (cmdstr && ((rc = cmd_queue(idata, cmdstr, flags)) < 0))
return rc;
if (flags & IMAP_CMD_QUEUE)
return 0;
if (idata->cmdbuf->dptr == idata->cmdbuf->data)
return IMAP_CMD_BAD;
rc = mutt_socket_send_d(idata->conn, idata->cmdbuf->data,
(flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD);
idata->cmdbuf->dptr = idata->cmdbuf->data;
/* unidle when command queue is flushed */
if (idata->state == IMAP_IDLE)
idata->state = IMAP_SELECTED;
return (rc < 0) ? IMAP_CMD_BAD : 0;
}
/**
* cmd_status - parse response line for tagged OK/NO/BAD
* @param s Status string from server
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_status(const char *s)
{
s = imap_next_word((char *) s);
if (mutt_str_strncasecmp("OK", s, 2) == 0)
return IMAP_CMD_OK;
if (mutt_str_strncasecmp("NO", s, 2) == 0)
return IMAP_CMD_NO;
return IMAP_CMD_BAD;
}
/**
* cmd_parse_expunge - Parse expunge command
* @param idata Server data
* @param s String containing MSN of message to expunge
*
* cmd_parse_expunge: mark headers with new sequence ID and mark idata to be
* reopened at our earliest convenience
*/
static void cmd_parse_expunge(struct ImapData *idata, const char *s)
{
unsigned int exp_msn;
struct Header *h = NULL;
mutt_debug(2, "Handling EXPUNGE\n");
if (mutt_str_atoui(s, &exp_msn) < 0 || exp_msn < 1 || exp_msn > idata->max_msn)
return;
h = idata->msn_index[exp_msn - 1];
if (h)
{
/* imap_expunge_mailbox() will rewrite h->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
h->index = INT_MAX;
HEADER_DATA(h)->msn = 0;
}
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < idata->max_msn; cur++)
{
h = idata->msn_index[cur];
if (h)
HEADER_DATA(h)->msn--;
idata->msn_index[cur - 1] = h;
}
idata->msn_index[idata->max_msn - 1] = NULL;
idata->max_msn--;
idata->reopen |= IMAP_EXPUNGE_PENDING;
}
/**
* cmd_parse_fetch - Load fetch response into ImapData
* @param idata Server data
* @param s String containing MSN of message to fetch
*
* Currently only handles unanticipated FETCH responses, and only FLAGS data.
* We get these if another client has changed flags for a mailbox we've
* selected. Of course, a lot of code here duplicates code in message.c.
*/
static void cmd_parse_fetch(struct ImapData *idata, char *s)
{
unsigned int msn, uid;
struct Header *h = NULL;
int server_changes = 0;
mutt_debug(3, "Handling FETCH\n");
if (mutt_str_atoui(s, &msn) < 0 || msn < 1 || msn > idata->max_msn)
{
mutt_debug(3, "#1 FETCH response ignored for this message\n");
return;
}
h = idata->msn_index[msn - 1];
if (!h || !h->active)
{
mutt_debug(3, "#2 FETCH response ignored for this message\n");
return;
}
mutt_debug(2, "Message UID %u updated\n", HEADER_DATA(h)->uid);
/* skip FETCH */
s = imap_next_word(s);
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Malformed FETCH response\n");
return;
}
s++;
while (*s)
{
SKIPWS(s);
if (mutt_str_strncasecmp("FLAGS", s, 5) == 0)
{
imap_set_flags(idata, h, s, &server_changes);
if (server_changes)
{
/* If server flags could conflict with neomutt's flags, reopen the mailbox. */
if (h->changed)
idata->reopen |= IMAP_EXPUNGE_PENDING;
else
idata->check_status = IMAP_FLAGS_PENDING;
}
return;
}
else if (mutt_str_strncasecmp("UID", s, 3) == 0)
{
s += 3;
SKIPWS(s);
if (mutt_str_atoui(s, &uid) < 0)
{
mutt_debug(2, "Illegal UID. Skipping update.\n");
return;
}
if (uid != HEADER_DATA(h)->uid)
{
mutt_debug(2, "FETCH UID vs MSN mismatch. Skipping update.\n");
return;
}
s = imap_next_word(s);
}
else if (*s == ')')
s++; /* end of request */
else if (*s)
{
mutt_debug(2, "Only handle FLAGS updates\n");
return;
}
}
}
/**
* cmd_parse_capability - set capability bits according to CAPABILITY response
* @param idata Server data
* @param s Command string with capabilities
*/
static void cmd_parse_capability(struct ImapData *idata, char *s)
{
mutt_debug(3, "Handling CAPABILITY\n");
s = imap_next_word(s);
char *bracket = strchr(s, ']');
if (bracket)
*bracket = '\0';
FREE(&idata->capstr);
idata->capstr = mutt_str_strdup(s);
memset(idata->capabilities, 0, sizeof(idata->capabilities));
while (*s)
{
for (int i = 0; i < CAPMAX; i++)
{
if (mutt_str_word_casecmp(Capabilities[i], s) == 0)
{
mutt_bit_set(idata->capabilities, i);
mutt_debug(4, " Found capability \"%s\": %d\n", Capabilities[i], i);
break;
}
}
s = imap_next_word(s);
}
}
/**
* cmd_parse_list - Parse a server LIST command (list mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_list(struct ImapData *idata, char *s)
{
struct ImapList *list = NULL;
struct ImapList lb;
char delimbuf[5]; /* worst case: "\\"\0 */
unsigned int litlen;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
list = (struct ImapList *) idata->cmddata;
else
list = &lb;
memset(list, 0, sizeof(struct ImapList));
/* flags */
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Bad LIST response\n");
return;
}
s++;
while (*s)
{
if (mutt_str_strncasecmp(s, "\\NoSelect", 9) == 0)
list->noselect = true;
else if (mutt_str_strncasecmp(s, "\\NoInferiors", 12) == 0)
list->noinferiors = true;
/* See draft-gahrns-imap-child-mailbox-?? */
else if (mutt_str_strncasecmp(s, "\\HasNoChildren", 14) == 0)
list->noinferiors = true;
s = imap_next_word(s);
if (*(s - 2) == ')')
break;
}
/* Delimiter */
if (mutt_str_strncasecmp(s, "NIL", 3) != 0)
{
delimbuf[0] = '\0';
mutt_str_strcat(delimbuf, 5, s);
imap_unquote_string(delimbuf);
list->delim = delimbuf[0];
}
/* Name */
s = imap_next_word(s);
/* Notes often responds with literals here. We need a real tokenizer. */
if (imap_get_literal_count(s, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
list->name = idata->buf;
}
else
{
imap_unmunge_mbox_name(idata, s);
list->name = s;
}
if (list->name[0] == '\0')
{
idata->delim = list->delim;
mutt_debug(3, "Root delimiter: %c\n", idata->delim);
}
}
/**
* cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_lsub(struct ImapData *idata, char *s)
{
char buf[STRING];
char errstr[STRING];
struct Buffer err, token;
struct Url url;
struct ImapList list;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
{
/* caller will handle response itself */
cmd_parse_list(idata, s);
return;
}
if (!ImapCheckSubscribed)
return;
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &list;
cmd_parse_list(idata, s);
idata->cmddata = NULL;
/* noselect is for a gmail quirk (#3445) */
if (!list.name || list.noselect)
return;
mutt_debug(3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&idata->conn->account, &url);
/* escape \ and " */
imap_quote_string(errstr, sizeof(errstr), list.name, true);
url.path = errstr + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
if (mutt_parse_rc_line(buf, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
/**
* cmd_parse_myrights - Set rights bits according to MYRIGHTS response
* @param idata Server data
* @param s Command string with rights info
*/
static void cmd_parse_myrights(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling MYRIGHTS\n");
s = imap_next_word((char *) s);
s = imap_next_word((char *) s);
/* zero out current rights set */
memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights));
while (*s && !isspace((unsigned char) *s))
{
switch (*s)
{
case 'a':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_ADMIN);
break;
case 'e':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
case 'i':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT);
break;
case 'k':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
break;
case 'l':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP);
break;
case 'p':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST);
break;
case 'r':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ);
break;
case 's':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN);
break;
case 't':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
break;
case 'w':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE);
break;
case 'x':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
/* obsolete rights */
case 'c':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
case 'd':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
default:
mutt_debug(1, "Unknown right: %c\n", *s);
}
s++;
}
}
/**
* cmd_parse_search - store SEARCH response for later use
* @param idata Server data
* @param s Command string with search results
*/
static void cmd_parse_search(struct ImapData *idata, const char *s)
{
unsigned int uid;
struct Header *h = NULL;
mutt_debug(2, "Handling SEARCH\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if (mutt_str_atoui(s, &uid) < 0)
continue;
h = (struct Header *) mutt_hash_int_find(idata->uid_hash, uid);
if (h)
h->matched = true;
}
}
/**
* cmd_parse_status - Parse status from server
* @param idata Server data
* @param s Command string with status info
*
* first cut: just do buffy update. Later we may wish to cache all mailbox
* information, even that not desired by buffy
*/
static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
/**
* cmd_parse_enabled - Record what the server has enabled
* @param idata Server data
* @param s Command string containing acceptable encodings
*/
static void cmd_parse_enabled(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling ENABLED\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) ||
(mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0))
{
idata->unicode = 1;
}
}
}
/**
* cmd_handle_untagged - fallback parser for otherwise unhandled messages
* @param idata Server data
* @retval 0 Success
* @retval -1 Failure
*/
static int cmd_handle_untagged(struct ImapData *idata)
{
unsigned int count = 0;
char *s = imap_next_word(idata->buf);
char *pn = imap_next_word(s);
if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
pn = s;
s = imap_next_word(s);
/* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
* connection, so update that one.
*/
if (mutt_str_strncasecmp("EXISTS", s, 6) == 0)
{
mutt_debug(2, "Handling EXISTS\n");
/* new mail arrived */
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(1, "Malformed EXISTS: '%s'\n", pn);
}
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(1, "Message count is out of sync\n");
return 0;
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == idata->max_msn)
mutt_debug(3, "superfluous EXISTS message.\n");
else
{
if (!(idata->reopen & IMAP_EXPUNGE_PENDING))
{
mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count);
idata->reopen |= IMAP_NEWMAIL_PENDING;
}
idata->new_mail_count = count;
}
}
/* pn vs. s: need initial seqno */
else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0)
cmd_parse_expunge(idata, pn);
else if (mutt_str_strncasecmp("FETCH", s, 5) == 0)
cmd_parse_fetch(idata, pn);
}
else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0)
cmd_parse_capability(idata, s);
else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0)
cmd_parse_capability(idata, pn);
else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0)
cmd_parse_capability(idata, imap_next_word(pn));
else if (mutt_str_strncasecmp("LIST", s, 4) == 0)
cmd_parse_list(idata, s);
else if (mutt_str_strncasecmp("LSUB", s, 4) == 0)
cmd_parse_lsub(idata, s);
else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0)
cmd_parse_myrights(idata, s);
else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0)
cmd_parse_search(idata, s);
else if (mutt_str_strncasecmp("STATUS", s, 6) == 0)
cmd_parse_status(idata, s);
else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0)
cmd_parse_enabled(idata, s);
else if (mutt_str_strncasecmp("BYE", s, 3) == 0)
{
mutt_debug(2, "Handling BYE\n");
/* check if we're logging out */
if (idata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(idata);
return -1;
}
else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0))
{
mutt_debug(2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 2);
}
return 0;
}
/**
* imap_cmd_start - Given an IMAP command, send it to the server
* @param idata Server data
* @param cmdstr Command string to send
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If cmdstr is NULL, sends queued commands.
*/
int imap_cmd_start(struct ImapData *idata, const char *cmdstr)
{
return cmd_start(idata, cmdstr, 0);
}
/**
* imap_cmd_step - Reads server responses from an IMAP command
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* detects tagged completion response, handles untagged messages, can read
* arbitrarily large strings (using malloc, so don't make it _too_ large!).
*/
int imap_cmd_step(struct ImapData *idata)
{
size_t len = 0;
int c;
int rc;
int stillrunning = 0;
struct ImapCommand *cmd = NULL;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
/* read into buffer, expanding buffer as necessary until we have a full
* line */
do
{
if (len == idata->blen)
{
mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE);
idata->blen = idata->blen + IMAP_CMD_BUFSIZE;
mutt_debug(3, "grew buffer to %u bytes\n", idata->blen);
}
/* back up over '\0' */
if (len)
len--;
c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn);
if (c <= 0)
{
mutt_debug(1, "Error reading server response.\n");
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
len += c;
}
/* if we've read all the way to the end of the buffer, we haven't read a
* full line (mutt_socket_readln strips the \r, so we always have at least
* one character free when we've read a full line) */
while (len == idata->blen);
/* don't let one large string make cmd->buf hog memory forever */
if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE))
{
mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE);
idata->blen = IMAP_CMD_BUFSIZE;
mutt_debug(3, "shrank buffer to %u bytes\n", idata->blen);
}
idata->lastread = time(NULL);
/* handle untagged messages. The caller still gets its shot afterwards. */
if (((mutt_str_strncmp(idata->buf, "* ", 2) == 0) ||
(mutt_str_strncmp(imap_next_word(idata->buf), "OK [", 4) == 0)) &&
cmd_handle_untagged(idata))
{
return IMAP_CMD_BAD;
}
/* server demands a continuation response from us */
if (idata->buf[0] == '+')
return IMAP_CMD_RESPOND;
/* Look for tagged command completions.
*
* Some response handlers can end up recursively calling
* imap_cmd_step() and end up handling all tagged command
* completions.
* (e.g. FETCH->set_flag->set_header_color->~h pattern match.)
*
* Other callers don't even create an idata->cmds entry.
*
* For both these cases, we default to returning OK */
rc = IMAP_CMD_OK;
c = idata->lastcmd;
do
{
cmd = &idata->cmds[c];
if (cmd->state == IMAP_CMD_NEW)
{
if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0)
{
if (!stillrunning)
{
/* first command in queue has finished - move queue pointer up */
idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots;
}
cmd->state = cmd_status(idata->buf);
/* bogus - we don't know which command result to return here. Caller
* should provide a tag. */
rc = cmd->state;
}
else
stillrunning++;
}
c = (c + 1) % idata->cmdslots;
} while (c != idata->nextcmd);
if (stillrunning)
rc = IMAP_CMD_CONTINUE;
else
{
mutt_debug(3, "IMAP queue drained\n");
imap_cmd_finish(idata);
}
return rc;
}
/**
* imap_code - Was the command successful
* @param s IMAP command status
* @retval 1 Command result was OK
* @retval 0 If NO or BAD
*/
bool imap_code(const char *s)
{
return (cmd_status(s) == IMAP_CMD_OK);
}
/**
* imap_cmd_trailer - Extra information after tagged command response if any
* @param idata Server data
* @retval ptr Extra command information (pointer into idata->buf)
* @retval "" Error (static string)
*/
const char *imap_cmd_trailer(struct ImapData *idata)
{
static const char *notrailer = "";
const char *s = idata->buf;
if (!s)
{
mutt_debug(2, "not a tagged response\n");
return notrailer;
}
s = imap_next_word((char *) s);
if (!s || ((mutt_str_strncasecmp(s, "OK", 2) != 0) &&
(mutt_str_strncasecmp(s, "NO", 2) != 0) &&
(mutt_str_strncasecmp(s, "BAD", 3) != 0)))
{
mutt_debug(2, "not a command completion: %s\n", idata->buf);
return notrailer;
}
s = imap_next_word((char *) s);
if (!s)
return notrailer;
return s;
}
/**
* imap_exec - Execute a command and wait for the response from the server
* @param idata IMAP data
* @param cmdstr Command to execute
* @param flags Flags (see below)
* @retval 0 Success
* @retval -1 Failure
* @retval -2 OK Failure
*
* Also, handle untagged responses.
*
* Flags:
* * IMAP_CMD_FAIL_OK: the calling procedure can handle failure.
* This is used for checking for a mailbox on append and login
* * IMAP_CMD_PASS: command contains a password. Suppress logging.
* * IMAP_CMD_QUEUE: only queue command, do not execute.
* * IMAP_CMD_POLL: poll the socket for a response before running imap_cmd_step.
*/
int imap_exec(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
rc = cmd_start(idata, cmdstr, flags);
if (rc < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if (flags & IMAP_CMD_QUEUE)
return 0;
if ((flags & IMAP_CMD_POLL) && (ImapPollTimeout > 0) &&
(mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
/* Allow interruptions, particularly useful if there are network problems. */
mutt_sig_allow_interrupt(1);
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
mutt_sig_allow_interrupt(0);
if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
return -2;
if (rc != IMAP_CMD_OK)
{
if ((flags & IMAP_CMD_FAIL_OK) && idata->status != IMAP_FATAL)
return -2;
mutt_debug(1, "command failed: %s\n", idata->buf);
return -1;
}
return 0;
}
/**
* imap_cmd_finish - Attempt to perform cleanup
* @param idata Server data
*
* Attempts to perform cleanup (eg fetch new mail if detected, do expunge).
* Called automatically by imap_cmd_step(), but may be called at any time.
* Called by imap_check_mailbox() just before the index is refreshed, for
* instance.
*/
void imap_cmd_finish(struct ImapData *idata)
{
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return;
}
if (!(idata->state >= IMAP_SELECTED) || idata->ctx->closing)
return;
if (idata->reopen & IMAP_REOPEN_ALLOW)
{
unsigned int count = idata->new_mail_count;
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
(idata->reopen & IMAP_NEWMAIL_PENDING) && count > idata->max_msn)
{
/* read new mail messages */
mutt_debug(2, "Fetching new mail\n");
/* check_status: curs_main uses imap_check_mailbox to detect
* whether the index needs updating */
idata->check_status = IMAP_NEWMAIL_PENDING;
imap_read_headers(idata, idata->max_msn + 1, count);
}
else if (idata->reopen & IMAP_EXPUNGE_PENDING)
{
mutt_debug(2, "Expunging mailbox\n");
imap_expunge_mailbox(idata);
/* Detect whether we've gotten unexpected EXPUNGE messages */
if ((idata->reopen & IMAP_EXPUNGE_PENDING) && !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
idata->check_status = IMAP_EXPUNGE_PENDING;
idata->reopen &=
~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING | IMAP_EXPUNGE_EXPECTED);
}
}
idata->status = false;
}
/**
* imap_cmd_idle - Enter the IDLE state
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
int imap_cmd_idle(struct ImapData *idata)
{
int rc;
if (cmd_start(idata, "IDLE", IMAP_CMD_POLL) < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if ((ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
/* successfully entered IDLE state */
idata->state = IMAP_IDLE;
/* queue automatic exit when next command is issued */
mutt_buffer_printf(idata->cmdbuf, "DONE\r\n");
rc = IMAP_CMD_OK;
}
if (rc != IMAP_CMD_OK)
{
mutt_debug(1, "error starting IDLE\n");
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_243_0 |
crossvul-cpp_data_bad_2027_0 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
* Copyright (c) 2002 Nokia Corp.
*
* This is part of the SCTP Linux Kernel Implementation.
*
* These are the state functions for the state machine.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation 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 GNU CC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <linux-sctp@vger.kernel.org>
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Mathew Kotowsky <kotowsky@sctp.org>
* Sridhar Samudrala <samudrala@us.ibm.com>
* Jon Grimm <jgrimm@us.ibm.com>
* Hui Huang <hui.huang@nokia.com>
* Dajiang Zhang <dajiang.zhang@nokia.com>
* Daisy Chang <daisyc@us.ibm.com>
* Ardelle Fan <ardelle.fan@intel.com>
* Ryan Layer <rmlayer@us.ibm.com>
* Kevin Gao <kevin.gao@intel.com>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/inet_ecn.h>
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/structs.h>
static struct sctp_packet *sctp_abort_pkt_new(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen);
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands);
static struct sctp_packet *sctp_ootb_pkt_new(struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk);
static void sctp_send_stale_cookie_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk);
static sctp_disposition_t sctp_sf_do_5_2_6_stale(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_tabort_8_4_8(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk);
static sctp_disposition_t sctp_stop_t1_and_abort(struct net *net,
sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport);
static sctp_disposition_t sctp_sf_abort_violation(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen);
static sctp_disposition_t sctp_sf_violation_chunklen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_paramlen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_chunk(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_ierror_t sctp_sf_authenticate(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk);
static sctp_disposition_t __sctp_sf_do_9_1_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
/* Small helper function that checks if the chunk length
* is of the appropriate length. The 'required_length' argument
* is set to be the size of a specific chunk we are testing.
* Return Values: 1 = Valid length
* 0 = Invalid length
*
*/
static inline int
sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
/**********************************************************
* These are the state functions for handling chunk events.
**********************************************************/
/*
* Process the final SHUTDOWN COMPLETE.
*
* Section: 4 (C) (diagram), 9.2
* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint will verify
* that it is in SHUTDOWN-ACK-SENT state, if it is not the chunk should be
* discarded. If the endpoint is in the SHUTDOWN-ACK-SENT state the endpoint
* should stop the T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED state).
*
* Verification Tag: 8.5.1(C), sctpimpguide 2.41.
* C) Rules for packet carrying SHUTDOWN COMPLETE:
* ...
* - The receiver of a SHUTDOWN COMPLETE shall accept the packet
* if the Verification Tag field of the packet matches its own tag and
* the T bit is not set
* OR
* it is set to its peer's tag and the T bit is set in the Chunk
* Flags.
* Otherwise, the receiver MUST silently discard the packet
* and take no further action. An endpoint MUST ignore the
* SHUTDOWN COMPLETE if it is not in the SHUTDOWN-ACK-SENT state.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_4_C(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 2960 6.10 Bundling
*
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_COMPLETE chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* RFC 2960 10.2 SCTP-to-ULP
*
* H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
/* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint
* will verify that it is in SHUTDOWN-ACK-SENT state, if it is
* not the chunk should be discarded. If the endpoint is in
* the SHUTDOWN-ACK-SENT state the endpoint should stop the
* T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED
* state).
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* Respond to a normal INIT chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, B
* B) "Z" shall respond immediately with an INIT ACK chunk. The
* destination IP address of the INIT ACK MUST be set to the source
* IP address of the INIT to which this INIT ACK is responding. In
* the response, besides filling in other parameters, "Z" must set the
* Verification Tag field to Tag_A, and also provide its own
* Verification Tag (Tag_Z) in the Initiate Tag field.
*
* Verification Tag: Must be 0.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1B_init(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
sctp_unrecognized_param_t *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* Normally, this would cause an ABORT with a Protocol Violation
* error, but since we don't have an association, we'll
* just discard the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the INIT is coming toward a closing socket, we'll send back
* and ABORT. Essentially, this catches the race of INIT being
* backloged to the socket at the same time as the user isses close().
* Since the socket and all its associations are going away, we
* can treat this OOTB
*/
if (sctp_sstate(ep->base.sk, CLOSING))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
return SCTP_DISPOSITION_CONSUME;
} else {
return SCTP_DISPOSITION_NOMEM;
}
} else {
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg,
commands);
}
}
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)),
GFP_ATOMIC) < 0)
goto nomem_init;
/* The call, sctp_process_init(), can fail on memory allocation. */
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem_init;
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk)
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem_init;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (sctp_unrecognized_param_t *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
sctp_chunk_free(err_chunk);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources, nor keep any states for the
* new association. Otherwise, "Z" will be vulnerable to resource
* attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_init:
sctp_association_free(new_asoc);
nomem:
if (err_chunk)
sctp_chunk_free(err_chunk);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal INIT ACK chunk.
* We are the side that is initiating the association.
*
* Section: 5.1 Normal Establishment of an Association, C
* C) Upon reception of the INIT ACK from "Z", "A" shall stop the T1-init
* timer and leave COOKIE-WAIT state. "A" shall then send the State
* Cookie received in the INIT ACK chunk in a COOKIE ECHO chunk, start
* the T1-cookie timer, and enter the COOKIE-ECHOED state.
*
* Note: The COOKIE ECHO chunk can be bundled with any pending outbound
* DATA chunks, but it MUST be the first chunk in the packet and
* until the COOKIE ACK is returned the sender MUST NOT send any
* other packets to the peer.
*
* Verification Tag: 3.3.3
* If the value of the Initiate Tag in a received INIT ACK chunk is
* found to be 0, the receiver MUST treat it as an error and close the
* association by transmitting an ABORT.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1C_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_init_chunk_t *initchunk;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT-ACK chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_initack_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
sctp_error_t error = SCTP_ERROR_NO_RESOURCE;
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes. If there are no causes,
* then there wasn't enough memory. Just terminate
* the association.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
error = SCTP_ERROR_INV_PARAM;
}
}
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED,
asoc, chunk->transport);
}
/* Tag the variable length parameters. Note that we never
* convert the parameters in an INIT chunk.
*/
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
initchunk = (sctp_init_chunk_t *) chunk->chunk_hdr;
sctp_add_cmd_sf(commands, SCTP_CMD_PEER_INIT,
SCTP_PEER_INIT(initchunk));
/* Reset init error count upon receipt of INIT-ACK. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* 5.1 C) "A" shall stop the T1-init timer and leave
* COOKIE-WAIT state. "A" shall then ... start the T1-cookie
* timer, and enter the COOKIE-ECHOED state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_ECHOED));
/* SCTP-AUTH: genereate the assocition shared keys so that
* we can potentially signe the COOKIE-ECHO.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_SHKEY, SCTP_NULL());
/* 5.1 C) "A" shall then send the State Cookie received in the
* INIT ACK chunk in a COOKIE ECHO chunk, ...
*/
/* If there is any errors to report, send the ERROR chunk generated
* for unknown parameters as well.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_COOKIE_ECHO,
SCTP_CHUNK(err_chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Respond to a normal COOKIE ECHO chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, D
* D) Upon reception of the COOKIE ECHO chunk, Endpoint "Z" will reply
* with a COOKIE ACK chunk after building a TCB and moving to
* the ESTABLISHED state. A COOKIE ACK chunk may be bundled with
* any pending DATA chunks (and/or SACK chunks), but the COOKIE ACK
* chunk MUST be the first chunk in the packet.
*
* IMPLEMENTATION NOTE: An implementation may choose to send the
* Communication Up notification to the SCTP user upon reception
* of a valid COOKIE ECHO chunk.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* D) Rules for packet carrying a COOKIE ECHO
*
* - When sending a COOKIE ECHO, the endpoint MUST use the value of the
* Initial Tag received in the INIT ACK.
*
* - The receiver of a COOKIE ECHO follows the procedures in Section 5.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
struct sctp_ulpevent *ev, *ai_ev = NULL;
int error = 0;
struct sctp_chunk *err_chk_p;
struct sock *sk;
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* Make sure that the COOKIE_ECHO chunk has a valid length.
* In this case, we check that we have enough for at least a
* chunk header. More detailed verification is done
* in sctp_unpack_cookie().
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the endpoint is not listening or if the number of associations
* on the TCP-style socket exceed the max backlog, respond with an
* ABORT.
*/
sk = ep->base.sk;
if (!sctp_sstate(sk, LISTENING) ||
(sctp_style(sk, TCP) && sk_acceptq_is_full(sk)))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr =
(struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint
* "Z" will reply with a COOKIE ACK chunk after building a TCB
* and moving to the ESTABLISHED state.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Delay state machine commands until later.
*
* Re-build the bind address for the association is done in
* the sctp_unpack_cookie() already.
*/
/* This is a brand-new association, so these are not yet side
* effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk,
&chunk->subh.cookie_hdr->c.peer_addr,
peer_init, GFP_ATOMIC))
goto nomem_init;
/* SCTP-AUTH: Now that we've populate required fields in
* sctp_process_init, set up the assocaition shared keys as
* necessary so that we can potentially authenticate the ACK
*/
error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC);
if (error)
goto nomem_init;
/* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo
* is supposed to be authenticated and we have to do delayed
* authentication. We've just recreated the association using
* the information in the cookie and now it's much easier to
* do the authentication.
*/
if (chunk->auth_chunk) {
struct sctp_chunk auth;
sctp_ierror_t ret;
/* set-up our fake chunk so that we can process it */
auth.skb = chunk->auth_chunk;
auth.asoc = chunk->asoc;
auth.sctp_hdr = chunk->sctp_hdr;
auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk,
sizeof(sctp_chunkhdr_t));
skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t));
auth.transport = chunk->transport;
ret = sctp_sf_authenticate(net, ep, new_asoc, type, &auth);
/* We can now safely free the auth_chunk clone */
kfree_skb(chunk->auth_chunk);
if (ret != SCTP_IERROR_NO_ERROR) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem_init;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (new_asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem_aiev;
}
/* Add all the state machine commands now since we've created
* everything. This way we don't introduce memory corruptions
* during side-effect processing and correclty count established
* associations.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* This will send the COOKIE ACK */
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* Queue the ASSOC_CHANGE event */
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Send up the Adaptation Layer Indication event */
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem_aiev:
sctp_ulpevent_free(ev);
nomem_ev:
sctp_chunk_free(repl);
nomem_init:
sctp_association_free(new_asoc);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal COOKIE ACK chunk.
* We are the side that is being asked for an association.
*
* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move from the
* COOKIE-ECHOED state to the ESTABLISHED state, stopping the T1-cookie
* timer. It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*
* Verification Tag:
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1E_ca(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Verify that the chunk length for the COOKIE-ACK is OK.
* If we don't do this, any bundled chunks may be junked.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Reset init error count upon receipt of COOKIE-ACK,
* to avoid problems with the managemement of this
* counter in stale cookie situations when a transition back
* from the COOKIE-ECHOED state to the COOKIE-WAIT
* state is performed.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move
* from the COOKIE-ECHOED state to the ESTABLISHED state,
* stopping the T1-cookie timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ACTIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_UP,
0, asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Generate and sendout a heartbeat packet. */
static sctp_disposition_t sctp_sf_heartbeat(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
struct sctp_chunk *reply;
/* Send a heartbeat to our peer. */
reply = sctp_make_heartbeat(asoc, transport);
if (!reply)
return SCTP_DISPOSITION_NOMEM;
/* Set rto_pending indicating that an RTT measurement
* is started with this heartbeat chunk.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_RTO_PENDING,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
}
/* Generate a HEARTBEAT packet on the given transport. */
sctp_disposition_t sctp_sf_sendbeat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
/* Section 3.3.5.
* The Sender-specific Heartbeat Info field should normally include
* information about the sender's current time when this HEARTBEAT
* chunk is sent and the destination transport address to which this
* HEARTBEAT is sent (see Section 8.3).
*/
if (transport->param_flags & SPP_HB_ENABLE) {
if (SCTP_DISPOSITION_NOMEM ==
sctp_sf_heartbeat(ep, asoc, type, arg,
commands))
return SCTP_DISPOSITION_NOMEM;
/* Set transport error counter and association error counter
* when sending heartbeat.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(transport));
}
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_IDLE,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMER_UPDATE,
SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an heartbeat request.
*
* Section: 8.3 Path Heartbeat
* The receiver of the HEARTBEAT should immediately respond with a
* HEARTBEAT ACK that contains the Heartbeat Information field copied
* from the received HEARTBEAT chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* When receiving an SCTP packet, the endpoint MUST ensure that the
* value in the Verification Tag field of the received SCTP packet
* matches its own Tag. If the received Verification Tag value does not
* match the receiver's own tag value, the receiver shall silently
* discard the packet and shall not process it any further except for
* those cases listed in Section 8.5.1 below.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_beat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_paramhdr_t *param_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
size_t paylen = 0;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_heartbeat_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* 8.3 The receiver of the HEARTBEAT should immediately
* respond with a HEARTBEAT ACK that contains the Heartbeat
* Information field copied from the received HEARTBEAT chunk.
*/
chunk->subh.hb_hdr = (sctp_heartbeathdr_t *) chunk->skb->data;
param_hdr = (sctp_paramhdr_t *) chunk->subh.hb_hdr;
paylen = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
if (ntohs(param_hdr->length) > paylen)
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
param_hdr, commands);
if (!pskb_pull(chunk->skb, paylen))
goto nomem;
reply = sctp_make_heartbeat_ack(asoc, chunk, param_hdr, paylen);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the returning HEARTBEAT ACK.
*
* Section: 8.3 Path Heartbeat
* Upon the receipt of the HEARTBEAT ACK, the sender of the HEARTBEAT
* should clear the error counter of the destination transport
* address to which the HEARTBEAT was sent, and mark the destination
* transport address as active if it is not so marked. The endpoint may
* optionally report to the upper layer when an inactive destination
* address is marked as active due to the reception of the latest
* HEARTBEAT ACK. The receiver of the HEARTBEAT ACK must also
* clear the association overall error count as well (as defined
* in section 8.1).
*
* The receiver of the HEARTBEAT ACK should also perform an RTT
* measurement for that destination transport address using the time
* value carried in the HEARTBEAT ACK chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_backbeat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
union sctp_addr from_addr;
struct sctp_transport *link;
sctp_sender_hb_info_t *hbinfo;
unsigned long max_interval;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT-ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t) +
sizeof(sctp_sender_hb_info_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
hbinfo = (sctp_sender_hb_info_t *) chunk->skb->data;
/* Make sure that the length of the parameter is what we expect */
if (ntohs(hbinfo->param_hdr.length) !=
sizeof(sctp_sender_hb_info_t)) {
return SCTP_DISPOSITION_DISCARD;
}
from_addr = hbinfo->daddr;
link = sctp_assoc_lookup_paddr(asoc, &from_addr);
/* This should never happen, but lets log it if so. */
if (unlikely(!link)) {
if (from_addr.sa.sa_family == AF_INET6) {
net_warn_ratelimited("%s association %p could not find address %pI6\n",
__func__,
asoc,
&from_addr.v6.sin6_addr);
} else {
net_warn_ratelimited("%s association %p could not find address %pI4\n",
__func__,
asoc,
&from_addr.v4.sin_addr.s_addr);
}
return SCTP_DISPOSITION_DISCARD;
}
/* Validate the 64-bit random nonce. */
if (hbinfo->hb_nonce != link->hb_nonce)
return SCTP_DISPOSITION_DISCARD;
max_interval = link->hbinterval + link->rto;
/* Check if the timestamp looks valid. */
if (time_after(hbinfo->sent_at, jiffies) ||
time_after(jiffies, hbinfo->sent_at + max_interval)) {
pr_debug("%s: HEARTBEAT ACK with invalid timestamp received "
"for transport:%p\n", __func__, link);
return SCTP_DISPOSITION_DISCARD;
}
/* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of
* the HEARTBEAT should clear the error counter of the
* destination transport address to which the HEARTBEAT was
* sent and mark the destination transport address as active if
* it is not so marked.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_ON, SCTP_TRANSPORT(link));
return SCTP_DISPOSITION_CONSUME;
}
/* Helper function to send out an abort for the restart
* condition.
*/
static int sctp_sf_send_restart_abort(struct net *net, union sctp_addr *ssa,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
int len;
struct sctp_packet *pkt;
union sctp_addr_param *addrparm;
struct sctp_errhdr *errhdr;
struct sctp_endpoint *ep;
char buffer[sizeof(struct sctp_errhdr)+sizeof(union sctp_addr_param)];
struct sctp_af *af = sctp_get_af_specific(ssa->v4.sin_family);
/* Build the error on the stack. We are way to malloc crazy
* throughout the code today.
*/
errhdr = (struct sctp_errhdr *)buffer;
addrparm = (union sctp_addr_param *)errhdr->variable;
/* Copy into a parm format. */
len = af->to_addr_param(ssa, addrparm);
len += sizeof(sctp_errhdr_t);
errhdr->cause = SCTP_ERROR_RESTART;
errhdr->length = htons(len);
/* Assign to the control socket. */
ep = sctp_sk(net->sctp.ctl_sock)->ep;
/* Association is NULL since this may be a restart attack and we
* want to send back the attacker's vtag.
*/
pkt = sctp_abort_pkt_new(net, ep, NULL, init, errhdr, len);
if (!pkt)
goto out;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(pkt));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
/* Discard the rest of the inbound packet. */
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
out:
/* Even if there is no memory, treat as a failure so
* the packet will get dropped.
*/
return 0;
}
static bool list_has_sctp_addr(const struct list_head *list,
union sctp_addr *ipaddr)
{
struct sctp_transport *addr;
list_for_each_entry(addr, list, transports) {
if (sctp_cmp_addr_exact(ipaddr, &addr->ipaddr))
return true;
}
return false;
}
/* A restart is occurring, check to make sure no new addresses
* are being added as we may be under a takeover attack.
*/
static int sctp_sf_check_restart_addrs(const struct sctp_association *new_asoc,
const struct sctp_association *asoc,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
struct net *net = sock_net(new_asoc->base.sk);
struct sctp_transport *new_addr;
int ret = 1;
/* Implementor's Guide - Section 5.2.2
* ...
* Before responding the endpoint MUST check to see if the
* unexpected INIT adds new addresses to the association. If new
* addresses are added to the association, the endpoint MUST respond
* with an ABORT..
*/
/* Search through all current addresses and make sure
* we aren't adding any new ones.
*/
list_for_each_entry(new_addr, &new_asoc->peer.transport_addr_list,
transports) {
if (!list_has_sctp_addr(&asoc->peer.transport_addr_list,
&new_addr->ipaddr)) {
sctp_sf_send_restart_abort(net, &new_addr->ipaddr, init,
commands);
ret = 0;
break;
}
}
/* Return success if all addresses were found. */
return ret;
}
/* Populate the verification/tie tags based on overlapping INIT
* scenario.
*
* Note: Do not use in CLOSED or SHUTDOWN-ACK-SENT state.
*/
static void sctp_tietags_populate(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
switch (asoc->state) {
/* 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State */
case SCTP_STATE_COOKIE_WAIT:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = 0;
break;
case SCTP_STATE_COOKIE_ECHOED:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
/* 5.2.2 Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
* COOKIE-WAIT and SHUTDOWN-ACK-SENT
*/
default:
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
}
/* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
*/
new_asoc->rwnd = asoc->rwnd;
new_asoc->c.sinit_num_ostreams = asoc->c.sinit_num_ostreams;
new_asoc->c.sinit_max_instreams = asoc->c.sinit_max_instreams;
new_asoc->c.initial_tsn = asoc->c.initial_tsn;
}
/*
* Compare vtag/tietag values to determine unexpected COOKIE-ECHO
* handling action.
*
* RFC 2960 5.2.4 Handle a COOKIE ECHO when a TCB exists.
*
* Returns value representing action to be taken. These action values
* correspond to Action/Description values in RFC 2960, Table 2.
*/
static char sctp_tietags_compare(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
/* In this case, the peer may have restarted. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag != new_asoc->c.peer_vtag) &&
(asoc->c.my_vtag == new_asoc->c.my_ttag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_ttag))
return 'A';
/* Collision case B. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
((asoc->c.peer_vtag != new_asoc->c.peer_vtag) ||
(0 == asoc->c.peer_vtag))) {
return 'B';
}
/* Collision case D. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag))
return 'D';
/* Collision case C. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag) &&
(0 == new_asoc->c.my_ttag) &&
(0 == new_asoc->c.peer_ttag))
return 'C';
/* No match to any of the special cases; discard this packet. */
return 'E';
}
/* Common helper routine for both duplicate and simulataneous INIT
* chunk handling.
*/
static sctp_disposition_t sctp_sf_do_unexpected_init(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
sctp_unrecognized_param_t *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* In this case, we generate a protocol violation since we have
* an association established.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
retval = SCTP_DISPOSITION_CONSUME;
} else {
retval = SCTP_DISPOSITION_NOMEM;
}
goto cleanup;
} else {
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg,
commands);
}
}
/*
* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
* FIXME: We are copying parameters from the endpoint not the
* association.
*/
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0)
goto nomem;
/* In the outbound INIT ACK the endpoint MUST copy its current
* Verification Tag and Peers Verification tag into a reserved
* place (local tie-tag and per tie-tag) within the state cookie.
*/
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Do not do this check for COOKIE-WAIT state,
* since there are no peer addresses to check against.
* Upon return an ABORT will have been sent if needed.
*/
if (!sctp_state(asoc, COOKIE_WAIT)) {
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk,
commands)) {
retval = SCTP_DISPOSITION_CONSUME;
goto nomem_retval;
}
}
sctp_tietags_populate(new_asoc, asoc);
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk) {
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
}
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (sctp_unrecognized_param_t *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources for this new association.
* Otherwise, "Z" will be vulnerable to resource attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
retval = SCTP_DISPOSITION_CONSUME;
return retval;
nomem:
retval = SCTP_DISPOSITION_NOMEM;
nomem_retval:
if (new_asoc)
sctp_association_free(new_asoc);
cleanup:
if (err_chunk)
sctp_chunk_free(err_chunk);
return retval;
}
/*
* Handle simultaneous INIT.
* This means we started an INIT and then we got an INIT request from
* our peer.
*
* Section: 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State (Item B)
* This usually indicates an initialization collision, i.e., each
* endpoint is attempting, at about the same time, to establish an
* association with the other endpoint.
*
* Upon receipt of an INIT in the COOKIE-WAIT or COOKIE-ECHOED state, an
* endpoint MUST respond with an INIT ACK using the same parameters it
* sent in its original INIT chunk (including its Verification Tag,
* unchanged). These original parameters are combined with those from the
* newly received INIT chunk. The endpoint shall also generate a State
* Cookie with the INIT ACK. The endpoint uses the parameters sent in its
* INIT to calculate the State Cookie.
*
* After that, the endpoint MUST NOT change its state, the T1-init
* timer shall be left running and the corresponding TCB MUST NOT be
* destroyed. The normal procedures for handling State Cookies when
* a TCB exists will resolve the duplicate INITs to a single association.
*
* For an endpoint that is in the COOKIE-ECHOED state it MUST populate
* its Tie-Tags with the Tag information of itself and its peer (see
* section 5.2.2 for a description of the Tie-Tags).
*
* Verification Tag: Not explicit, but an INIT can not have a valid
* verification tag, so we skip the check.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_1_siminit(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands);
}
/*
* Handle duplicated INIT messages. These are usually delayed
* restransmissions.
*
* Section: 5.2.2 Unexpected INIT in States Other than CLOSED,
* COOKIE-ECHOED and COOKIE-WAIT
*
* Unless otherwise stated, upon reception of an unexpected INIT for
* this association, the endpoint shall generate an INIT ACK with a
* State Cookie. In the outbound INIT ACK the endpoint MUST copy its
* current Verification Tag and peer's Verification Tag into a reserved
* place within the state cookie. We shall refer to these locations as
* the Peer's-Tie-Tag and the Local-Tie-Tag. The outbound SCTP packet
* containing this INIT ACK MUST carry a Verification Tag value equal to
* the Initiation Tag found in the unexpected INIT. And the INIT ACK
* MUST contain a new Initiation Tag (randomly generated see Section
* 5.3.1). Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of outbound
* streams) into the INIT ACK and cookie.
*
* After sending out the INIT ACK, the endpoint shall take no further
* actions, i.e., the existing association, including its current state,
* and the corresponding TCB MUST NOT be changed.
*
* Note: Only when a TCB exists and the association is not in a COOKIE-
* WAIT state are the Tie-Tags populated. For a normal association INIT
* (i.e. the endpoint is in a COOKIE-WAIT state), the Tie-Tags MUST be
* set to 0 (indicating that no previous TCB existed). The INIT ACK and
* State Cookie are populated as specified in section 5.2.1.
*
* Verification Tag: Not specified, but an INIT has no way of knowing
* what the verification tag could be, so we ignore it.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_2_dupinit(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands);
}
/*
* Unexpected INIT-ACK handler.
*
* Section 5.2.3
* If an INIT ACK received by an endpoint in any state other than the
* COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
* An unexpected INIT ACK usually indicates the processing of an old or
* duplicated INIT chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_3_initack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* Per the above section, we'll discard the chunk if we have an
* endpoint. If this is an OOTB INIT-ACK, treat it as such.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep)
return sctp_sf_ootb(net, ep, asoc, type, arg, commands);
else
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
}
/* Unexpected COOKIE-ECHO handler for peer restart (Table 2, action 'A')
*
* Section 5.2.4
* A) In this case, the peer may have restarted.
*/
static sctp_disposition_t sctp_sf_do_dupcook_a(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_ulpevent *ev;
struct sctp_chunk *repl;
struct sctp_chunk *err;
sctp_disposition_t disposition;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Though this is a pretty complicated attack
* since you'd have to get inside the cookie.
*/
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) {
return SCTP_DISPOSITION_CONSUME;
}
/* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
* the peer has restarted (Action A), it MUST NOT setup a new
* association but instead resend the SHUTDOWN ACK and send an ERROR
* chunk with a "Cookie Received while Shutting Down" error cause to
* its peer.
*/
if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) {
disposition = sctp_sf_do_9_2_reshutack(net, ep, asoc,
SCTP_ST_CHUNK(chunk->chunk_hdr->type),
chunk, commands);
if (SCTP_DISPOSITION_NOMEM == disposition)
goto nomem;
err = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_COOKIE_IN_SHUTDOWN,
NULL, 0, 0);
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_DISPOSITION_CONSUME;
}
/* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked
* data. Consider the optional choice of resending of this data.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_SACK));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL());
/* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue
* and ASCONF-ACK cache.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL());
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
/* Report association restart to upper layer. */
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return SCTP_DISPOSITION_CONSUME;
nomem_ev:
sctp_chunk_free(repl);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'B')
*
* Section 5.2.4
* B) In this case, both sides may be attempting to start an association
* at about the same time but the peer endpoint started its INIT
* after responding to the local endpoint's INIT
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_b(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*
* Sadly, this needs to be implemented as a side-effect, because
* we are not guaranteed to have set the association id of the real
* association and so these notifications need to be delayed until
* the association id is allocated.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_CHANGE, SCTP_U8(SCTP_COMM_UP));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*
* This also needs to be done as a side effect for the same reason as
* above.
*/
if (asoc->peer.adaptation_ind)
sctp_add_cmd_sf(commands, SCTP_CMD_ADAPTATION_IND, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'C')
*
* Section 5.2.4
* C) In this case, the local endpoint's cookie has arrived late.
* Before it arrived, the local endpoint sent an INIT and received an
* INIT-ACK and finally sent a COOKIE ECHO with the peer's same tag
* but a new tag of its own.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_c(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
/* The cookie should be silently discarded.
* The endpoint SHOULD NOT change states and should leave
* any timers running.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* Unexpected COOKIE-ECHO handler lost chunk (Table 2, action 'D')
*
* Section 5.2.4
*
* D) When both local and remote tags match the endpoint should always
* enter the ESTABLISHED state, if it has not already done so.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_d(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
struct sctp_ulpevent *ev = NULL, *ai_ev = NULL;
struct sctp_chunk *repl;
/* Clarification from Implementor's Guide:
* D) When both local and remote tags match the endpoint should
* enter the ESTABLISHED state, if it is in the COOKIE-ECHOED state.
* It should stop any cookie timer that may be running and send
* a COOKIE ACK.
*/
/* Don't accidentally move back into established state. */
if (asoc->state < SCTP_STATE_ESTABLISHED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START,
SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose
* to send the Communication Up notification to the
* SCTP user upon reception of a valid COOKIE
* ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0,
SCTP_COMM_UP, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter,
* SCTP delivers this notification to inform the application
* that of the peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem;
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem:
if (ai_ev)
sctp_ulpevent_free(ai_ev);
if (ev)
sctp_ulpevent_free(ev);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a duplicate COOKIE-ECHO. This usually means a cookie-carrying
* chunk was retransmitted and then delayed in the network.
*
* Section: 5.2.4 Handle a COOKIE ECHO when a TCB exists
*
* Verification Tag: None. Do cookie validation.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
int error = 0;
char action;
struct sctp_chunk *err_chk_p;
/* Make sure that the chunk has a valid length from the protocol
* perspective. In this case check to make sure we have at least
* enough for the chunk header. Cookie length verification is
* done later.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie
* of a duplicate COOKIE ECHO match the Verification Tags of the
* current association, consider the State Cookie valid even if
* the lifespan is exceeded.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Compare the tie_tag in cookie with the verification tag of
* current association.
*/
action = sctp_tietags_compare(new_asoc, asoc);
switch (action) {
case 'A': /* Association restart. */
retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'B': /* Collision case B. */
retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'C': /* Collision case C. */
retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'D': /* Collision case D. */
retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands,
new_asoc);
break;
default: /* Discard packet for all others. */
retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
break;
}
/* Delete the tempory new association. */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
/* Restore association pointer to provide SCTP command interpeter
* with a valid context in case it needs to manipulate
* the queues */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC,
SCTP_ASOC((struct sctp_association *)asoc));
return retval;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT. (SHUTDOWN-PENDING state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_pending_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_sent_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-ACK-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_ack_sent_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_abort(net, ep, asoc, type, arg, commands);
}
/*
* Handle an Error received in COOKIE_ECHOED state.
*
* Only handle the error type of stale COOKIE Error, the other errors will
* be ignored.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_cookie_echoed_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length.
* The parameter walking depends on this as well.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Process the error here */
/* FUTURE FIXME: When PR-SCTP related and other optional
* parms are emitted, this will have to change to handle multiple
* errors.
*/
sctp_walk_errors(err, chunk->chunk_hdr) {
if (SCTP_ERROR_STALE_COOKIE == err->cause)
return sctp_sf_do_5_2_6_stale(net, ep, asoc, type,
arg, commands);
}
/* It is possible to have malformed error causes, and that
* will cause us to end the walk early. However, since
* we are discarding the packet, there should be no adverse
* affects.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/*
* Handle a Stale COOKIE Error
*
* Section: 5.2.6 Handle Stale COOKIE Error
* If the association is in the COOKIE-ECHOED state, the endpoint may elect
* one of the following three alternatives.
* ...
* 3) Send a new INIT chunk to the endpoint, adding a Cookie
* Preservative parameter requesting an extension to the lifetime of
* the State Cookie. When calculating the time extension, an
* implementation SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no more
* than 1 second beyond the measured RTT, due to long State Cookie
* lifetimes making the endpoint more subject to a replay attack.
*
* Verification Tag: Not explicit, but safe to ignore.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_do_5_2_6_stale(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
time_t stale;
sctp_cookie_preserve_param_t bht;
sctp_errhdr_t *err;
struct sctp_chunk *reply;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
if (attempts > asoc->max_init_attempts) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_STALE_COOKIE));
return SCTP_DISPOSITION_DELETE_TCB;
}
err = (sctp_errhdr_t *)(chunk->skb->data);
/* When calculating the time extension, an implementation
* SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no
* more than 1 second beyond the measured RTT, due to long
* State Cookie lifetimes making the endpoint more subject to
* a replay attack.
* Measure of Staleness's unit is usec. (1/1000000 sec)
* Suggested Cookie Life-span Increment's unit is msec.
* (1/1000 sec)
* In general, if you use the suggested cookie life, the value
* found in the field of measure of staleness should be doubled
* to give ample time to retransmit the new cookie and thus
* yield a higher probability of success on the reattempt.
*/
stale = ntohl(*(__be32 *)((u8 *)err + sizeof(sctp_errhdr_t)));
stale = (stale * 2) / 1000;
bht.param_hdr.type = SCTP_PARAM_COOKIE_PRESERVATIVE;
bht.param_hdr.length = htons(sizeof(bht));
bht.lifespan_increment = htonl(stale);
/* Build that new INIT chunk. */
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
reply = sctp_make_init(asoc, bp, GFP_ATOMIC, sizeof(bht));
if (!reply)
goto nomem;
sctp_addto_chunk(reply, sizeof(bht), &bht);
/* Clear peer's init_tag cached in assoc as we are sending a new INIT */
sctp_add_cmd_sf(commands, SCTP_CMD_CLEAR_INIT_TAG, SCTP_NULL());
/* Stop pending T3-rtx and heartbeat timers */
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
/* Delete non-primary peer ip addresses since we are transitioning
* back to the COOKIE-WAIT state
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DEL_NON_PRIMARY, SCTP_NULL());
/* If we've sent any data bundled with COOKIE-ECHO we will need to
* resend
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T1_RETRAN,
SCTP_TRANSPORT(asoc->peer.primary_path));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_INC, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT.
*
* Section: 9.1
* After checking the Verification Tag, the receiving endpoint shall
* remove the association from its record, and shall report the
* termination to its upper layer.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* B) Rules for packet carrying ABORT:
*
* - The endpoint shall always fill in the Verification Tag field of the
* outbound packet with the destination endpoint's tag value if it
* is known.
*
* - If the ABORT is sent in response to an OOTB packet, the endpoint
* MUST follow the procedure described in Section 8.4.
*
* - The receiver MUST accept the packet if the Verification Tag
* matches either its own tag, OR the tag of its peer. Otherwise, the
* receiver MUST silently discard the packet and take no further
* action.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_9_1_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
static sctp_disposition_t __sctp_sf_do_9_1_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned int len;
__be16 error = SCTP_ERROR_NO_ERROR;
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr)) {
sctp_errhdr_t *err;
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
}
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNRESET));
/* ASSOC_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(error));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/*
* Process an ABORT. (COOKIE-WAIT state)
*
* See sctp_sf_do_9_1_abort() above.
*/
sctp_disposition_t sctp_sf_cookie_wait_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned int len;
__be16 error = SCTP_ERROR_NO_ERROR;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr))
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED, asoc,
chunk->transport);
}
/*
* Process an incoming ICMP as an ABORT. (COOKIE-WAIT state)
*/
sctp_disposition_t sctp_sf_cookie_wait_icmp_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return sctp_stop_t1_and_abort(net, commands, SCTP_ERROR_NO_ERROR,
ENOPROTOOPT, asoc,
(struct sctp_transport *)arg);
}
/*
* Process an ABORT. (COOKIE-ECHOED state)
*/
sctp_disposition_t sctp_sf_cookie_echoed_abort(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_abort(net, ep, asoc, type, arg, commands);
}
/*
* Stop T1 timer and abort association with "INIT failed".
*
* This is common code called by several sctp_sf_*_abort() functions above.
*/
static sctp_disposition_t sctp_stop_t1_and_abort(struct net *net,
sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport)
{
pr_debug("%s: ABORT received (INIT)\n", __func__);
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(sk_err));
/* CMD_INIT_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(error));
return SCTP_DISPOSITION_ABORT;
}
/*
* sctp_sf_do_9_2_shut
*
* Section: 9.2
* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
*
* - stop accepting new data from its SCTP user
*
* - verify, by checking the Cumulative TSN Ack field of the chunk,
* that all its outstanding DATA chunks have been received by the
* SHUTDOWN sender.
*
* Once an endpoint as reached the SHUTDOWN-RECEIVED state it MUST NOT
* send a SHUTDOWN in response to a ULP request. And should discard
* subsequent SHUTDOWN chunks.
*
* If there are still outstanding DATA chunks left, the SHUTDOWN
* receiver shall continue to follow normal data transmission
* procedures defined in Section 6 until all outstanding DATA chunks
* are acknowledged; however, the SHUTDOWN receiver MUST NOT accept
* new data from its SCTP user.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_9_2_shutdown(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
sctp_disposition_t disposition;
struct sctp_ulpevent *ev;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Convert the elaborate header. */
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_shutdownhdr_t));
chunk->subh.shutdown_hdr = sdh;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* API 5.3.1.5 SCTP_SHUTDOWN_EVENT
* When a peer sends a SHUTDOWN, SCTP delivers this notification to
* inform the application that it should cease sending data.
*/
ev = sctp_ulpevent_make_shutdown_event(asoc, 0, GFP_ATOMIC);
if (!ev) {
disposition = SCTP_DISPOSITION_NOMEM;
goto out;
}
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
* - stop accepting new data from its SCTP user
*
* [This is implicit in the new state.]
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_RECEIVED));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_shutdown_ack(net, ep, asoc, type,
arg, commands);
}
if (SCTP_DISPOSITION_NOMEM == disposition)
goto out;
/* - verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(chunk->subh.shutdown_hdr->cum_tsn_ack));
out:
return disposition;
}
/*
* sctp_sf_do_9_2_shut_ctsn
*
* Once an endpoint has reached the SHUTDOWN-RECEIVED state,
* it MUST NOT send a SHUTDOWN in response to a ULP request.
* The Cumulative TSN Ack of the received SHUTDOWN chunk
* MUST be processed.
*/
sctp_disposition_t sctp_sf_do_9_2_shut_ctsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(sdh->cum_tsn_ack));
return SCTP_DISPOSITION_CONSUME;
}
/* RFC 2960 9.2
* If an endpoint is in SHUTDOWN-ACK-SENT state and receives an INIT chunk
* (e.g., if the SHUTDOWN COMPLETE was lost) with source and destination
* transport addresses (either in the IP addresses or in the INIT chunk)
* that belong to this association, it should discard the INIT chunk and
* retransmit the SHUTDOWN ACK chunk.
*/
sctp_disposition_t sctp_sf_do_9_2_reshutack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* Make sure that the chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Since we are not going to really process this INIT, there
* is no point in verifying chunk boundries. Just generate
* the SHUTDOWN ACK.
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (NULL == reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-SHUTDOWN timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* sctp_sf_do_ecn_cwr
*
* Section: Appendix A: Explicit Congestion Notification
*
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecn_cwr(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_cwrhdr_t *cwr;
struct sctp_chunk *chunk = arg;
u32 lowest_tsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
cwr = (sctp_cwrhdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_cwrhdr_t));
lowest_tsn = ntohl(cwr->lowest_tsn);
/* Does this CWR ack the last sent congestion notification? */
if (TSN_lte(asoc->last_ecne_tsn, lowest_tsn)) {
/* Stop sending ECNE. */
sctp_add_cmd_sf(commands,
SCTP_CMD_ECN_CWR,
SCTP_U32(lowest_tsn));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_do_ecne
*
* Section: Appendix A: Explicit Congestion Notification
*
* ECN-Echo
*
* RFC 2481 details a specific bit for a receiver to send back in its
* TCP acknowledgements to notify the sender of the Congestion
* Experienced (CE) bit having arrived from the network. For SCTP this
* same indication is made by including the ECNE chunk. This chunk
* contains one data element, i.e. the lowest TSN associated with the IP
* datagram marked with the CE bit.....
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecne(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_ecnehdr_t *ecne;
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ecne = (sctp_ecnehdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_ecnehdr_t));
/* If this is a newer ECNE than the last CWR packet we sent out */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_ECNE,
SCTP_U32(ntohl(ecne->lowest_tsn)));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of each valid
* DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated within
* 200 ms of the arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to be more
* conservative than the algorithms detailed in this document allow.
* However, an SCTP transmitter MUST NOT be more aggressive than the
* following algorithms allow.
*
* A SCTP receiver MUST NOT generate more than one SACK for every
* incoming packet, other than to update the offered window as the
* receiving application consumes new data.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_data_6_2(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_arg_t force = SCTP_NOFORCE();
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case SCTP_IERROR_NO_ERROR:
break;
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_BAD_STREAM:
SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_noforce;
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_force;
case SCTP_IERROR_NO_DATA:
goto consume;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
if (chunk->chunk_hdr->flags & SCTP_DATA_SACK_IMM)
force = SCTP_FORCE();
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* If this is the last chunk in a packet, we need to count it
* toward sack generation. Note that we need to SACK every
* OTHER packet containing data chunks, EVEN IF WE DISCARD
* THEM. We elect to NOT generate SACK's if the chunk fails
* the verification tag test.
*
* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of
* each valid DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm
* specified in Section 4.2 of [RFC2581] SHOULD be followed.
* Specifically, an acknowledgement SHOULD be generated for at
* least every second packet (not every second DATA chunk)
* received, and SHOULD be generated within 200 ms of the
* arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to
* be more conservative than the algorithms detailed in this
* document allow. However, an SCTP transmitter MUST NOT be
* more aggressive than the following algorithms allow.
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_CONSUME;
discard_force:
/* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* When a packet arrives with duplicate DATA chunk(s) and with
* no new DATA chunk(s), the endpoint MUST immediately send a
* SACK with no delay. If a packet arrives with duplicate
* DATA chunk(s) bundled with new DATA chunks, the endpoint
* MAY immediately send a SACK. Normally receipt of duplicate
* DATA chunks will occur when the original SACK chunk was lost
* and the peer's RTO has expired. The duplicate TSN number(s)
* SHOULD be reported in the SACK as duplicate.
*/
/* In our case, we split the MAY SACK advice up whether or not
* the last chunk is a duplicate.'
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_DISCARD;
discard_noforce:
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_DISCARD;
consume:
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_eat_data_fast_4_4
*
* Section: 4 (4)
* (4) In SHUTDOWN-SENT state the endpoint MUST acknowledge any received
* DATA chunks without delay.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_data_fast_4_4(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case SCTP_IERROR_NO_ERROR:
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
case SCTP_IERROR_BAD_STREAM:
break;
case SCTP_IERROR_NO_DATA:
goto consume;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
/* Go a head and force a SACK, since we are shutting down. */
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
if (chunk->end_of_packet) {
/* We must delay the chunk creation since the cumulative
* TSN has not been updated yet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
}
consume:
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Processing a Received SACK
* D) Any time a SACK arrives, the endpoint performs the following:
*
* i) If Cumulative TSN Ack is less than the Cumulative TSN Ack Point,
* then drop the SACK. Since Cumulative TSN Ack is monotonically
* increasing, a SACK whose Cumulative TSN Ack is less than the
* Cumulative TSN Ack Point indicates an out-of-order SACK.
*
* ii) Set rwnd equal to the newly received a_rwnd minus the number
* of bytes still outstanding after processing the Cumulative TSN Ack
* and the Gap Ack Blocks.
*
* iii) If the SACK is missing a TSN that was previously
* acknowledged via a Gap Ack Block (e.g., the data receiver
* reneged on the data), then mark the corresponding DATA chunk
* as available for retransmit: Mark it as missing for fast
* retransmit as described in Section 7.2.4 and if no retransmit
* timer is running for the destination address to which the DATA
* chunk was originally transmitted, then T3-rtx is started for
* that destination address.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_sack_6_2(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_sackhdr_t *sackh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_sack_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Pull the SACK chunk from the data buffer */
sackh = sctp_sm_pull_sack(chunk);
/* Was this a bogus SACK? */
if (!sackh)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
chunk->subh.sack_hdr = sackh;
ctsn = ntohl(sackh->cum_tsn_ack);
/* i) If Cumulative TSN Ack is less than the Cumulative TSN
* Ack Point, then drop the SACK. Since Cumulative TSN
* Ack is monotonically increasing, a SACK whose
* Cumulative TSN Ack is less than the Cumulative TSN Ack
* Point indicates an out-of-order SACK.
*/
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* Return this SACK for further processing. */
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_SACK, SCTP_CHUNK(chunk));
/* Note: We do the rest of the work on the PROCESS_SACK
* sideeffect.
*/
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate an ABORT in response to a packet.
*
* Section: 8.4 Handle "Out of the blue" Packets, sctpimpguide 2.41
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*
* Verification Tag:
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_tabort_8_4_8(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT. The T bit will be set if the asoc
* is NULL.
*/
abort = sctp_make_abort(asoc, chunk, 0);
if (!abort) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
}
return SCTP_DISPOSITION_NOMEM;
}
/*
* Received an ERROR chunk from peer. Generate SCTP_REMOTE_ERROR
* event as ULP notification for each cause included in the chunk.
*
* API 5.3.1.3 - SCTP_REMOTE_ERROR
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_operr_notify(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err, commands);
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_OPERR,
SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an inbound SHUTDOWN ACK.
*
* From Section 9.2:
* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its
* peer, and remove all record of the association.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_final(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* 10.2 H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* ...send a SHUTDOWN COMPLETE chunk to its peer, */
reply = sctp_make_shutdown_complete(asoc, chunk);
if (!reply)
goto nomem_chunk;
/* Do all the commands now (after allocation), so that we
* have consistent state if memory allocation failes
*/
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer,
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
/* ...and remove all record of the association. */
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_chunk:
sctp_ulpevent_free(ev);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*/
sctp_disposition_t sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/*
* Handle an "Out of the blue" SHUTDOWN ACK.
*
* Section: 8.4 5, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* Inputs
* (endpoint, asoc, type, arg, commands)
*
* Outputs
* (sctp_disposition_t)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *shut;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an SHUTDOWN_COMPLETE.
* The T bit will be set if the asoc is NULL.
*/
shut = sctp_make_shutdown_complete(asoc, chunk);
if (!shut) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(shut))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
shut->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, shut);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
/* If the chunk length is invalid, we don't want to process
* the reset of the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* We need to discard the rest of the packet to prevent
* potential bomming attacks from additional bundled chunks.
* This is documented in SCTP Threats ID.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle SHUTDOWN ACK in COOKIE_ECHOED or COOKIE_WAIT state.
*
* Verification Tag: 8.5.1 E) Rules for packet carrying a SHUTDOWN ACK
* If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state the
* procedures in section 8.4 SHOULD be followed, in other words it
* should be treated as an Out Of The Blue packet.
* [This means that we do NOT check the Verification Tag on these
* chunks. --piggy ]
*
*/
sctp_disposition_t sctp_sf_do_8_5_1_E_sa(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Although we do have an association in this case, it corresponds
* to a restarted association. So the packet is treated as an OOTB
* packet and the state function that handles OOTB SHUTDOWN_ACK is
* called with a NULL association.
*/
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_shut_8_4_5(net, ep, NULL, type, arg, commands);
}
/* ADDIP Section 4.2 Upon reception of an ASCONF Chunk. */
sctp_disposition_t sctp_sf_do_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *asconf_ack = NULL;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *hdr;
union sctp_addr_param *addr_param;
__u32 serial;
int length;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* ADD-IP: Section 4.1.1
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!net->sctp.addip_noauth && !chunk->auth)
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the ASCONF ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
hdr = (sctp_addiphdr_t *)chunk->skb->data;
serial = ntohl(hdr->serial);
addr_param = (union sctp_addr_param *)hdr->params;
length = ntohs(addr_param->p.length);
if (length < sizeof(sctp_paramhdr_t))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)addr_param, commands);
/* Verify the ASCONF chunk before processing it. */
if (!sctp_verify_asconf(asoc,
(sctp_paramhdr_t *)((void *)addr_param + length),
(void *)chunk->chunk_end,
&err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
/* ADDIP 5.2 E1) Compare the value of the serial number to the value
* the endpoint stored in a new association variable
* 'Peer-Serial-Number'.
*/
if (serial == asoc->peer.addip_serial + 1) {
/* If this is the first instance of ASCONF in the packet,
* we can clean our old ASCONF-ACKs.
*/
if (!chunk->has_asconf)
sctp_assoc_clean_asconf_ack_cache(asoc);
/* ADDIP 5.2 E4) When the Sequence Number matches the next one
* expected, process the ASCONF as described below and after
* processing the ASCONF Chunk, append an ASCONF-ACK Chunk to
* the response packet and cache a copy of it (in the event it
* later needs to be retransmitted).
*
* Essentially, do V1-V5.
*/
asconf_ack = sctp_process_asconf((struct sctp_association *)
asoc, chunk);
if (!asconf_ack)
return SCTP_DISPOSITION_NOMEM;
} else if (serial < asoc->peer.addip_serial + 1) {
/* ADDIP 5.2 E2)
* If the value found in the Sequence Number is less than the
* ('Peer- Sequence-Number' + 1), simply skip to the next
* ASCONF, and include in the outbound response packet
* any previously cached ASCONF-ACK response that was
* sent and saved that matches the Sequence Number of the
* ASCONF. Note: It is possible that no cached ASCONF-ACK
* Chunk exists. This will occur when an older ASCONF
* arrives out of order. In such a case, the receiver
* should skip the ASCONF Chunk and not include ASCONF-ACK
* Chunk for that chunk.
*/
asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial);
if (!asconf_ack)
return SCTP_DISPOSITION_DISCARD;
/* Reset the transport so that we select the correct one
* this time around. This is to make sure that we don't
* accidentally use a stale transport that's been removed.
*/
asconf_ack->transport = NULL;
} else {
/* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since
* it must be either a stale packet or from an attacker.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* ADDIP 5.2 E6) The destination address of the SCTP packet
* containing the ASCONF-ACK Chunks MUST be the source address of
* the SCTP packet that held the ASCONF Chunks.
*
* To do this properly, we'll set the destination address of the chunk
* and at the transmit time, will try look up the transport to use.
* Since ASCONFs may be bundled, the correct transport may not be
* created until we process the entire packet, thus this workaround.
*/
asconf_ack->dest = chunk->source;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack));
if (asoc->new_transport) {
sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands);
((struct sctp_association *)asoc)->new_transport = NULL;
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.3 General rules for address manipulation
* When building TLV parameters for the ASCONF Chunk that will add or
* delete IP addresses the D0 to D13 rules should be applied:
*/
sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *asconf_ack = arg;
struct sctp_chunk *last_asconf = asoc->addip_last_asconf;
struct sctp_chunk *abort;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *addip_hdr;
__u32 sent_serial, rcvd_serial;
if (!sctp_vtag_verify(asconf_ack, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* ADD-IP, Section 4.1.2:
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!net->sctp.addip_noauth && !asconf_ack->auth)
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data;
rcvd_serial = ntohl(addip_hdr->serial);
/* Verify the ASCONF-ACK chunk before processing it. */
if (!sctp_verify_asconf(asoc,
(sctp_paramhdr_t *)addip_hdr->params,
(void *)asconf_ack->chunk_end,
&err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
if (last_asconf) {
addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr;
sent_serial = ntohl(addip_hdr->serial);
} else {
sent_serial = asoc->addip_serial - 1;
}
/* D0) If an endpoint receives an ASCONF-ACK that is greater than or
* equal to the next serial number to be used but no ASCONF chunk is
* outstanding the endpoint MUST ABORT the association. Note that a
* sequence number is greater than if it is no more than 2^^31-1
* larger than the current sequence number (using serial arithmetic).
*/
if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&
!(asoc->addip_last_asconf)) {
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
if (!sctp_process_asconf_ack((struct sctp_association *)asoc,
asconf_ack)) {
/* Successfully processed ASCONF_ACK. We can
* release the next asconf if we have one.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF,
SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* PR-SCTP Section 3.6 Receiver Side Implementation of PR-SCTP
*
* When a FORWARD TSN chunk arrives, the data receiver MUST first update
* its cumulative TSN point to the value carried in the FORWARD TSN
* chunk, and then MUST further advance its cumulative TSN point locally
* if possible.
* After the above processing, the data receiver MUST stop reporting any
* missing TSNs earlier than or equal to the new cumulative TSN point.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_fwd_tsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto discard_noforce;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto discard_noforce;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Count this as receiving DATA. */
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* FIXME: For now send a SACK, but DATA processing may
* send another.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE());
return SCTP_DISPOSITION_CONSUME;
discard_noforce:
return SCTP_DISPOSITION_DISCARD;
}
sctp_disposition_t sctp_sf_eat_fwd_tsn_fast(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto gen_shutdown;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto gen_shutdown;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Go a head and force a SACK, since we are shutting down. */
gen_shutdown:
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* SCTP-AUTH Section 6.3 Receiving authenticated chukns
*
* The receiver MUST use the HMAC algorithm indicated in the HMAC
* Identifier field. If this algorithm was not specified by the
* receiver in the HMAC-ALGO parameter in the INIT or INIT-ACK chunk
* during association setup, the AUTH chunk and all chunks after it MUST
* be discarded and an ERROR chunk SHOULD be sent with the error cause
* defined in Section 4.1.
*
* If an endpoint with no shared key receives a Shared Key Identifier
* other than 0, it MUST silently discard all authenticated chunks. If
* the endpoint has at least one endpoint pair shared key for the peer,
* it MUST use the key specified by the Shared Key Identifier if a
* key has been configured for that Shared Key Identifier. If no
* endpoint pair shared key has been configured for that Shared Key
* Identifier, all authenticated chunks MUST be silently discarded.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
static sctp_ierror_t sctp_sf_authenticate(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk)
{
struct sctp_authhdr *auth_hdr;
struct sctp_hmac *hmac;
unsigned int sig_len;
__u16 key_id;
__u8 *save_digest;
__u8 *digest;
/* Pull in the auth header, so we can do some more verification */
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
chunk->subh.auth_hdr = auth_hdr;
skb_pull(chunk->skb, sizeof(struct sctp_authhdr));
/* Make sure that we support the HMAC algorithm from the auth
* chunk.
*/
if (!sctp_auth_asoc_verify_hmac_id(asoc, auth_hdr->hmac_id))
return SCTP_IERROR_AUTH_BAD_HMAC;
/* Make sure that the provided shared key identifier has been
* configured
*/
key_id = ntohs(auth_hdr->shkey_id);
if (key_id != asoc->active_key_id && !sctp_auth_get_shkey(asoc, key_id))
return SCTP_IERROR_AUTH_BAD_KEYID;
/* Make sure that the length of the signature matches what
* we expect.
*/
sig_len = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_auth_chunk_t);
hmac = sctp_auth_get_hmac(ntohs(auth_hdr->hmac_id));
if (sig_len != hmac->hmac_len)
return SCTP_IERROR_PROTO_VIOLATION;
/* Now that we've done validation checks, we can compute and
* verify the hmac. The steps involved are:
* 1. Save the digest from the chunk.
* 2. Zero out the digest in the chunk.
* 3. Compute the new digest
* 4. Compare saved and new digests.
*/
digest = auth_hdr->hmac;
skb_pull(chunk->skb, sig_len);
save_digest = kmemdup(digest, sig_len, GFP_ATOMIC);
if (!save_digest)
goto nomem;
memset(digest, 0, sig_len);
sctp_auth_calculate_hmac(asoc, chunk->skb,
(struct sctp_auth_chunk *)chunk->chunk_hdr,
GFP_ATOMIC);
/* Discard the packet if the digests do not match */
if (memcmp(save_digest, digest, sig_len)) {
kfree(save_digest);
return SCTP_IERROR_BAD_SIG;
}
kfree(save_digest);
chunk->auth = 1;
return SCTP_IERROR_NO_ERROR;
nomem:
return SCTP_IERROR_NOMEM;
}
sctp_disposition_t sctp_sf_eat_auth(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_authhdr *auth_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *err_chunk;
sctp_ierror_t error;
/* Make sure that the peer has AUTH capable */
if (!asoc->peer.auth_capable)
return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands);
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the AUTH chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_auth_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
error = sctp_sf_authenticate(net, ep, asoc, type, chunk);
switch (error) {
case SCTP_IERROR_AUTH_BAD_HMAC:
/* Generate the ERROR chunk and discard the rest
* of the packet
*/
err_chunk = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_UNSUP_HMAC,
&auth_hdr->hmac_id,
sizeof(__u16), 0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Fall Through */
case SCTP_IERROR_AUTH_BAD_KEYID:
case SCTP_IERROR_BAD_SIG:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
case SCTP_IERROR_NOMEM:
return SCTP_DISPOSITION_NOMEM;
default: /* Prevent gcc warnings */
break;
}
if (asoc->active_key_id != ntohs(auth_hdr->shkey_id)) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, ntohs(auth_hdr->shkey_id),
SCTP_AUTH_NEWKEY, GFP_ATOMIC);
if (!ev)
return -ENOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an unknown chunk.
*
* Section: 3.2. Also, 2.1 in the implementor's guide.
*
* Chunk Types are encoded such that the highest-order two bits specify
* the action that must be taken if the processing endpoint does not
* recognize the Chunk Type.
*
* 00 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it.
*
* 01 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it, and report the unrecognized
* chunk in an 'Unrecognized Chunk Type'.
*
* 10 - Skip this chunk and continue processing.
*
* 11 - Skip this chunk and continue processing, but report in an ERROR
* Chunk using the 'Unrecognized Chunk Type' cause of error.
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_unk_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *unk_chunk = arg;
struct sctp_chunk *err_chunk;
sctp_chunkhdr_t *hdr;
pr_debug("%s: processing unknown chunk id:%d\n", __func__, type.chunk);
if (!sctp_vtag_verify(unk_chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(unk_chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
switch (type.chunk & SCTP_CID_ACTION_MASK) {
case SCTP_CID_ACTION_DISCARD:
/* Discard the packet. */
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
break;
case SCTP_CID_ACTION_DISCARD_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
WORD_ROUND(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Discard the packet. */
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
break;
case SCTP_CID_ACTION_SKIP:
/* Skip the chunk. */
return SCTP_DISPOSITION_DISCARD;
break;
case SCTP_CID_ACTION_SKIP_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
WORD_ROUND(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Skip the chunk. */
return SCTP_DISPOSITION_CONSUME;
break;
default:
break;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the chunk.
*
* Section: 0.2, 5.2.3, 5.2.5, 5.2.6, 6.0, 8.4.6, 8.5.1c, 9.2
* [Too numerous to mention...]
* Verification Tag: No verification needed.
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_discard_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
pr_debug("%s: chunk:%d is discarded\n", __func__, type.chunk);
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the whole packet.
*
* Section: 8.4 2)
*
* 2) If the OOTB packet contains an ABORT chunk, the receiver MUST
* silently discard the OOTB packet and take no further action.
*
* Verification Tag: No verification necessary
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_pdiscard(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_DISCARDS);
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
/*
* The other end is violating protocol.
*
* Section: Not specified
* Verification Tag: Not specified
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* We simply tag the chunk as a violation. The state machine will log
* the violation and continue.
*/
sctp_disposition_t sctp_sf_violation(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
return SCTP_DISPOSITION_VIOLATION;
}
/*
* Common function to handle a protocol violation.
*/
static sctp_disposition_t sctp_sf_abort_violation(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort = NULL;
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_abort_violation(asoc, chunk, payload, paylen);
if (!abort)
goto nomem;
if (asoc) {
/* Treat INIT-ACK as a special case during COOKIE-WAIT. */
if (chunk->chunk_hdr->type == SCTP_CID_INIT_ACK &&
!asoc->peer.i.init_tag) {
sctp_initack_chunk_t *initack;
initack = (sctp_initack_chunk_t *)chunk->chunk_hdr;
if (!sctp_chunk_length_valid(chunk,
sizeof(sctp_initack_chunk_t)))
abort->chunk_hdr->flags |= SCTP_CHUNK_FLAG_T;
else {
unsigned int inittag;
inittag = ntohl(initack->init_hdr.init_tag);
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_INITTAG,
SCTP_U32(inittag));
}
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
if (asoc->state <= SCTP_STATE_COOKIE_ECHOED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
}
} else {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
goto nomem_pkt;
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
}
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem_pkt:
sctp_chunk_free(abort);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a protocol violation when the chunk length is invalid.
* "Invalid" length is identified as smaller than the minimal length a
* given chunk can be. For example, a SACK chunk has invalid length
* if its length is set to be smaller than the size of sctp_sack_chunk_t.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*
* Section: Not specified
* Verification Tag: Nothing to do
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (reply_msg, msg_up, counters)
*
* Generate an ABORT chunk and terminate the association.
*/
static sctp_disposition_t sctp_sf_violation_chunklen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The following chunk had invalid length:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/*
* Handle a protocol violation when the parameter length is invalid.
* If the length is smaller than the minimum length of a given parameter,
* or accumulated length in multi parameters exceeds the end of the chunk,
* the length is considered as invalid.
*/
static sctp_disposition_t sctp_sf_violation_paramlen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_paramhdr *param = ext;
struct sctp_chunk *abort = NULL;
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_violation_paramlen(asoc, chunk, param);
if (!abort)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle a protocol violation when the peer trying to advance the
* cumulative tsn ack to a point beyond the max tsn currently sent.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*/
static sctp_disposition_t sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The cumulative tsn ack beyond the max tsn currently sent:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/* Handle protocol violation of an invalid chunk bundling. For example,
* when we have an association and we receive bundled INIT-ACK, or
* SHUDOWN-COMPLETE, our peer is clearly violationg the "MUST NOT bundle"
* statement from the specs. Additionally, there might be an attacker
* on the path and we may not want to continue this communication.
*/
static sctp_disposition_t sctp_sf_violation_chunk(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The following chunk violates protocol:";
if (!asoc)
return sctp_sf_violation(net, ep, asoc, type, arg, commands);
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/***************************************************************************
* These are the state functions for handling primitive (Section 10) events.
***************************************************************************/
/*
* sctp_sf_do_prm_asoc
*
* Section: 10.1 ULP-to-SCTP
* B) Associate
*
* Format: ASSOCIATE(local SCTP instance name, destination transport addr,
* outbound stream count)
* -> association id [,destination transport addr list] [,outbound stream
* count]
*
* This primitive allows the upper layer to initiate an association to a
* specific peer endpoint.
*
* The peer endpoint shall be specified by one of the transport addresses
* which defines the endpoint (see Section 1.4). If the local SCTP
* instance has not been initialized, the ASSOCIATE is considered an
* error.
* [This is not relevant for the kernel implementation since we do all
* initialization at boot time. It we hadn't initialized we wouldn't
* get anywhere near this code.]
*
* An association id, which is a local handle to the SCTP association,
* will be returned on successful establishment of the association. If
* SCTP is not able to open an SCTP association with the peer endpoint,
* an error is returned.
* [In the kernel implementation, the struct sctp_association needs to
* be created BEFORE causing this primitive to run.]
*
* Other association parameters may be returned, including the
* complete destination transport addresses of the peer as well as the
* outbound stream count of the local endpoint. One of the transport
* address from the returned destination addresses will be selected by
* the local endpoint as default primary path for sending SCTP packets
* to this peer. The returned "destination transport addr list" can
* be used by the ULP to change the default primary path or to force
* sending a packet to a specific transport address. [All of this
* stuff happens when the INIT ACK arrives. This is a NON-BLOCKING
* function.]
*
* Mandatory attributes:
*
* o local SCTP instance name - obtained from the INITIALIZE operation.
* [This is the argument asoc.]
* o destination transport addr - specified as one of the transport
* addresses of the peer endpoint with which the association is to be
* established.
* [This is asoc->peer.active_path.]
* o outbound stream count - the number of outbound streams the ULP
* would like to open towards this peer endpoint.
* [BUG: This is not currently implemented.]
* Optional attributes:
*
* None.
*
* The return value is a disposition.
*/
sctp_disposition_t sctp_sf_do_prm_asoc(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl;
struct sctp_association *my_asoc;
/* The comment below says that we enter COOKIE-WAIT AFTER
* sending the INIT, but that doesn't actually work in our
* implementation...
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* A) "A" first sends an INIT chunk to "Z". In the INIT, "A"
* must provide its Verification Tag (Tag_A) in the Initiate
* Tag field. Tag_A SHOULD be a random number in the range of
* 1 to 4294967295 (see 5.3.1 for Tag value selection). ...
*/
repl = sctp_make_init(asoc, &asoc->base.bind_addr, GFP_ATOMIC, 0);
if (!repl)
goto nomem;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
my_asoc = (struct sctp_association *)asoc;
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(my_asoc));
/* After sending the INIT, "A" starts the T1-init timer and
* enters the COOKIE-WAIT state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the SEND primitive.
*
* Section: 10.1 ULP-to-SCTP
* E) Send
*
* Format: SEND(association id, buffer address, byte count [,context]
* [,stream id] [,life time] [,destination transport address]
* [,unorder flag] [,no-bundle flag] [,payload protocol-id] )
* -> result
*
* This is the main method to send user data via SCTP.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o buffer address - the location where the user message to be
* transmitted is stored;
*
* o byte count - The size of the user data in number of bytes;
*
* Optional attributes:
*
* o context - an optional 32 bit integer that will be carried in the
* sending failure notification to the ULP if the transportation of
* this User Message fails.
*
* o stream id - to indicate which stream to send the data on. If not
* specified, stream 0 will be used.
*
* o life time - specifies the life time of the user data. The user data
* will not be sent by SCTP after the life time expires. This
* parameter can be used to avoid efforts to transmit stale
* user messages. SCTP notifies the ULP if the data cannot be
* initiated to transport (i.e. sent to the destination via SCTP's
* send primitive) within the life time variable. However, the
* user data will be transmitted if SCTP has attempted to transmit a
* chunk before the life time expired.
*
* o destination transport address - specified as one of the destination
* transport addresses of the peer endpoint to which this packet
* should be sent. Whenever possible, SCTP should use this destination
* transport address for sending the packets, instead of the current
* primary path.
*
* o unorder flag - this flag, if present, indicates that the user
* would like the data delivered in an unordered fashion to the peer
* (i.e., the U flag is set to 1 on all DATA chunks carrying this
* message).
*
* o no-bundle flag - instructs SCTP not to bundle this user data with
* other outbound DATA chunks. SCTP MAY still bundle even when
* this flag is present, when faced with network congestion.
*
* o payload protocol-id - A 32 bit unsigned integer that is to be
* passed to the peer indicating the type of payload protocol data
* being transmitted. This value is passed as opaque data by SCTP.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_prm_send(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_datamsg *msg = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_MSG, SCTP_DATAMSG(msg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process the SHUTDOWN primitive.
*
* Section: 10.1:
* C) Shutdown
*
* Format: SHUTDOWN(association id)
* -> result
*
* Gracefully closes an association. Any locally queued user data
* will be delivered to the peer. The association will be terminated only
* after the peer acknowledges all the SCTP packets sent. A success code
* will be returned on successful termination of the association. If
* attempting to terminate the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*
* Process the ABORT primitive.
*
* Section: 10.1:
* C) Abort
*
* Format: Abort(association id [, cause code])
* -> result
*
* Ungracefully closes an association. Any locally queued user data
* will be discarded and an ABORT chunk is sent to the peer. A success code
* will be returned on successful abortion of the association. If
* attempting to abort the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* o cause code - reason of the abort to be passed to the peer
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_1_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* From 9.1 Abort of an Association
* Upon receipt of the ABORT primitive from its upper
* layer, the endpoint enters CLOSED state and
* discard all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
struct sctp_chunk *abort = arg;
sctp_disposition_t retval;
retval = SCTP_DISPOSITION_CONSUME;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return retval;
}
/* We tried an illegal operation on an association which is closed. */
sctp_disposition_t sctp_sf_error_closed(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR, SCTP_ERROR(-EINVAL));
return SCTP_DISPOSITION_CONSUME;
}
/* We tried an illegal operation on an association which is shutting
* down.
*/
sctp_disposition_t sctp_sf_error_shutdown(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR,
SCTP_ERROR(-ESHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_cookie_wait_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_wait_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* sctp_cookie_echoed_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_echoed_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_shutdown(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_wait_prm_abort
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_wait_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *abort = arg;
sctp_disposition_t retval;
/* Stop T1-init timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
retval = SCTP_DISPOSITION_CONSUME;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
return retval;
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Section: 4 Note: 3
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_echoed_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_pending_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-PENDING state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_pending_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_sent_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-SENT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_sent_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_ack_sent_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process the REQUESTHEARTBEAT primitive
*
* 10.1 ULP-to-SCTP
* J) Request Heartbeat
*
* Format: REQUESTHEARTBEAT(association id, destination transport address)
*
* -> result
*
* Instructs the local endpoint to perform a HeartBeat on the specified
* destination transport address of the given association. The returned
* result should indicate whether the transmission of the HEARTBEAT
* chunk to the destination address is successful.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o destination transport address - the transport address of the
* association on which a heartbeat should be issued.
*/
sctp_disposition_t sctp_sf_do_prm_requestheartbeat(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type,
(struct sctp_transport *)arg, commands))
return SCTP_DISPOSITION_NOMEM;
/*
* RFC 2960 (bis), section 8.3
*
* D) Request an on-demand HEARTBEAT on a specific destination
* transport address of a given association.
*
* The endpoint should increment the respective error counter of
* the destination transport address each time a HEARTBEAT is sent
* to that address and not acknowledged within one RTO.
*
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(arg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do A1 to A9
*/
sctp_disposition_t sctp_sf_do_prm_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Ignore the primitive event
*
* The return value is the disposition of the primitive.
*/
sctp_disposition_t sctp_sf_ignore_primitive(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: primitive type:%d is ignored\n", __func__,
type.primitive);
return SCTP_DISPOSITION_DISCARD;
}
/***************************************************************************
* These are the state functions for the OTHER events.
***************************************************************************/
/*
* When the SCTP stack has no more user data to send or retransmit, this
* notification is given to the user. Also, at the time when a user app
* subscribes to this event, if there is no data to be sent or
* retransmit, the stack will immediately send up this notification.
*/
sctp_disposition_t sctp_sf_do_no_pending_tsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_ulpevent *event;
event = sctp_ulpevent_make_sender_dry_event(asoc, GFP_ATOMIC);
if (!event)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(event));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Start the shutdown negotiation.
*
* From Section 9.2:
* Once all its outstanding data has been acknowledged, the endpoint
* shall send a SHUTDOWN chunk to its peer including in the Cumulative
* TSN Ack field the last sequential TSN it has received from the peer.
* It shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
* state. If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_start_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply;
/* Once all its outstanding data has been acknowledged, the
* endpoint shall send a SHUTDOWN chunk to its peer including
* in the Cumulative TSN Ack field the last sequential TSN it
* has received from the peer.
*/
reply = sctp_make_shutdown(asoc, NULL);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN chunk and the timeout for the
* T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* It shall then start the T2-shutdown timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* RFC 4960 Section 9.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* and enter the SHUTDOWN-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Generate a SHUTDOWN ACK now that everything is SACK'd.
*
* From Section 9.2:
*
* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK and start a T2-shutdown timer of its own,
* entering the SHUTDOWN-ACK-SENT state. If the timer expires, the
* endpoint must re-send the SHUTDOWN ACK.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_shutdown_ack(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* There are 2 ways of getting here:
* 1) called in response to a SHUTDOWN chunk
* 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued.
*
* For the case (2), the arg parameter is set to NULL. We need
* to check that we have a chunk before accessing it's fields.
*/
if (chunk) {
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
}
/* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK ...
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and start/restart a T2-shutdown timer of its own, */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* Enter the SHUTDOWN-ACK-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Ignore the event defined as other
*
* The return value is the disposition of the event.
*/
sctp_disposition_t sctp_sf_ignore_other(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: the event other type:%d is ignored\n",
__func__, type.other);
return SCTP_DISPOSITION_DISCARD;
}
/************************************************************
* These are the state functions for handling timeout events.
************************************************************/
/*
* RTX Timeout
*
* Section: 6.3.3 Handle T3-rtx Expiration
*
* Whenever the retransmission timer T3-rtx expires for a destination
* address, do the following:
* [See below]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_6_3_3_rtx(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = arg;
SCTP_INC_STATS(net, SCTP_MIB_T3_RTX_EXPIREDS);
if (asoc->overall_error_count >= asoc->max_retrans) {
if (asoc->state == SCTP_STATE_SHUTDOWN_PENDING) {
/*
* We are here likely because the receiver had its rwnd
* closed for a while and we have not been able to
* transmit the locally queued data within the maximum
* retransmission attempts limit. Start the T5
* shutdown guard timer to give the receiver one last
* chance and some additional time to recover before
* aborting.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START_ONCE,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
}
/* E1) For the destination address for which the timer
* expires, adjust its ssthresh with rules defined in Section
* 7.2.3 and set the cwnd <- MTU.
*/
/* E2) For the destination address for which the timer
* expires, set RTO <- RTO * 2 ("back off the timer"). The
* maximum value discussed in rule C7 above (RTO.max) may be
* used to provide an upper bound to this doubling operation.
*/
/* E3) Determine how many of the earliest (i.e., lowest TSN)
* outstanding DATA chunks for the address for which the
* T3-rtx has expired will fit into a single packet, subject
* to the MTU constraint for the path corresponding to the
* destination transport address to which the retransmission
* is being sent (this may be different from the address for
* which the timer expires [see Section 6.4]). Call this
* value K. Bundle and retransmit those K DATA chunks in a
* single packet to the destination endpoint.
*
* Note: Any DATA chunks that were sent to the address for
* which the T3-rtx timer expired but did not fit in one MTU
* (rule E3 above), should be marked for retransmission and
* sent as soon as cwnd allows (normally when a SACK arrives).
*/
/* Do some failure management (Section 8.2). */
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
/* NB: Rules E4 and F1 are implicit in R1. */
sctp_add_cmd_sf(commands, SCTP_CMD_RETRAN, SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate delayed SACK on timeout
*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated
* within 200 ms of the arrival of any unacknowledged DATA chunk. In
* some situations it may be beneficial for an SCTP transmitter to be
* more conservative than the algorithms detailed in this document
* allow. However, an SCTP transmitter MUST NOT be more aggressive than
* the following algorithms allow.
*/
sctp_disposition_t sctp_sf_do_6_2_sack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(net, SCTP_MIB_DELAY_SACK_EXPIREDS);
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_init_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 2) If the T1-init timer expires, the endpoint MUST retransmit INIT
* and re-start the T1-init timer without changing state. This MUST
* be repeated up to 'Max.Init.Retransmits' times. After that, the
* endpoint MUST abort the initialization process and report the
* error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t sctp_sf_t1_init_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
pr_debug("%s: timer T1 expired (INIT)\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T1_INIT_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
repl = sctp_make_init(asoc, bp, GFP_ATOMIC, 0);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
pr_debug("%s: giving up on INIT, attempts:%d "
"max_init_attempts:%d\n", __func__, attempts,
asoc->max_init_attempts);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_cookie_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 3) If the T1-cookie timer expires, the endpoint MUST retransmit
* COOKIE ECHO and re-start the T1-cookie timer without changing
* state. This MUST be repeated up to 'Max.Init.Retransmits' times.
* After that, the endpoint MUST abort the initialization process and
* report the error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t sctp_sf_t1_cookie_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
int attempts = asoc->init_err_counter + 1;
pr_debug("%s: timer T1 expired (COOKIE-ECHO)\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T1_COOKIE_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
repl = sctp_make_cookie_echo(asoc, NULL);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_COOKIEECHO_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/* RFC2960 9.2 If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* An endpoint should limit the number of retransmissions of the
* SHUTDOWN chunk to the protocol parameter 'Association.Max.Retrans'.
* If this threshold is exceeded the endpoint should destroy the TCB and
* MUST report the peer endpoint unreachable to the upper layer (and
* thus the association enters the CLOSED state). The reception of any
* packet from its peer (i.e. as the peer sends all of its queued DATA
* chunks) should clear the endpoint's retransmission count and restart
* the T2-Shutdown timer, giving its peer ample opportunity to transmit
* all of its queued DATA chunks that have not yet been sent.
*/
sctp_disposition_t sctp_sf_t2_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T2 expired\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T2_SHUTDOWN_EXPIREDS);
((struct sctp_association *)asoc)->shutdown_retries++;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* Note: CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
switch (asoc->state) {
case SCTP_STATE_SHUTDOWN_SENT:
reply = sctp_make_shutdown(asoc, NULL);
break;
case SCTP_STATE_SHUTDOWN_ACK_SENT:
reply = sctp_make_shutdown_ack(asoc, NULL);
break;
default:
BUG();
break;
}
if (!reply)
goto nomem;
/* Do some failure management (Section 8.2).
* If we remove the transport an SHUTDOWN was last sent to, don't
* do failure management.
*/
if (asoc->shutdown_last_sent_to)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(asoc->shutdown_last_sent_to));
/* Set the transport for the SHUTDOWN/ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* Restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* ADDIP Section 4.1 ASCONF CHunk Procedures
* If the T4 RTO timer expires the endpoint should do B1 to B5
*/
sctp_disposition_t sctp_sf_t4_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = asoc->addip_last_asconf;
struct sctp_transport *transport = chunk->transport;
SCTP_INC_STATS(net, SCTP_MIB_T4_RTO_EXPIREDS);
/* ADDIP 4.1 B1) Increment the error counters and perform path failure
* detection on the appropriate destination address as defined in
* RFC2960 [5] section 8.1 and 8.2.
*/
if (transport)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(transport));
/* Reconfig T4 timer and transport. */
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
/* ADDIP 4.1 B2) Increment the association error counters and perform
* endpoint failure detection on the association as defined in
* RFC2960 [5] section 8.1 and 8.2.
* association error counter is incremented in SCTP_CMD_STRIKE.
*/
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/* ADDIP 4.1 B3) Back-off the destination address RTO value to which
* the ASCONF chunk was sent by doubling the RTO timer value.
* This is done in SCTP_CMD_STRIKE.
*/
/* ADDIP 4.1 B4) Re-transmit the ASCONF Chunk last sent and if possible
* choose an alternate destination address (please refer to RFC2960
* [5] section 6.4.1). An endpoint MUST NOT add new parameters to this
* chunk, it MUST be the same (including its serial number) as the last
* ASCONF sent.
*/
sctp_chunk_hold(asoc->addip_last_asconf);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(asoc->addip_last_asconf));
/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different
* destination is selected, then the RTO used will be that of the new
* destination address.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
return SCTP_DISPOSITION_CONSUME;
}
/* sctpimpguide-05 Section 2.12.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
* At the expiration of this timer the sender SHOULD abort the association
* by sending an ABORT chunk.
*/
sctp_disposition_t sctp_sf_t5_timer_expire(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T5 expired\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T5_SHUTDOWN_GUARD_EXPIREDS);
reply = sctp_make_abort(asoc, NULL, 0);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle expiration of AUTOCLOSE timer. When the autoclose timer expires,
* the association is automatically closed by starting the shutdown process.
* The work that needs to be done is same as when SHUTDOWN is initiated by
* the user. So this routine looks same as sctp_sf_do_9_2_prm_shutdown().
*/
sctp_disposition_t sctp_sf_autoclose_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
SCTP_INC_STATS(net, SCTP_MIB_AUTOCLOSE_EXPIREDS);
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*****************************************************************************
* These are sa state functions which could apply to all types of events.
****************************************************************************/
/*
* This table entry is not implemented.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_not_impl(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return SCTP_DISPOSITION_NOT_IMPL;
}
/*
* This table entry represents a bug.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_bug(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return SCTP_DISPOSITION_BUG;
}
/*
* This table entry represents the firing of a timer in the wrong state.
* Since timer deletion cannot be guaranteed a timer 'may' end up firing
* when the association is in the wrong state. This event should
* be ignored, so as to prevent any rearming of the timer.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_timer_ignore(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: timer %d ignored\n", __func__, type.chunk);
return SCTP_DISPOSITION_CONSUME;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Pull the SACK chunk based on the SACK header. */
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk)
{
struct sctp_sackhdr *sack;
unsigned int len;
__u16 num_blocks;
__u16 num_dup_tsns;
/* Protect ourselves from reading too far into
* the skb from a bogus sender.
*/
sack = (struct sctp_sackhdr *) chunk->skb->data;
num_blocks = ntohs(sack->num_gap_ack_blocks);
num_dup_tsns = ntohs(sack->num_dup_tsns);
len = sizeof(struct sctp_sackhdr);
len += (num_blocks + num_dup_tsns) * sizeof(__u32);
if (len > chunk->skb->len)
return NULL;
skb_pull(chunk->skb, len);
return sack;
}
/* Create an ABORT packet to be sent as a response, with the specified
* error causes.
*/
static struct sctp_packet *sctp_abort_pkt_new(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen)
{
struct sctp_packet *packet;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT.
* The T bit will be set if the asoc is NULL.
*/
abort = sctp_make_abort(asoc, chunk, paylen);
if (!abort) {
sctp_ootb_pkt_free(packet);
return NULL;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Add specified error causes, i.e., payload, to the
* end of the chunk.
*/
sctp_addto_chunk(abort, paylen, payload);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
}
return packet;
}
/* Allocate a packet for responding in the OOTB conditions. */
static struct sctp_packet *sctp_ootb_pkt_new(struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_packet *packet;
struct sctp_transport *transport;
__u16 sport;
__u16 dport;
__u32 vtag;
/* Get the source and destination port from the inbound packet. */
sport = ntohs(chunk->sctp_hdr->dest);
dport = ntohs(chunk->sctp_hdr->source);
/* The V-tag is going to be the same as the inbound packet if no
* association exists, otherwise, use the peer's vtag.
*/
if (asoc) {
/* Special case the INIT-ACK as there is no peer's vtag
* yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT_ACK:
{
sctp_initack_chunk_t *initack;
initack = (sctp_initack_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(initack->init_hdr.init_tag);
break;
}
default:
vtag = asoc->peer.i.init_tag;
break;
}
} else {
/* Special case the INIT and stale COOKIE_ECHO as there is no
* vtag yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT:
{
sctp_init_chunk_t *init;
init = (sctp_init_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(init->init_hdr.init_tag);
break;
}
default:
vtag = ntohl(chunk->sctp_hdr->vtag);
break;
}
}
/* Make a transport for the bucket, Eliza... */
transport = sctp_transport_new(net, sctp_source(chunk), GFP_ATOMIC);
if (!transport)
goto nomem;
/* Cache a route for the transport with the chunk's destination as
* the source address.
*/
sctp_transport_route(transport, (union sctp_addr *)&chunk->dest,
sctp_sk(net->sctp.ctl_sock));
packet = sctp_packet_init(&transport->packet, transport, sport, dport);
packet = sctp_packet_config(packet, vtag, 0);
return packet;
nomem:
return NULL;
}
/* Free the packet allocated earlier for responding in the OOTB condition. */
void sctp_ootb_pkt_free(struct sctp_packet *packet)
{
sctp_transport_free(packet->transport);
}
/* Send a stale cookie error when a invalid COOKIE ECHO chunk is found */
static void sctp_send_stale_cookie_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk)
{
struct sctp_packet *packet;
if (err_chunk) {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
struct sctp_signed_cookie *cookie;
/* Override the OOTB vtag from the cookie. */
cookie = chunk->subh.cookie_hdr;
packet->vtag = cookie->c.peer_vtag;
/* Set the skb to the belonging sock for accounting. */
err_chunk->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, err_chunk);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
} else
sctp_chunk_free (err_chunk);
}
}
/* Process a data chunk */
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands)
{
sctp_datahdr_t *data_hdr;
struct sctp_chunk *err;
size_t datalen;
sctp_verb_t deliver;
int tmp;
__u32 tsn;
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
u16 ssn;
u16 sid;
u8 ordered = 0;
data_hdr = chunk->subh.data_hdr = (sctp_datahdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_datahdr_t));
tsn = ntohl(data_hdr->tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* ASSERT: Now skb->data is really the user data. */
/* Process ECN based congestion.
*
* Since the chunk structure is reused for all chunks within
* a packet, we use ecn_ce_done to track if we've already
* done CE processing for this packet.
*
* We need to do ECN processing even if we plan to discard the
* chunk later.
*/
if (!chunk->ecn_ce_done) {
struct sctp_af *af;
chunk->ecn_ce_done = 1;
af = sctp_get_af_specific(
ipver2af(ip_hdr(chunk->skb)->version));
if (af && af->is_ce(chunk->skb) && asoc->peer.ecn_capable) {
/* Do real work as sideffect. */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CE,
SCTP_U32(tsn));
}
}
tmp = sctp_tsnmap_check(&asoc->peer.tsn_map, tsn);
if (tmp < 0) {
/* The TSN is too high--silently discard the chunk and
* count on it getting retransmitted later.
*/
if (chunk->asoc)
chunk->asoc->stats.outofseqtsns++;
return SCTP_IERROR_HIGH_TSN;
} else if (tmp > 0) {
/* This is a duplicate. Record it. */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_DUP, SCTP_U32(tsn));
return SCTP_IERROR_DUP_TSN;
}
/* This is a new TSN. */
/* Discard if there is no room in the receive window.
* Actually, allow a little bit of overflow (up to a MTU).
*/
datalen = ntohs(chunk->chunk_hdr->length);
datalen -= sizeof(sctp_data_chunk_t);
deliver = SCTP_CMD_CHUNK_ULP;
/* Think about partial delivery. */
if ((datalen >= asoc->rwnd) && (!asoc->ulpq.pd_mode)) {
/* Even if we don't accept this chunk there is
* memory pressure.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PART_DELIVER, SCTP_NULL());
}
/* Spill over rwnd a little bit. Note: While allowed, this spill over
* seems a bit troublesome in that frag_point varies based on
* PMTU. In cases, such as loopback, this might be a rather
* large spill over.
*/
if ((!chunk->data_accepted) && (!asoc->rwnd ||
(datalen > asoc->rwnd + asoc->frag_point))) {
/* If this is the next TSN, consider reneging to make
* room. Note: Playing nice with a confused sender. A
* malicious sender can still eat up all our buffer
* space and in the future we may want to detect and
* do more drastic reneging.
*/
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
pr_debug("%s: reneging for tsn:%u\n", __func__, tsn);
deliver = SCTP_CMD_RENEGE;
} else {
pr_debug("%s: discard tsn:%u len:%zu, rwnd:%d\n",
__func__, tsn, datalen, asoc->rwnd);
return SCTP_IERROR_IGNORE_TSN;
}
}
/*
* Also try to renege to limit our memory usage in the event that
* we are under memory pressure
* If we can't renege, don't worry about it, the sk_rmem_schedule
* in sctp_ulpevent_make_rcvmsg will drop the frame if we grow our
* memory usage too much
*/
if (*sk->sk_prot_creator->memory_pressure) {
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
pr_debug("%s: under pressure, reneging for tsn:%u\n",
__func__, tsn);
deliver = SCTP_CMD_RENEGE;
}
}
/*
* Section 3.3.10.9 No User Data (9)
*
* Cause of error
* ---------------
* No User Data: This error cause is returned to the originator of a
* DATA chunk if a received DATA chunk has no user data.
*/
if (unlikely(0 == datalen)) {
err = sctp_make_abort_no_data(asoc, chunk, tsn);
if (err) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_DATA));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_IERROR_NO_DATA;
}
chunk->data_accepted = 1;
/* Note: Some chunks may get overcounted (if we drop) or overcounted
* if we renege and the chunk arrives again.
*/
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
SCTP_INC_STATS(net, SCTP_MIB_INUNORDERCHUNKS);
if (chunk->asoc)
chunk->asoc->stats.iuodchunks++;
} else {
SCTP_INC_STATS(net, SCTP_MIB_INORDERCHUNKS);
if (chunk->asoc)
chunk->asoc->stats.iodchunks++;
ordered = 1;
}
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* If an endpoint receive a DATA chunk with an invalid stream
* identifier, it shall acknowledge the reception of the DATA chunk
* following the normal procedure, immediately send an ERROR chunk
* with cause set to "Invalid Stream Identifier" (See Section 3.3.10)
* and discard the DATA chunk.
*/
sid = ntohs(data_hdr->stream);
if (sid >= asoc->c.sinit_max_instreams) {
/* Mark tsn as received even though we drop it */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_TSN, SCTP_U32(tsn));
err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_INV_STRM,
&data_hdr->stream,
sizeof(data_hdr->stream),
sizeof(u16));
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_IERROR_BAD_STREAM;
}
/* Check to see if the SSN is possible for this TSN.
* The biggest gap we can record is 4K wide. Since SSNs wrap
* at an unsigned short, there is no way that an SSN can
* wrap and for a valid TSN. We can simply check if the current
* SSN is smaller then the next expected one. If it is, it wrapped
* and is invalid.
*/
ssn = ntohs(data_hdr->ssn);
if (ordered && SSN_lt(ssn, sctp_ssn_peek(&asoc->ssnmap->in, sid))) {
return SCTP_IERROR_PROTO_VIOLATION;
}
/* Send the data up to the user. Note: Schedule the
* SCTP_CMD_CHUNK_ULP cmd before the SCTP_CMD_GEN_SACK, as the SACK
* chunk needs the updated rwnd.
*/
sctp_add_cmd_sf(commands, deliver, SCTP_CHUNK(chunk));
return SCTP_IERROR_NO_ERROR;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2027_0 |
crossvul-cpp_data_bad_5115_1 | /*
* packet-ppi.c
* Routines for PPI Packet Header dissection
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 2007 Gerald Combs
*
* Copyright (c) 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
*
*
* Dustin Johnson - Dustin@Dustinj.us, Dustin.Johnson@cacetech.com
* May 7, 2008 - Added 'Aggregation Extension' and '802.3 Extension'
*/
#include "config.h"
#include <epan/packet.h>
#include <epan/exceptions.h>
#include <epan/ptvcursor.h>
#include <epan/prefs.h>
#include <epan/expert.h>
#include <epan/reassemble.h>
#include <wsutil/frequency-utils.h>
#include <wsutil/pint.h>
/* Needed for wtap_pcap_encap_to_wtap_encap(). */
#include <wiretap/pcap-encap.h>
#include "packet-frame.h"
#include "packet-eth.h"
#include "packet-ieee80211.h"
#include "packet-ppi.h"
/*
* Per-Packet Information (PPI) header.
* See the PPI Packet Header documentation at http://www.cacetech.com/documents
* for details.
*/
/*
* PPI headers have the following format:
*
* ,---------------------------------------------------------.
* | PPH | PFH 1 | Field data 1 | PFH 2 | Field data 2 | ... |
* `---------------------------------------------------------'
*
* The PPH struct has the following format:
*
* typedef struct ppi_packetheader {
* guint8 pph_version; // Version. Currently 0
* guint8 pph_flags; // Flags.
* guint16 pph_len; // Length of entire message, including this header and TLV payload.
* guint32 pph_dlt; // libpcap Data Link Type of the captured packet data.
* } ppi_packetheader_t;
*
* The PFH struct has the following format:
*
* typedef struct ppi_fieldheader {
* guint16 pfh_type; // Type
* guint16 pfh_datalen; // Length of data
* } ppi_fieldheader_t;
*
* Anyone looking to add their own PPI dissector would probably do well to imitate the GPS
* ones separation into a distinct file. Here is a step by step guide:
* 1) add the number you received to the enum ppi_field_type declaration.
* 2) Add a value string for your number into vs_ppi_field_type
* 3) declare a dissector handle by the ppi_gps_handle, and initialize it inside proto_reg_handoff
* 4) add case inside dissect_ppi to call your new handle.
* 5) Write your parser, and get it loaded.
* Following these steps will result in less churn inside the ppi proper parser, and avoid namespace issues.
*/
#define PPI_PADDED (1 << 0)
#define PPI_V0_HEADER_LEN 8
#define PPI_80211_COMMON_LEN 20
#define PPI_80211N_MAC_LEN 12
#define PPI_80211N_MAC_PHY_OFF 9
#define PPI_80211N_MAC_PHY_LEN 48
#define PPI_AGGREGATION_EXTENSION_LEN 4
#define PPI_8023_EXTENSION_LEN 8
#define PPI_FLAG_ALIGN 0x01
#define IS_PPI_FLAG_ALIGN(x) ((x) & PPI_FLAG_ALIGN)
#define DOT11_FLAG_HAVE_FCS 0x0001
#define DOT11_FLAG_TSF_TIMER_MS 0x0002
#define DOT11_FLAG_FCS_INVALID 0x0004
#define DOT11_FLAG_PHY_ERROR 0x0008
#define DOT11N_FLAG_GREENFIELD 0x0001
#define DOT11N_FLAG_HT40 0x0002
#define DOT11N_FLAG_SHORT_GI 0x0004
#define DOT11N_FLAG_DUPLICATE_RX 0x0008
#define DOT11N_FLAG_IS_AGGREGATE 0x0010
#define DOT11N_FLAG_MORE_AGGREGATES 0x0020
#define DOT11N_FLAG_AGG_CRC_ERROR 0x0040
#define DOT11N_IS_AGGREGATE(flags) (flags & DOT11N_FLAG_IS_AGGREGATE)
#define DOT11N_MORE_AGGREGATES(flags) ( \
(flags & DOT11N_FLAG_MORE_AGGREGATES) && \
!(flags & DOT11N_FLAG_AGG_CRC_ERROR))
#define AGGREGATE_MAX 65535
#define AMPDU_MAX 16383
/* XXX - Start - Copied from packet-radiotap.c */
/* Channel flags. */
#define IEEE80211_CHAN_TURBO 0x0010 /* Turbo channel */
#define IEEE80211_CHAN_CCK 0x0020 /* CCK channel */
#define IEEE80211_CHAN_OFDM 0x0040 /* OFDM channel */
#define IEEE80211_CHAN_2GHZ 0x0080 /* 2 GHz spectrum channel. */
#define IEEE80211_CHAN_5GHZ 0x0100 /* 5 GHz spectrum channel */
#define IEEE80211_CHAN_PASSIVE 0x0200 /* Only passive scan allowed */
#define IEEE80211_CHAN_DYN 0x0400 /* Dynamic CCK-OFDM channel */
#define IEEE80211_CHAN_GFSK 0x0800 /* GFSK channel (FHSS PHY) */
#define IEEE80211_CHAN_ALL \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_GFSK | \
IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_ALLTURBO \
(IEEE80211_CHAN_ALL | IEEE80211_CHAN_TURBO)
/*
* Useful combinations of channel characteristics.
*/
#define IEEE80211_CHAN_FHSS \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK)
#define IEEE80211_CHAN_DSSS \
(IEEE80211_CHAN_2GHZ)
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_PUREG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_108A \
(IEEE80211_CHAN_A | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_108G \
(IEEE80211_CHAN_G | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_108PUREG \
(IEEE80211_CHAN_PUREG | IEEE80211_CHAN_TURBO)
/* XXX - End - Copied from packet-radiotap.c */
void proto_register_ppi(void);
void proto_reg_handoff_ppi(void);
typedef enum {
/* 0 - 29999: Public types */
PPI_80211_COMMON = 2,
PPI_80211N_MAC = 3,
PPI_80211N_MAC_PHY = 4,
PPI_SPECTRUM_MAP = 5,
PPI_PROCESS_INFO = 6,
PPI_CAPTURE_INFO = 7,
PPI_AGGREGATION_EXTENSION = 8,
PPI_8023_EXTENSION = 9,
/* 11 - 29999: RESERVED */
/* 30000 - 65535: Private types */
INTEL_CORP_PRIVATE = 30000,
MOHAMED_THAGA_PRIVATE = 30001,
PPI_GPS_INFO = 30002, /* 30002 - 30005 described in PPI-GEOLOCATION specifcation */
PPI_VECTOR_INFO = 30003, /* currently available in draft from. jellch@harris.com */
PPI_SENSOR_INFO = 30004,
PPI_ANTENNA_INFO = 30005,
FNET_PRIVATE = 0xC017,
CACE_PRIVATE = 0xCACE
/* All others RESERVED. Contact the WinPcap team for an assignment */
} ppi_field_type;
/* Protocol */
static int proto_ppi = -1;
/* Packet header */
static int hf_ppi_head_version = -1;
static int hf_ppi_head_flags = -1;
static int hf_ppi_head_flag_alignment = -1;
static int hf_ppi_head_flag_reserved = -1;
static int hf_ppi_head_len = -1;
static int hf_ppi_head_dlt = -1;
/* Field header */
static int hf_ppi_field_type = -1;
static int hf_ppi_field_len = -1;
/* 802.11 Common */
static int hf_80211_common_tsft = -1;
static int hf_80211_common_flags = -1;
static int hf_80211_common_flags_fcs = -1;
static int hf_80211_common_flags_tsft = -1;
static int hf_80211_common_flags_fcs_valid = -1;
static int hf_80211_common_flags_phy_err = -1;
static int hf_80211_common_rate = -1;
static int hf_80211_common_chan_freq = -1;
static int hf_80211_common_chan_flags = -1;
static int hf_80211_common_chan_flags_turbo = -1;
static int hf_80211_common_chan_flags_cck = -1;
static int hf_80211_common_chan_flags_ofdm = -1;
static int hf_80211_common_chan_flags_2ghz = -1;
static int hf_80211_common_chan_flags_5ghz = -1;
static int hf_80211_common_chan_flags_passive = -1;
static int hf_80211_common_chan_flags_dynamic = -1;
static int hf_80211_common_chan_flags_gfsk = -1;
static int hf_80211_common_fhss_hopset = -1;
static int hf_80211_common_fhss_pattern = -1;
static int hf_80211_common_dbm_antsignal = -1;
static int hf_80211_common_dbm_antnoise = -1;
/* 802.11n MAC */
static int hf_80211n_mac_flags = -1;
static int hf_80211n_mac_flags_greenfield = -1;
static int hf_80211n_mac_flags_ht20_40 = -1;
static int hf_80211n_mac_flags_rx_guard_interval = -1;
static int hf_80211n_mac_flags_duplicate_rx = -1;
static int hf_80211n_mac_flags_more_aggregates = -1;
static int hf_80211n_mac_flags_aggregate = -1;
static int hf_80211n_mac_flags_delimiter_crc_after = -1;
static int hf_80211n_mac_ampdu_id = -1;
static int hf_80211n_mac_num_delimiters = -1;
static int hf_80211n_mac_reserved = -1;
/* 802.11n MAC+PHY */
static int hf_80211n_mac_phy_mcs = -1;
static int hf_80211n_mac_phy_num_streams = -1;
static int hf_80211n_mac_phy_rssi_combined = -1;
static int hf_80211n_mac_phy_rssi_ant0_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant1_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant2_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant3_ctl = -1;
static int hf_80211n_mac_phy_rssi_ant0_ext = -1;
static int hf_80211n_mac_phy_rssi_ant1_ext = -1;
static int hf_80211n_mac_phy_rssi_ant2_ext = -1;
static int hf_80211n_mac_phy_rssi_ant3_ext = -1;
static int hf_80211n_mac_phy_ext_chan_freq = -1;
static int hf_80211n_mac_phy_ext_chan_flags = -1;
static int hf_80211n_mac_phy_ext_chan_flags_turbo = -1;
static int hf_80211n_mac_phy_ext_chan_flags_cck = -1;
static int hf_80211n_mac_phy_ext_chan_flags_ofdm = -1;
static int hf_80211n_mac_phy_ext_chan_flags_2ghz = -1;
static int hf_80211n_mac_phy_ext_chan_flags_5ghz = -1;
static int hf_80211n_mac_phy_ext_chan_flags_passive = -1;
static int hf_80211n_mac_phy_ext_chan_flags_dynamic = -1;
static int hf_80211n_mac_phy_ext_chan_flags_gfsk = -1;
static int hf_80211n_mac_phy_dbm_ant0signal = -1;
static int hf_80211n_mac_phy_dbm_ant0noise = -1;
static int hf_80211n_mac_phy_dbm_ant1signal = -1;
static int hf_80211n_mac_phy_dbm_ant1noise = -1;
static int hf_80211n_mac_phy_dbm_ant2signal = -1;
static int hf_80211n_mac_phy_dbm_ant2noise = -1;
static int hf_80211n_mac_phy_dbm_ant3signal = -1;
static int hf_80211n_mac_phy_dbm_ant3noise = -1;
static int hf_80211n_mac_phy_evm0 = -1;
static int hf_80211n_mac_phy_evm1 = -1;
static int hf_80211n_mac_phy_evm2 = -1;
static int hf_80211n_mac_phy_evm3 = -1;
/* 802.11n-Extensions A-MPDU fragments */
static int hf_ampdu_reassembled_in = -1;
/* static int hf_ampdu_segments = -1; */
static int hf_ampdu_segment = -1;
static int hf_ampdu_count = -1;
/* Spectrum-Map */
static int hf_spectrum_map = -1;
/* Process-Info */
static int hf_process_info = -1;
/* Capture-Info */
static int hf_capture_info = -1;
/* Aggregation Extension */
static int hf_aggregation_extension_interface_id = -1;
/* 802.3 Extension */
static int hf_8023_extension_flags = -1;
static int hf_8023_extension_flags_fcs_present = -1;
static int hf_8023_extension_errors = -1;
static int hf_8023_extension_errors_fcs = -1;
static int hf_8023_extension_errors_sequence = -1;
static int hf_8023_extension_errors_symbol = -1;
static int hf_8023_extension_errors_data = -1;
/* Generated from convert_proto_tree_add_text.pl */
static int hf_ppi_antenna = -1;
static int hf_ppi_harris = -1;
static int hf_ppi_reserved = -1;
static int hf_ppi_vector = -1;
static int hf_ppi_fnet = -1;
static int hf_ppi_gps = -1;
static gint ett_ppi_pph = -1;
static gint ett_ppi_flags = -1;
static gint ett_dot11_common = -1;
static gint ett_dot11_common_flags = -1;
static gint ett_dot11_common_channel_flags = -1;
static gint ett_dot11n_mac = -1;
static gint ett_dot11n_mac_flags = -1;
static gint ett_dot11n_mac_phy = -1;
static gint ett_dot11n_mac_phy_ext_channel_flags = -1;
static gint ett_ampdu_segments = -1;
static gint ett_ampdu = -1;
static gint ett_ampdu_segment = -1;
static gint ett_aggregation_extension = -1;
static gint ett_8023_extension = -1;
static gint ett_8023_extension_flags = -1;
static gint ett_8023_extension_errors = -1;
/* Generated from convert_proto_tree_add_text.pl */
static expert_field ei_ppi_invalid_length = EI_INIT;
static dissector_handle_t ppi_handle;
static dissector_handle_t data_handle;
static dissector_handle_t ieee80211_radio_handle;
static dissector_handle_t ppi_gps_handle, ppi_vector_handle, ppi_sensor_handle, ppi_antenna_handle;
static dissector_handle_t ppi_fnet_handle;
static const true_false_string tfs_ppi_head_flag_alignment = { "32-bit aligned", "Not aligned" };
static const true_false_string tfs_tsft_ms = { "milliseconds", "microseconds" };
static const true_false_string tfs_ht20_40 = { "HT40", "HT20" };
static const true_false_string tfs_phy_error = { "PHY error", "No errors"};
static const value_string vs_ppi_field_type[] = {
{PPI_80211_COMMON, "802.11-Common"},
{PPI_80211N_MAC, "802.11n MAC Extensions"},
{PPI_80211N_MAC_PHY, "802.11n MAC+PHY Extensions"},
{PPI_SPECTRUM_MAP, "Spectrum-Map"},
{PPI_PROCESS_INFO, "Process-Info"},
{PPI_CAPTURE_INFO, "Capture-Info"},
{PPI_AGGREGATION_EXTENSION, "Aggregation Extension"},
{PPI_8023_EXTENSION, "802.3 Extension"},
{INTEL_CORP_PRIVATE, "Intel Corporation (private)"},
{MOHAMED_THAGA_PRIVATE, "Mohamed Thaga (private)"},
{PPI_GPS_INFO, "GPS Tagging"},
{PPI_VECTOR_INFO, "Vector Tagging"},
{PPI_SENSOR_INFO, "Sensor tagging"},
{PPI_ANTENNA_INFO, "Antenna Tagging"},
{FNET_PRIVATE, "FlukeNetworks (private)"},
{CACE_PRIVATE, "CACE Technologies (private)"},
{0, NULL}
};
/* Table for A-MPDU reassembly */
static reassembly_table ampdu_reassembly_table;
/* Reassemble A-MPDUs? */
static gboolean ppi_ampdu_reassemble = TRUE;
void
capture_ppi(const guchar *pd, int len, packet_counts *ld)
{
guint32 dlt;
guint ppi_len;
ppi_len = pletoh16(pd+2);
if(ppi_len < PPI_V0_HEADER_LEN || !BYTES_ARE_IN_FRAME(0, len, ppi_len)) {
ld->other++;
return;
}
dlt = pletoh32(pd+4);
/* XXX - We should probably combine this with capture_info.c:capture_info_packet() */
switch(dlt) {
case 1: /* DLT_EN10MB */
capture_eth(pd, ppi_len, len, ld);
return;
case 105: /* DLT_DLT_IEEE802_11 */
capture_ieee80211(pd, ppi_len, len, ld);
return;
default:
break;
}
ld->other++;
}
static void
ptvcursor_add_invalid_check(ptvcursor_t *csr, int hf, gint len, guint64 invalid_val) {
proto_item *ti;
guint64 val = invalid_val;
switch (len) {
case 8:
val = tvb_get_letoh64(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
case 4:
val = tvb_get_letohl(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
case 2:
val = tvb_get_letohs(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
case 1:
val = tvb_get_guint8(ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr));
break;
default:
DISSECTOR_ASSERT_NOT_REACHED();
}
ti = ptvcursor_add(csr, hf, len, ENC_LITTLE_ENDIAN);
if (val == invalid_val)
proto_item_append_text(ti, " [invalid]");
}
static void
add_ppi_field_header(tvbuff_t *tvb, proto_tree *tree, int *offset)
{
ptvcursor_t *csr;
csr = ptvcursor_new(tree, tvb, *offset);
ptvcursor_add(csr, hf_ppi_field_type, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_ppi_field_len, 2, ENC_LITTLE_ENDIAN);
ptvcursor_free(csr);
*offset=ptvcursor_current_offset(csr);
}
/* XXX - The main dissection function in the 802.11 dissector has the same name. */
static void
dissect_80211_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, int data_len, struct ieee_802_11_phdr *phdr)
{
proto_tree *ftree;
proto_item *ti;
ptvcursor_t *csr;
guint64 tsft_raw;
guint rate_raw;
guint rate_kbps;
guint32 common_flags;
guint16 common_frequency;
guint16 chan_flags;
gint8 dbm_value;
gchar *chan_str;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11_common, NULL, "802.11-Common");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_80211_COMMON_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
common_flags = tvb_get_letohs(tvb, offset + 8);
if (common_flags & DOT11_FLAG_HAVE_FCS)
phdr->fcs_len = 4;
else
phdr->fcs_len = 0;
csr = ptvcursor_new(ftree, tvb, offset);
tsft_raw = tvb_get_letoh64(tvb, offset);
if (tsft_raw != 0) {
phdr->presence_flags |= PHDR_802_11_HAS_TSF_TIMESTAMP;
if (common_flags & DOT11_FLAG_TSF_TIMER_MS)
phdr->tsf_timestamp = tsft_raw * 1000;
else
phdr->tsf_timestamp = tsft_raw;
}
ptvcursor_add_invalid_check(csr, hf_80211_common_tsft, 8, 0);
ptvcursor_add_with_subtree(csr, hf_80211_common_flags, 2, ENC_LITTLE_ENDIAN,
ett_dot11_common_flags);
ptvcursor_add_no_advance(csr, hf_80211_common_flags_fcs, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_flags_tsft, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_flags_fcs_valid, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211_common_flags_phy_err, 2, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
rate_raw = tvb_get_letohs(tvb, ptvcursor_current_offset(csr));
if (rate_raw != 0) {
phdr->presence_flags |= PHDR_802_11_HAS_DATA_RATE;
phdr->data_rate = rate_raw;
}
rate_kbps = rate_raw * 500;
ti = proto_tree_add_uint_format(ftree, hf_80211_common_rate, tvb,
ptvcursor_current_offset(csr), 2, rate_kbps, "Rate: %.1f Mbps",
rate_kbps / 1000.0);
if (rate_kbps == 0)
proto_item_append_text(ti, " [invalid]");
col_add_fstr(pinfo->cinfo, COL_TX_RATE, "%.1f Mbps", rate_kbps / 1000.0);
ptvcursor_advance(csr, 2);
common_frequency = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
if (common_frequency != 0) {
gint calc_channel;
phdr->presence_flags |= PHDR_802_11_HAS_FREQUENCY;
phdr->frequency = common_frequency;
calc_channel = ieee80211_mhz_to_chan(common_frequency);
if (calc_channel != -1) {
phdr->presence_flags |= PHDR_802_11_HAS_CHANNEL;
phdr->channel = calc_channel;
}
}
chan_str = ieee80211_mhz_to_str(common_frequency);
proto_tree_add_uint_format_value(ptvcursor_tree(csr), hf_80211_common_chan_freq, ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr), 2, common_frequency, "%s", chan_str);
col_add_fstr(pinfo->cinfo, COL_FREQ_CHAN, "%s", chan_str);
g_free(chan_str);
ptvcursor_advance(csr, 2);
chan_flags = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
switch (chan_flags & IEEE80211_CHAN_ALLTURBO) {
case IEEE80211_CHAN_FHSS:
phdr->phy = PHDR_802_11_PHY_11_FHSS;
phdr->phy_info.info_11_fhss.presence_flags =
PHDR_802_11_FHSS_HAS_HOP_SET |
PHDR_802_11_FHSS_HAS_HOP_PATTERN;
break;
case IEEE80211_CHAN_DSSS:
phdr->phy = PHDR_802_11_PHY_11_DSSS;
break;
case IEEE80211_CHAN_A:
phdr->phy = PHDR_802_11_PHY_11A;
phdr->phy_info.info_11a.presence_flags = PHDR_802_11A_HAS_TURBO_TYPE;
phdr->phy_info.info_11a.turbo_type = PHDR_802_11A_TURBO_TYPE_NORMAL;
break;
case IEEE80211_CHAN_B:
phdr->phy = PHDR_802_11_PHY_11B;
phdr->phy_info.info_11b.presence_flags = 0;
break;
case IEEE80211_CHAN_PUREG:
phdr->phy = PHDR_802_11_PHY_11G;
phdr->phy_info.info_11g.presence_flags = PHDR_802_11G_HAS_MODE;
phdr->phy_info.info_11g.mode = PHDR_802_11G_MODE_NORMAL;
break;
case IEEE80211_CHAN_G:
phdr->phy = PHDR_802_11_PHY_11G;
phdr->phy_info.info_11g.presence_flags = PHDR_802_11G_HAS_MODE;
phdr->phy_info.info_11g.mode = PHDR_802_11G_MODE_NORMAL;
break;
case IEEE80211_CHAN_108A:
phdr->phy = PHDR_802_11_PHY_11A;
phdr->phy_info.info_11a.presence_flags = PHDR_802_11A_HAS_TURBO_TYPE;
/* We assume non-STURBO is dynamic turbo */
phdr->phy_info.info_11a.turbo_type = PHDR_802_11A_TURBO_TYPE_DYNAMIC_TURBO;
break;
case IEEE80211_CHAN_108PUREG:
phdr->phy = PHDR_802_11_PHY_11G;
phdr->phy_info.info_11g.presence_flags = PHDR_802_11G_HAS_MODE;
phdr->phy_info.info_11g.mode = PHDR_802_11G_MODE_SUPER_G;
break;
}
ptvcursor_add_with_subtree(csr, hf_80211_common_chan_flags, 2, ENC_LITTLE_ENDIAN,
ett_dot11_common_channel_flags);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_turbo, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_cck, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_ofdm, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_2ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_5ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_passive, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211_common_chan_flags_dynamic, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211_common_chan_flags_gfsk, 2, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
if (phdr->phy == PHDR_802_11_PHY_11_FHSS)
phdr->phy_info.info_11_fhss.hop_set = tvb_get_guint8(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
ptvcursor_add(csr, hf_80211_common_fhss_hopset, 1, ENC_LITTLE_ENDIAN);
if (phdr->phy == PHDR_802_11_PHY_11_FHSS)
phdr->phy_info.info_11_fhss.hop_pattern = tvb_get_guint8(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
ptvcursor_add(csr, hf_80211_common_fhss_pattern, 1, ENC_LITTLE_ENDIAN);
dbm_value = (gint8) tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
if (dbm_value != -128 && dbm_value != 0) {
/*
* XXX - the spec says -128 is invalid, presumably meaning "use
* -128 if you don't have the signal strength", but some captures
* have 0 for noise, presumably meaning it's incorrectly being
* used for "don't have it", so we check for it as well.
*/
col_add_fstr(pinfo->cinfo, COL_RSSI, "%d dBm", dbm_value);
phdr->presence_flags |= PHDR_802_11_HAS_SIGNAL_DBM;
phdr->signal_dbm = dbm_value;
}
ptvcursor_add_invalid_check(csr, hf_80211_common_dbm_antsignal, 1, 0x80); /* -128 */
dbm_value = (gint8) tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
if (dbm_value != -128 && dbm_value != 0) {
/*
* XXX - the spec says -128 is invalid, presumably meaning "use
* -128 if you don't have the noise level", but some captures
* have 0, presumably meaning it's incorrectly being used for
* "don't have it", so we check for it as well.
*/
phdr->presence_flags |= PHDR_802_11_HAS_NOISE_DBM;
phdr->noise_dbm = dbm_value;
}
ptvcursor_add_invalid_check(csr, hf_80211_common_dbm_antnoise, 1, 0x80);
ptvcursor_free(csr);
}
static void
dissect_80211n_mac(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len, gboolean add_subtree, guint32 *n_mac_flags, guint32 *ampdu_id, struct ieee_802_11_phdr *phdr)
{
proto_tree *ftree = tree;
ptvcursor_t *csr;
int subtree_off = add_subtree ? 4 : 0;
guint32 flags;
phdr->phy = PHDR_802_11_PHY_11N;
*n_mac_flags = tvb_get_letohl(tvb, offset + subtree_off);
*ampdu_id = tvb_get_letohl(tvb, offset + 4 + subtree_off);
if (add_subtree) {
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11n_mac, NULL, "802.11n MAC");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
}
if (data_len != PPI_80211N_MAC_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
csr = ptvcursor_new(ftree, tvb, offset);
flags = tvb_get_letohl(tvb, ptvcursor_current_offset(csr));
phdr->phy_info.info_11n.presence_flags = PHDR_802_11N_HAS_SHORT_GI|PHDR_802_11N_HAS_GREENFIELD;
phdr->phy_info.info_11n.short_gi = ((flags & DOT11N_FLAG_SHORT_GI) != 0);
phdr->phy_info.info_11n.greenfield = ((flags & DOT11N_FLAG_GREENFIELD) != 0);
ptvcursor_add_with_subtree(csr, hf_80211n_mac_flags, 4, ENC_LITTLE_ENDIAN,
ett_dot11n_mac_flags);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_greenfield, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_ht20_40, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_rx_guard_interval, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_duplicate_rx, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_aggregate, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_more_aggregates, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211n_mac_flags_delimiter_crc_after, 4, ENC_LITTLE_ENDIAN); /* Last */
ptvcursor_pop_subtree(csr);
ptvcursor_add(csr, hf_80211n_mac_ampdu_id, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211n_mac_num_delimiters, 1, ENC_LITTLE_ENDIAN);
if (add_subtree) {
ptvcursor_add(csr, hf_80211n_mac_reserved, 3, ENC_LITTLE_ENDIAN);
}
ptvcursor_free(csr);
}
static void
dissect_80211n_mac_phy(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, int data_len, guint32 *n_mac_flags, guint32 *ampdu_id, struct ieee_802_11_phdr *phdr)
{
proto_tree *ftree;
proto_item *ti;
ptvcursor_t *csr;
guint8 mcs;
guint8 ness;
guint16 ext_frequency;
gchar *chan_str;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11n_mac_phy, NULL, "802.11n MAC+PHY");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_80211N_MAC_PHY_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
dissect_80211n_mac(tvb, pinfo, ftree, offset, PPI_80211N_MAC_LEN,
FALSE, n_mac_flags, ampdu_id, phdr);
offset += PPI_80211N_MAC_PHY_OFF;
csr = ptvcursor_new(ftree, tvb, offset);
mcs = tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
if (mcs != 255) {
phdr->phy_info.info_11n.presence_flags |= PHDR_802_11N_HAS_MCS_INDEX;
phdr->phy_info.info_11n.mcs_index = mcs;
}
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_mcs, 1, 255);
ness = tvb_get_guint8(tvb, ptvcursor_current_offset(csr));
phdr->phy_info.info_11n.presence_flags |= PHDR_802_11N_HAS_NESS;
phdr->phy_info.info_11n.ness = ness;
ti = ptvcursor_add(csr, hf_80211n_mac_phy_num_streams, 1, ENC_LITTLE_ENDIAN);
if (tvb_get_guint8(tvb, ptvcursor_current_offset(csr) - 1) == 0)
proto_item_append_text(ti, " (unknown)");
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_combined, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant0_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant1_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant2_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant3_ctl, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant0_ext, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant1_ext, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant2_ext, 1, 255);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_rssi_ant3_ext, 1, 255);
ext_frequency = tvb_get_letohs(ptvcursor_tvbuff(csr), ptvcursor_current_offset(csr));
chan_str = ieee80211_mhz_to_str(ext_frequency);
proto_tree_add_uint_format(ptvcursor_tree(csr), hf_80211n_mac_phy_ext_chan_freq, ptvcursor_tvbuff(csr),
ptvcursor_current_offset(csr), 2, ext_frequency, "Ext. Channel frequency: %s", chan_str);
g_free(chan_str);
ptvcursor_advance(csr, 2);
ptvcursor_add_with_subtree(csr, hf_80211n_mac_phy_ext_chan_flags, 2, ENC_LITTLE_ENDIAN,
ett_dot11n_mac_phy_ext_channel_flags);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_turbo, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_cck, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_ofdm, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_2ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_5ghz, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_passive, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_80211n_mac_phy_ext_chan_flags_dynamic, 2, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_80211n_mac_phy_ext_chan_flags_gfsk, 2, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant0signal, 1, 0x80); /* -128 */
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant0noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant1signal, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant1noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant2signal, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant2noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant3signal, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_dbm_ant3noise, 1, 0x80);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm0, 4, 0);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm1, 4, 0);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm2, 4, 0);
ptvcursor_add_invalid_check(csr, hf_80211n_mac_phy_evm3, 4, 0);
ptvcursor_free(csr);
}
static void
dissect_aggregation_extension(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len)
{
proto_tree *ftree;
ptvcursor_t *csr;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_aggregation_extension, NULL, "Aggregation Extension");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_AGGREGATION_EXTENSION_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
csr = ptvcursor_new(ftree, tvb, offset);
ptvcursor_add(csr, hf_aggregation_extension_interface_id, 4, ENC_LITTLE_ENDIAN); /* Last */
ptvcursor_free(csr);
}
static void
dissect_8023_extension(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len)
{
proto_tree *ftree;
ptvcursor_t *csr;
ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_8023_extension, NULL, "802.3 Extension");
add_ppi_field_header(tvb, ftree, &offset);
data_len -= 4; /* Subtract field header length */
if (data_len != PPI_8023_EXTENSION_LEN) {
proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, "Invalid length: %u", data_len);
THROW(ReportedBoundsError);
}
csr = ptvcursor_new(ftree, tvb, offset);
ptvcursor_add_with_subtree(csr, hf_8023_extension_flags, 4, ENC_LITTLE_ENDIAN, ett_8023_extension_flags);
ptvcursor_add(csr, hf_8023_extension_flags_fcs_present, 4, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
ptvcursor_add_with_subtree(csr, hf_8023_extension_errors, 4, ENC_LITTLE_ENDIAN, ett_8023_extension_errors);
ptvcursor_add_no_advance(csr, hf_8023_extension_errors_fcs, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_8023_extension_errors_sequence, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add_no_advance(csr, hf_8023_extension_errors_symbol, 4, ENC_LITTLE_ENDIAN);
ptvcursor_add(csr, hf_8023_extension_errors_data, 4, ENC_LITTLE_ENDIAN);
ptvcursor_pop_subtree(csr);
ptvcursor_free(csr);
}
#define PADDING4(x) ((((x + 3) >> 2) << 2) - x)
#define ADD_BASIC_TAG(hf_tag) \
if (tree) \
proto_tree_add_item(ppi_tree, hf_tag, tvb, offset, data_len, ENC_NA)
static void
dissect_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL;
proto_tree *agg_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint version, flags;
gint tot_len, data_len;
guint data_type;
guint32 dlt;
guint32 n_ext_flags = 0;
guint32 ampdu_id = 0;
fragment_head *fd_head = NULL;
fragment_item *ft_fdh = NULL;
gint mpdu_count = 0;
gchar *mpdu_str;
gboolean first_mpdu = TRUE;
guint last_frame = 0;
gint len_remain, /*pad_len = 0,*/ ampdu_len = 0;
struct ieee_802_11_phdr phdr;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPI");
col_clear(pinfo->cinfo, COL_INFO);
version = tvb_get_guint8(tvb, offset);
flags = tvb_get_guint8(tvb, offset + 1);
tot_len = tvb_get_letohs(tvb, offset+2);
dlt = tvb_get_letohl(tvb, offset+4);
col_add_fstr(pinfo->cinfo, COL_INFO, "PPI version %u, %u bytes",
version, tot_len);
/* Dissect the packet */
if (tree) {
ti = proto_tree_add_protocol_format(tree, proto_ppi,
tvb, 0, tot_len, "PPI version %u, %u bytes", version, tot_len);
ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph);
proto_tree_add_item(ppi_tree, hf_ppi_head_version,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags);
proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved,
tvb, offset + 1, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_tree, hf_ppi_head_len,
tvb, offset + 2, 2, ENC_LITTLE_ENDIAN);
proto_tree_add_item(ppi_tree, hf_ppi_head_dlt,
tvb, offset + 4, 4, ENC_LITTLE_ENDIAN);
}
tot_len -= PPI_V0_HEADER_LEN;
offset += 8;
/* We don't have any 802.11 metadata yet. */
memset(&phdr, 0, sizeof(phdr));
phdr.fcs_len = -1;
phdr.decrypted = FALSE;
phdr.datapad = FALSE;
phdr.phy = PHDR_802_11_PHY_UNKNOWN;
phdr.presence_flags = 0;
while (tot_len > 0) {
data_type = tvb_get_letohs(tvb, offset);
data_len = tvb_get_letohs(tvb, offset + 2) + 4;
tot_len -= data_len;
switch (data_type) {
case PPI_80211_COMMON:
dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr);
break;
case PPI_80211N_MAC:
dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len,
TRUE, &n_ext_flags, &du_id, &phdr);
break;
case PPI_80211N_MAC_PHY:
dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset,
data_len, &n_ext_flags, &du_id, &phdr);
break;
case PPI_SPECTRUM_MAP:
ADD_BASIC_TAG(hf_spectrum_map);
break;
case PPI_PROCESS_INFO:
ADD_BASIC_TAG(hf_process_info);
break;
case PPI_CAPTURE_INFO:
ADD_BASIC_TAG(hf_capture_info);
break;
case PPI_AGGREGATION_EXTENSION:
dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len);
break;
case PPI_8023_EXTENSION:
dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len);
break;
case PPI_GPS_INFO:
if (ppi_gps_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_VECTOR_INFO:
if (ppi_vector_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_SENSOR_INFO:
if (ppi_sensor_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree);
}
break;
case PPI_ANTENNA_INFO:
if (ppi_antenna_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree);
}
break;
case FNET_PRIVATE:
if (ppi_fnet_handle == NULL)
{
proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA);
}
else /* we found a suitable dissector */
{
/* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */
next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1);
call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree);
}
break;
default:
proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA);
}
offset += data_len;
if (IS_PPI_FLAG_ALIGN(flags)){
offset += PADDING4(offset);
}
}
if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) {
len_remain = tvb_captured_length_remaining(tvb, offset);
#if 0 /* XXX: pad_len never actually used ?? */
if (DOT11N_MORE_AGGREGATES(n_ext_flags)) {
pad_len = PADDING4(len_remain);
}
#endif
pinfo->fragmented = TRUE;
/* Make sure we aren't going to go past AGGREGATE_MAX
* and caclulate our full A-MPDU length */
fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);
while (fd_head) {
ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4;
fd_head = fd_head->next;
}
if (ampdu_len > AGGREGATE_MAX) {
if (tree) {
proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, "Aggregate length greater than maximum (%u)", AGGREGATE_MAX);
THROW(ReportedBoundsError);
} else {
return;
}
}
/*
* Note that we never actually reassemble our A-MPDUs. Doing
* so would require prepending each MPDU with an A-MPDU delimiter
* and appending it with padding, only to hand it off to some
* routine which would un-do the work we just did. We're using
* the reassembly code to track MPDU sizes and frame numbers.
*/
/*??fd_head = */fragment_add_seq_next(&du_reassembly_table,
tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE);
pinfo->fragmented = TRUE;
/* Do reassembly? */
fd_head = fragment_get(&du_reassembly_table, pinfo, ampdu_id, NULL);
/* Show our fragments */
if (fd_head && tree) {
ft_fdh = fd_head;
/* List our fragments */
seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1,
ett_ampdu_segments, &ti, "A-MPDU (%u bytes w/hdrs):", ampdu_len);
PROTO_ITEM_SET_GENERATED(ti);
while (ft_fdh) {
if (ft_fdh->tvb_data && ft_fdh->len) {
last_frame = ft_fdh->frame;
if (!first_mpdu)
proto_item_append_text(ti, ",");
first_mpdu = FALSE;
proto_item_append_text(ti, " #%u(%u)",
ft_fdh->frame, ft_fdh->len);
proto_tree_add_uint_format(seg_tree, hf_ampdu_segment,
tvb, 0, 0, last_frame,
"Frame: %u (%u byte%s)",
last_frame,
ft_fdh->len,
plurality(ft_fdh->len, "", "s"));
}
ft_fdh = ft_fdh->next;
}
if (last_frame && last_frame != pinfo->fd->num)
proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in,
tvb, 0, 0, last_frame);
}
if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) {
if (tree) {
ti = proto_tree_add_protocol_format(tree,
proto_get_id_by_filter_name("wlan_aggregate"),
tvb, 0, tot_len, "IEEE 802.11 Aggregate MPDU");
agg_tree = proto_item_add_subtree(ti, ett_ampdu);
}
while (fd_head) {
if (fd_head->tvb_data && fd_head->len) {
mpdu_count++;
mpdu_str = wmem_strdup_printf(wmem_packet_scope(), "MPDU #%d", mpdu_count);
next_tvb = tvb_new_chain(tvb, fd_head->tvb_data);
add_new_data_source(pinfo, next_tvb, mpdu_str);
ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str);
call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr);
}
fd_head = fd_head->next;
}
proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count);
pinfo->fragmented=FALSE;
} else {
next_tvb = tvb_new_subset_remaining(tvb, offset);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE 802.11n");
col_set_str(pinfo->cinfo, COL_INFO, "Unreassembled A-MPDU data");
call_dissector(data_handle, next_tvb, pinfo, tree);
}
return;
}
next_tvb = tvb_new_subset_remaining(tvb, offset);
/*
* You can't just call an arbitrary subdissector based on a
* LINKTYPE_ value, because they may expect a particular
* pseudo-header to be passed to them.
*
* So we look for LINKTYPE_IEEE802_11, which is 105, and, if
* that's what the LINKTYPE_ value is, pass it a pointer
* to a struct ieee_802_11_phdr; otherwise, we pass it
* a null pointer - if it actually matters, we need to
* construct the appropriate pseudo-header and pass that.
*/
if (dlt == 105) {
/* LINKTYPE_IEEE802_11 */
call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr);
} else {
/* Everything else. This will pass a NULL data argument. */
dissector_try_uint(wtap_encap_dissector_table,
wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree);
}
}
/* Establish our beachead */
static void
ampdu_reassemble_init(void)
{
reassembly_table_init(&du_reassembly_table,
&addresses_reassembly_table_functions);
}
static void
ampdu_reassemble_cleanup(void)
{
reassembly_table_destroy(&du_reassembly_table);
}
void
proto_register_ppi(void)
{
static hf_register_info hf[] = {
{ &hf_ppi_head_version,
{ "Version", "ppi.version",
FT_UINT8, BASE_DEC, NULL, 0x0,
"PPI header format version", HFILL } },
{ &hf_ppi_head_flags,
{ "Flags", "ppi.flags",
FT_UINT8, BASE_HEX, NULL, 0x0,
"PPI header flags", HFILL } },
{ &hf_ppi_head_flag_alignment,
{ "Alignment", "ppi.flags.alignment",
FT_BOOLEAN, 8, TFS(&tfs_ppi_head_flag_alignment), 0x01,
"PPI header flags - 32bit Alignment", HFILL } },
{ &hf_ppi_head_flag_reserved,
{ "Reserved", "ppi.flags.reserved",
FT_UINT8, BASE_HEX, NULL, 0xFE,
"PPI header flags - Reserved Flags", HFILL } },
{ &hf_ppi_head_len,
{ "Header length", "ppi.length",
FT_UINT16, BASE_DEC, NULL, 0x0,
"Length of header including payload", HFILL } },
{ &hf_ppi_head_dlt,
{ "DLT", "ppi.dlt",
FT_UINT32, BASE_DEC, NULL, 0x0, "libpcap Data Link Type (DLT) of the payload", HFILL } },
{ &hf_ppi_field_type,
{ "Field type", "ppi.field_type",
FT_UINT16, BASE_DEC, VALS(vs_ppi_field_type), 0x0, "PPI data field type", HFILL } },
{ &hf_ppi_field_len,
{ "Field length", "ppi.field_len",
FT_UINT16, BASE_DEC, NULL, 0x0, "PPI data field length", HFILL } },
{ &hf_80211_common_tsft,
{ "TSFT", "ppi.80211-common.tsft",
FT_UINT64, BASE_DEC, NULL, 0x0, "PPI 802.11-Common Timing Synchronization Function Timer (TSFT)", HFILL } },
{ &hf_80211_common_flags,
{ "Flags", "ppi.80211-common.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Flags", HFILL } },
{ &hf_80211_common_flags_fcs,
{ "FCS present flag", "ppi.80211-common.flags.fcs",
FT_BOOLEAN, 16, TFS(&tfs_present_absent), DOT11_FLAG_HAVE_FCS, "PPI 802.11-Common Frame Check Sequence (FCS) Present Flag", HFILL } },
{ &hf_80211_common_flags_tsft,
{ "TSFT flag", "ppi.80211-common.flags.tsft",
FT_BOOLEAN, 16, TFS(&tfs_tsft_ms), DOT11_FLAG_TSF_TIMER_MS, "PPI 802.11-Common Timing Synchronization Function Timer (TSFT) msec/usec flag", HFILL } },
{ &hf_80211_common_flags_fcs_valid,
{ "FCS validity", "ppi.80211-common.flags.fcs-invalid",
FT_BOOLEAN, 16, TFS(&tfs_invalid_valid), DOT11_FLAG_FCS_INVALID, "PPI 802.11-Common Frame Check Sequence (FCS) Validity flag", HFILL } },
{ &hf_80211_common_flags_phy_err,
{ "PHY error flag", "ppi.80211-common.flags.phy-err",
FT_BOOLEAN, 16, TFS(&tfs_phy_error), DOT11_FLAG_PHY_ERROR, "PPI 802.11-Common Physical level (PHY) Error", HFILL } },
{ &hf_80211_common_rate,
{ "Data rate", "ppi.80211-common.rate",
FT_UINT16, BASE_DEC, NULL, 0x0, "PPI 802.11-Common Data Rate (x 500 Kbps)", HFILL } },
{ &hf_80211_common_chan_freq,
{ "Channel frequency", "ppi.80211-common.chan.freq",
FT_UINT16, BASE_DEC, NULL, 0x0,
"PPI 802.11-Common Channel Frequency", HFILL } },
{ &hf_80211_common_chan_flags,
{ "Channel flags", "ppi.80211-common.chan.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Channel Flags", HFILL } },
{ &hf_80211_common_chan_flags_turbo,
{ "Turbo", "ppi.80211-common.chan.flags.turbo",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_TURBO, "PPI 802.11-Common Channel Flags Turbo", HFILL } },
{ &hf_80211_common_chan_flags_cck,
{ "Complementary Code Keying (CCK)", "ppi.80211-common.chan.flags.cck",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_CCK, "PPI 802.11-Common Channel Flags Complementary Code Keying (CCK) Modulation", HFILL } },
{ &hf_80211_common_chan_flags_ofdm,
{ "Orthogonal Frequency-Division Multiplexing (OFDM)", "ppi.80211-common.chan.flags.ofdm",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_OFDM, "PPI 802.11-Common Channel Flags Orthogonal Frequency-Division Multiplexing (OFDM)", HFILL } },
{ &hf_80211_common_chan_flags_2ghz,
{ "2 GHz spectrum", "ppi.80211-common.chan.flags.2ghz",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_2GHZ, "PPI 802.11-Common Channel Flags 2 GHz spectrum", HFILL } },
{ &hf_80211_common_chan_flags_5ghz,
{ "5 GHz spectrum", "ppi.80211-common.chan.flags.5ghz",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_5GHZ, "PPI 802.11-Common Channel Flags 5 GHz spectrum", HFILL } },
{ &hf_80211_common_chan_flags_passive,
{ "Passive", "ppi.80211-common.chan.flags.passive",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_PASSIVE, "PPI 802.11-Common Channel Flags Passive", HFILL } },
{ &hf_80211_common_chan_flags_dynamic,
{ "Dynamic CCK-OFDM", "ppi.80211-common.chan.flags.dynamic",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_DYN, "PPI 802.11-Common Channel Flags Dynamic CCK-OFDM Channel", HFILL } },
{ &hf_80211_common_chan_flags_gfsk,
{ "Gaussian Frequency Shift Keying (GFSK)", "ppi.80211-common.chan.flags.gfsk",
FT_BOOLEAN, 16, NULL, IEEE80211_CHAN_GFSK, "PPI 802.11-Common Channel Flags Gaussian Frequency Shift Keying (GFSK) Modulation", HFILL } },
{ &hf_80211_common_fhss_hopset,
{ "FHSS hopset", "ppi.80211-common.fhss.hopset",
FT_UINT8, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Frequency-Hopping Spread Spectrum (FHSS) Hopset", HFILL } },
{ &hf_80211_common_fhss_pattern,
{ "FHSS pattern", "ppi.80211-common.fhss.pattern",
FT_UINT8, BASE_HEX, NULL, 0x0, "PPI 802.11-Common Frequency-Hopping Spread Spectrum (FHSS) Pattern", HFILL } },
{ &hf_80211_common_dbm_antsignal,
{ "dBm antenna signal", "ppi.80211-common.dbm.antsignal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11-Common dBm Antenna Signal", HFILL } },
{ &hf_80211_common_dbm_antnoise,
{ "dBm antenna noise", "ppi.80211-common.dbm.antnoise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11-Common dBm Antenna Noise", HFILL } },
/* 802.11n MAC */
{ &hf_80211n_mac_flags,
{ "MAC flags", "ppi.80211n-mac.flags",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC flags", HFILL } },
{ &hf_80211n_mac_flags_greenfield,
{ "Greenfield flag", "ppi.80211n-mac.flags.greenfield",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_GREENFIELD, "PPI 802.11n MAC Greenfield Flag", HFILL } },
{ &hf_80211n_mac_flags_ht20_40,
{ "HT20/HT40 flag", "ppi.80211n-mac.flags.ht20_40",
FT_BOOLEAN, 32, TFS(&tfs_ht20_40), DOT11N_FLAG_HT40, "PPI 802.11n MAC HT20/HT40 Flag", HFILL } },
{ &hf_80211n_mac_flags_rx_guard_interval,
{ "RX Short Guard Interval (SGI) flag", "ppi.80211n-mac.flags.rx.short_guard_interval",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_SHORT_GI, "PPI 802.11n MAC RX Short Guard Interval (SGI) Flag", HFILL } },
{ &hf_80211n_mac_flags_duplicate_rx,
{ "Duplicate RX flag", "ppi.80211n-mac.flags.rx.duplicate",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_DUPLICATE_RX, "PPI 802.11n MAC Duplicate RX Flag", HFILL } },
{ &hf_80211n_mac_flags_aggregate,
{ "Aggregate flag", "ppi.80211n-mac.flags.agg",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_IS_AGGREGATE, "PPI 802.11 MAC Aggregate Flag", HFILL } },
{ &hf_80211n_mac_flags_more_aggregates,
{ "More aggregates flag", "ppi.80211n-mac.flags.more_agg",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_MORE_AGGREGATES, "PPI 802.11n MAC More Aggregates Flag", HFILL } },
{ &hf_80211n_mac_flags_delimiter_crc_after,
{ "A-MPDU Delimiter CRC error after this frame flag", "ppi.80211n-mac.flags.delim_crc_error_after",
FT_BOOLEAN, 32, TFS(&tfs_true_false), DOT11N_FLAG_AGG_CRC_ERROR, "PPI 802.11n MAC A-MPDU Delimiter CRC Error After This Frame Flag", HFILL } },
{ &hf_80211n_mac_ampdu_id,
{ "AMPDU-ID", "ppi.80211n-mac.ampdu_id",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC AMPDU-ID", HFILL } },
{ &hf_80211n_mac_num_delimiters,
{ "Num-Delimiters", "ppi.80211n-mac.num_delimiters",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC number of zero-length pad delimiters", HFILL } },
{ &hf_80211n_mac_reserved,
{ "Reserved", "ppi.80211n-mac.reserved",
FT_UINT24, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC Reserved", HFILL } },
/* 802.11n MAC+PHY */
{ &hf_80211n_mac_phy_mcs,
{ "MCS", "ppi.80211n-mac-phy.mcs",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Modulation Coding Scheme (MCS)", HFILL } },
{ &hf_80211n_mac_phy_num_streams,
{ "Number of spatial streams", "ppi.80211n-mac-phy.num_streams",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY number of spatial streams", HFILL } },
{ &hf_80211n_mac_phy_rssi_combined,
{ "RSSI combined", "ppi.80211n-mac-phy.rssi.combined",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Received Signal Strength Indication (RSSI) Combined", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant0_ctl,
{ "Antenna 0 control RSSI", "ppi.80211n-mac-phy.rssi.ant0ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 0 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant1_ctl,
{ "Antenna 1 control RSSI", "ppi.80211n-mac-phy.rssi.ant1ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 1 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant2_ctl,
{ "Antenna 2 control RSSI", "ppi.80211n-mac-phy.rssi.ant2ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 2 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant3_ctl,
{ "Antenna 3 control RSSI", "ppi.80211n-mac-phy.rssi.ant3ctl",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 3 Control Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant0_ext,
{ "Antenna 0 extension RSSI", "ppi.80211n-mac-phy.rssi.ant0ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 0 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant1_ext,
{ "Antenna 1 extension RSSI", "ppi.80211n-mac-phy.rssi.ant1ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 1 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant2_ext,
{ "Antenna 2 extension RSSI", "ppi.80211n-mac-phy.rssi.ant2ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 2 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_rssi_ant3_ext,
{ "Antenna 3 extension RSSI", "ppi.80211n-mac-phy.rssi.ant3ext",
FT_UINT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Antenna 3 Extension Channel Received Signal Strength Indication (RSSI)", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_freq,
{ "Extended channel frequency", "ppi.80211-mac-phy.ext-chan.freq",
FT_UINT16, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Extended Channel Frequency", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags,
{ "Channel flags", "ppi.80211-mac-phy.ext-chan.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, "PPI 802.11n MAC+PHY Channel Flags", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_turbo,
{ "Turbo", "ppi.80211-mac-phy.ext-chan.flags.turbo",
FT_BOOLEAN, 16, NULL, 0x0010, "PPI 802.11n MAC+PHY Channel Flags Turbo", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_cck,
{ "Complementary Code Keying (CCK)", "ppi.80211-mac-phy.ext-chan.flags.cck",
FT_BOOLEAN, 16, NULL, 0x0020, "PPI 802.11n MAC+PHY Channel Flags Complementary Code Keying (CCK) Modulation", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_ofdm,
{ "Orthogonal Frequency-Division Multiplexing (OFDM)", "ppi.80211-mac-phy.ext-chan.flags.ofdm",
FT_BOOLEAN, 16, NULL, 0x0040, "PPI 802.11n MAC+PHY Channel Flags Orthogonal Frequency-Division Multiplexing (OFDM)", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_2ghz,
{ "2 GHz spectrum", "ppi.80211-mac-phy.ext-chan.flags.2ghz",
FT_BOOLEAN, 16, NULL, 0x0080, "PPI 802.11n MAC+PHY Channel Flags 2 GHz spectrum", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_5ghz,
{ "5 GHz spectrum", "ppi.80211-mac-phy.ext-chan.flags.5ghz",
FT_BOOLEAN, 16, NULL, 0x0100, "PPI 802.11n MAC+PHY Channel Flags 5 GHz spectrum", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_passive,
{ "Passive", "ppi.80211-mac-phy.ext-chan.flags.passive",
FT_BOOLEAN, 16, NULL, 0x0200, "PPI 802.11n MAC+PHY Channel Flags Passive", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_dynamic,
{ "Dynamic CCK-OFDM", "ppi.80211-mac-phy.ext-chan.flags.dynamic",
FT_BOOLEAN, 16, NULL, 0x0400, "PPI 802.11n MAC+PHY Channel Flags Dynamic CCK-OFDM Channel", HFILL } },
{ &hf_80211n_mac_phy_ext_chan_flags_gfsk,
{ "Gaussian Frequency Shift Keying (GFSK)", "ppi.80211-mac-phy.ext-chan.flags.gfsk",
FT_BOOLEAN, 16, NULL, 0x0800, "PPI 802.11n MAC+PHY Channel Flags Gaussian Frequency Shift Keying (GFSK) Modulation", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant0signal,
{ "dBm antenna 0 signal", "ppi.80211n-mac-phy.dbmant0.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 0 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant0noise,
{ "dBm antenna 0 noise", "ppi.80211n-mac-phy.dbmant0.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 0 Noise", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant1signal,
{ "dBm antenna 1 signal", "ppi.80211n-mac-phy.dbmant1.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 1 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant1noise,
{ "dBm antenna 1 noise", "ppi.80211n-mac-phy.dbmant1.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 1 Noise", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant2signal,
{ "dBm antenna 2 signal", "ppi.80211n-mac-phy.dbmant2.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 2 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant2noise,
{ "dBm antenna 2 noise", "ppi.80211n-mac-phy.dbmant2.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 2 Noise", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant3signal,
{ "dBm antenna 3 signal", "ppi.80211n-mac-phy.dbmant3.signal",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 3 Signal", HFILL } },
{ &hf_80211n_mac_phy_dbm_ant3noise,
{ "dBm antenna 3 noise", "ppi.80211n-mac-phy.dbmant3.noise",
FT_INT8, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY dBm Antenna 3 Noise", HFILL } },
{ &hf_80211n_mac_phy_evm0,
{ "EVM-0", "ppi.80211n-mac-phy.evm0",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 0", HFILL } },
{ &hf_80211n_mac_phy_evm1,
{ "EVM-1", "ppi.80211n-mac-phy.evm1",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 1", HFILL } },
{ &hf_80211n_mac_phy_evm2,
{ "EVM-2", "ppi.80211n-mac-phy.evm2",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 2", HFILL } },
{ &hf_80211n_mac_phy_evm3,
{ "EVM-3", "ppi.80211n-mac-phy.evm3",
FT_UINT32, BASE_DEC, NULL, 0x0, "PPI 802.11n MAC+PHY Error Vector Magnitude (EVM) for chain 3", HFILL } },
{ &hf_ampdu_segment,
{ "A-MPDU", "ppi.80211n-mac.ampdu",
FT_FRAMENUM, BASE_NONE, NULL, 0x0, "802.11n Aggregated MAC Protocol Data Unit (A-MPDU)", HFILL }},
#if 0
{ &hf_ampdu_segments,
{ "Reassembled A-MPDU", "ppi.80211n-mac.ampdu.reassembled",
FT_NONE, BASE_NONE, NULL, 0x0, "Reassembled Aggregated MAC Protocol Data Unit (A-MPDU)", HFILL }},
#endif
{ &hf_ampdu_reassembled_in,
{ "Reassembled A-MPDU in frame", "ppi.80211n-mac.ampdu.reassembled_in",
FT_FRAMENUM, BASE_NONE, NULL, 0x0,
"The A-MPDU that doesn't end in this segment is reassembled in this frame",
HFILL }},
{ &hf_ampdu_count,
{ "MPDU count", "ppi.80211n-mac.ampdu.count",
FT_UINT16, BASE_DEC, NULL, 0x0, "The number of aggregated MAC Protocol Data Units (MPDUs)", HFILL }},
{ &hf_spectrum_map,
{ "Radio spectrum map", "ppi.spectrum-map",
FT_BYTES, BASE_NONE, NULL, 0x0, "PPI Radio spectrum map", HFILL } },
{ &hf_process_info,
{ "Process information", "ppi.proc-info",
FT_BYTES, BASE_NONE, NULL, 0x0, "PPI Process information", HFILL } },
{ &hf_capture_info,
{ "Capture information", "ppi.cap-info",
FT_BYTES, BASE_NONE, NULL, 0x0, "PPI Capture information", HFILL } },
/* Aggregtion Extension */
{ &hf_aggregation_extension_interface_id,
{ "Interface ID", "ppi.aggregation_extension.interface_id",
FT_UINT32, BASE_DEC, NULL, 0x0, "Zero-based index of the physical interface the packet was captured from", HFILL } },
/* 802.3 Extension */
{ &hf_8023_extension_flags,
{ "Flags", "ppi.8023_extension.flags",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.3 Extension Flags", HFILL } },
{ &hf_8023_extension_flags_fcs_present,
{ "FCS Present Flag", "ppi.8023_extension.flags.fcs_present",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0001, "FCS (4 bytes) is present at the end of the packet", HFILL } },
{ &hf_8023_extension_errors,
{ "Errors", "ppi.8023_extension.errors",
FT_UINT32, BASE_HEX, NULL, 0x0, "PPI 802.3 Extension Errors", HFILL } },
{ &hf_8023_extension_errors_fcs,
{ "FCS Error", "ppi.8023_extension.errors.fcs",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0001,
"PPI 802.3 Extension FCS Error", HFILL } },
{ &hf_8023_extension_errors_sequence,
{ "Sequence Error", "ppi.8023_extension.errors.sequence",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0002,
"PPI 802.3 Extension Sequence Error", HFILL } },
{ &hf_8023_extension_errors_symbol,
{ "Symbol Error", "ppi.8023_extension.errors.symbol",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0004,
"PPI 802.3 Extension Symbol Error", HFILL } },
{ &hf_8023_extension_errors_data,
{ "Data Error", "ppi.8023_extension.errors.data",
FT_BOOLEAN, 32, TFS(&tfs_true_false), 0x0008,
"PPI 802.3 Extension Data Error", HFILL } },
/* Generated from convert_proto_tree_add_text.pl */
{ &hf_ppi_gps, { "GPS", "ppi.gps", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_vector, { "VECTOR", "ppi.vector", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_harris, { "HARRIS", "ppi.harris", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_antenna, { "ANTENNA", "ppi.antenna", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_fnet, { "FNET", "ppi.fnet", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_ppi_reserved, { "Reserved", "ppi.reserved", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
};
static gint *ett[] = {
&ett_ppi_pph,
&ett_ppi_flags,
&ett_dot11_common,
&ett_dot11_common_flags,
&ett_dot11_common_channel_flags,
&ett_dot11n_mac,
&ett_dot11n_mac_flags,
&ett_dot11n_mac_phy,
&ett_dot11n_mac_phy_ext_channel_flags,
&ett_ampdu_segments,
&ett_ampdu,
&ett_ampdu_segment,
&ett_aggregation_extension,
&ett_8023_extension,
&ett_8023_extension_flags,
&ett_8023_extension_errors
};
static ei_register_info ei[] = {
{ &ei_ppi_invalid_length, { "ppi.invalid_length", PI_MALFORMED, PI_ERROR, "Invalid length", EXPFILL }},
};
module_t *ppi_module;
expert_module_t* expert_ppi;
proto_ppi = proto_register_protocol("PPI Packet Header", "PPI", "ppi");
proto_register_field_array(proto_ppi, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_ppi = expert_register_protocol(proto_ppi);
expert_register_field_array(expert_ppi, ei, array_length(ei));
ppi_handle = register_dissector("ppi", dissect_ppi, proto_ppi);
register_init_routine(ampdu_reassemble_init);
register_cleanup_routine(ampdu_reassemble_cleanup);
/* Configuration options */
ppi_module = prefs_register_protocol(proto_ppi, NULL);
prefs_register_bool_preference(ppi_module, "reassemble",
"Reassemble fragmented 802.11 A-MPDUs",
"Whether fragmented 802.11 aggregated MPDUs should be reassembled",
&ppi_ampdu_reassemble);
}
void
proto_reg_handoff_ppi(void)
{
data_handle = find_dissector("data");
ieee80211_radio_handle = find_dissector("wlan_radio");
ppi_gps_handle = find_dissector("ppi_gps");
ppi_vector_handle = find_dissector("ppi_vector");
ppi_sensor_handle = find_dissector("ppi_sensor");
ppi_antenna_handle = find_dissector("ppi_antenna");
ppi_fnet_handle = find_dissector("ppi_fnet");
dissector_add_uint("wtap_encap", WTAP_ENCAP_PPI, ppi_handle);
}
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5115_1 |
crossvul-cpp_data_bad_5259_1 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 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: Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_WDDX
#include "ext/xml/expat_compat.h"
#include "php_wddx.h"
#include "php_wddx_api.h"
#define PHP_XML_INTERNAL
#include "ext/xml/php_xml.h"
#include "ext/standard/php_incomplete_class.h"
#include "ext/standard/base64.h"
#include "ext/standard/info.h"
#include "ext/standard/php_smart_str.h"
#include "ext/standard/html.h"
#include "ext/standard/php_string.h"
#include "ext/date/php_date.h"
#include "zend_globals.h"
#define WDDX_BUF_LEN 256
#define PHP_CLASS_NAME_VAR "php_class_name"
#define EL_ARRAY "array"
#define EL_BINARY "binary"
#define EL_BOOLEAN "boolean"
#define EL_CHAR "char"
#define EL_CHAR_CODE "code"
#define EL_NULL "null"
#define EL_NUMBER "number"
#define EL_PACKET "wddxPacket"
#define EL_STRING "string"
#define EL_STRUCT "struct"
#define EL_VALUE "value"
#define EL_VAR "var"
#define EL_NAME "name"
#define EL_VERSION "version"
#define EL_RECORDSET "recordset"
#define EL_FIELD "field"
#define EL_DATETIME "dateTime"
#define php_wddx_deserialize(a,b) \
php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b))
#define SET_STACK_VARNAME \
if (stack->varname) { \
ent.varname = estrdup(stack->varname); \
efree(stack->varname); \
stack->varname = NULL; \
} else \
ent.varname = NULL; \
static int le_wddx;
typedef struct {
zval *data;
enum {
ST_ARRAY,
ST_BOOLEAN,
ST_NULL,
ST_NUMBER,
ST_STRING,
ST_BINARY,
ST_STRUCT,
ST_RECORDSET,
ST_FIELD,
ST_DATETIME
} type;
char *varname;
} st_entry;
typedef struct {
int top, max;
char *varname;
zend_bool done;
void **elements;
} wddx_stack;
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len);
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1)
ZEND_ARG_INFO(0, var)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1)
ZEND_ARG_INFO(0, packet_id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2)
ZEND_ARG_INFO(0, packet_id)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1)
ZEND_ARG_INFO(0, packet)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ wddx_functions[]
*/
const zend_function_entry wddx_functions[] = {
PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value)
PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars)
PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start)
PHP_FE(wddx_packet_end, arginfo_wddx_packet_end)
PHP_FE(wddx_add_vars, arginfo_wddx_add_vars)
PHP_FE(wddx_deserialize, arginfo_wddx_deserialize)
PHP_FE_END
};
/* }}} */
PHP_MINIT_FUNCTION(wddx);
PHP_MINFO_FUNCTION(wddx);
/* {{{ dynamically loadable module stuff */
#ifdef COMPILE_DL_WDDX
ZEND_GET_MODULE(wddx)
#endif /* COMPILE_DL_WDDX */
/* }}} */
/* {{{ wddx_module_entry
*/
zend_module_entry wddx_module_entry = {
STANDARD_MODULE_HEADER,
"wddx",
wddx_functions,
PHP_MINIT(wddx),
NULL,
NULL,
NULL,
PHP_MINFO(wddx),
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
/* {{{ wddx_stack_init
*/
static int wddx_stack_init(wddx_stack *stack)
{
stack->top = 0;
stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0);
stack->max = STACK_BLOCK_SIZE;
stack->varname = NULL;
stack->done = 0;
return SUCCESS;
}
/* }}} */
/* {{{ wddx_stack_push
*/
static int wddx_stack_push(wddx_stack *stack, void *element, int size)
{
if (stack->top >= stack->max) { /* we need to allocate more memory */
stack->elements = (void **) erealloc(stack->elements,
(sizeof(void **) * (stack->max += STACK_BLOCK_SIZE)));
}
stack->elements[stack->top] = (void *) emalloc(size);
memcpy(stack->elements[stack->top], element, size);
return stack->top++;
}
/* }}} */
/* {{{ wddx_stack_top
*/
static int wddx_stack_top(wddx_stack *stack, void **element)
{
if (stack->top > 0) {
*element = stack->elements[stack->top - 1];
return SUCCESS;
} else {
*element = NULL;
return FAILURE;
}
}
/* }}} */
/* {{{ wddx_stack_is_empty
*/
static int wddx_stack_is_empty(wddx_stack *stack)
{
if (stack->top == 0) {
return 1;
} else {
return 0;
}
}
/* }}} */
/* {{{ wddx_stack_destroy
*/
static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
/* }}} */
/* {{{ release_wddx_packet_rsrc
*/
static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
smart_str *str = (smart_str *)rsrc->ptr;
smart_str_free(str);
efree(str);
}
/* }}} */
#include "ext/session/php_session.h"
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
/* {{{ PS_SERIALIZER_ENCODE_FUNC
*/
PS_SERIALIZER_ENCODE_FUNC(wddx)
{
wddx_packet *packet;
PS_ENCODE_VARS;
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
PS_ENCODE_LOOP(
php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC);
);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
*newstr = php_wddx_gather(packet);
php_wddx_destructor(packet);
if (newlen) {
*newlen = strlen(*newstr);
}
return SUCCESS;
}
/* }}} */
/* {{{ PS_SERIALIZER_DECODE_FUNC
*/
PS_SERIALIZER_DECODE_FUNC(wddx)
{
zval *retval;
zval **ent;
char *key;
uint key_length;
char tmp[128];
ulong idx;
int hash_type;
int ret;
if (vallen == 0) {
return SUCCESS;
}
MAKE_STD_ZVAL(retval);
if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) {
if (Z_TYPE_P(retval) != IS_ARRAY) {
zval_ptr_dtor(&retval);
return FAILURE;
}
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval));
zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS;
zend_hash_move_forward(Z_ARRVAL_P(retval))) {
hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL);
switch (hash_type) {
case HASH_KEY_IS_LONG:
key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1;
key = tmp;
/* fallthru */
case HASH_KEY_IS_STRING:
php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC);
PS_ADD_VAR(key);
}
}
}
zval_ptr_dtor(&retval);
return ret;
}
/* }}} */
#endif
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(wddx)
{
le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number);
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_session_register_serializer("wddx",
PS_SERIALIZER_ENCODE_NAME(wddx),
PS_SERIALIZER_DECODE_NAME(wddx));
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(wddx)
{
php_info_print_table_start();
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_info_print_table_header(2, "WDDX Support", "enabled" );
php_info_print_table_row(2, "WDDX Session Serializer", "enabled" );
#else
php_info_print_table_row(2, "WDDX Support", "enabled" );
#endif
php_info_print_table_end();
}
/* }}} */
/* {{{ php_wddx_packet_start
*/
void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len)
{
php_wddx_add_chunk_static(packet, WDDX_PACKET_S);
if (comment) {
char *escaped;
size_t escaped_len;
TSRMLS_FETCH();
escaped = php_escape_html_entities(
comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_static(packet, WDDX_HEADER_S);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_S);
php_wddx_add_chunk_ex(packet, escaped, escaped_len);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_E);
php_wddx_add_chunk_static(packet, WDDX_HEADER_E);
str_efree(escaped);
} else {
php_wddx_add_chunk_static(packet, WDDX_HEADER);
}
php_wddx_add_chunk_static(packet, WDDX_DATA_S);
}
/* }}} */
/* {{{ php_wddx_packet_end
*/
void php_wddx_packet_end(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_DATA_E);
php_wddx_add_chunk_static(packet, WDDX_PACKET_E);
}
/* }}} */
#define FLUSH_BUF() \
if (l > 0) { \
php_wddx_add_chunk_ex(packet, buf, l); \
l = 0; \
}
/* {{{ php_wddx_serialize_string
*/
static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC)
{
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
if (Z_STRLEN_P(var) > 0) {
char *buf;
size_t buf_len;
buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_ex(packet, buf, buf_len);
str_efree(buf);
}
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
}
/* }}} */
/* {{{ php_wddx_serialize_number
*/
static void php_wddx_serialize_number(wddx_packet *packet, zval *var)
{
char tmp_buf[WDDX_BUF_LEN];
zval tmp;
tmp = *var;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp));
zval_dtor(&tmp);
php_wddx_add_chunk(packet, tmp_buf);
}
/* }}} */
/* {{{ php_wddx_serialize_boolean
*/
static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var)
{
php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE);
}
/* }}} */
/* {{{ php_wddx_serialize_unset
*/
static void php_wddx_serialize_unset(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_NULL);
}
/* }}} */
/* {{{ php_wddx_serialize_object
*/
static void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
TSRMLS_FETCH();
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
/* }}} */
/* {{{ php_wddx_serialize_array
*/
static void php_wddx_serialize_array(wddx_packet *packet, zval *arr)
{
zval **ent;
char *key;
uint key_len;
int is_struct = 0, ent_type;
ulong idx;
HashTable *target_hash;
char tmp_buf[WDDX_BUF_LEN];
ulong ind = 0;
int type;
TSRMLS_FETCH();
target_hash = HASH_OF(arr);
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
type = zend_hash_get_current_key(target_hash, &key, &idx, 0);
if (type == HASH_KEY_IS_STRING) {
is_struct = 1;
break;
}
if (idx != ind) {
is_struct = 1;
break;
}
ind++;
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
} else {
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash));
php_wddx_add_chunk(packet, tmp_buf);
}
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
if (*ent == arr) {
continue;
}
if (is_struct) {
ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL);
if (ent_type == HASH_KEY_IS_STRING) {
php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
} else {
php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC);
}
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
} else {
php_wddx_add_chunk_static(packet, WDDX_ARRAY_E);
}
}
/* }}} */
/* {{{ php_wddx_serialize_var
*/
void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC)
{
HashTable *ht;
if (name) {
size_t name_esc_len;
char *tmp_buf, *name_esc;
name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S));
snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc);
php_wddx_add_chunk(packet, tmp_buf);
efree(tmp_buf);
str_efree(name_esc);
}
switch(Z_TYPE_P(var)) {
case IS_STRING:
php_wddx_serialize_string(packet, var TSRMLS_CC);
break;
case IS_LONG:
case IS_DOUBLE:
php_wddx_serialize_number(packet, var);
break;
case IS_BOOL:
php_wddx_serialize_boolean(packet, var);
break;
case IS_NULL:
php_wddx_serialize_unset(packet);
break;
case IS_ARRAY:
ht = Z_ARRVAL_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_array(packet, var);
ht->nApplyCount--;
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_object(packet, var);
ht->nApplyCount--;
break;
}
if (name) {
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
}
}
/* }}} */
/* {{{ php_wddx_add_var
*/
static void php_wddx_add_var(wddx_packet *packet, zval *name_var)
{
zval **val;
HashTable *target_hash;
TSRMLS_FETCH();
if (Z_TYPE_P(name_var) == IS_STRING) {
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var),
Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) {
php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC);
}
} else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) {
int is_array = Z_TYPE_P(name_var) == IS_ARRAY;
target_hash = HASH_OF(name_var);
if (is_array && target_hash->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected");
return;
}
zend_hash_internal_pointer_reset(target_hash);
while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) {
if (is_array) {
target_hash->nApplyCount++;
}
php_wddx_add_var(packet, *val);
if (is_array) {
target_hash->nApplyCount--;
}
zend_hash_move_forward(target_hash);
}
}
}
/* }}} */
/* {{{ php_wddx_push_element
*/
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i], strlen(atts[i]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
/* }}} */
/* {{{ php_wddx_pop_element
*/
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
/* }}} */
/* {{{ php_wddx_process_data
*/
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if(!ent->data) {
break;
}
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
ent->varname = NULL;
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
}
efree(tmp);
}
break;
default:
break;
}
}
}
/* }}} */
/* {{{ php_wddx_deserialize_ex
*/
int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
/* }}} */
/* {{{ proto string wddx_serialize_value(mixed var [, string comment])
Creates a new packet and serializes the given value */
PHP_FUNCTION(wddx_serialize_value)
{
zval *var;
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...])
Creates a new packet and serializes given variables into a struct */
PHP_FUNCTION(wddx_serialize_vars)
{
int num_args, i;
wddx_packet *packet;
zval ***args = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, *args[i]);
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
efree(args);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ php_wddx_constructor
*/
wddx_packet *php_wddx_constructor(void)
{
smart_str *packet;
packet = (smart_str *)emalloc(sizeof(smart_str));
packet->c = NULL;
return packet;
}
/* }}} */
/* {{{ php_wddx_destructor
*/
void php_wddx_destructor(wddx_packet *packet)
{
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto resource wddx_packet_start([string comment])
Starts a WDDX packet with optional comment and returns the packet id */
PHP_FUNCTION(wddx_packet_start)
{
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
comment = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx);
}
/* }}} */
/* {{{ proto string wddx_packet_end(resource packet_id)
Ends specified WDDX packet and returns the string containing the packet */
PHP_FUNCTION(wddx_packet_end)
{
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
zend_list_delete(Z_LVAL_P(packet_id));
}
/* }}} */
/* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...])
Serializes given variables and adds them to packet given by packet_id */
PHP_FUNCTION(wddx_add_vars)
{
int num_args, i;
zval ***args = NULL;
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) {
return;
}
if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) {
efree(args);
RETURN_FALSE;
}
if (!packet) {
efree(args);
RETURN_FALSE;
}
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, (*args[i]));
}
efree(args);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed wddx_deserialize(mixed packet)
Deserializes given packet and returns a PHP value */
PHP_FUNCTION(wddx_deserialize)
{
zval *packet;
char *payload;
int payload_len;
php_stream *stream = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) {
return;
}
if (Z_TYPE_P(packet) == IS_STRING) {
payload = Z_STRVAL_P(packet);
payload_len = Z_STRLEN_P(packet);
} else if (Z_TYPE_P(packet) == IS_RESOURCE) {
php_stream_from_zval(stream, &packet);
if (stream) {
payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream");
return;
}
if (payload_len == 0) {
return;
}
php_wddx_deserialize_ex(payload, payload_len, return_value);
if (stream) {
pefree(payload, 0);
}
}
/* }}} */
#endif /* HAVE_LIBEXPAT */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5259_1 |
crossvul-cpp_data_good_4701_0 | /*
network-ssl.c : SSL support
Copyright (C) 2002 vjt
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 "module.h"
#include "network.h"
#include "misc.h"
#ifdef HAVE_OPENSSL
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
/* ssl i/o channel object */
typedef struct
{
GIOChannel pad;
gint fd;
GIOChannel *giochan;
SSL *ssl;
SSL_CTX *ctx;
unsigned int verify:1;
const char *hostname;
} GIOSSLChannel;
static SSL_CTX *ssl_ctx = NULL;
static void irssi_ssl_free(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
g_io_channel_unref(chan->giochan);
SSL_free(chan->ssl);
if (chan->ctx != ssl_ctx)
SSL_CTX_free(chan->ctx);
g_free(chan);
}
/* Checks if the given string has internal NUL characters. */
static gboolean has_internal_nul(const char* str, int len) {
/* Remove trailing nul characters. They would give false alarms */
while (len > 0 && str[len-1] == 0)
len--;
return strlen(str) != len;
}
/* tls_dns_name - Extract valid DNS name from subjectAltName value */
static const char *tls_dns_name(const GENERAL_NAME * gn)
{
const char *dnsname;
/* We expect the OpenSSL library to construct GEN_DNS extension objects as
ASN1_IA5STRING values. Check we got the right union member. */
if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING) {
g_warning("Invalid ASN1 value type in subjectAltName");
return NULL;
}
/* Safe to treat as an ASCII string possibly holding a DNS name */
dnsname = (char *) ASN1_STRING_data(gn->d.ia5);
if (has_internal_nul(dnsname, ASN1_STRING_length(gn->d.ia5))) {
g_warning("Internal NUL in subjectAltName");
return NULL;
}
return dnsname;
}
/* tls_text_name - extract certificate property value by name */
static char *tls_text_name(X509_NAME *name, int nid)
{
int pos;
X509_NAME_ENTRY *entry;
ASN1_STRING *entry_str;
int utf8_length;
unsigned char *utf8_value;
char *result;
if (name == 0 || (pos = X509_NAME_get_index_by_NID(name, nid, -1)) < 0) {
return NULL;
}
entry = X509_NAME_get_entry(name, pos);
g_return_val_if_fail(entry != NULL, NULL);
entry_str = X509_NAME_ENTRY_get_data(entry);
g_return_val_if_fail(entry_str != NULL, NULL);
/* Convert everything into UTF-8. It's up to OpenSSL to do something
reasonable when converting ASCII formats that contain non-ASCII
content. */
if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, entry_str)) < 0) {
g_warning("Error decoding ASN.1 type=%d", ASN1_STRING_type(entry_str));
return NULL;
}
if (has_internal_nul((char *)utf8_value, utf8_length)) {
g_warning("NUL character in hostname in certificate");
OPENSSL_free(utf8_value);
return NULL;
}
result = g_strdup((char *) utf8_value);
OPENSSL_free(utf8_value);
return result;
}
/** check if a hostname in the certificate matches the hostname we used for the connection */
static gboolean match_hostname(const char *cert_hostname, const char *hostname)
{
const char *hostname_left;
if (!strcasecmp(cert_hostname, hostname)) { /* exact match */
return TRUE;
} else if (cert_hostname[0] == '*' && cert_hostname[1] == '.' && cert_hostname[2] != 0) { /* wildcard match */
/* The initial '*' matches exactly one hostname component */
hostname_left = strchr(hostname, '.');
if (hostname_left != NULL && ! strcasecmp(hostname_left + 1, cert_hostname + 2)) {
return TRUE;
}
}
return FALSE;
}
/* based on verify_extract_name from tls_client.c in postfix */
static gboolean irssi_ssl_verify_hostname(X509 *cert, const char *hostname)
{
int gen_index, gen_count;
gboolean matched = FALSE, has_dns_name = FALSE;
const char *cert_dns_name;
char *cert_subject_cn;
const GENERAL_NAME *gn;
STACK_OF(GENERAL_NAME) * gens;
/* Verify the dNSName(s) in the peer certificate against the hostname. */
gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
if (gens) {
gen_count = sk_GENERAL_NAME_num(gens);
for (gen_index = 0; gen_index < gen_count && !matched; ++gen_index) {
gn = sk_GENERAL_NAME_value(gens, gen_index);
if (gn->type != GEN_DNS)
continue;
/* Even if we have an invalid DNS name, we still ultimately
ignore the CommonName, because subjectAltName:DNS is
present (though malformed). */
has_dns_name = TRUE;
cert_dns_name = tls_dns_name(gn);
if (cert_dns_name && *cert_dns_name) {
matched = match_hostname(cert_dns_name, hostname);
}
}
/* Free stack *and* member GENERAL_NAME objects */
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
}
if (has_dns_name) {
if (! matched) {
/* The CommonName in the issuer DN is obsolete when SubjectAltName is available. */
g_warning("None of the Subject Alt Names in the certificate match hostname '%s'", hostname);
}
return matched;
} else { /* No subjectAltNames, look at CommonName */
cert_subject_cn = tls_text_name(X509_get_subject_name(cert), NID_commonName);
if (cert_subject_cn && *cert_subject_cn) {
matched = match_hostname(cert_subject_cn, hostname);
if (! matched) {
g_warning("SSL certificate common name '%s' doesn't match host name '%s'", cert_subject_cn, hostname);
}
} else {
g_warning("No subjectAltNames and no valid common name in certificate");
}
free(cert_subject_cn);
}
return matched;
}
static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, const char* hostname, X509 *cert)
{
if (SSL_get_verify_result(ssl) != X509_V_OK) {
unsigned char md[EVP_MAX_MD_SIZE];
unsigned int n;
char *str;
g_warning("Could not verify SSL servers certificate:");
if ((str = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0)) == NULL)
g_warning(" Could not get subject-name from peer certificate");
else {
g_warning(" Subject : %s", str);
free(str);
}
if ((str = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0)) == NULL)
g_warning(" Could not get issuer-name from peer certificate");
else {
g_warning(" Issuer : %s", str);
free(str);
}
if (! X509_digest(cert, EVP_md5(), md, &n))
g_warning(" Could not get fingerprint from peer certificate");
else {
char hex[] = "0123456789ABCDEF";
char fp[EVP_MAX_MD_SIZE*3];
if (n < sizeof(fp)) {
unsigned int i;
for (i = 0; i < n; i++) {
fp[i*3+0] = hex[(md[i] >> 4) & 0xF];
fp[i*3+1] = hex[(md[i] >> 0) & 0xF];
fp[i*3+2] = i == n - 1 ? '\0' : ':';
}
g_warning(" MD5 Fingerprint : %s", fp);
}
}
return FALSE;
} else if (! irssi_ssl_verify_hostname(cert, hostname)){
return FALSE;
}
return TRUE;
}
static GIOStatus irssi_ssl_read(GIOChannel *handle, gchar *buf, gsize len, gsize *ret, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
gint ret1, err;
const char *errstr;
ret1 = SSL_read(chan->ssl, buf, len);
if(ret1 <= 0)
{
*ret = 0;
err = SSL_get_error(chan->ssl, ret1);
if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
return G_IO_STATUS_AGAIN;
else if(err == SSL_ERROR_ZERO_RETURN)
return G_IO_STATUS_EOF;
else if (err == SSL_ERROR_SYSCALL)
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret1 == -1)
errstr = strerror(errno);
if (errstr == NULL)
errstr = "server closed connection unexpectedly";
}
else
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL)
errstr = "unknown SSL error";
}
g_warning("SSL read error: %s", errstr);
*gerr = g_error_new_literal(G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED,
errstr);
return G_IO_STATUS_ERROR;
}
else
{
*ret = ret1;
return G_IO_STATUS_NORMAL;
}
/*UNREACH*/
return G_IO_STATUS_ERROR;
}
static GIOStatus irssi_ssl_write(GIOChannel *handle, const gchar *buf, gsize len, gsize *ret, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
gint ret1, err;
const char *errstr;
ret1 = SSL_write(chan->ssl, (const char *)buf, len);
if(ret1 <= 0)
{
*ret = 0;
err = SSL_get_error(chan->ssl, ret1);
if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
return G_IO_STATUS_AGAIN;
else if(err == SSL_ERROR_ZERO_RETURN)
errstr = "server closed connection";
else if (err == SSL_ERROR_SYSCALL)
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret1 == -1)
errstr = strerror(errno);
if (errstr == NULL)
errstr = "server closed connection unexpectedly";
}
else
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL)
errstr = "unknown SSL error";
}
g_warning("SSL write error: %s", errstr);
*gerr = g_error_new_literal(G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED,
errstr);
return G_IO_STATUS_ERROR;
}
else
{
*ret = ret1;
return G_IO_STATUS_NORMAL;
}
/*UNREACH*/
return G_IO_STATUS_ERROR;
}
static GIOStatus irssi_ssl_seek(GIOChannel *handle, gint64 offset, GSeekType type, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_seek(handle, offset, type, gerr);
}
static GIOStatus irssi_ssl_close(GIOChannel *handle, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_close(handle, gerr);
}
static GSource *irssi_ssl_create_watch(GIOChannel *handle, GIOCondition cond)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_create_watch(handle, cond);
}
static GIOStatus irssi_ssl_set_flags(GIOChannel *handle, GIOFlags flags, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_set_flags(handle, flags, gerr);
}
static GIOFlags irssi_ssl_get_flags(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_get_flags(handle);
}
static GIOFuncs irssi_ssl_channel_funcs = {
irssi_ssl_read,
irssi_ssl_write,
irssi_ssl_seek,
irssi_ssl_close,
irssi_ssl_create_watch,
irssi_ssl_free,
irssi_ssl_set_flags,
irssi_ssl_get_flags
};
static gboolean irssi_ssl_init(void)
{
SSL_library_init();
SSL_load_error_strings();
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if(!ssl_ctx)
{
g_error("Initialization of the SSL library failed");
return FALSE;
}
return TRUE;
}
static GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *hostname, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
{
GIOSSLChannel *chan;
GIOChannel *gchan;
int fd;
SSL *ssl;
SSL_CTX *ctx = NULL;
g_return_val_if_fail(handle != NULL, NULL);
if(!ssl_ctx && !irssi_ssl_init())
return NULL;
if(!(fd = g_io_channel_unix_get_fd(handle)))
return NULL;
if (mycert && *mycert) {
char *scert = NULL, *spkey = NULL;
if ((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
scert = convert_home(mycert);
if (mypkey && *mypkey)
spkey = convert_home(mypkey);
if (! SSL_CTX_use_certificate_file(ctx, scert, SSL_FILETYPE_PEM))
g_warning("Loading of client certificate '%s' failed", mycert);
else if (! SSL_CTX_use_PrivateKey_file(ctx, spkey ? spkey : scert, SSL_FILETYPE_PEM))
g_warning("Loading of private key '%s' failed", mypkey ? mypkey : mycert);
else if (! SSL_CTX_check_private_key(ctx))
g_warning("Private key does not match the certificate");
g_free(scert);
g_free(spkey);
}
if ((cafile && *cafile) || (capath && *capath)) {
char *scafile = NULL;
char *scapath = NULL;
if (! ctx && (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
if (cafile && *cafile)
scafile = convert_home(cafile);
if (capath && *capath)
scapath = convert_home(capath);
if (! SSL_CTX_load_verify_locations(ctx, scafile, scapath)) {
g_warning("Could not load CA list for verifying SSL server certificate");
g_free(scafile);
g_free(scapath);
SSL_CTX_free(ctx);
return NULL;
}
g_free(scafile);
g_free(scapath);
verify = TRUE;
}
if (ctx == NULL)
ctx = ssl_ctx;
if(!(ssl = SSL_new(ctx)))
{
g_warning("Failed to allocate SSL structure");
return NULL;
}
if(!SSL_set_fd(ssl, fd))
{
g_warning("Failed to associate socket to SSL stream");
SSL_free(ssl);
if (ctx != ssl_ctx)
SSL_CTX_free(ctx);
return NULL;
}
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
chan = g_new0(GIOSSLChannel, 1);
chan->fd = fd;
chan->giochan = handle;
chan->ssl = ssl;
chan->ctx = ctx;
chan->verify = verify;
chan->hostname = hostname;
gchan = (GIOChannel *)chan;
gchan->funcs = &irssi_ssl_channel_funcs;
g_io_channel_init(gchan);
gchan->is_readable = gchan->is_writeable = TRUE;
gchan->use_buffer = FALSE;
return gchan;
}
GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, const char* hostname, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
{
GIOChannel *handle, *ssl_handle;
handle = net_connect_ip(ip, port, my_ip);
if (handle == NULL)
return NULL;
ssl_handle = irssi_ssl_get_iochannel(handle, hostname, cert, pkey, cafile, capath, verify);
if (ssl_handle == NULL)
g_io_channel_unref(handle);
return ssl_handle;
}
int irssi_ssl_handshake(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
int ret, err;
X509 *cert;
const char *errstr;
ret = SSL_connect(chan->ssl);
if (ret <= 0) {
err = SSL_get_error(chan->ssl, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
return 1;
case SSL_ERROR_WANT_WRITE:
return 3;
case SSL_ERROR_ZERO_RETURN:
g_warning("SSL handshake failed: %s", "server closed connection");
return -1;
case SSL_ERROR_SYSCALL:
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret == -1)
errstr = strerror(errno);
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly");
return -1;
default:
errstr = ERR_reason_error_string(ERR_get_error());
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error");
return -1;
}
}
cert = SSL_get_peer_certificate(chan->ssl);
if (cert == NULL) {
g_warning("SSL server supplied no certificate");
return -1;
}
ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, chan->hostname, cert);
X509_free(cert);
return ret ? 0 : -1;
}
#else /* HAVE_OPENSSL */
GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
{
g_warning("Connection failed: SSL support not enabled in this build.");
errno = ENOSYS;
return NULL;
}
#endif /* ! HAVE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4701_0 |
crossvul-cpp_data_bad_5511_0 | /*
* Internet Control Message Protocol (ICMPv6)
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Based on net/ipv4/icmp.c
*
* RFC 1885
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/*
* Changes:
*
* Andi Kleen : exception handling
* Andi Kleen add rate limits. never reply to a icmp.
* add more length checks and other fixes.
* yoshfuji : ensure to sent parameter problem for
* fragments.
* YOSHIFUJI Hideaki @USAGI: added sysctl for icmp rate limit.
* Randy Dunlap and
* YOSHIFUJI Hideaki @USAGI: Per-interface statistics support
* Kazunori MIYAZAWA @USAGI: change output process to use ip6_append_data
*/
#define pr_fmt(fmt) "IPv6: " fmt
#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/sockios.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/netfilter.h>
#include <linux/slab.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/icmpv6.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/ip6_checksum.h>
#include <net/ping.h>
#include <net/protocol.h>
#include <net/raw.h>
#include <net/rawv6.h>
#include <net/transp_v6.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/inet_common.h>
#include <net/dsfield.h>
#include <net/l3mdev.h>
#include <asm/uaccess.h>
/*
* The ICMP socket(s). This is the most convenient way to flow control
* our ICMP output as well as maintain a clean interface throughout
* all layers. All Socketless IP sends will soon be gone.
*
* On SMP we have one ICMP socket per-cpu.
*/
static inline struct sock *icmpv6_sk(struct net *net)
{
return net->ipv6.icmp_sk[smp_processor_id()];
}
static void icmpv6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
/* icmpv6_notify checks 8 bytes can be pulled, icmp6hdr is 8 bytes */
struct icmp6hdr *icmp6 = (struct icmp6hdr *) (skb->data + offset);
struct net *net = dev_net(skb->dev);
if (type == ICMPV6_PKT_TOOBIG)
ip6_update_pmtu(skb, net, info, 0, 0);
else if (type == NDISC_REDIRECT)
ip6_redirect(skb, net, skb->dev->ifindex, 0);
if (!(type & ICMPV6_INFOMSG_MASK))
if (icmp6->icmp6_type == ICMPV6_ECHO_REQUEST)
ping_err(skb, offset, ntohl(info));
}
static int icmpv6_rcv(struct sk_buff *skb);
static const struct inet6_protocol icmpv6_protocol = {
.handler = icmpv6_rcv,
.err_handler = icmpv6_err,
.flags = INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL,
};
static __inline__ struct sock *icmpv6_xmit_lock(struct net *net)
{
struct sock *sk;
local_bh_disable();
sk = icmpv6_sk(net);
if (unlikely(!spin_trylock(&sk->sk_lock.slock))) {
/* This can happen if the output path (f.e. SIT or
* ip6ip6 tunnel) signals dst_link_failure() for an
* outgoing ICMP6 packet.
*/
local_bh_enable();
return NULL;
}
return sk;
}
static __inline__ void icmpv6_xmit_unlock(struct sock *sk)
{
spin_unlock_bh(&sk->sk_lock.slock);
}
/*
* Figure out, may we reply to this packet with icmp error.
*
* We do not reply, if:
* - it was icmp error message.
* - it is truncated, so that it is known, that protocol is ICMPV6
* (i.e. in the middle of some exthdr)
*
* --ANK (980726)
*/
static bool is_ineligible(const struct sk_buff *skb)
{
int ptr = (u8 *)(ipv6_hdr(skb) + 1) - skb->data;
int len = skb->len - ptr;
__u8 nexthdr = ipv6_hdr(skb)->nexthdr;
__be16 frag_off;
if (len < 0)
return true;
ptr = ipv6_skip_exthdr(skb, ptr, &nexthdr, &frag_off);
if (ptr < 0)
return false;
if (nexthdr == IPPROTO_ICMPV6) {
u8 _type, *tp;
tp = skb_header_pointer(skb,
ptr+offsetof(struct icmp6hdr, icmp6_type),
sizeof(_type), &_type);
if (!tp || !(*tp & ICMPV6_INFOMSG_MASK))
return true;
}
return false;
}
/*
* Check the ICMP output rate limit
*/
static bool icmpv6_xrlim_allow(struct sock *sk, u8 type,
struct flowi6 *fl6)
{
struct net *net = sock_net(sk);
struct dst_entry *dst;
bool res = false;
/* Informational messages are not limited. */
if (type & ICMPV6_INFOMSG_MASK)
return true;
/* Do not limit pmtu discovery, it would break it. */
if (type == ICMPV6_PKT_TOOBIG)
return true;
/*
* Look up the output route.
* XXX: perhaps the expire for routing entries cloned by
* this lookup should be more aggressive (not longer than timeout).
*/
dst = ip6_route_output(net, sk, fl6);
if (dst->error) {
IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_OUTNOROUTES);
} else if (dst->dev && (dst->dev->flags&IFF_LOOPBACK)) {
res = true;
} else {
struct rt6_info *rt = (struct rt6_info *)dst;
int tmo = net->ipv6.sysctl.icmpv6_time;
/* Give more bandwidth to wider prefixes. */
if (rt->rt6i_dst.plen < 128)
tmo >>= ((128 - rt->rt6i_dst.plen)>>5);
if (icmp_global_allow()) {
struct inet_peer *peer;
peer = inet_getpeer_v6(net->ipv6.peers,
&fl6->daddr, 1);
res = inet_peer_xrlim_allow(peer, tmo);
if (peer)
inet_putpeer(peer);
}
}
dst_release(dst);
return res;
}
/*
* an inline helper for the "simple" if statement below
* checks if parameter problem report is caused by an
* unrecognized IPv6 option that has the Option Type
* highest-order two bits set to 10
*/
static bool opt_unrec(struct sk_buff *skb, __u32 offset)
{
u8 _optval, *op;
offset += skb_network_offset(skb);
op = skb_header_pointer(skb, offset, sizeof(_optval), &_optval);
if (!op)
return true;
return (*op & 0xC0) == 0x80;
}
int icmpv6_push_pending_frames(struct sock *sk, struct flowi6 *fl6,
struct icmp6hdr *thdr, int len)
{
struct sk_buff *skb;
struct icmp6hdr *icmp6h;
int err = 0;
skb = skb_peek(&sk->sk_write_queue);
if (!skb)
goto out;
icmp6h = icmp6_hdr(skb);
memcpy(icmp6h, thdr, sizeof(struct icmp6hdr));
icmp6h->icmp6_cksum = 0;
if (skb_queue_len(&sk->sk_write_queue) == 1) {
skb->csum = csum_partial(icmp6h,
sizeof(struct icmp6hdr), skb->csum);
icmp6h->icmp6_cksum = csum_ipv6_magic(&fl6->saddr,
&fl6->daddr,
len, fl6->flowi6_proto,
skb->csum);
} else {
__wsum tmp_csum = 0;
skb_queue_walk(&sk->sk_write_queue, skb) {
tmp_csum = csum_add(tmp_csum, skb->csum);
}
tmp_csum = csum_partial(icmp6h,
sizeof(struct icmp6hdr), tmp_csum);
icmp6h->icmp6_cksum = csum_ipv6_magic(&fl6->saddr,
&fl6->daddr,
len, fl6->flowi6_proto,
tmp_csum);
}
ip6_push_pending_frames(sk);
out:
return err;
}
struct icmpv6_msg {
struct sk_buff *skb;
int offset;
uint8_t type;
};
static int icmpv6_getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb)
{
struct icmpv6_msg *msg = (struct icmpv6_msg *) from;
struct sk_buff *org_skb = msg->skb;
__wsum csum = 0;
csum = skb_copy_and_csum_bits(org_skb, msg->offset + offset,
to, len, csum);
skb->csum = csum_block_add(skb->csum, csum, odd);
if (!(msg->type & ICMPV6_INFOMSG_MASK))
nf_ct_attach(skb, org_skb);
return 0;
}
#if IS_ENABLED(CONFIG_IPV6_MIP6)
static void mip6_addr_swap(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct ipv6_destopt_hao *hao;
struct in6_addr tmp;
int off;
if (opt->dsthao) {
off = ipv6_find_tlv(skb, opt->dsthao, IPV6_TLV_HAO);
if (likely(off >= 0)) {
hao = (struct ipv6_destopt_hao *)
(skb_network_header(skb) + off);
tmp = iph->saddr;
iph->saddr = hao->addr;
hao->addr = tmp;
}
}
}
#else
static inline void mip6_addr_swap(struct sk_buff *skb) {}
#endif
static struct dst_entry *icmpv6_route_lookup(struct net *net,
struct sk_buff *skb,
struct sock *sk,
struct flowi6 *fl6)
{
struct dst_entry *dst, *dst2;
struct flowi6 fl2;
int err;
err = ip6_dst_lookup(net, sk, &dst, fl6);
if (err)
return ERR_PTR(err);
/*
* We won't send icmp if the destination is known
* anycast.
*/
if (ipv6_anycast_destination(dst, &fl6->daddr)) {
net_dbg_ratelimited("icmp6_send: acast source\n");
dst_release(dst);
return ERR_PTR(-EINVAL);
}
/* No need to clone since we're just using its address. */
dst2 = dst;
dst = xfrm_lookup(net, dst, flowi6_to_flowi(fl6), sk, 0);
if (!IS_ERR(dst)) {
if (dst != dst2)
return dst;
} else {
if (PTR_ERR(dst) == -EPERM)
dst = NULL;
else
return dst;
}
err = xfrm_decode_session_reverse(skb, flowi6_to_flowi(&fl2), AF_INET6);
if (err)
goto relookup_failed;
err = ip6_dst_lookup(net, sk, &dst2, &fl2);
if (err)
goto relookup_failed;
dst2 = xfrm_lookup(net, dst2, flowi6_to_flowi(&fl2), sk, XFRM_LOOKUP_ICMP);
if (!IS_ERR(dst2)) {
dst_release(dst);
dst = dst2;
} else {
err = PTR_ERR(dst2);
if (err == -EPERM) {
dst_release(dst);
return dst2;
} else
goto relookup_failed;
}
relookup_failed:
if (dst)
return dst;
return ERR_PTR(err);
}
/*
* Send an ICMP message in response to a packet in error
*/
static void icmp6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info,
const struct in6_addr *force_saddr)
{
struct net *net = dev_net(skb->dev);
struct inet6_dev *idev = NULL;
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct sock *sk;
struct ipv6_pinfo *np;
const struct in6_addr *saddr = NULL;
struct dst_entry *dst;
struct icmp6hdr tmp_hdr;
struct flowi6 fl6;
struct icmpv6_msg msg;
struct sockcm_cookie sockc_unused = {0};
struct ipcm6_cookie ipc6;
int iif = 0;
int addr_type = 0;
int len;
int err = 0;
u32 mark = IP6_REPLY_MARK(net, skb->mark);
if ((u8 *)hdr < skb->head ||
(skb_network_header(skb) + sizeof(*hdr)) > skb_tail_pointer(skb))
return;
/*
* Make sure we respect the rules
* i.e. RFC 1885 2.4(e)
* Rule (e.1) is enforced by not using icmp6_send
* in any code that processes icmp errors.
*/
addr_type = ipv6_addr_type(&hdr->daddr);
if (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0) ||
ipv6_chk_acast_addr_src(net, skb->dev, &hdr->daddr))
saddr = &hdr->daddr;
/*
* Dest addr check
*/
if (addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST) {
if (type != ICMPV6_PKT_TOOBIG &&
!(type == ICMPV6_PARAMPROB &&
code == ICMPV6_UNK_OPTION &&
(opt_unrec(skb, info))))
return;
saddr = NULL;
}
addr_type = ipv6_addr_type(&hdr->saddr);
/*
* Source addr check
*/
if (__ipv6_addr_needs_scope_id(addr_type))
iif = skb->dev->ifindex;
else
iif = l3mdev_master_ifindex(skb_dst(skb)->dev);
/*
* Must not send error if the source does not uniquely
* identify a single node (RFC2463 Section 2.4).
* We check unspecified / multicast addresses here,
* and anycast addresses will be checked later.
*/
if ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) {
net_dbg_ratelimited("icmp6_send: addr_any/mcast source [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
return;
}
/*
* Never answer to a ICMP packet.
*/
if (is_ineligible(skb)) {
net_dbg_ratelimited("icmp6_send: no reply to icmp error [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
return;
}
mip6_addr_swap(skb);
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_ICMPV6;
fl6.daddr = hdr->saddr;
if (force_saddr)
saddr = force_saddr;
if (saddr)
fl6.saddr = *saddr;
fl6.flowi6_mark = mark;
fl6.flowi6_oif = iif;
fl6.fl6_icmp_type = type;
fl6.fl6_icmp_code = code;
security_skb_classify_flow(skb, flowi6_to_flowi(&fl6));
sk = icmpv6_xmit_lock(net);
if (!sk)
return;
sk->sk_mark = mark;
np = inet6_sk(sk);
if (!icmpv6_xrlim_allow(sk, type, &fl6))
goto out;
tmp_hdr.icmp6_type = type;
tmp_hdr.icmp6_code = code;
tmp_hdr.icmp6_cksum = 0;
tmp_hdr.icmp6_pointer = htonl(info);
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;
ipc6.tclass = np->tclass;
fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);
dst = icmpv6_route_lookup(net, skb, sk, &fl6);
if (IS_ERR(dst))
goto out;
ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
ipc6.dontfrag = np->dontfrag;
ipc6.opt = NULL;
msg.skb = skb;
msg.offset = skb_network_offset(skb);
msg.type = type;
len = skb->len - msg.offset;
len = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(struct icmp6hdr));
if (len < 0) {
net_dbg_ratelimited("icmp: len problem [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
goto out_dst_release;
}
rcu_read_lock();
idev = __in6_dev_get(skb->dev);
err = ip6_append_data(sk, icmpv6_getfrag, &msg,
len + sizeof(struct icmp6hdr),
sizeof(struct icmp6hdr),
&ipc6, &fl6, (struct rt6_info *)dst,
MSG_DONTWAIT, &sockc_unused);
if (err) {
ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS);
ip6_flush_pending_frames(sk);
} else {
err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,
len + sizeof(struct icmp6hdr));
}
rcu_read_unlock();
out_dst_release:
dst_release(dst);
out:
icmpv6_xmit_unlock(sk);
}
/* Slightly more convenient version of icmp6_send.
*/
void icmpv6_param_prob(struct sk_buff *skb, u8 code, int pos)
{
icmp6_send(skb, ICMPV6_PARAMPROB, code, pos, NULL);
kfree_skb(skb);
}
/* Generate icmpv6 with type/code ICMPV6_DEST_UNREACH/ICMPV6_ADDR_UNREACH
* if sufficient data bytes are available
* @nhs is the size of the tunnel header(s) :
* Either an IPv4 header for SIT encap
* an IPv4 header + GRE header for GRE encap
*/
int ip6_err_gen_icmpv6_unreach(struct sk_buff *skb, int nhs, int type,
unsigned int data_len)
{
struct in6_addr temp_saddr;
struct rt6_info *rt;
struct sk_buff *skb2;
u32 info = 0;
if (!pskb_may_pull(skb, nhs + sizeof(struct ipv6hdr) + 8))
return 1;
/* RFC 4884 (partial) support for ICMP extensions */
if (data_len < 128 || (data_len & 7) || skb->len < data_len)
data_len = 0;
skb2 = data_len ? skb_copy(skb, GFP_ATOMIC) : skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return 1;
skb_dst_drop(skb2);
skb_pull(skb2, nhs);
skb_reset_network_header(skb2);
rt = rt6_lookup(dev_net(skb->dev), &ipv6_hdr(skb2)->saddr, NULL, 0, 0);
if (rt && rt->dst.dev)
skb2->dev = rt->dst.dev;
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &temp_saddr);
if (data_len) {
/* RFC 4884 (partial) support :
* insert 0 padding at the end, before the extensions
*/
__skb_push(skb2, nhs);
skb_reset_network_header(skb2);
memmove(skb2->data, skb2->data + nhs, data_len - nhs);
memset(skb2->data + data_len - nhs, 0, nhs);
/* RFC 4884 4.5 : Length is measured in 64-bit words,
* and stored in reserved[0]
*/
info = (data_len/8) << 24;
}
if (type == ICMP_TIME_EXCEEDED)
icmp6_send(skb2, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT,
info, &temp_saddr);
else
icmp6_send(skb2, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH,
info, &temp_saddr);
if (rt)
ip6_rt_put(rt);
kfree_skb(skb2);
return 0;
}
EXPORT_SYMBOL(ip6_err_gen_icmpv6_unreach);
static void icmpv6_echo_reply(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sock *sk;
struct inet6_dev *idev;
struct ipv6_pinfo *np;
const struct in6_addr *saddr = NULL;
struct icmp6hdr *icmph = icmp6_hdr(skb);
struct icmp6hdr tmp_hdr;
struct flowi6 fl6;
struct icmpv6_msg msg;
struct dst_entry *dst;
struct ipcm6_cookie ipc6;
int err = 0;
u32 mark = IP6_REPLY_MARK(net, skb->mark);
struct sockcm_cookie sockc_unused = {0};
saddr = &ipv6_hdr(skb)->daddr;
if (!ipv6_unicast_destination(skb) &&
!(net->ipv6.sysctl.anycast_src_echo_reply &&
ipv6_anycast_destination(skb_dst(skb), saddr)))
saddr = NULL;
memcpy(&tmp_hdr, icmph, sizeof(tmp_hdr));
tmp_hdr.icmp6_type = ICMPV6_ECHO_REPLY;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_ICMPV6;
fl6.daddr = ipv6_hdr(skb)->saddr;
if (saddr)
fl6.saddr = *saddr;
fl6.flowi6_oif = skb->dev->ifindex;
fl6.fl6_icmp_type = ICMPV6_ECHO_REPLY;
fl6.flowi6_mark = mark;
security_skb_classify_flow(skb, flowi6_to_flowi(&fl6));
sk = icmpv6_xmit_lock(net);
if (!sk)
return;
sk->sk_mark = mark;
np = inet6_sk(sk);
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;
err = ip6_dst_lookup(net, sk, &dst, &fl6);
if (err)
goto out;
dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), sk, 0);
if (IS_ERR(dst))
goto out;
idev = __in6_dev_get(skb->dev);
msg.skb = skb;
msg.offset = 0;
msg.type = ICMPV6_ECHO_REPLY;
ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
ipc6.tclass = ipv6_get_dsfield(ipv6_hdr(skb));
ipc6.dontfrag = np->dontfrag;
ipc6.opt = NULL;
err = ip6_append_data(sk, icmpv6_getfrag, &msg, skb->len + sizeof(struct icmp6hdr),
sizeof(struct icmp6hdr), &ipc6, &fl6,
(struct rt6_info *)dst, MSG_DONTWAIT,
&sockc_unused);
if (err) {
__ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS);
ip6_flush_pending_frames(sk);
} else {
err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,
skb->len + sizeof(struct icmp6hdr));
}
dst_release(dst);
out:
icmpv6_xmit_unlock(sk);
}
void icmpv6_notify(struct sk_buff *skb, u8 type, u8 code, __be32 info)
{
const struct inet6_protocol *ipprot;
int inner_offset;
__be16 frag_off;
u8 nexthdr;
struct net *net = dev_net(skb->dev);
if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
goto out;
nexthdr = ((struct ipv6hdr *)skb->data)->nexthdr;
if (ipv6_ext_hdr(nexthdr)) {
/* now skip over extension headers */
inner_offset = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr),
&nexthdr, &frag_off);
if (inner_offset < 0)
goto out;
} else {
inner_offset = sizeof(struct ipv6hdr);
}
/* Checkin header including 8 bytes of inner protocol header. */
if (!pskb_may_pull(skb, inner_offset+8))
goto out;
/* BUGGG_FUTURE: we should try to parse exthdrs in this packet.
Without this we will not able f.e. to make source routed
pmtu discovery.
Corresponding argument (opt) to notifiers is already added.
--ANK (980726)
*/
ipprot = rcu_dereference(inet6_protos[nexthdr]);
if (ipprot && ipprot->err_handler)
ipprot->err_handler(skb, NULL, type, code, inner_offset, info);
raw6_icmp_error(skb, nexthdr, type, code, inner_offset, info);
return;
out:
__ICMP6_INC_STATS(net, __in6_dev_get(skb->dev), ICMP6_MIB_INERRORS);
}
/*
* Handle icmp messages
*/
static int icmpv6_rcv(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct inet6_dev *idev = __in6_dev_get(dev);
const struct in6_addr *saddr, *daddr;
struct icmp6hdr *hdr;
u8 type;
bool success = false;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) {
struct sec_path *sp = skb_sec_path(skb);
int nh;
if (!(sp && sp->xvec[sp->len - 1]->props.flags &
XFRM_STATE_ICMP))
goto drop_no_count;
if (!pskb_may_pull(skb, sizeof(*hdr) + sizeof(struct ipv6hdr)))
goto drop_no_count;
nh = skb_network_offset(skb);
skb_set_network_header(skb, sizeof(*hdr));
if (!xfrm6_policy_check_reverse(NULL, XFRM_POLICY_IN, skb))
goto drop_no_count;
skb_set_network_header(skb, nh);
}
__ICMP6_INC_STATS(dev_net(dev), idev, ICMP6_MIB_INMSGS);
saddr = &ipv6_hdr(skb)->saddr;
daddr = &ipv6_hdr(skb)->daddr;
if (skb_checksum_validate(skb, IPPROTO_ICMPV6, ip6_compute_pseudo)) {
net_dbg_ratelimited("ICMPv6 checksum failed [%pI6c > %pI6c]\n",
saddr, daddr);
goto csum_error;
}
if (!pskb_pull(skb, sizeof(*hdr)))
goto discard_it;
hdr = icmp6_hdr(skb);
type = hdr->icmp6_type;
ICMP6MSGIN_INC_STATS(dev_net(dev), idev, type);
switch (type) {
case ICMPV6_ECHO_REQUEST:
icmpv6_echo_reply(skb);
break;
case ICMPV6_ECHO_REPLY:
success = ping_rcv(skb);
break;
case ICMPV6_PKT_TOOBIG:
/* BUGGG_FUTURE: if packet contains rthdr, we cannot update
standard destination cache. Seems, only "advanced"
destination cache will allow to solve this problem
--ANK (980726)
*/
if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
goto discard_it;
hdr = icmp6_hdr(skb);
/*
* Drop through to notify
*/
case ICMPV6_DEST_UNREACH:
case ICMPV6_TIME_EXCEED:
case ICMPV6_PARAMPROB:
icmpv6_notify(skb, type, hdr->icmp6_code, hdr->icmp6_mtu);
break;
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
ndisc_rcv(skb);
break;
case ICMPV6_MGM_QUERY:
igmp6_event_query(skb);
break;
case ICMPV6_MGM_REPORT:
igmp6_event_report(skb);
break;
case ICMPV6_MGM_REDUCTION:
case ICMPV6_NI_QUERY:
case ICMPV6_NI_REPLY:
case ICMPV6_MLD2_REPORT:
case ICMPV6_DHAAD_REQUEST:
case ICMPV6_DHAAD_REPLY:
case ICMPV6_MOBILE_PREFIX_SOL:
case ICMPV6_MOBILE_PREFIX_ADV:
break;
default:
/* informational */
if (type & ICMPV6_INFOMSG_MASK)
break;
net_dbg_ratelimited("icmpv6: msg of unknown type [%pI6c > %pI6c]\n",
saddr, daddr);
/*
* error of unknown type.
* must pass to upper level
*/
icmpv6_notify(skb, type, hdr->icmp6_code, hdr->icmp6_mtu);
}
/* until the v6 path can be better sorted assume failure and
* preserve the status quo behaviour for the rest of the paths to here
*/
if (success)
consume_skb(skb);
else
kfree_skb(skb);
return 0;
csum_error:
__ICMP6_INC_STATS(dev_net(dev), idev, ICMP6_MIB_CSUMERRORS);
discard_it:
__ICMP6_INC_STATS(dev_net(dev), idev, ICMP6_MIB_INERRORS);
drop_no_count:
kfree_skb(skb);
return 0;
}
void icmpv6_flow_init(struct sock *sk, struct flowi6 *fl6,
u8 type,
const struct in6_addr *saddr,
const struct in6_addr *daddr,
int oif)
{
memset(fl6, 0, sizeof(*fl6));
fl6->saddr = *saddr;
fl6->daddr = *daddr;
fl6->flowi6_proto = IPPROTO_ICMPV6;
fl6->fl6_icmp_type = type;
fl6->fl6_icmp_code = 0;
fl6->flowi6_oif = oif;
security_sk_classify_flow(sk, flowi6_to_flowi(fl6));
}
static int __net_init icmpv6_sk_init(struct net *net)
{
struct sock *sk;
int err, i, j;
net->ipv6.icmp_sk =
kzalloc(nr_cpu_ids * sizeof(struct sock *), GFP_KERNEL);
if (!net->ipv6.icmp_sk)
return -ENOMEM;
for_each_possible_cpu(i) {
err = inet_ctl_sock_create(&sk, PF_INET6,
SOCK_RAW, IPPROTO_ICMPV6, net);
if (err < 0) {
pr_err("Failed to initialize the ICMP6 control socket (err %d)\n",
err);
goto fail;
}
net->ipv6.icmp_sk[i] = sk;
/* Enough space for 2 64K ICMP packets, including
* sk_buff struct overhead.
*/
sk->sk_sndbuf = 2 * SKB_TRUESIZE(64 * 1024);
}
return 0;
fail:
for (j = 0; j < i; j++)
inet_ctl_sock_destroy(net->ipv6.icmp_sk[j]);
kfree(net->ipv6.icmp_sk);
return err;
}
static void __net_exit icmpv6_sk_exit(struct net *net)
{
int i;
for_each_possible_cpu(i) {
inet_ctl_sock_destroy(net->ipv6.icmp_sk[i]);
}
kfree(net->ipv6.icmp_sk);
}
static struct pernet_operations icmpv6_sk_ops = {
.init = icmpv6_sk_init,
.exit = icmpv6_sk_exit,
};
int __init icmpv6_init(void)
{
int err;
err = register_pernet_subsys(&icmpv6_sk_ops);
if (err < 0)
return err;
err = -EAGAIN;
if (inet6_add_protocol(&icmpv6_protocol, IPPROTO_ICMPV6) < 0)
goto fail;
err = inet6_register_icmp_sender(icmp6_send);
if (err)
goto sender_reg_err;
return 0;
sender_reg_err:
inet6_del_protocol(&icmpv6_protocol, IPPROTO_ICMPV6);
fail:
pr_err("Failed to register ICMP6 protocol\n");
unregister_pernet_subsys(&icmpv6_sk_ops);
return err;
}
void icmpv6_cleanup(void)
{
inet6_unregister_icmp_sender(icmp6_send);
unregister_pernet_subsys(&icmpv6_sk_ops);
inet6_del_protocol(&icmpv6_protocol, IPPROTO_ICMPV6);
}
static const struct icmp6_err {
int err;
int fatal;
} tab_unreach[] = {
{ /* NOROUTE */
.err = ENETUNREACH,
.fatal = 0,
},
{ /* ADM_PROHIBITED */
.err = EACCES,
.fatal = 1,
},
{ /* Was NOT_NEIGHBOUR, now reserved */
.err = EHOSTUNREACH,
.fatal = 0,
},
{ /* ADDR_UNREACH */
.err = EHOSTUNREACH,
.fatal = 0,
},
{ /* PORT_UNREACH */
.err = ECONNREFUSED,
.fatal = 1,
},
{ /* POLICY_FAIL */
.err = EACCES,
.fatal = 1,
},
{ /* REJECT_ROUTE */
.err = EACCES,
.fatal = 1,
},
};
int icmpv6_err_convert(u8 type, u8 code, int *err)
{
int fatal = 0;
*err = EPROTO;
switch (type) {
case ICMPV6_DEST_UNREACH:
fatal = 1;
if (code < ARRAY_SIZE(tab_unreach)) {
*err = tab_unreach[code].err;
fatal = tab_unreach[code].fatal;
}
break;
case ICMPV6_PKT_TOOBIG:
*err = EMSGSIZE;
break;
case ICMPV6_PARAMPROB:
*err = EPROTO;
fatal = 1;
break;
case ICMPV6_TIME_EXCEED:
*err = EHOSTUNREACH;
break;
}
return fatal;
}
EXPORT_SYMBOL(icmpv6_err_convert);
#ifdef CONFIG_SYSCTL
static struct ctl_table ipv6_icmp_table_template[] = {
{
.procname = "ratelimit",
.data = &init_net.ipv6.sysctl.icmpv6_time,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{ },
};
struct ctl_table * __net_init ipv6_icmp_sysctl_init(struct net *net)
{
struct ctl_table *table;
table = kmemdup(ipv6_icmp_table_template,
sizeof(ipv6_icmp_table_template),
GFP_KERNEL);
if (table)
table[0].data = &net->ipv6.sysctl.icmpv6_time;
return table;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5511_0 |
crossvul-cpp_data_bad_3141_0 | /*
* linux/ipc/shm.c
* Copyright (C) 1992, 1993 Krishna Balasubramanian
* Many improvements/fixes by Bruno Haible.
* Replaced `struct shm_desc' by `struct vm_area_struct', July 1994.
* Fixed the shm swap deallocation (shm_unuse()), August 1998 Andrea Arcangeli.
*
* /proc/sysvipc/shm support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
* BIGMEM support, Andrea Arcangeli <andrea@suse.de>
* SMP thread shm, Jean-Luc Boyard <jean-luc.boyard@siemens.fr>
* HIGHMEM support, Ingo Molnar <mingo@redhat.com>
* Make shmmax, shmall, shmmni sysctl'able, Christoph Rohland <cr@sap.com>
* Shared /dev/zero support, Kanoj Sarcar <kanoj@sgi.com>
* Move the mm functionality over to mm/shmem.c, Christoph Rohland <cr@sap.com>
*
* support for audit of ipc object properties and permission changes
* Dustin Kirkland <dustin.kirkland@us.ibm.com>
*
* namespaces support
* OpenVZ, SWsoft Inc.
* Pavel Emelianov <xemul@openvz.org>
*
* Better ipc lock (kern_ipc_perm.lock) handling
* Davidlohr Bueso <davidlohr.bueso@hp.com>, June 2013.
*/
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/shm.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/mman.h>
#include <linux/shmem_fs.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/ptrace.h>
#include <linux/seq_file.h>
#include <linux/rwsem.h>
#include <linux/nsproxy.h>
#include <linux/mount.h>
#include <linux/ipc_namespace.h>
#include <linux/uaccess.h>
#include "util.h"
struct shm_file_data {
int id;
struct ipc_namespace *ns;
struct file *file;
const struct vm_operations_struct *vm_ops;
};
#define shm_file_data(file) (*((struct shm_file_data **)&(file)->private_data))
static const struct file_operations shm_file_operations;
static const struct vm_operations_struct shm_vm_ops;
#define shm_ids(ns) ((ns)->ids[IPC_SHM_IDS])
#define shm_unlock(shp) \
ipc_unlock(&(shp)->shm_perm)
static int newseg(struct ipc_namespace *, struct ipc_params *);
static void shm_open(struct vm_area_struct *vma);
static void shm_close(struct vm_area_struct *vma);
static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp);
#ifdef CONFIG_PROC_FS
static int sysvipc_shm_proc_show(struct seq_file *s, void *it);
#endif
void shm_init_ns(struct ipc_namespace *ns)
{
ns->shm_ctlmax = SHMMAX;
ns->shm_ctlall = SHMALL;
ns->shm_ctlmni = SHMMNI;
ns->shm_rmid_forced = 0;
ns->shm_tot = 0;
ipc_init_ids(&shm_ids(ns));
}
/*
* Called with shm_ids.rwsem (writer) and the shp structure locked.
* Only shm_ids.rwsem remains locked on exit.
*/
static void do_shm_rmid(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_nattch) {
shp->shm_perm.mode |= SHM_DEST;
/* Do not find it any more */
shp->shm_perm.key = IPC_PRIVATE;
shm_unlock(shp);
} else
shm_destroy(ns, shp);
}
#ifdef CONFIG_IPC_NS
void shm_exit_ns(struct ipc_namespace *ns)
{
free_ipcs(ns, &shm_ids(ns), do_shm_rmid);
idr_destroy(&ns->ids[IPC_SHM_IDS].ipcs_idr);
}
#endif
static int __init ipc_ns_init(void)
{
shm_init_ns(&init_ipc_ns);
return 0;
}
pure_initcall(ipc_ns_init);
void __init shm_init(void)
{
ipc_init_proc_interface("sysvipc/shm",
#if BITS_PER_LONG <= 32
" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n",
#else
" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n",
#endif
IPC_SHM_IDS, sysvipc_shm_proc_show);
}
static inline struct shmid_kernel *shm_obtain_object(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
static inline struct shmid_kernel *shm_obtain_object_check(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
/*
* shm_lock_(check_) routines are called in the paths where the rwsem
* is not necessarily held.
*/
static inline struct shmid_kernel *shm_lock(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_lock(&shm_ids(ns), id);
/*
* Callers of shm_lock() must validate the status of the returned ipc
* object pointer (as returned by ipc_lock()), and error out as
* appropriate.
*/
if (IS_ERR(ipcp))
return (void *)ipcp;
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
static inline void shm_lock_by_ptr(struct shmid_kernel *ipcp)
{
rcu_read_lock();
ipc_lock_object(&ipcp->shm_perm);
}
static void shm_rcu_free(struct rcu_head *head)
{
struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
struct shmid_kernel *shp = ipc_rcu_to_struct(p);
security_shm_free(shp);
ipc_rcu_free(head);
}
static inline void shm_rmid(struct ipc_namespace *ns, struct shmid_kernel *s)
{
list_del(&s->shm_clist);
ipc_rmid(&shm_ids(ns), &s->shm_perm);
}
static int __shm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct shmid_kernel *shp;
shp = shm_lock(sfd->ns, sfd->id);
if (IS_ERR(shp))
return PTR_ERR(shp);
shp->shm_atim = get_seconds();
shp->shm_lprid = task_tgid_vnr(current);
shp->shm_nattch++;
shm_unlock(shp);
return 0;
}
/* This is called by fork, once for every shm attach. */
static void shm_open(struct vm_area_struct *vma)
{
int err = __shm_open(vma);
/*
* We raced in the idr lookup or with shm_destroy().
* Either way, the ID is busted.
*/
WARN_ON_ONCE(err);
}
/*
* shm_destroy - free the struct shmid_kernel
*
* @ns: namespace
* @shp: struct to free
*
* It has to be called with shp and shm_ids.rwsem (writer) locked,
* but returns with shp unlocked and freed.
*/
static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
struct file *shm_file;
shm_file = shp->shm_file;
shp->shm_file = NULL;
ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;
shm_rmid(ns, shp);
shm_unlock(shp);
if (!is_file_hugepages(shm_file))
shmem_lock(shm_file, 0, shp->mlock_user);
else if (shp->mlock_user)
user_shm_unlock(i_size_read(file_inode(shm_file)),
shp->mlock_user);
fput(shm_file);
ipc_rcu_putref(shp, shm_rcu_free);
}
/*
* shm_may_destroy - identifies whether shm segment should be destroyed now
*
* Returns true if and only if there are no active users of the segment and
* one of the following is true:
*
* 1) shmctl(id, IPC_RMID, NULL) was called for this shp
*
* 2) sysctl kernel.shm_rmid_forced is set to 1.
*/
static bool shm_may_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
return (shp->shm_nattch == 0) &&
(ns->shm_rmid_forced ||
(shp->shm_perm.mode & SHM_DEST));
}
/*
* remove the attach descriptor vma.
* free memory for segment if it is marked destroyed.
* The descriptor has already been removed from the current->mm->mmap list
* and will later be kfree()d.
*/
static void shm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct shmid_kernel *shp;
struct ipc_namespace *ns = sfd->ns;
down_write(&shm_ids(ns).rwsem);
/* remove from the list of attaches of the shm segment */
shp = shm_lock(ns, sfd->id);
/*
* We raced in the idr lookup or with shm_destroy().
* Either way, the ID is busted.
*/
if (WARN_ON_ONCE(IS_ERR(shp)))
goto done; /* no-op */
shp->shm_lprid = task_tgid_vnr(current);
shp->shm_dtim = get_seconds();
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
done:
up_write(&shm_ids(ns).rwsem);
}
/* Called with ns->shm_ids(ns).rwsem locked */
static int shm_try_destroy_orphaned(int id, void *p, void *data)
{
struct ipc_namespace *ns = data;
struct kern_ipc_perm *ipcp = p;
struct shmid_kernel *shp = container_of(ipcp, struct shmid_kernel, shm_perm);
/*
* We want to destroy segments without users and with already
* exit'ed originating process.
*
* As shp->* are changed under rwsem, it's safe to skip shp locking.
*/
if (shp->shm_creator != NULL)
return 0;
if (shm_may_destroy(ns, shp)) {
shm_lock_by_ptr(shp);
shm_destroy(ns, shp);
}
return 0;
}
void shm_destroy_orphaned(struct ipc_namespace *ns)
{
down_write(&shm_ids(ns).rwsem);
if (shm_ids(ns).in_use)
idr_for_each(&shm_ids(ns).ipcs_idr, &shm_try_destroy_orphaned, ns);
up_write(&shm_ids(ns).rwsem);
}
/* Locking assumes this will only be called with task == current */
void exit_shm(struct task_struct *task)
{
struct ipc_namespace *ns = task->nsproxy->ipc_ns;
struct shmid_kernel *shp, *n;
if (list_empty(&task->sysvshm.shm_clist))
return;
/*
* If kernel.shm_rmid_forced is not set then only keep track of
* which shmids are orphaned, so that a later set of the sysctl
* can clean them up.
*/
if (!ns->shm_rmid_forced) {
down_read(&shm_ids(ns).rwsem);
list_for_each_entry(shp, &task->sysvshm.shm_clist, shm_clist)
shp->shm_creator = NULL;
/*
* Only under read lock but we are only called on current
* so no entry on the list will be shared.
*/
list_del(&task->sysvshm.shm_clist);
up_read(&shm_ids(ns).rwsem);
return;
}
/*
* Destroy all already created segments, that were not yet mapped,
* and mark any mapped as orphan to cover the sysctl toggling.
* Destroy is skipped if shm_may_destroy() returns false.
*/
down_write(&shm_ids(ns).rwsem);
list_for_each_entry_safe(shp, n, &task->sysvshm.shm_clist, shm_clist) {
shp->shm_creator = NULL;
if (shm_may_destroy(ns, shp)) {
shm_lock_by_ptr(shp);
shm_destroy(ns, shp);
}
}
/* Remove the list head from any segments still attached. */
list_del(&task->sysvshm.shm_clist);
up_write(&shm_ids(ns).rwsem);
}
static int shm_fault(struct vm_fault *vmf)
{
struct file *file = vmf->vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
return sfd->vm_ops->fault(vmf);
}
#ifdef CONFIG_NUMA
static int shm_set_policy(struct vm_area_struct *vma, struct mempolicy *new)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
int err = 0;
if (sfd->vm_ops->set_policy)
err = sfd->vm_ops->set_policy(vma, new);
return err;
}
static struct mempolicy *shm_get_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct mempolicy *pol = NULL;
if (sfd->vm_ops->get_policy)
pol = sfd->vm_ops->get_policy(vma, addr);
else if (vma->vm_policy)
pol = vma->vm_policy;
return pol;
}
#endif
static int shm_mmap(struct file *file, struct vm_area_struct *vma)
{
struct shm_file_data *sfd = shm_file_data(file);
int ret;
/*
* In case of remap_file_pages() emulation, the file can represent
* removed IPC ID: propogate shm_lock() error to caller.
*/
ret = __shm_open(vma);
if (ret)
return ret;
ret = sfd->file->f_op->mmap(sfd->file, vma);
if (ret) {
shm_close(vma);
return ret;
}
sfd->vm_ops = vma->vm_ops;
#ifdef CONFIG_MMU
WARN_ON(!sfd->vm_ops->fault);
#endif
vma->vm_ops = &shm_vm_ops;
return 0;
}
static int shm_release(struct inode *ino, struct file *file)
{
struct shm_file_data *sfd = shm_file_data(file);
put_ipc_ns(sfd->ns);
shm_file_data(file) = NULL;
kfree(sfd);
return 0;
}
static int shm_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
struct shm_file_data *sfd = shm_file_data(file);
if (!sfd->file->f_op->fsync)
return -EINVAL;
return sfd->file->f_op->fsync(sfd->file, start, end, datasync);
}
static long shm_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct shm_file_data *sfd = shm_file_data(file);
if (!sfd->file->f_op->fallocate)
return -EOPNOTSUPP;
return sfd->file->f_op->fallocate(file, mode, offset, len);
}
static unsigned long shm_get_unmapped_area(struct file *file,
unsigned long addr, unsigned long len, unsigned long pgoff,
unsigned long flags)
{
struct shm_file_data *sfd = shm_file_data(file);
return sfd->file->f_op->get_unmapped_area(sfd->file, addr, len,
pgoff, flags);
}
static const struct file_operations shm_file_operations = {
.mmap = shm_mmap,
.fsync = shm_fsync,
.release = shm_release,
.get_unmapped_area = shm_get_unmapped_area,
.llseek = noop_llseek,
.fallocate = shm_fallocate,
};
/*
* shm_file_operations_huge is now identical to shm_file_operations,
* but we keep it distinct for the sake of is_file_shm_hugepages().
*/
static const struct file_operations shm_file_operations_huge = {
.mmap = shm_mmap,
.fsync = shm_fsync,
.release = shm_release,
.get_unmapped_area = shm_get_unmapped_area,
.llseek = noop_llseek,
.fallocate = shm_fallocate,
};
bool is_file_shm_hugepages(struct file *file)
{
return file->f_op == &shm_file_operations_huge;
}
static const struct vm_operations_struct shm_vm_ops = {
.open = shm_open, /* callback for a new vm-area open */
.close = shm_close, /* callback for when the vm-area is released */
.fault = shm_fault,
#if defined(CONFIG_NUMA)
.set_policy = shm_set_policy,
.get_policy = shm_get_policy,
#endif
};
/**
* newseg - Create a new shared memory segment
* @ns: namespace
* @params: ptr to the structure that contains key, size and shmflg
*
* Called with shm_ids.rwsem held as a writer.
*/
static int newseg(struct ipc_namespace *ns, struct ipc_params *params)
{
key_t key = params->key;
int shmflg = params->flg;
size_t size = params->u.size;
int error;
struct shmid_kernel *shp;
size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
struct file *file;
char name[13];
int id;
vm_flags_t acctflag = 0;
if (size < SHMMIN || size > ns->shm_ctlmax)
return -EINVAL;
if (numpages << PAGE_SHIFT < size)
return -ENOSPC;
if (ns->shm_tot + numpages < ns->shm_tot ||
ns->shm_tot + numpages > ns->shm_ctlall)
return -ENOSPC;
shp = ipc_rcu_alloc(sizeof(*shp));
if (!shp)
return -ENOMEM;
shp->shm_perm.key = key;
shp->shm_perm.mode = (shmflg & S_IRWXUGO);
shp->mlock_user = NULL;
shp->shm_perm.security = NULL;
error = security_shm_alloc(shp);
if (error) {
ipc_rcu_putref(shp, ipc_rcu_free);
return error;
}
sprintf(name, "SYSV%08x", key);
if (shmflg & SHM_HUGETLB) {
struct hstate *hs;
size_t hugesize;
hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
if (!hs) {
error = -EINVAL;
goto no_file;
}
hugesize = ALIGN(size, huge_page_size(hs));
/* hugetlb_file_setup applies strict accounting */
if (shmflg & SHM_NORESERVE)
acctflag = VM_NORESERVE;
file = hugetlb_file_setup(name, hugesize, acctflag,
&shp->mlock_user, HUGETLB_SHMFS_INODE,
(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
} else {
/*
* Do not allow no accounting for OVERCOMMIT_NEVER, even
* if it's asked for.
*/
if ((shmflg & SHM_NORESERVE) &&
sysctl_overcommit_memory != OVERCOMMIT_NEVER)
acctflag = VM_NORESERVE;
file = shmem_kernel_file_setup(name, size, acctflag);
}
error = PTR_ERR(file);
if (IS_ERR(file))
goto no_file;
shp->shm_cprid = task_tgid_vnr(current);
shp->shm_lprid = 0;
shp->shm_atim = shp->shm_dtim = 0;
shp->shm_ctim = get_seconds();
shp->shm_segsz = size;
shp->shm_nattch = 0;
shp->shm_file = file;
shp->shm_creator = current;
id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);
if (id < 0) {
error = id;
goto no_id;
}
list_add(&shp->shm_clist, ¤t->sysvshm.shm_clist);
/*
* shmid gets reported as "inode#" in /proc/pid/maps.
* proc-ps tools use this. Changing this will break them.
*/
file_inode(file)->i_ino = shp->shm_perm.id;
ns->shm_tot += numpages;
error = shp->shm_perm.id;
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
return error;
no_id:
if (is_file_hugepages(file) && shp->mlock_user)
user_shm_unlock(size, shp->mlock_user);
fput(file);
no_file:
ipc_rcu_putref(shp, shm_rcu_free);
return error;
}
/*
* Called with shm_ids.rwsem and ipcp locked.
*/
static inline int shm_security(struct kern_ipc_perm *ipcp, int shmflg)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
return security_shm_associate(shp, shmflg);
}
/*
* Called with shm_ids.rwsem and ipcp locked.
*/
static inline int shm_more_checks(struct kern_ipc_perm *ipcp,
struct ipc_params *params)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_segsz < params->u.size)
return -EINVAL;
return 0;
}
SYSCALL_DEFINE3(shmget, key_t, key, size_t, size, int, shmflg)
{
struct ipc_namespace *ns;
static const struct ipc_ops shm_ops = {
.getnew = newseg,
.associate = shm_security,
.more_checks = shm_more_checks,
};
struct ipc_params shm_params;
ns = current->nsproxy->ipc_ns;
shm_params.key = key;
shm_params.flg = shmflg;
shm_params.u.size = size;
return ipcget(ns, &shm_ids(ns), &shm_ops, &shm_params);
}
static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version)
{
switch (version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shmid_ds out;
memset(&out, 0, sizeof(out));
ipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm);
out.shm_segsz = in->shm_segsz;
out.shm_atime = in->shm_atime;
out.shm_dtime = in->shm_dtime;
out.shm_ctime = in->shm_ctime;
out.shm_cpid = in->shm_cpid;
out.shm_lpid = in->shm_lpid;
out.shm_nattch = in->shm_nattch;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
static inline unsigned long
copy_shmid_from_user(struct shmid64_ds *out, void __user *buf, int version)
{
switch (version) {
case IPC_64:
if (copy_from_user(out, buf, sizeof(*out)))
return -EFAULT;
return 0;
case IPC_OLD:
{
struct shmid_ds tbuf_old;
if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
return -EFAULT;
out->shm_perm.uid = tbuf_old.shm_perm.uid;
out->shm_perm.gid = tbuf_old.shm_perm.gid;
out->shm_perm.mode = tbuf_old.shm_perm.mode;
return 0;
}
default:
return -EINVAL;
}
}
static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminfo64 *in, int version)
{
switch (version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shminfo out;
if (in->shmmax > INT_MAX)
out.shmmax = INT_MAX;
else
out.shmmax = (int)in->shmmax;
out.shmmin = in->shmmin;
out.shmmni = in->shmmni;
out.shmseg = in->shmseg;
out.shmall = in->shmall;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
/*
* Calculate and add used RSS and swap pages of a shm.
* Called with shm_ids.rwsem held as a reader
*/
static void shm_add_rss_swap(struct shmid_kernel *shp,
unsigned long *rss_add, unsigned long *swp_add)
{
struct inode *inode;
inode = file_inode(shp->shm_file);
if (is_file_hugepages(shp->shm_file)) {
struct address_space *mapping = inode->i_mapping;
struct hstate *h = hstate_file(shp->shm_file);
*rss_add += pages_per_huge_page(h) * mapping->nrpages;
} else {
#ifdef CONFIG_SHMEM
struct shmem_inode_info *info = SHMEM_I(inode);
spin_lock_irq(&info->lock);
*rss_add += inode->i_mapping->nrpages;
*swp_add += info->swapped;
spin_unlock_irq(&info->lock);
#else
*rss_add += inode->i_mapping->nrpages;
#endif
}
}
/*
* Called with shm_ids.rwsem held as a reader
*/
static void shm_get_stat(struct ipc_namespace *ns, unsigned long *rss,
unsigned long *swp)
{
int next_id;
int total, in_use;
*rss = 0;
*swp = 0;
in_use = shm_ids(ns).in_use;
for (total = 0, next_id = 0; total < in_use; next_id++) {
struct kern_ipc_perm *ipc;
struct shmid_kernel *shp;
ipc = idr_find(&shm_ids(ns).ipcs_idr, next_id);
if (ipc == NULL)
continue;
shp = container_of(ipc, struct shmid_kernel, shm_perm);
shm_add_rss_swap(shp, rss, swp);
total++;
}
}
/*
* This function handles some shmctl commands which require the rwsem
* to be held in write mode.
* NOTE: no locks must be held, the rwsem is taken inside this function.
*/
static int shmctl_down(struct ipc_namespace *ns, int shmid, int cmd,
struct shmid_ds __user *buf, int version)
{
struct kern_ipc_perm *ipcp;
struct shmid64_ds shmid64;
struct shmid_kernel *shp;
int err;
if (cmd == IPC_SET) {
if (copy_shmid_from_user(&shmid64, buf, version))
return -EFAULT;
}
down_write(&shm_ids(ns).rwsem);
rcu_read_lock();
ipcp = ipcctl_pre_down_nolock(ns, &shm_ids(ns), shmid, cmd,
&shmid64.shm_perm, 0);
if (IS_ERR(ipcp)) {
err = PTR_ERR(ipcp);
goto out_unlock1;
}
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
switch (cmd) {
case IPC_RMID:
ipc_lock_object(&shp->shm_perm);
/* do_shm_rmid unlocks the ipc object and rcu */
do_shm_rmid(ns, ipcp);
goto out_up;
case IPC_SET:
ipc_lock_object(&shp->shm_perm);
err = ipc_update_perm(&shmid64.shm_perm, ipcp);
if (err)
goto out_unlock0;
shp->shm_ctim = get_seconds();
break;
default:
err = -EINVAL;
goto out_unlock1;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
out_up:
up_write(&shm_ids(ns).rwsem);
return err;
}
static int shmctl_nolock(struct ipc_namespace *ns, int shmid,
int cmd, int version, void __user *buf)
{
int err;
struct shmid_kernel *shp;
/* preliminary security checks for *_INFO */
if (cmd == IPC_INFO || cmd == SHM_INFO) {
err = security_shm_shmctl(NULL, cmd);
if (err)
return err;
}
switch (cmd) {
case IPC_INFO:
{
struct shminfo64 shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmmni = shminfo.shmseg = ns->shm_ctlmni;
shminfo.shmmax = ns->shm_ctlmax;
shminfo.shmall = ns->shm_ctlall;
shminfo.shmmin = SHMMIN;
if (copy_shminfo_to_user(buf, &shminfo, version))
return -EFAULT;
down_read(&shm_ids(ns).rwsem);
err = ipc_get_maxid(&shm_ids(ns));
up_read(&shm_ids(ns).rwsem);
if (err < 0)
err = 0;
goto out;
}
case SHM_INFO:
{
struct shm_info shm_info;
memset(&shm_info, 0, sizeof(shm_info));
down_read(&shm_ids(ns).rwsem);
shm_info.used_ids = shm_ids(ns).in_use;
shm_get_stat(ns, &shm_info.shm_rss, &shm_info.shm_swp);
shm_info.shm_tot = ns->shm_tot;
shm_info.swap_attempts = 0;
shm_info.swap_successes = 0;
err = ipc_get_maxid(&shm_ids(ns));
up_read(&shm_ids(ns).rwsem);
if (copy_to_user(buf, &shm_info, sizeof(shm_info))) {
err = -EFAULT;
goto out;
}
err = err < 0 ? 0 : err;
goto out;
}
case SHM_STAT:
case IPC_STAT:
{
struct shmid64_ds tbuf;
int result;
rcu_read_lock();
if (cmd == SHM_STAT) {
shp = shm_obtain_object(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
result = shp->shm_perm.id;
} else {
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
result = 0;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, S_IRUGO))
goto out_unlock;
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock;
memset(&tbuf, 0, sizeof(tbuf));
kernel_to_ipc64_perm(&shp->shm_perm, &tbuf.shm_perm);
tbuf.shm_segsz = shp->shm_segsz;
tbuf.shm_atime = shp->shm_atim;
tbuf.shm_dtime = shp->shm_dtim;
tbuf.shm_ctime = shp->shm_ctim;
tbuf.shm_cpid = shp->shm_cprid;
tbuf.shm_lpid = shp->shm_lprid;
tbuf.shm_nattch = shp->shm_nattch;
rcu_read_unlock();
if (copy_shmid_to_user(buf, &tbuf, version))
err = -EFAULT;
else
err = result;
goto out;
}
default:
return -EINVAL;
}
out_unlock:
rcu_read_unlock();
out:
return err;
}
SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf)
{
struct shmid_kernel *shp;
int err, version;
struct ipc_namespace *ns;
if (cmd < 0 || shmid < 0)
return -EINVAL;
version = ipc_parse_version(&cmd);
ns = current->nsproxy->ipc_ns;
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
case SHM_STAT:
case IPC_STAT:
return shmctl_nolock(ns, shmid, cmd, version, buf);
case IPC_RMID:
case IPC_SET:
return shmctl_down(ns, shmid, cmd, buf, version);
case SHM_LOCK:
case SHM_UNLOCK:
{
struct file *shm_file;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock1;
}
audit_ipc_obj(&(shp->shm_perm));
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
err = -EIDRM;
goto out_unlock0;
}
if (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) {
kuid_t euid = current_euid();
if (!uid_eq(euid, shp->shm_perm.uid) &&
!uid_eq(euid, shp->shm_perm.cuid)) {
err = -EPERM;
goto out_unlock0;
}
if (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) {
err = -EPERM;
goto out_unlock0;
}
}
shm_file = shp->shm_file;
if (is_file_hugepages(shm_file))
goto out_unlock0;
if (cmd == SHM_LOCK) {
struct user_struct *user = current_user();
err = shmem_lock(shm_file, 1, user);
if (!err && !(shp->shm_perm.mode & SHM_LOCKED)) {
shp->shm_perm.mode |= SHM_LOCKED;
shp->mlock_user = user;
}
goto out_unlock0;
}
/* SHM_UNLOCK */
if (!(shp->shm_perm.mode & SHM_LOCKED))
goto out_unlock0;
shmem_lock(shm_file, 0, shp->mlock_user);
shp->shm_perm.mode &= ~SHM_LOCKED;
shp->mlock_user = NULL;
get_file(shm_file);
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
shmem_unlock_mapping(shm_file->f_mapping);
fput(shm_file);
return err;
}
default:
return -EINVAL;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
return err;
}
/*
* Fix shmaddr, allocate descriptor, map shm, add attach descriptor to lists.
*
* NOTE! Despite the name, this is NOT a direct system call entrypoint. The
* "raddr" thing points to kernel space, and there has to be a wrapper around
* this.
*/
long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr,
unsigned long shmlba)
{
struct shmid_kernel *shp;
unsigned long addr;
unsigned long size;
struct file *file;
int err;
unsigned long flags;
unsigned long prot;
int acc_mode;
struct ipc_namespace *ns;
struct shm_file_data *sfd;
struct path path;
fmode_t f_mode;
unsigned long populate = 0;
err = -EINVAL;
if (shmid < 0)
goto out;
else if ((addr = (ulong)shmaddr)) {
if (addr & (shmlba - 1)) {
if (shmflg & SHM_RND)
addr &= ~(shmlba - 1); /* round down */
else
#ifndef __ARCH_FORCE_SHMLBA
if (addr & ~PAGE_MASK)
#endif
goto out;
}
flags = MAP_SHARED | MAP_FIXED;
} else {
if ((shmflg & SHM_REMAP))
goto out;
flags = MAP_SHARED;
}
if (shmflg & SHM_RDONLY) {
prot = PROT_READ;
acc_mode = S_IRUGO;
f_mode = FMODE_READ;
} else {
prot = PROT_READ | PROT_WRITE;
acc_mode = S_IRUGO | S_IWUGO;
f_mode = FMODE_READ | FMODE_WRITE;
}
if (shmflg & SHM_EXEC) {
prot |= PROT_EXEC;
acc_mode |= S_IXUGO;
}
/*
* We cannot rely on the fs check since SYSV IPC does have an
* additional creator id...
*/
ns = current->nsproxy->ipc_ns;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, acc_mode))
goto out_unlock;
err = security_shm_shmat(shp, shmaddr, shmflg);
if (err)
goto out_unlock;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
ipc_unlock_object(&shp->shm_perm);
err = -EIDRM;
goto out_unlock;
}
path = shp->shm_file->f_path;
path_get(&path);
shp->shm_nattch++;
size = i_size_read(d_inode(path.dentry));
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
err = -ENOMEM;
sfd = kzalloc(sizeof(*sfd), GFP_KERNEL);
if (!sfd) {
path_put(&path);
goto out_nattch;
}
file = alloc_file(&path, f_mode,
is_file_hugepages(shp->shm_file) ?
&shm_file_operations_huge :
&shm_file_operations);
err = PTR_ERR(file);
if (IS_ERR(file)) {
kfree(sfd);
path_put(&path);
goto out_nattch;
}
file->private_data = sfd;
file->f_mapping = shp->shm_file->f_mapping;
sfd->id = shp->shm_perm.id;
sfd->ns = get_ipc_ns(ns);
sfd->file = shp->shm_file;
sfd->vm_ops = NULL;
err = security_mmap_file(file, prot, flags);
if (err)
goto out_fput;
if (down_write_killable(¤t->mm->mmap_sem)) {
err = -EINTR;
goto out_fput;
}
if (addr && !(shmflg & SHM_REMAP)) {
err = -EINVAL;
if (addr + size < addr)
goto invalid;
if (find_vma_intersection(current->mm, addr, addr + size))
goto invalid;
}
addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL);
*raddr = addr;
err = 0;
if (IS_ERR_VALUE(addr))
err = (long)addr;
invalid:
up_write(¤t->mm->mmap_sem);
if (populate)
mm_populate(addr, populate);
out_fput:
fput(file);
out_nattch:
down_write(&shm_ids(ns).rwsem);
shp = shm_lock(ns, shmid);
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
up_write(&shm_ids(ns).rwsem);
return err;
out_unlock:
rcu_read_unlock();
out:
return err;
}
SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)
{
unsigned long ret;
long err;
err = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);
if (err)
return err;
force_successful_syscall_return();
return (long)ret;
}
/*
* detach and kill segment if marked destroyed.
* The work is done in shm_close.
*/
SYSCALL_DEFINE1(shmdt, char __user *, shmaddr)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long addr = (unsigned long)shmaddr;
int retval = -EINVAL;
#ifdef CONFIG_MMU
loff_t size = 0;
struct file *file;
struct vm_area_struct *next;
#endif
if (addr & ~PAGE_MASK)
return retval;
if (down_write_killable(&mm->mmap_sem))
return -EINTR;
/*
* This function tries to be smart and unmap shm segments that
* were modified by partial mlock or munmap calls:
* - It first determines the size of the shm segment that should be
* unmapped: It searches for a vma that is backed by shm and that
* started at address shmaddr. It records it's size and then unmaps
* it.
* - Then it unmaps all shm vmas that started at shmaddr and that
* are within the initially determined size and that are from the
* same shm segment from which we determined the size.
* Errors from do_munmap are ignored: the function only fails if
* it's called with invalid parameters or if it's called to unmap
* a part of a vma. Both calls in this function are for full vmas,
* the parameters are directly copied from the vma itself and always
* valid - therefore do_munmap cannot fail. (famous last words?)
*/
/*
* If it had been mremap()'d, the starting address would not
* match the usual checks anyway. So assume all vma's are
* above the starting address given.
*/
vma = find_vma(mm, addr);
#ifdef CONFIG_MMU
while (vma) {
next = vma->vm_next;
/*
* Check if the starting address would match, i.e. it's
* a fragment created by mprotect() and/or munmap(), or it
* otherwise it starts at this address with no hassles.
*/
if ((vma->vm_ops == &shm_vm_ops) &&
(vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) {
/*
* Record the file of the shm segment being
* unmapped. With mremap(), someone could place
* page from another segment but with equal offsets
* in the range we are unmapping.
*/
file = vma->vm_file;
size = i_size_read(file_inode(vma->vm_file));
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
/*
* We discovered the size of the shm segment, so
* break out of here and fall through to the next
* loop that uses the size information to stop
* searching for matching vma's.
*/
retval = 0;
vma = next;
break;
}
vma = next;
}
/*
* We need look no further than the maximum address a fragment
* could possibly have landed at. Also cast things to loff_t to
* prevent overflows and make comparisons vs. equal-width types.
*/
size = PAGE_ALIGN(size);
while (vma && (loff_t)(vma->vm_end - addr) <= size) {
next = vma->vm_next;
/* finding a matching vma now does not alter retval */
if ((vma->vm_ops == &shm_vm_ops) &&
((vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) &&
(vma->vm_file == file))
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
vma = next;
}
#else /* CONFIG_MMU */
/* under NOMMU conditions, the exact address to be destroyed must be
* given
*/
if (vma && vma->vm_start == addr && vma->vm_ops == &shm_vm_ops) {
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start, NULL);
retval = 0;
}
#endif
up_write(&mm->mmap_sem);
return retval;
}
#ifdef CONFIG_PROC_FS
static int sysvipc_shm_proc_show(struct seq_file *s, void *it)
{
struct user_namespace *user_ns = seq_user_ns(s);
struct shmid_kernel *shp = it;
unsigned long rss = 0, swp = 0;
shm_add_rss_swap(shp, &rss, &swp);
#if BITS_PER_LONG <= 32
#define SIZE_SPEC "%10lu"
#else
#define SIZE_SPEC "%21lu"
#endif
seq_printf(s,
"%10d %10d %4o " SIZE_SPEC " %5u %5u "
"%5lu %5u %5u %5u %5u %10lu %10lu %10lu "
SIZE_SPEC " " SIZE_SPEC "\n",
shp->shm_perm.key,
shp->shm_perm.id,
shp->shm_perm.mode,
shp->shm_segsz,
shp->shm_cprid,
shp->shm_lprid,
shp->shm_nattch,
from_kuid_munged(user_ns, shp->shm_perm.uid),
from_kgid_munged(user_ns, shp->shm_perm.gid),
from_kuid_munged(user_ns, shp->shm_perm.cuid),
from_kgid_munged(user_ns, shp->shm_perm.cgid),
shp->shm_atim,
shp->shm_dtim,
shp->shm_ctim,
rss * PAGE_SIZE,
swp * PAGE_SIZE);
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3141_0 |
crossvul-cpp_data_good_2884_0 | /*
BNEP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2001-2002 Inventel Systemes
Written 2001-2002 by
Clément Moreau <clement.moreau@inventel.fr>
David Libault <david.libault@inventel.fr>
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/file.h>
#include <linux/etherdevice.h>
#include <asm/unaligned.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/l2cap.h>
#include <net/bluetooth/hci_core.h>
#include "bnep.h"
#define VERSION "1.3"
static bool compress_src = true;
static bool compress_dst = true;
static LIST_HEAD(bnep_session_list);
static DECLARE_RWSEM(bnep_session_sem);
static struct bnep_session *__bnep_get_session(u8 *dst)
{
struct bnep_session *s;
BT_DBG("");
list_for_each_entry(s, &bnep_session_list, list)
if (ether_addr_equal(dst, s->eh.h_source))
return s;
return NULL;
}
static void __bnep_link_session(struct bnep_session *s)
{
list_add(&s->list, &bnep_session_list);
}
static void __bnep_unlink_session(struct bnep_session *s)
{
list_del(&s->list);
}
static int bnep_send(struct bnep_session *s, void *data, size_t len)
{
struct socket *sock = s->sock;
struct kvec iv = { data, len };
return kernel_sendmsg(sock, &s->msg, &iv, 1, len);
}
static int bnep_send_rsp(struct bnep_session *s, u8 ctrl, u16 resp)
{
struct bnep_control_rsp rsp;
rsp.type = BNEP_CONTROL;
rsp.ctrl = ctrl;
rsp.resp = htons(resp);
return bnep_send(s, &rsp, sizeof(rsp));
}
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
static inline void bnep_set_default_proto_filter(struct bnep_session *s)
{
/* (IPv4, ARP) */
s->proto_filter[0].start = ETH_P_IP;
s->proto_filter[0].end = ETH_P_ARP;
/* (RARP, AppleTalk) */
s->proto_filter[1].start = ETH_P_RARP;
s->proto_filter[1].end = ETH_P_AARP;
/* (IPX, IPv6) */
s->proto_filter[2].start = ETH_P_IPX;
s->proto_filter[2].end = ETH_P_IPV6;
}
#endif
static int bnep_ctrl_set_netfilter(struct bnep_session *s, __be16 *data, int len)
{
int n;
if (len < 2)
return -EILSEQ;
n = get_unaligned_be16(data);
data++;
len -= 2;
if (len < n)
return -EILSEQ;
BT_DBG("filter len %d", n);
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
n /= 4;
if (n <= BNEP_MAX_PROTO_FILTERS) {
struct bnep_proto_filter *f = s->proto_filter;
int i;
for (i = 0; i < n; i++) {
f[i].start = get_unaligned_be16(data++);
f[i].end = get_unaligned_be16(data++);
BT_DBG("proto filter start %d end %d",
f[i].start, f[i].end);
}
if (i < BNEP_MAX_PROTO_FILTERS)
memset(f + i, 0, sizeof(*f));
if (n == 0)
bnep_set_default_proto_filter(s);
bnep_send_rsp(s, BNEP_FILTER_NET_TYPE_RSP, BNEP_SUCCESS);
} else {
bnep_send_rsp(s, BNEP_FILTER_NET_TYPE_RSP, BNEP_FILTER_LIMIT_REACHED);
}
#else
bnep_send_rsp(s, BNEP_FILTER_NET_TYPE_RSP, BNEP_FILTER_UNSUPPORTED_REQ);
#endif
return 0;
}
static int bnep_ctrl_set_mcfilter(struct bnep_session *s, u8 *data, int len)
{
int n;
if (len < 2)
return -EILSEQ;
n = get_unaligned_be16(data);
data += 2;
len -= 2;
if (len < n)
return -EILSEQ;
BT_DBG("filter len %d", n);
#ifdef CONFIG_BT_BNEP_MC_FILTER
n /= (ETH_ALEN * 2);
if (n > 0) {
int i;
s->mc_filter = 0;
/* Always send broadcast */
set_bit(bnep_mc_hash(s->dev->broadcast), (ulong *) &s->mc_filter);
/* Add address ranges to the multicast hash */
for (; n > 0; n--) {
u8 a1[6], *a2;
memcpy(a1, data, ETH_ALEN);
data += ETH_ALEN;
a2 = data;
data += ETH_ALEN;
BT_DBG("mc filter %pMR -> %pMR", a1, a2);
/* Iterate from a1 to a2 */
set_bit(bnep_mc_hash(a1), (ulong *) &s->mc_filter);
while (memcmp(a1, a2, 6) < 0 && s->mc_filter != ~0LL) {
/* Increment a1 */
i = 5;
while (i >= 0 && ++a1[i--] == 0)
;
set_bit(bnep_mc_hash(a1), (ulong *) &s->mc_filter);
}
}
}
BT_DBG("mc filter hash 0x%llx", s->mc_filter);
bnep_send_rsp(s, BNEP_FILTER_MULTI_ADDR_RSP, BNEP_SUCCESS);
#else
bnep_send_rsp(s, BNEP_FILTER_MULTI_ADDR_RSP, BNEP_FILTER_UNSUPPORTED_REQ);
#endif
return 0;
}
static int bnep_rx_control(struct bnep_session *s, void *data, int len)
{
u8 cmd = *(u8 *)data;
int err = 0;
data++;
len--;
switch (cmd) {
case BNEP_CMD_NOT_UNDERSTOOD:
case BNEP_SETUP_CONN_RSP:
case BNEP_FILTER_NET_TYPE_RSP:
case BNEP_FILTER_MULTI_ADDR_RSP:
/* Ignore these for now */
break;
case BNEP_FILTER_NET_TYPE_SET:
err = bnep_ctrl_set_netfilter(s, data, len);
break;
case BNEP_FILTER_MULTI_ADDR_SET:
err = bnep_ctrl_set_mcfilter(s, data, len);
break;
case BNEP_SETUP_CONN_REQ:
err = bnep_send_rsp(s, BNEP_SETUP_CONN_RSP, BNEP_CONN_NOT_ALLOWED);
break;
default: {
u8 pkt[3];
pkt[0] = BNEP_CONTROL;
pkt[1] = BNEP_CMD_NOT_UNDERSTOOD;
pkt[2] = cmd;
bnep_send(s, pkt, sizeof(pkt));
}
break;
}
return err;
}
static int bnep_rx_extension(struct bnep_session *s, struct sk_buff *skb)
{
struct bnep_ext_hdr *h;
int err = 0;
do {
h = (void *) skb->data;
if (!skb_pull(skb, sizeof(*h))) {
err = -EILSEQ;
break;
}
BT_DBG("type 0x%x len %d", h->type, h->len);
switch (h->type & BNEP_TYPE_MASK) {
case BNEP_EXT_CONTROL:
bnep_rx_control(s, skb->data, skb->len);
break;
default:
/* Unknown extension, skip it. */
break;
}
if (!skb_pull(skb, h->len)) {
err = -EILSEQ;
break;
}
} while (!err && (h->type & BNEP_EXT_HEADER));
return err;
}
static u8 __bnep_rx_hlen[] = {
ETH_HLEN, /* BNEP_GENERAL */
0, /* BNEP_CONTROL */
2, /* BNEP_COMPRESSED */
ETH_ALEN + 2, /* BNEP_COMPRESSED_SRC_ONLY */
ETH_ALEN + 2 /* BNEP_COMPRESSED_DST_ONLY */
};
static int bnep_rx_frame(struct bnep_session *s, struct sk_buff *skb)
{
struct net_device *dev = s->dev;
struct sk_buff *nskb;
u8 type;
dev->stats.rx_bytes += skb->len;
type = *(u8 *) skb->data;
skb_pull(skb, 1);
if ((type & BNEP_TYPE_MASK) >= sizeof(__bnep_rx_hlen))
goto badframe;
if ((type & BNEP_TYPE_MASK) == BNEP_CONTROL) {
bnep_rx_control(s, skb->data, skb->len);
kfree_skb(skb);
return 0;
}
skb_reset_mac_header(skb);
/* Verify and pull out header */
if (!skb_pull(skb, __bnep_rx_hlen[type & BNEP_TYPE_MASK]))
goto badframe;
s->eh.h_proto = get_unaligned((__be16 *) (skb->data - 2));
if (type & BNEP_EXT_HEADER) {
if (bnep_rx_extension(s, skb) < 0)
goto badframe;
}
/* Strip 802.1p header */
if (ntohs(s->eh.h_proto) == ETH_P_8021Q) {
if (!skb_pull(skb, 4))
goto badframe;
s->eh.h_proto = get_unaligned((__be16 *) (skb->data - 2));
}
/* We have to alloc new skb and copy data here :(. Because original skb
* may not be modified and because of the alignment requirements. */
nskb = alloc_skb(2 + ETH_HLEN + skb->len, GFP_KERNEL);
if (!nskb) {
dev->stats.rx_dropped++;
kfree_skb(skb);
return -ENOMEM;
}
skb_reserve(nskb, 2);
/* Decompress header and construct ether frame */
switch (type & BNEP_TYPE_MASK) {
case BNEP_COMPRESSED:
memcpy(__skb_put(nskb, ETH_HLEN), &s->eh, ETH_HLEN);
break;
case BNEP_COMPRESSED_SRC_ONLY:
memcpy(__skb_put(nskb, ETH_ALEN), s->eh.h_dest, ETH_ALEN);
memcpy(__skb_put(nskb, ETH_ALEN), skb_mac_header(skb), ETH_ALEN);
put_unaligned(s->eh.h_proto, (__be16 *) __skb_put(nskb, 2));
break;
case BNEP_COMPRESSED_DST_ONLY:
memcpy(__skb_put(nskb, ETH_ALEN), skb_mac_header(skb),
ETH_ALEN);
memcpy(__skb_put(nskb, ETH_ALEN + 2), s->eh.h_source,
ETH_ALEN + 2);
break;
case BNEP_GENERAL:
memcpy(__skb_put(nskb, ETH_ALEN * 2), skb_mac_header(skb),
ETH_ALEN * 2);
put_unaligned(s->eh.h_proto, (__be16 *) __skb_put(nskb, 2));
break;
}
skb_copy_from_linear_data(skb, __skb_put(nskb, skb->len), skb->len);
kfree_skb(skb);
dev->stats.rx_packets++;
nskb->ip_summed = CHECKSUM_NONE;
nskb->protocol = eth_type_trans(nskb, dev);
netif_rx_ni(nskb);
return 0;
badframe:
dev->stats.rx_errors++;
kfree_skb(skb);
return 0;
}
static u8 __bnep_tx_types[] = {
BNEP_GENERAL,
BNEP_COMPRESSED_SRC_ONLY,
BNEP_COMPRESSED_DST_ONLY,
BNEP_COMPRESSED
};
static int bnep_tx_frame(struct bnep_session *s, struct sk_buff *skb)
{
struct ethhdr *eh = (void *) skb->data;
struct socket *sock = s->sock;
struct kvec iv[3];
int len = 0, il = 0;
u8 type = 0;
BT_DBG("skb %p dev %p type %d", skb, skb->dev, skb->pkt_type);
if (!skb->dev) {
/* Control frame sent by us */
goto send;
}
iv[il++] = (struct kvec) { &type, 1 };
len++;
if (compress_src && ether_addr_equal(eh->h_dest, s->eh.h_source))
type |= 0x01;
if (compress_dst && ether_addr_equal(eh->h_source, s->eh.h_dest))
type |= 0x02;
if (type)
skb_pull(skb, ETH_ALEN * 2);
type = __bnep_tx_types[type];
switch (type) {
case BNEP_COMPRESSED_SRC_ONLY:
iv[il++] = (struct kvec) { eh->h_source, ETH_ALEN };
len += ETH_ALEN;
break;
case BNEP_COMPRESSED_DST_ONLY:
iv[il++] = (struct kvec) { eh->h_dest, ETH_ALEN };
len += ETH_ALEN;
break;
}
send:
iv[il++] = (struct kvec) { skb->data, skb->len };
len += skb->len;
/* FIXME: linearize skb */
{
len = kernel_sendmsg(sock, &s->msg, iv, il, len);
}
kfree_skb(skb);
if (len > 0) {
s->dev->stats.tx_bytes += len;
s->dev->stats.tx_packets++;
return 0;
}
return len;
}
static int bnep_session(void *arg)
{
struct bnep_session *s = arg;
struct net_device *dev = s->dev;
struct sock *sk = s->sock->sk;
struct sk_buff *skb;
wait_queue_t wait;
BT_DBG("");
set_user_nice(current, -15);
init_waitqueue_entry(&wait, current);
add_wait_queue(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (atomic_read(&s->terminate))
break;
/* RX */
while ((skb = skb_dequeue(&sk->sk_receive_queue))) {
skb_orphan(skb);
if (!skb_linearize(skb))
bnep_rx_frame(s, skb);
else
kfree_skb(skb);
}
if (sk->sk_state != BT_CONNECTED)
break;
/* TX */
while ((skb = skb_dequeue(&sk->sk_write_queue)))
if (bnep_tx_frame(s, skb))
break;
netif_wake_queue(dev);
schedule();
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
/* Cleanup session */
down_write(&bnep_session_sem);
/* Delete network device */
unregister_netdev(dev);
/* Wakeup user-space polling for socket errors */
s->sock->sk->sk_err = EUNATCH;
wake_up_interruptible(sk_sleep(s->sock->sk));
/* Release the socket */
fput(s->sock->file);
__bnep_unlink_session(s);
up_write(&bnep_session_sem);
free_netdev(dev);
module_put_and_exit(0);
return 0;
}
static struct device *bnep_get_device(struct bnep_session *session)
{
struct hci_conn *conn;
conn = l2cap_pi(session->sock->sk)->chan->conn->hcon;
if (!conn)
return NULL;
return &conn->dev;
}
static struct device_type bnep_type = {
.name = "bluetooth",
};
int bnep_add_connection(struct bnep_connadd_req *req, struct socket *sock)
{
struct net_device *dev;
struct bnep_session *s, *ss;
u8 dst[ETH_ALEN], src[ETH_ALEN];
int err;
BT_DBG("");
if (!l2cap_is_socket(sock))
return -EBADFD;
baswap((void *) dst, &l2cap_pi(sock->sk)->chan->dst);
baswap((void *) src, &l2cap_pi(sock->sk)->chan->src);
/* session struct allocated as private part of net_device */
dev = alloc_netdev(sizeof(struct bnep_session),
(*req->device) ? req->device : "bnep%d",
NET_NAME_UNKNOWN,
bnep_net_setup);
if (!dev)
return -ENOMEM;
down_write(&bnep_session_sem);
ss = __bnep_get_session(dst);
if (ss && ss->state == BT_CONNECTED) {
err = -EEXIST;
goto failed;
}
s = netdev_priv(dev);
/* This is rx header therefore addresses are swapped.
* ie. eh.h_dest is our local address. */
memcpy(s->eh.h_dest, &src, ETH_ALEN);
memcpy(s->eh.h_source, &dst, ETH_ALEN);
memcpy(dev->dev_addr, s->eh.h_dest, ETH_ALEN);
s->dev = dev;
s->sock = sock;
s->role = req->role;
s->state = BT_CONNECTED;
s->msg.msg_flags = MSG_NOSIGNAL;
#ifdef CONFIG_BT_BNEP_MC_FILTER
/* Set default mc filter */
set_bit(bnep_mc_hash(dev->broadcast), (ulong *) &s->mc_filter);
#endif
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
/* Set default protocol filter */
bnep_set_default_proto_filter(s);
#endif
SET_NETDEV_DEV(dev, bnep_get_device(s));
SET_NETDEV_DEVTYPE(dev, &bnep_type);
err = register_netdev(dev);
if (err)
goto failed;
__bnep_link_session(s);
__module_get(THIS_MODULE);
s->task = kthread_run(bnep_session, s, "kbnepd %s", dev->name);
if (IS_ERR(s->task)) {
/* Session thread start failed, gotta cleanup. */
module_put(THIS_MODULE);
unregister_netdev(dev);
__bnep_unlink_session(s);
err = PTR_ERR(s->task);
goto failed;
}
up_write(&bnep_session_sem);
strcpy(req->device, dev->name);
return 0;
failed:
up_write(&bnep_session_sem);
free_netdev(dev);
return err;
}
int bnep_del_connection(struct bnep_conndel_req *req)
{
struct bnep_session *s;
int err = 0;
BT_DBG("");
down_read(&bnep_session_sem);
s = __bnep_get_session(req->dst);
if (s) {
atomic_inc(&s->terminate);
wake_up_process(s->task);
} else
err = -ENOENT;
up_read(&bnep_session_sem);
return err;
}
static void __bnep_copy_ci(struct bnep_conninfo *ci, struct bnep_session *s)
{
memset(ci, 0, sizeof(*ci));
memcpy(ci->dst, s->eh.h_source, ETH_ALEN);
strcpy(ci->device, s->dev->name);
ci->flags = s->flags;
ci->state = s->state;
ci->role = s->role;
}
int bnep_get_connlist(struct bnep_connlist_req *req)
{
struct bnep_session *s;
int err = 0, n = 0;
down_read(&bnep_session_sem);
list_for_each_entry(s, &bnep_session_list, list) {
struct bnep_conninfo ci;
__bnep_copy_ci(&ci, s);
if (copy_to_user(req->ci, &ci, sizeof(ci))) {
err = -EFAULT;
break;
}
if (++n >= req->cnum)
break;
req->ci++;
}
req->cnum = n;
up_read(&bnep_session_sem);
return err;
}
int bnep_get_conninfo(struct bnep_conninfo *ci)
{
struct bnep_session *s;
int err = 0;
down_read(&bnep_session_sem);
s = __bnep_get_session(ci->dst);
if (s)
__bnep_copy_ci(ci, s);
else
err = -ENOENT;
up_read(&bnep_session_sem);
return err;
}
static int __init bnep_init(void)
{
char flt[50] = "";
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
strcat(flt, "protocol ");
#endif
#ifdef CONFIG_BT_BNEP_MC_FILTER
strcat(flt, "multicast");
#endif
BT_INFO("BNEP (Ethernet Emulation) ver %s", VERSION);
if (flt[0])
BT_INFO("BNEP filters: %s", flt);
bnep_sock_init();
return 0;
}
static void __exit bnep_exit(void)
{
bnep_sock_cleanup();
}
module_init(bnep_init);
module_exit(bnep_exit);
module_param(compress_src, bool, 0644);
MODULE_PARM_DESC(compress_src, "Compress sources headers");
module_param(compress_dst, bool, 0644);
MODULE_PARM_DESC(compress_dst, "Compress destination headers");
MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
MODULE_DESCRIPTION("Bluetooth BNEP ver " VERSION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL");
MODULE_ALIAS("bt-proto-4");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2884_0 |
crossvul-cpp_data_good_2976_1 | /*
* Salsa20: Salsa20 stream cipher algorithm
*
* Copyright (c) 2007 Tan Swee Heng <thesweeheng@gmail.com>
*
* Derived from:
* - salsa20.c: Public domain C code by Daniel J. Bernstein <djb@cr.yp.to>
*
* Salsa20 is a stream cipher candidate in eSTREAM, the ECRYPT Stream
* Cipher Project. It is designed by Daniel J. Bernstein <djb@cr.yp.to>.
* More information about eSTREAM and Salsa20 can be found here:
* http://www.ecrypt.eu.org/stream/
* http://cr.yp.to/snuffle.html
*
* 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/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/crypto.h>
#include <linux/types.h>
#include <linux/bitops.h>
#include <crypto/algapi.h>
#include <asm/byteorder.h>
#define SALSA20_IV_SIZE 8U
#define SALSA20_MIN_KEY_SIZE 16U
#define SALSA20_MAX_KEY_SIZE 32U
/*
* Start of code taken from D. J. Bernstein's reference implementation.
* With some modifications and optimizations made to suit our needs.
*/
/*
salsa20-ref.c version 20051118
D. J. Bernstein
Public domain.
*/
#define U32TO8_LITTLE(p, v) \
{ (p)[0] = (v >> 0) & 0xff; (p)[1] = (v >> 8) & 0xff; \
(p)[2] = (v >> 16) & 0xff; (p)[3] = (v >> 24) & 0xff; }
#define U8TO32_LITTLE(p) \
(((u32)((p)[0]) ) | ((u32)((p)[1]) << 8) | \
((u32)((p)[2]) << 16) | ((u32)((p)[3]) << 24) )
struct salsa20_ctx
{
u32 input[16];
};
static void salsa20_wordtobyte(u8 output[64], const u32 input[16])
{
u32 x[16];
int i;
memcpy(x, input, sizeof(x));
for (i = 20; i > 0; i -= 2) {
x[ 4] ^= rol32((x[ 0] + x[12]), 7);
x[ 8] ^= rol32((x[ 4] + x[ 0]), 9);
x[12] ^= rol32((x[ 8] + x[ 4]), 13);
x[ 0] ^= rol32((x[12] + x[ 8]), 18);
x[ 9] ^= rol32((x[ 5] + x[ 1]), 7);
x[13] ^= rol32((x[ 9] + x[ 5]), 9);
x[ 1] ^= rol32((x[13] + x[ 9]), 13);
x[ 5] ^= rol32((x[ 1] + x[13]), 18);
x[14] ^= rol32((x[10] + x[ 6]), 7);
x[ 2] ^= rol32((x[14] + x[10]), 9);
x[ 6] ^= rol32((x[ 2] + x[14]), 13);
x[10] ^= rol32((x[ 6] + x[ 2]), 18);
x[ 3] ^= rol32((x[15] + x[11]), 7);
x[ 7] ^= rol32((x[ 3] + x[15]), 9);
x[11] ^= rol32((x[ 7] + x[ 3]), 13);
x[15] ^= rol32((x[11] + x[ 7]), 18);
x[ 1] ^= rol32((x[ 0] + x[ 3]), 7);
x[ 2] ^= rol32((x[ 1] + x[ 0]), 9);
x[ 3] ^= rol32((x[ 2] + x[ 1]), 13);
x[ 0] ^= rol32((x[ 3] + x[ 2]), 18);
x[ 6] ^= rol32((x[ 5] + x[ 4]), 7);
x[ 7] ^= rol32((x[ 6] + x[ 5]), 9);
x[ 4] ^= rol32((x[ 7] + x[ 6]), 13);
x[ 5] ^= rol32((x[ 4] + x[ 7]), 18);
x[11] ^= rol32((x[10] + x[ 9]), 7);
x[ 8] ^= rol32((x[11] + x[10]), 9);
x[ 9] ^= rol32((x[ 8] + x[11]), 13);
x[10] ^= rol32((x[ 9] + x[ 8]), 18);
x[12] ^= rol32((x[15] + x[14]), 7);
x[13] ^= rol32((x[12] + x[15]), 9);
x[14] ^= rol32((x[13] + x[12]), 13);
x[15] ^= rol32((x[14] + x[13]), 18);
}
for (i = 0; i < 16; ++i)
x[i] += input[i];
for (i = 0; i < 16; ++i)
U32TO8_LITTLE(output + 4 * i,x[i]);
}
static const char sigma[16] = "expand 32-byte k";
static const char tau[16] = "expand 16-byte k";
static void salsa20_keysetup(struct salsa20_ctx *ctx, const u8 *k, u32 kbytes)
{
const char *constants;
ctx->input[1] = U8TO32_LITTLE(k + 0);
ctx->input[2] = U8TO32_LITTLE(k + 4);
ctx->input[3] = U8TO32_LITTLE(k + 8);
ctx->input[4] = U8TO32_LITTLE(k + 12);
if (kbytes == 32) { /* recommended */
k += 16;
constants = sigma;
} else { /* kbytes == 16 */
constants = tau;
}
ctx->input[11] = U8TO32_LITTLE(k + 0);
ctx->input[12] = U8TO32_LITTLE(k + 4);
ctx->input[13] = U8TO32_LITTLE(k + 8);
ctx->input[14] = U8TO32_LITTLE(k + 12);
ctx->input[0] = U8TO32_LITTLE(constants + 0);
ctx->input[5] = U8TO32_LITTLE(constants + 4);
ctx->input[10] = U8TO32_LITTLE(constants + 8);
ctx->input[15] = U8TO32_LITTLE(constants + 12);
}
static void salsa20_ivsetup(struct salsa20_ctx *ctx, const u8 *iv)
{
ctx->input[6] = U8TO32_LITTLE(iv + 0);
ctx->input[7] = U8TO32_LITTLE(iv + 4);
ctx->input[8] = 0;
ctx->input[9] = 0;
}
static void salsa20_encrypt_bytes(struct salsa20_ctx *ctx, u8 *dst,
const u8 *src, unsigned int bytes)
{
u8 buf[64];
if (dst != src)
memcpy(dst, src, bytes);
while (bytes) {
salsa20_wordtobyte(buf, ctx->input);
ctx->input[8]++;
if (!ctx->input[8])
ctx->input[9]++;
if (bytes <= 64) {
crypto_xor(dst, buf, bytes);
return;
}
crypto_xor(dst, buf, 64);
bytes -= 64;
dst += 64;
}
}
/*
* End of code taken from D. J. Bernstein's reference implementation.
*/
static int setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keysize)
{
struct salsa20_ctx *ctx = crypto_tfm_ctx(tfm);
salsa20_keysetup(ctx, key, keysize);
return 0;
}
static int encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, 64);
salsa20_ivsetup(ctx, walk.iv);
while (walk.nbytes >= 64) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr,
walk.nbytes - (walk.nbytes % 64));
err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);
}
if (walk.nbytes) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, walk.nbytes);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
static struct crypto_alg alg = {
.cra_name = "salsa20",
.cra_driver_name = "salsa20-generic",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_type = &crypto_blkcipher_type,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct salsa20_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_u = {
.blkcipher = {
.setkey = setkey,
.encrypt = encrypt,
.decrypt = encrypt,
.min_keysize = SALSA20_MIN_KEY_SIZE,
.max_keysize = SALSA20_MAX_KEY_SIZE,
.ivsize = SALSA20_IV_SIZE,
}
}
};
static int __init salsa20_generic_mod_init(void)
{
return crypto_register_alg(&alg);
}
static void __exit salsa20_generic_mod_fini(void)
{
crypto_unregister_alg(&alg);
}
module_init(salsa20_generic_mod_init);
module_exit(salsa20_generic_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION ("Salsa20 stream cipher algorithm");
MODULE_ALIAS_CRYPTO("salsa20");
MODULE_ALIAS_CRYPTO("salsa20-generic");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2976_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.